The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Agents registration CRUD and integration with Sessions (#61)
Srajan Asthanaffbb7e7e6449
diff --git a/fern/openapi/openapi.json b/fern/openapi/openapi.jsonindex 37041cf84..6a29758fc 100644--- a/fern/openapi/openapi.json+++ b/fern/openapi/openapi.json@@ -23,6 +23,38 @@}]},+ "Agent": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AgentSpec"+ },+ {+ "properties": {+ "id": {+ "description": "Immutable server-generated agent identifier.",+ "minLength": 1,+ "type": "string"+ },+ "name": {+ "allOf": [+ {+ "$ref": "#/components/schemas/ResourceName"+ },+ {+ "description": "Immutable unique agent name within the tenant."+ }+ ]+ }+ },+ "required": [+ "id",+ "name"+ ],+ "type": "object"+ }+ ],+ "description": "Agent Definition"+ },"AgentInfo": {"properties": {"input": {@@ -143,6 +175,25 @@],"type": "object"},+ "AgentWriteRequest": {+ "allOf": [+ {+ "$ref": "#/components/schemas/AgentSpec"+ },+ {+ "properties": {+ "name": {+ "$ref": "#/components/schemas/ResourceName"+ }+ },+ "required": [+ "name"+ ],+ "type": "object"+ }+ ],+ "description": "Agent Definition"+ },"ApprovalAllow": {"properties": {"status": {@@ -645,14 +696,26 @@},"type": "object"},+ "CreateAgentResponse": {+ "properties": {+ "data": {+ "$ref": "#/components/schemas/Agent"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"CreateSessionRequest": {+ "additionalProperties": false,"properties": {- "agent_spec": {- "$ref": "#/components/schemas/AgentSpec"+ "agent": {+ "$ref": "#/components/schemas/SessionAgent"}},"required": [- "agent_spec"+ "agent"],"type": "object"},@@ -805,6 +868,17 @@},"type": "object"},+ "GetAgentResponse": {+ "properties": {+ "data": {+ "$ref": "#/components/schemas/Agent"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"GetCapabilitiesResponse": {"properties": {"data": {@@ -958,6 +1032,20 @@},"type": "object"},+ "ListAgentsResponse": {+ "properties": {+ "data": {+ "items": {+ "$ref": "#/components/schemas/Agent"+ },+ "type": "array"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"ListAvailableMcpServersResponse": {"properties": {"data": {@@ -1825,6 +1913,17 @@"default": "auto","description": "Defaults to 'auto' (chain to session last turn). Use 'null' for the session's first turn."},+ "PutAgentResponse": {+ "properties": {+ "data": {+ "$ref": "#/components/schemas/Agent"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ },"PutMcpServerResponse": {"properties": {"data": {@@ -2191,8 +2290,8 @@},"Session": {"properties": {- "agent_spec": {- "$ref": "#/components/schemas/AgentSpec"+ "agent": {+ "$ref": "#/components/schemas/SessionAgent"},"created_at": {"type": "string"@@ -2212,13 +2311,69 @@},"required": ["id",- "agent_spec",+ "agent","title","created_at","updated_at"],"type": "object"},+ "SessionAgent": {+ "discriminator": {+ "mapping": {+ "ref": "#/components/schemas/SessionAgentRef",+ "value": "#/components/schemas/SessionAgentValue"+ },+ "propertyName": "type"+ },+ "oneOf": [+ {+ "$ref": "#/components/schemas/SessionAgentRef"+ },+ {+ "$ref": "#/components/schemas/SessionAgentValue"+ }+ ]+ },+ "SessionAgentRef": {+ "additionalProperties": false,+ "properties": {+ "agent_id": {+ "minLength": 1,+ "type": "string"+ },+ "type": {+ "enum": [+ "ref"+ ],+ "type": "string"+ }+ },+ "required": [+ "type",+ "agent_id"+ ],+ "type": "object"+ },+ "SessionAgentValue": {+ "additionalProperties": false,+ "properties": {+ "agent_spec": {+ "$ref": "#/components/schemas/AgentSpec"+ },+ "type": {+ "enum": [+ "value"+ ],+ "type": "string"+ }+ },+ "required": [+ "type",+ "agent_spec"+ ],+ "type": "object"+ },"SessionEvent": {"discriminator": {"mapping": {@@ -3093,10 +3248,55 @@}]},+ "UpdateAgentRequest": {+ "description": "Agent Definition",+ "properties": {+ "config": {+ "$ref": "#/components/schemas/RuntimeConfig"+ },+ "instructions": {+ "type": "string"+ },+ "mcp_servers": {+ "items": {+ "$ref": "#/components/schemas/MCPServer"+ },+ "type": "array"+ },+ "messages": {+ "items": {+ "$ref": "#/components/schemas/AgentSpecUserMessage"+ },+ "type": "array"+ },+ "model": {+ "$ref": "#/components/schemas/AgentSpecModel"+ },+ "response_format": {+ "$ref": "#/components/schemas/ResponseFormat"+ },+ "skills": {+ "items": {+ "$ref": "#/components/schemas/SkillNameRef"+ },+ "type": "array"+ },+ "variables": {+ "additionalProperties": {+ "type": "string"+ },+ "type": "object"+ }+ },+ "required": [+ "model"+ ],+ "type": "object"+ },"UpdateSessionRequest": {"properties": {- "agent_spec": {- "$ref": "#/components/schemas/AgentSpec"+ "agent": {+ "$ref": "#/components/schemas/SessionAgentValue"}},"type": "object"@@ -3248,12 +3448,232 @@}},"info": {- "description": "Agent server with DB-backed sessions, settings catalogs, and model/MCP/skill providers.",+ "description": "Agent server with DB-backed sessions, agent registry, settings catalogs, and model/MCP/skill providers.","title": "Agent Server","version": "0.1.0"},"openapi": "3.1.0","paths": {+ "/api/v1/agents": {+ "get": {+ "description": "All configured agents for the tenant.",+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ListAgentsResponse"+ }+ }+ },+ "description": "All configured agents."+ }+ },+ "summary": "List agents",+ "tags": [+ "Agents"+ ],+ "x-fern-sdk-group-name": [+ "agents"+ ],+ "x-fern-sdk-method-name": "list"+ },+ "post": {+ "description": "Creates an agent and allocates an immutable id. Fails if `name` is already taken. Name cannot be changed later.",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AgentWriteRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreateAgentResponse"+ }+ }+ },+ "description": "The created agent."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid request body or unknown model/MCP/skill refs."+ },+ "409": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "An agent with this name already exists."+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The agent spec is valid but requires a capability this server does not provide (e.g. sandbox or skills)."+ }+ },+ "summary": "Create an agent",+ "tags": [+ "Agents"+ ],+ "x-fern-sdk-group-name": [+ "agents"+ ],+ "x-fern-sdk-method-name": "create"+ }+ },+ "/api/v1/agents/{agent_id}": {+ "get": {+ "description": "Fetch a configured agent by immutable id.",+ "parameters": [+ {+ "description": "Immutable agent identifier.",+ "in": "path",+ "name": "agent_id",+ "required": true,+ "schema": {+ "description": "Immutable agent identifier.",+ "maxLength": 64,+ "minLength": 1,+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetAgentResponse"+ }+ }+ },+ "description": "The agent."+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Agent not found."+ }+ },+ "summary": "Get an agent",+ "tags": [+ "Agents"+ ],+ "x-fern-sdk-group-name": [+ "agents"+ ],+ "x-fern-sdk-method-name": "get"+ }+ },+ "/api/v1/agents/{name}": {+ "put": {+ "description": "Replaces the AgentSpec for an existing agent keyed by immutable `name`.",+ "parameters": [+ {+ "description": "Immutable unique agent name within the tenant.",+ "in": "path",+ "name": "name",+ "required": true,+ "schema": {+ "allOf": [+ {+ "$ref": "#/components/schemas/ResourceName"+ },+ {+ "description": "Immutable unique agent name within the tenant."+ }+ ]+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/UpdateAgentRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PutAgentResponse"+ }+ }+ },+ "description": "The saved agent."+ },+ "400": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Invalid request body or unknown model/MCP/skill refs."+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Agent not found."+ },+ "422": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "The agent spec is valid but requires a capability this server does not provide (e.g. sandbox or skills)."+ }+ },+ "summary": "Update an agent",+ "tags": [+ "Agents"+ ],+ "x-fern-sdk-group-name": [+ "agents"+ ],+ "x-fern-sdk-method-name": "update"+ }+ },"/api/v1/auth/callback": {"get": {"description": "Browser-redirect target hit by the identity provider after login, never called directly by SDK consumers. In local/single-binary mode, redirects straight back into the app.",@@ -3690,7 +4110,7 @@},"/api/v1/sessions": {"get": {- "description": "List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.",+ "description": "List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.","parameters": [{"description": "Page size. Defaults to 10, max 100.",@@ -3745,6 +4165,17 @@"format": "date-time","type": "string"}+ },+ {+ "description": "When set, only sessions bound to this agent id are returned.",+ "in": "query",+ "name": "agent_id",+ "required": false,+ "schema": {+ "description": "When set, only sessions bound to this agent id are returned.",+ "minLength": 1,+ "type": "string"+ }}],"responses": {@@ -3784,7 +4215,7 @@"x-fern-sdk-method-name": "list"},"post": {- "description": "Create a session holding an inline agent spec. Turns are executed against this spec.",+ "description": "Create a session with `agent` as either `{ type: \"value\", agent_spec }` (draft) or `{ type: \"ref\", agent_id }` (named). Named sessions resolve the live agent on each turn.","requestBody": {"content": {"application/json": {@@ -3816,6 +4247,16 @@},"description": "Invalid request body."},+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Named `agent_id` not found."+ },"422": {"content": {"application/json": {@@ -3916,7 +4357,7 @@"x-fern-sdk-method-name": "get"},"patch": {- "description": "Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.",+ "description": "Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.","parameters": [{"description": "Session identifier.",@@ -3960,7 +4401,7 @@}}},- "description": "Invalid request body."+ "description": "Invalid request body, or named session rejected an agent update."},"404": {"content": {@@ -4320,7 +4761,7 @@}}},- "description": "The session is valid but a required resource is no longer available (e.g. model, MCP server, skill, or sandbox provider)."+ "description": "The session is valid but a required resource is no longer available (e.g. named agent, model, MCP server, skill, or sandbox provider)."}},"summary": "Create and execute a turn in a session",diff --git a/packages/frontend/src/harnessServer.ts b/packages/frontend/src/harnessServer.tsindex cecde802f..0dbde8cc4 100644--- a/packages/frontend/src/harnessServer.ts+++ b/packages/frontend/src/harnessServer.ts@@ -38,8 +38,8 @@ export interface HarnessAgentSpec extends AgentSpec<Harness.AgentSpecModel, Harn}export interface HarnessSession extends Session<HarnessAgentSpec> {- agentSpec: HarnessAgentSpec;- isMutable: true;+ agentSpec?: HarnessAgentSpec;+ isMutable: boolean;}export type CreateHarnessServerOptions = CreateHarnessClientOptions;@@ -82,12 +82,15 @@ function toUiAgentSpec(spec: Harness.AgentSpec): HarnessAgentSpec {}function toUiSession(session: Harness.Session): HarnessSession {- const { title, agentSpec, ...rest } = session;+ // Value agents are draft/mutable; ref agents are named/immutable.+ const isMutable = session.agent.type === 'value';return {- ...rest,- agentSpec: toUiAgentSpec(agentSpec),- isMutable: true,- ...(title === null ? {} : { title }),+ id: session.id,+ isMutable,+ createdAt: session.createdAt,+ updatedAt: session.updatedAt,+ ...(session.title === null ? {} : { title: session.title }),+ ...(session.agent.type === 'value' ? { agentSpec: toUiAgentSpec(session.agent.agentSpec) } : {}),};}@@ -182,7 +185,9 @@ export function createHarnessChatServer(options: CreateHarnessServerOptions = {}if (!request.agentSpec) {throw new Error('Harness sessions require an agentSpec');}- const created = await client.sessions.create({ agentSpec: toHarnessAgentSpec(request.agentSpec) });+ const created = await client.sessions.create({+ agent: { type: 'value', agentSpec: toHarnessAgentSpec(request.agentSpec) },+ });return toUiSession(created.data);},@@ -202,7 +207,7 @@ export function createHarnessChatServer(options: CreateHarnessServerOptions = {}async updateSession({ sessionId, agentSpec }) {const response = await client.sessions.update(sessionId, {- ...(agentSpec === undefined ? {} : { agentSpec: toHarnessAgentSpec(agentSpec) }),+ ...(agentSpec === undefined ? {} : { agent: { type: 'value', agentSpec: toHarnessAgentSpec(agentSpec) } }),});return toUiSession(response.data);},diff --git a/packages/frontend/tests/harnessServer.test.ts b/packages/frontend/tests/harnessServer.test.tsindex 8409a2732..68fe444c4 100644--- a/packages/frontend/tests/harnessServer.test.ts+++ b/packages/frontend/tests/harnessServer.test.ts@@ -4,10 +4,13 @@ import { createHarnessChatServer, type HarnessAgentSpec } from '../src/harnessSeconst session = {id: 'ses_1',- agent_spec: {- model: { name: 'test/model' },- mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],- skills: [{ name: 'review' }],+ agent: {+ type: 'value',+ agent_spec: {+ model: { name: 'test/model' },+ mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],+ skills: [{ name: 'review' }],+ },},title: null,created_at: '2026-08-03T00:00:00.000Z',@@ -78,11 +81,14 @@ describe('createHarnessChatServer', () => {});const sent = sessionRequests.at(-1);- assert.ok(sent !== null && typeof sent === 'object' && 'agent_spec' in sent);- assert.deepEqual(sent.agent_spec, {- model: { name: 'test/model' },- mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],- skills: [{ name: 'review' }],+ assert.ok(sent !== null && typeof sent === 'object' && 'agent' in sent);+ assert.deepEqual(sent.agent, {+ type: 'value',+ agent_spec: {+ model: { name: 'test/model' },+ mcp_servers: [{ name: 'github', enable_tools: ['@all'] }],+ skills: [{ name: 'review' }],+ },});});diff --git a/packages/harness/src/agent-session/ITurnResourceResolver.ts b/packages/harness/src/agent-session/ITurnResourceResolver.tsindex eb3c7477e..91b1e6dfa 100644--- a/packages/harness/src/agent-session/ITurnResourceResolver.ts+++ b/packages/harness/src/agent-session/ITurnResourceResolver.ts@@ -16,6 +16,11 @@ export interface ITurnResourceResolver<TTurnCustom extends object = Record<strinreadonly logger: Logger;/** Called exactly once per run, before any other method. */createTracing(): AgentTracing;+ /**+ * Look up the live AgentSpec for a named (ref) session agent.+ * Draft (value) sessions use the stored spec and never call this.+ */+ resolveAgentSpec(input: { agent_id: string }): Promise<AgentSpec>;/*** Called exactly once per run, before any thread is built; the harness holds* the result and shares the same reference across all threads. Returndiff --git a/packages/harness/src/agent-session/SessionHandle.ts b/packages/harness/src/agent-session/SessionHandle.tsindex a0895536c..3634806f1 100644--- a/packages/harness/src/agent-session/SessionHandle.ts+++ b/packages/harness/src/agent-session/SessionHandle.ts@@ -22,9 +22,11 @@ import { builtinsFromSpec } from './builtinsFromSpec';import type { ITurnResourceResolver } from './ITurnResourceResolver';import type { SessionRecord } from './models/SessionRecord';import { MAIN_THREAD_ID, type TurnRecord } from './models/TurnRecord';+import type { AgentSpec } from './schemas/agentSpec';import type { SessionEventItem } from './schemas/events';import { EventType, type TurnDoneEvent } from './schemas/events';import type { TokenPagination } from './schemas/pagination';+import type { SessionAgent } from './schemas/session';import type { TurnInputItem } from './schemas/turn';import { CancellationReason } from './schemas/turn';import type { ISessionStore, NewThreadInit, TurnContextAppend, TurnRecordWithoutSnapshot } from './store/ISessionStore';@@ -133,8 +135,8 @@ export class SessionHandle<return this.session.tenant_id;}- get agent_spec() {- return this.session.agent_spec;+ get agent(): SessionAgent {+ return this.session.agent;}get custom(): TSessionCustom | null {@@ -189,7 +191,6 @@ export class SessionHandle<const custom = typeof input.custom === 'function' ? input.custom(previous?.custom ?? undefined) : input.custom;- const spec = this.session.agent_spec;// Dispose-on-early-failure: any resource acquired below (sandbox handle,// MCP connections) is owned by createTurn() until the TurnHandle is returned; from then// on TurnHandle.stream()'s finally owns resolver.close(). On any throw in this@@ -198,6 +199,9 @@ export class SessionHandle<// wraps getAgent/handler.init and calls gatewayStore.dispose() on failure.try {const tracing = input.resolver.createTracing();+ const agent = this.session.agent;+ const spec =+ agent.type === 'value' ? agent.agent_spec : await input.resolver.resolveAgentSpec({ agent_id: agent.agent_id });const sandbox = await input.resolver.resolveSandbox({spec,existing: previous?.snapshot.sandbox_info ?? undefined,@@ -209,6 +213,7 @@ export class SessionHandle<const agentThreads = await this.buildThreads({previous,resolver: input.resolver,+ spec,sandbox,tracing,signal: input.signal,@@ -217,6 +222,7 @@ export class SessionHandle<const createDynamicSubAgentThread = this.makeCreateDynamicSubAgentThread({resolver: input.resolver,previous,+ spec,sandbox,tracing,});@@ -352,6 +358,7 @@ export class SessionHandle<private async buildThreads(input: {previous: TurnRecord<TTurnCustom> | undefined;resolver: ITurnResourceResolver<TTurnCustom>;+ spec: AgentSpec;sandbox: Sandbox | undefined;tracing: AgentTracing;signal: AbortSignal;@@ -368,6 +375,7 @@ export class SessionHandle<data,resolver: input.resolver,previous: input.previous,+ spec: input.spec,sandbox: input.sandbox,tracing: input.tracing,signal: input.signal,@@ -382,12 +390,13 @@ export class SessionHandle<data?: AgentThreadSnapshot | undefined;resolver: ITurnResourceResolver<TTurnCustom>;previous: TurnRecord<TTurnCustom> | undefined;+ spec: AgentSpec;sandbox: Sandbox | undefined;tracing: AgentTracing;signal: AbortSignal;}): Promise<AgentThread> {const { definition, extraCapabilities } = await input.resolver.resolveAgentDefinition({- spec: this.session.agent_spec,+ spec: input.spec,thread_id: input.threadId,agent_info: input.data?.agent_info ?? undefined,previousTurn: input.previous,@@ -397,7 +406,7 @@ export class SessionHandle<const isChild = Boolean(input.data?.parent);const capabilities = [...builtinsFromSpec({- spec: this.session.agent_spec,+ spec: input.spec,definition,isChild,sandboxAvailable: Boolean(input.sandbox),@@ -426,12 +435,13 @@ export class SessionHandle<private makeCreateDynamicSubAgentThread(input: {resolver: ITurnResourceResolver<TTurnCustom>;previous: TurnRecord<TTurnCustom> | undefined;+ spec: AgentSpec;sandbox: Sandbox | undefined;tracing: AgentTracing;}): CreateDynamicSubAgentThread {return async params => {const { definition, extraCapabilities } = await input.resolver.resolveAgentDefinition({- spec: this.session.agent_spec,+ spec: input.spec,thread_id: params.threadId,agent_info: params.request,previousTurn: input.previous,@@ -456,7 +466,7 @@ export class SessionHandle<};const capabilities = [...builtinsFromSpec({- spec: this.session.agent_spec,+ spec: input.spec,definition: childDefinition,isChild: true,sandboxAvailable: Boolean(input.sandbox),diff --git a/packages/harness/src/agent-session/Sessions.ts b/packages/harness/src/agent-session/Sessions.tsindex afc129f7f..872cd09ea 100644--- a/packages/harness/src/agent-session/Sessions.ts+++ b/packages/harness/src/agent-session/Sessions.ts@@ -20,8 +20,7 @@ export class Sessions<}/**- * Creates and persists a new session. `agent_spec` is the fully hydrated- * spec; the store may internally persist a blob and/or a uri/id.+ * Creates and persists a new session with a ref or value agent binding.*/async create(input: SessionsCreateInput<TSessionCustom>): Promise<SessionHandle<TSessionCustom, TTurnCustom>> {await this.store.createSession({@@ -42,9 +41,8 @@ export class Sessions<}/**- * Returns the session with `agent_spec` hydrated (even if the store persists- * only a uri/id), or undefined if not found. Read-only: does not bump- * last_activity_timestamp_ms.+ * Returns the session as stored (ref agents are not hydrated to a value), or+ * undefined if not found. Read-only: does not bump last_activity_timestamp_ms.*/async get(input: GetSessionInput): Promise<SessionHandle<TSessionCustom, TTurnCustom> | undefined> {const record = await this.store.getSession(input);diff --git a/packages/harness/src/agent-session/TurnResourceResolver.ts b/packages/harness/src/agent-session/TurnResourceResolver.tsindex a19e08135..e9a50c6c0 100644--- a/packages/harness/src/agent-session/TurnResourceResolver.ts+++ b/packages/harness/src/agent-session/TurnResourceResolver.ts@@ -58,8 +58,8 @@ export class TurnResourceResolver<constructor(protected readonly deps: {- /** Model name → client. Called once per resolved definition. */- llm: (model: string) => ILLM;+ /** Model name → client. Called once per resolved definition; may load provider config. */+ llm: (model: string) => Promise<ILLM>;/*** MCP server name → connection details. Required to use spec.mcp_servers:* the AgentSpec carries names only (no url/headers on the wire) — the@@ -71,6 +71,11 @@ export class TurnResourceResolver<mcpConnectTimeoutMs: number;/** One sandbox type per runtime. Omit = no sandbox support. */sandboxProvider?: TurnSandboxFactory | undefined;+ /**+ * Named-agent lookup (registry id → live AgentSpec). Required when a+ * session is bound by ref; omit only if all sessions use value agents.+ */+ agent?: ((agentId: string) => Promise<AgentSpec>) | undefined;/** Forwarded to RemoteMCP / AgentThread (required by their constructors). */logger: Logger;},@@ -85,6 +90,18 @@ export class TurnResourceResolver<return NOOP_AGENT_TRACING;}+ /** Named (ref) session agent → live registry lookup via deps.agent. */+ async resolveAgentSpec(input: { agent_id: string }): Promise<AgentSpec> {+ if (this.deps.agent === undefined) {+ // Host forgot to wire deps.agent — not "agent id missing from the registry"+ // (that failure belongs in the lookup callback, e.g. HTTP 422 on the server).+ throw new Error(+ `Named agent '${input.agent_id}' cannot be resolved: no agent lookup configured on the turn resolver`,+ );+ }+ return await this.deps.agent(input.agent_id);+ }+/*** Default: creates a sandbox iff a provider is configured AND the spec wants* one; reattaches to the previous turn's VM via `existing.sandbox_id` when@@ -179,7 +196,7 @@ export class TurnResourceResolver<return {definition: {model: spec.model.name,- modelClient: this.deps.llm(spec.model.name),+ modelClient: await this.deps.llm(spec.model.name),// Sub-agents receive the delegated task as a user message; their system// prompt is SUB_AGENT_IDENTITY (added by AgentThread), not user instructions.instruction: agentInfo ? undefined : spec.instructions,diff --git a/packages/harness/src/agent-session/index.ts b/packages/harness/src/agent-session/index.tsindex 014d46b45..69b4a2461 100644--- a/packages/harness/src/agent-session/index.ts+++ b/packages/harness/src/agent-session/index.ts@@ -22,7 +22,7 @@ export {export type { TerminalTurnState, Turn, TurnInputItem, TurnMetrics, TurnState } from './schemas/turn';export { CreateSessionRequestSchema, SessionSchema, UpdateSessionRequestSchema } from './schemas/session';-export type { Session } from './schemas/session';+export type { Session, SessionAgent } from './schemas/session';export {EventType,diff --git a/packages/harness/src/agent-session/models/SessionRecord.ts b/packages/harness/src/agent-session/models/SessionRecord.tsindex 5e7134172..862376882 100644--- a/packages/harness/src/agent-session/models/SessionRecord.ts+++ b/packages/harness/src/agent-session/models/SessionRecord.ts@@ -1,17 +1,13 @@-import type { AgentSpec } from '../schemas/agentSpec';+import type { SessionAgent } from '../schemas/session';/**- * Every Session / SessionRecord exposes a hydrated `agent_spec`. Persistence- * may store the full blob or only a uri/id — an ISessionStore impl detail.- * `getSession` MUST hydrate so callers (and Session.run) never see a bare- * pointer; agent resolution stays inside the store. Callers rewrite the- * binding via the updateSession patch.+ * Session persistence record. Agent binding is a single discriminated `agent`+ * (`ref` | `value`). Named agents are not hydrated on read.*/export interface SessionRecord<TCustom extends object = Record<string, never>> {tenant_id: string;session_id: string;- /** Always hydrated on read. Source of `spec` in SessionHandle.createTurn(). */- agent_spec: AgentSpec;+ agent: SessionAgent;/*** Wire SessionSchema.title (nullable). Written via updateSession patch or* createTurn's update_session_title_if_not_exist (first write wins; caller derives).diff --git a/packages/harness/src/agent-session/schemas/session.ts b/packages/harness/src/agent-session/schemas/session.tsindex c9989c0a4..39b11149c 100644--- a/packages/harness/src/agent-session/schemas/session.ts+++ b/packages/harness/src/agent-session/schemas/session.ts@@ -1,27 +1,57 @@-/** Session product schemas. A session owns an inline AgentSpec. */+/**+ * Session product schemas. Agent binding is a single discriminated `agent`+ * field (`ref` | `value`). DB may still store agent_id / agent_spec columns.+ */import { z } from '@hono/zod-openapi';import { AgentSpecSchema } from './agentSpec';+export const SessionAgentRefSchema = z+ .object({+ type: z.literal('ref'),+ agent_id: z.string().min(1),+ })+ .strict()+ .openapi('SessionAgentRef');++export const SessionAgentValueSchema = z+ .object({+ type: z.literal('value'),+ agent_spec: AgentSpecSchema,+ })+ .strict()+ .openapi('SessionAgentValue');++/** Named registry binding or inline draft spec — exactly one arm. */+export const SessionAgentSchema = z+ .discriminatedUnion('type', [SessionAgentRefSchema, SessionAgentValueSchema])+ .openapi('SessionAgent');+export const SessionSchema = z.object({id: z.string(),- agent_spec: AgentSpecSchema,+ agent: SessionAgentSchema,title: z.string().nullable(),created_at: z.string(),updated_at: z.string(),}).openapi('Session');+/** Create binds a single agent (ref or value). */export const CreateSessionRequestSchema = z.object({- agent_spec: AgentSpecSchema,+ agent: SessionAgentSchema,})+ .strict().openapi('CreateSessionRequest');+/** Draft sessions only may replace the value agent; named (ref) sessions reject it. */export const UpdateSessionRequestSchema = z.object({- agent_spec: AgentSpecSchema.optional(),+ agent: SessionAgentValueSchema.optional(),}).openapi('UpdateSessionRequest');+export type SessionAgentRef = z.infer<typeof SessionAgentRefSchema>;+export type SessionAgentValue = z.infer<typeof SessionAgentValueSchema>;+export type SessionAgent = z.infer<typeof SessionAgentSchema>;export type Session = z.infer<typeof SessionSchema>;diff --git a/packages/harness/src/agent-session/store/ISessionStore.ts b/packages/harness/src/agent-session/store/ISessionStore.tsindex 06a7cd936..da3d5716f 100644--- a/packages/harness/src/agent-session/store/ISessionStore.ts+++ b/packages/harness/src/agent-session/store/ISessionStore.ts@@ -13,20 +13,26 @@ import type { PersistedTurnEvent, SessionEventItem } from '../schemas/events';import type { TokenPagination } from '../schemas/pagination';import type { TerminalTurnState } from '../schemas/turn';-/** Caller-supplied fields for creating a session; the store owns timestamps and tip state. */+/**+ * Caller-supplied fields for creating a session; the store owns timestamps and tip state.+ * `agent` is a discriminated ref | value binding.+ */export type CreateSessionInput<TSessionCustom extends object = Record<string, never>> = Pick<SessionRecord<TSessionCustom>,- 'tenant_id' | 'session_id' | 'agent_spec'+ 'tenant_id' | 'session_id' | 'agent'> & {custom: TSessionCustom | null;};-/** PATCH fields for an existing session; `undefined` fields are left unchanged. */+/**+ * PATCH fields for an existing session; `undefined` fields are left unchanged.+ * `agent` may be set only on draft (value) sessions, and only as a value arm.+ */export type UpdateSessionInput<TSessionCustom extends object = Record<string, never>> = Pick<SessionRecord<TSessionCustom>,'tenant_id' | 'session_id'> & {- agent_spec: SessionRecord<TSessionCustom>['agent_spec'] | undefined;+ agent: Extract<SessionRecord<TSessionCustom>['agent'], { type: 'value' }> | undefined;title: SessionRecord<TSessionCustom>['title'] | undefined;};@@ -49,6 +55,8 @@ export interface ListSessionsInput {start_timestamp: Date | undefined;/** Inclusive upper bound on `created_at` (instant). */end_timestamp: Date | undefined;+ /** When set, only sessions bound to this named agent id. */+ agent_id: string | undefined;}/** Turn row fields without assembled snapshot (create input / listTurns). */@@ -193,16 +201,15 @@ export interface ListSessionEventsInput {* subscription members. Callers authorize the parent session before using* turn-scoped operations, which rely on globally unique session_id values.* Capability maps are initialized atomically by createTurn and subsequently- * updated through patchThreadCapabilityState. Agent binding is session-scoped:- * reads always return a hydrated agent_spec even if the backend persists a uri/id.+ * updated through patchThreadCapabilityState. Agent binding is session-scoped+ * as a discriminated `agent` (ref | value); named agents are not hydrated on read.*/export interface ISessionStore<TSessionCustom extends object = Record<string, never>,TTurnCustom extends object = Record<string, never>,> {/**- * Accepts a hydrated AgentSpec. Impl may persist the blob and/or a uri/id derived- * from it — callers do not pass a bare pointer through this API.+ * Persists a discriminated `agent` (ref | value). SQL backends may flatten to columns.* `session_id` is globally unique across tenants.* Sets `last_activity_timestamp_ms` (= now) on create.*/@@ -212,16 +219,14 @@ export interface ISessionStore<deleteSession(input: DeleteSessionInput): Promise<void>;/**- * MUST return SessionRecord with `agent_spec` fully hydrated, even if the backend- * only stores a uri/id (or named-agent ref). Hydration is the store's job — harness- * and SessionHandle.createTurn never resolve agents themselves.+ * Returns the session as stored (ref agents are not hydrated to a value).* Does **not** bump `last_activity_timestamp_ms` (read path).*/getSession(input: GetSessionInput): Promise<SessionRecord<TSessionCustom> | undefined>;/*** PATCH semantics — update only the provided fields:- * - agent_spec: rewrite binding (full spec and/or backing uri/id). Next getSession hydrates.+ * - agent: replace value binding (draft sessions only; ref → invariant error).* - title: set/replace the session title.* Bumps `last_activity_timestamp_ms` (= now) in the same update.*/@@ -230,7 +235,8 @@ export interface ISessionStore</*** Paginated list of the tenant's sessions ordered by `created_at`* (`order` defaults to `desc`). `start_timestamp` / `end_timestamp` are- * inclusive instant bounds on `created_at`.+ * inclusive instant bounds on `created_at`. Optional `agent_id` filters+ * ref-bound sessions.* Does **not** bump `last_activity_timestamp_ms` (read path).*/listSessions(diff --git a/packages/harness/src/agent-session/store/InMemorySessionStore.ts b/packages/harness/src/agent-session/store/InMemorySessionStore.tsindex 6d3b71629..2cd8a592e 100644--- a/packages/harness/src/agent-session/store/InMemorySessionStore.ts+++ b/packages/harness/src/agent-session/store/InMemorySessionStore.ts@@ -165,7 +165,7 @@ export class InMemorySessionStore<const record: SessionRecord<TSessionCustom> = {tenant_id: input.tenant_id,session_id: input.session_id,- agent_spec: deepCopy(input.agent_spec),+ agent: deepCopy(input.agent),title: null,last_turn_id: null,created_at: now,@@ -202,8 +202,11 @@ export class InMemorySessionStore<if (stored?.record.tenant_id !== input.tenant_id) {throw new SessionNotFoundError(input.session_id);}- if (input.agent_spec !== undefined) {- stored.record.agent_spec = deepCopy(input.agent_spec);+ if (input.agent !== undefined) {+ if (stored.record.agent.type === 'ref') {+ throw new SessionStoreInvariantError(`Session ${input.session_id} is named; agent cannot be updated`);+ }+ stored.record.agent = deepCopy(input.agent);}if (input.title !== undefined) {stored.record.title = input.title;@@ -220,6 +223,12 @@ export class InMemorySessionStore<const records: SessionRecord<TSessionCustom>[] = [];for (const stored of this.sessions.values()) {if (stored.record.tenant_id !== input.tenant_id) continue;+ if (+ input.agent_id !== undefined &&+ (stored.record.agent.type !== 'ref' || stored.record.agent.agent_id !== input.agent_id)+ ) {+ continue;+ }const createdAt = stored.record.created_at.getTime();if (input.start_timestamp !== undefined && createdAt < input.start_timestamp.getTime()) continue;if (input.end_timestamp !== undefined && createdAt > input.end_timestamp.getTime()) continue;diff --git a/packages/harness/tests/agent-session/capabilityState.test.ts b/packages/harness/tests/agent-session/capabilityState.test.tsindex 8b75d2df9..ec8d71238 100644--- a/packages/harness/tests/agent-session/capabilityState.test.ts+++ b/packages/harness/tests/agent-session/capabilityState.test.ts@@ -62,7 +62,7 @@ describe('capability_state (tfy.plan fixture)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});const planV1: JsonValue = {@@ -133,7 +133,7 @@ describe('capability_state (tfy.plan fixture)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});const planV1: JsonValue = {todo: [{ title: 'step', description: 'do it', status: 'done' }],@@ -165,6 +165,7 @@ describe('capability_state (tfy.plan fixture)', () => {return logger;},createTracing: () => resolver.createTracing(),+ resolveAgentSpec: (input: Parameters<typeof resolver.resolveAgentSpec>[0]) => resolver.resolveAgentSpec(input),resolveSandbox: (input: Parameters<typeof resolver.resolveSandbox>[0]) => resolver.resolveSandbox(input),resolveAgentDefinition: (input: Parameters<typeof resolver.resolveAgentDefinition>[0]) =>resolver.resolveAgentDefinition(input),@@ -224,7 +225,7 @@ describe('capability_state (tfy.plan fixture)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});const turn = await session.createTurn({turn_id: mintTestTurnId(),diff --git a/packages/harness/tests/agent-session/resolveAgentSpec.test.ts b/packages/harness/tests/agent-session/resolveAgentSpec.test.tsnew file mode 100644index 000000000..03068c4a4--- /dev/null+++ b/packages/harness/tests/agent-session/resolveAgentSpec.test.ts@@ -0,0 +1,44 @@+import { EventType } from '../../src/agent-session/schemas/events';+import { Sessions } from '../../src/agent-session/Sessions';+import { InMemorySessionStore } from '../../src/agent-session/store/InMemorySessionStore';+import { TurnResourceResolver } from '../../src/agent-session/TurnResourceResolver';+import { makeAgentSpec, makeMockILLM, makeSilentLogger, makeTestResolver, mintTestTurnId } from './testHelpers';++describe('TurnResourceResolver.resolveAgentSpec', () => {+ it('fails closed when deps.agent is not wired for a named lookup', async () => {+ const resolver = new TurnResourceResolver({+ llm: () => Promise.resolve(makeMockILLM()),+ mcp: () => Promise.reject(new Error('unused')),+ mcpRequestTimeoutMs: 1_000,+ mcpConnectTimeoutMs: 1_000,+ logger: makeSilentLogger(),+ });++ await expect(resolver.resolveAgentSpec({ agent_id: 'missing' })).rejects.toThrow(/no agent lookup configured/);+ });+});++describe('SessionHandle.createTurn named resolve', () => {+ it('loads the live AgentSpec through resolver.agent for ref sessions', async () => {+ const store = new InMemorySessionStore();+ const sessions = new Sessions({ sessionStore: store });+ const session = await sessions.create({+ tenant_id: 'tenant-1',+ session_id: 's-named',+ agent: { type: 'ref', agent_id: 'agent-abc' },+ });++ const live = makeAgentSpec({ instructions: 'from-registry' });+ const agent = jest.fn().mockResolvedValue(live);+ const turn = await session.createTurn({+ turn_id: mintTestTurnId(),+ input: [{ type: EventType.USER_MESSAGE, content: 'hi' }],+ previous_turn_id: null,+ signal: new AbortController().signal,+ resolver: makeTestResolver({ agent }),+ });++ expect(turn.state.status).toBe('running');+ expect(agent).toHaveBeenCalledWith('agent-abc');+ });+});diff --git a/packages/harness/tests/agent-session/sessions.test.ts b/packages/harness/tests/agent-session/sessions.test.tsindex eaf7ff552..9de9989cc 100644--- a/packages/harness/tests/agent-session/sessions.test.ts+++ b/packages/harness/tests/agent-session/sessions.test.ts@@ -7,20 +7,26 @@ import { makeAgentSpec, makeTestResolver, mintTestTurnId } from './testHelpers';describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {const tenant = 'tenant-1';- it('create/get hydrates agent_spec', async () => {+ it('create/get persists an inline value-agent session', async () => {const store = new InMemorySessionStore<{ tag: string }>();const sessions = new Sessions<{ tag: string }>({ sessionStore: store });const created = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec({ instructions: 'hydrate-me' }),+ agent: { type: 'value', agent_spec: makeAgentSpec({ instructions: 'hydrate-me' }) },custom: { tag: 'a' },});- expect(created.agent_spec.instructions).toBe('hydrate-me');+ expect(created.agent).toEqual({+ type: 'value',+ agent_spec: expect.objectContaining({ instructions: 'hydrate-me' }),+ });expect(created.custom).toEqual({ tag: 'a' });const loaded = await sessions.get({ tenant_id: tenant, session_id: 's1' });- expect(loaded?.agent_spec.instructions).toBe('hydrate-me');+ expect(loaded?.agent).toEqual({+ type: 'value',+ agent_spec: expect.objectContaining({ instructions: 'hydrate-me' }),+ });expect(loaded?.session_id).toBe('s1');});@@ -30,7 +36,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});const turn = await session.createTurn({turn_id: mintTestTurnId(),@@ -59,7 +65,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});const created = await session.createTurn({turn_id: mintTestTurnId(),@@ -95,7 +101,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});const t1 = await session.createTurn({turn_id: mintTestTurnId(),@@ -124,7 +130,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});const first = await session.createTurn({turn_id: mintTestTurnId(),@@ -155,7 +161,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});await expect(session.createTurn({@@ -191,7 +197,7 @@ describe('Sessions / SessionHandle / TurnHandle (storage + createTurn)', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },});// Failure path: resources acquired before the throw must be released.diff --git a/packages/harness/tests/agent-session/store/storeContractSuite.ts b/packages/harness/tests/agent-session/store/storeContractSuite.tsindex ec0bf876a..d4a0cd235 100644--- a/packages/harness/tests/agent-session/store/storeContractSuite.ts+++ b/packages/harness/tests/agent-session/store/storeContractSuite.ts@@ -82,7 +82,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {await store.createSession({tenant_id: tenant,session_id: sessionId,- agent_spec: agentSpec,+ agent: { type: 'value', agent_spec: agentSpec },custom: null,});}@@ -159,18 +159,65 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {}describe('session CRUD + activity', () => {- it('createSession hydrates agent_spec and sets last_activity_timestamp_ms', async () => {+ it('createSession stores a value agent and sets last_activity_timestamp_ms', async () => {const store = createStore();const before = Date.now();await seedSession(store);const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });expect(session).toBeDefined();expect(mustGet(session).tenant_id).toBe(tenant);- expect(mustGet(session).agent_spec.model.name).toBe('test-provider/test-model');+ expect(mustGet(session).agent).toMatchObject({+ type: 'value',+ agent_spec: { model: { name: 'test-provider/test-model' } },+ });expect(mustGet(session).last_activity_timestamp_ms).toBeGreaterThanOrEqual(before);expect(mustGet(session).title).toBeNull();});+ it('persists ref agents and listSessions filters by agent_id', async () => {+ const store = createStore();+ await store.createSession({+ tenant_id: tenant,+ session_id: 'named-1',+ agent: { type: 'ref', agent_id: 'agent-abc' },+ custom: null,+ });+ await seedSession(store);++ const named = mustGet(await store.getSession({ tenant_id: tenant, session_id: 'named-1' }));+ expect(named.agent).toEqual({ type: 'ref', agent_id: 'agent-abc' });++ const filtered = await store.listSessions({+ agent_id: 'agent-abc',+ tenant_id: tenant,+ limit: 10,+ page_token: undefined,+ order: undefined,+ start_timestamp: undefined,+ end_timestamp: undefined,+ });+ expect(filtered.data.map(row => row.session_id)).toEqual(['named-1']);+ });++ it('rejects agent updates on sessions bound by agent_id', async () => {+ const store = createStore();+ await store.createSession({+ tenant_id: tenant,+ session_id: 'named-1',+ agent: { type: 'ref', agent_id: 'agent-abc' },+ custom: null,+ });++ await expect(+ store.updateSession({+ tenant_id: tenant,+ session_id: 'named-1',+ agent: { type: 'value', agent_spec: makeAgentSpec({ instructions: 'nope' }) },+ title: undefined,+ }),+ ).rejects.toBeInstanceOf(SessionStoreInvariantError);+ });+it('getSession does not bump last_activity_timestamp_ms', async () => {const store = createStore();await seedSession(store);@@ -189,11 +236,14 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {await store.updateSession({tenant_id: tenant,session_id: sessionId,- agent_spec: nextSpec,+ agent: { type: 'value', agent_spec: nextSpec },title: 'Hello',});const after = await store.getSession({ tenant_id: tenant, session_id: sessionId });- expect(mustGet(after).agent_spec.instructions).toBe('updated');+ expect(mustGet(after).agent).toMatchObject({+ type: 'value',+ agent_spec: { instructions: 'updated' },+ });expect(mustGet(after).title).toBe('Hello');expect(mustGet(after).last_activity_timestamp_ms).toBeGreaterThan(mustGet(before).last_activity_timestamp_ms);});@@ -211,7 +261,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {store.createSession({tenant_id: 'other',session_id: sessionId,- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },custom: null,}),).rejects.toBeInstanceOf(SessionStoreConflictError);@@ -225,7 +275,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {await store.createSession({tenant_id: 'other',session_id: 'other-session',- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },custom: null,});@@ -306,6 +356,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {).rejects.toBeInstanceOf(SessionNotFoundError);const listed = await store.listSessions({+ agent_id: undefined,tenant_id: tenant,limit: 10,page_token: undefined,@@ -346,7 +397,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {store.updateSession({tenant_id: tenant,session_id: sessionId,- agent_spec: undefined,+ agent: undefined,title: 'new-title',}),).rejects.toBeInstanceOf(SessionNotFoundError);@@ -404,7 +455,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {await store.createSession({tenant_id: tenant,session_id: nested,- agent_spec: makeAgentSpec(),+ agent: { type: 'value', agent_spec: makeAgentSpec() },custom: null,});await store.createTurn(makeCreateTurnInput({ sessionId: nested, turnId: 'turn-1' }));@@ -477,7 +528,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {store.updateSession({tenant_id: tenant,session_id: missingSessionId,- agent_spec: undefined,+ agent: undefined,title: 'new-title',}),).rejects.toBeInstanceOf(SessionNotFoundError);@@ -528,7 +579,12 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {describe('listSessions', () => {async function seedThreeSessions(store: ISessionStore) {for (const id of ['sa', 'sb', 'sc']) {- await store.createSession({ tenant_id: tenant, session_id: id, agent_spec: makeAgentSpec(), custom: null });+ await store.createSession({+ tenant_id: tenant,+ session_id: id,+ agent: { type: 'value', agent_spec: makeAgentSpec() },+ custom: null,+ });await new Promise(r => setTimeout(r, 2));}}@@ -536,9 +592,15 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {it('lists newest-first by default, asc on request, scoped to tenant', async () => {const store = createStore();await seedThreeSessions(store);- await store.createSession({ tenant_id: 'other', session_id: 'sx', agent_spec: makeAgentSpec(), custom: null });+ await store.createSession({+ tenant_id: 'other',+ session_id: 'sx',+ agent: { type: 'value', agent_spec: makeAgentSpec() },+ custom: null,+ });const desc = await store.listSessions({+ agent_id: undefined,tenant_id: tenant,limit: 10,page_token: undefined,@@ -549,6 +611,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {expect(desc.data.map(s => s.session_id)).toEqual(['sc', 'sb', 'sa']);const asc = await store.listSessions({+ agent_id: undefined,tenant_id: tenant,limit: 10,page_token: undefined,@@ -564,6 +627,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {await seedThreeSessions(store);const first = await store.listSessions({+ agent_id: undefined,tenant_id: tenant,limit: 2,page_token: undefined,@@ -574,6 +638,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {expect(first.data).toHaveLength(2);expect(first.pagination.next_page_token).toBeDefined();const second = await store.listSessions({+ agent_id: undefined,tenant_id: tenant,limit: 2,page_token: first.pagination.next_page_token,@@ -585,6 +650,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {expect(second.pagination.next_page_token).toBeUndefined();const all = await store.listSessions({+ agent_id: undefined,tenant_id: tenant,limit: 10,page_token: undefined,@@ -596,6 +662,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {if (!middleSession) throw new Error('expected middle session in list');const middleCreatedAt = middleSession.created_at;const bounded = await store.listSessions({+ agent_id: undefined,tenant_id: tenant,limit: 10,order: 'asc',@@ -1476,7 +1543,7 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {await store.updateSession({tenant_id: tenant,session_id: sessionId,- agent_spec: undefined,+ agent: undefined,title: jsonLooking,});await store.createTurn(@@ -1498,7 +1565,10 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {});const session = mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId }));expect(session.title).toBe(jsonLooking);- expect(session.agent_spec.instructions).toBe(jsonLooking);+ expect(session.agent).toMatchObject({+ type: 'value',+ agent_spec: { instructions: jsonLooking },+ });expect(mustGet(turn).snapshot.threads[MAIN_THREAD_ID]?.context).toEqual([{ role: 'user', content: jsonLooking }]);});@@ -1820,10 +1890,16 @@ export function runStoreContractSuite(createStore: () => ISessionStore) {it('mutating a returned session does not mutate the store', async () => {const store = createStore();await seedSession(store);- const session = await store.getSession({ tenant_id: tenant, session_id: sessionId });- mustGet(session).agent_spec.instructions = 'mutated';- const again = await store.getSession({ tenant_id: tenant, session_id: sessionId });- expect(mustGet(again).agent_spec.instructions).toBe('You are a test agent.');+ const session = mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId }));+ if (session.agent.type !== 'value') {+ throw new Error('expected value agent');+ }+ session.agent.agent_spec.instructions = 'mutated';+ const again = mustGet(await store.getSession({ tenant_id: tenant, session_id: sessionId }));+ expect(again.agent).toMatchObject({+ type: 'value',+ agent_spec: { instructions: 'You are a test agent.' },+ });});});diff --git a/packages/harness/tests/agent-session/testHelpers.ts b/packages/harness/tests/agent-session/testHelpers.tsindex 69a84d53e..4a376473e 100644--- a/packages/harness/tests/agent-session/testHelpers.ts+++ b/packages/harness/tests/agent-session/testHelpers.ts@@ -83,18 +83,21 @@ export function makeTestResolver<TTurnCustom extends object = Record<string, nevsandbox?: Sandbox;close?: () => Promise<void>;usage?: CompletionUsage;+ /** Named-agent lookup for sessions bound by agent_id. */+ agent?: ((agentId: string) => Promise<AgentSpec>) | undefined;}): ITurnResourceResolver<TTurnCustom> {const llm = makeMockILLM({create: jest.fn().mockImplementation(() => emptyLlmStream(options?.usage)),});const base = new TurnResourceResolver<TTurnCustom>({- llm: () => llm,+ llm: () => Promise.resolve(llm),mcp: name => {return Promise.reject(new Error(`unexpected mcp lookup: ${name}`));},mcpRequestTimeoutMs: 60_000,mcpConnectTimeoutMs: 5_000,logger: makeSilentLogger(),+ ...(options?.agent !== undefined ? { agent: options.agent } : {}),...(options?.sandbox? {sandboxProvider: () => {@@ -116,6 +119,7 @@ export function makeTestResolver<TTurnCustom extends object = Record<string, nevreturn base.logger;},createTracing: () => base.createTracing(),+ resolveAgentSpec: input => base.resolveAgentSpec(input),resolveSandbox: input => base.resolveSandbox(input),resolveAgentDefinition: async input => {const resolved = await base.resolveAgentDefinition(input);diff --git a/packages/harness/tests/agent-session/turnStream.test.ts b/packages/harness/tests/agent-session/turnStream.test.tsindex 454830a1c..f57f5b029 100644--- a/packages/harness/tests/agent-session/turnStream.test.ts+++ b/packages/harness/tests/agent-session/turnStream.test.ts@@ -23,11 +23,14 @@ describe('TurnHandle.stream()', () => {const session = await sessions.create({tenant_id: tenant,session_id: 's1',- agent_spec: makeAgentSpec({- config: {- sandbox: { enabled: true, file_downloads: true },- },- }),+ agent: {+ type: 'value',+ agent_spec: makeAgentSpec({+ config: {+ sandbox: { enabled: true, file_downloads: true },+ },+ }),+ },});return { store, session };}@@ -387,7 +390,7 @@ describe('TurnHandle.stream()', () => {const closeSpy = jest.spyOn(sandbox, 'close').mockResolvedValue(undefined);const logger = makeSilentLogger();const resolver = new TurnResourceResolver({- llm: () => makeMockILLM({ create: jest.fn().mockImplementation(() => emptyLlmStream()) }),+ llm: () => Promise.resolve(makeMockILLM({ create: jest.fn().mockImplementation(() => emptyLlmStream()) })),mcp: () => Promise.resolve({ url: 'http://localhost' }),mcpRequestTimeoutMs: 60_000,mcpConnectTimeoutMs: 5_000,@@ -441,7 +444,7 @@ describe('TurnResourceResolver caches', () => {expect(a).toBe(b);}})({- llm: () => makeMockILLM(),+ llm: () => Promise.resolve(makeMockILLM()),mcp: () => Promise.resolve({ url: 'http://example.invalid' }),mcpRequestTimeoutMs: 60_000,mcpConnectTimeoutMs: 5_000,@@ -457,7 +460,7 @@ describe('TurnResourceResolver caches', () => {let sandboxCreates = 0;const logger = makeSilentLogger();const resolver = new TurnResourceResolver({- llm: () => makeMockILLM({ create: jest.fn().mockImplementation(() => emptyLlmStream()) }),+ llm: () => Promise.resolve(makeMockILLM({ create: jest.fn().mockImplementation(() => emptyLlmStream()) })),mcp: () => Promise.resolve({ url: 'http://localhost' }),mcpRequestTimeoutMs: 60_000,mcpConnectTimeoutMs: 5_000,@@ -472,11 +475,14 @@ describe('TurnResourceResolver caches', () => {const session = await sessions.create({tenant_id: 't',session_id: 's',- agent_spec: makeAgentSpec({- config: {- sandbox: { enabled: true, file_downloads: true },- },- }),+ agent: {+ type: 'value',+ agent_spec: makeAgentSpec({+ config: {+ sandbox: { enabled: true, file_downloads: true },+ },+ }),+ },});const turn = await session.createTurn({turn_id: mintTestTurnId(),diff --git a/packages/sdk/.fern/metadata.json b/packages/sdk/.fern/metadata.jsonindex f750a2858..1d15a783d 100644--- a/packages/sdk/.fern/metadata.json+++ b/packages/sdk/.fern/metadata.json@@ -27,7 +27,7 @@"streamType": "web","useDefaultRequestParameterValues": true},- "originGitCommit": "7d0c801e20eea2050de9b248836faf98f5425c43",+ "originGitCommit": "7c5244e21d9e9590677f0862bc3d1cc0dd7a1bbc","originGitCommitIsDirty": true,"invokedBy": "ci","requestedVersion": "0.0.0",diff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex db6b370a3..510d218fe 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -62,7 +62,7 @@ following namespace:```typescriptimport { TrueForge } from "trueforge";-const request: TrueForge.AuthorizeMcpServersRequest = {+const request: TrueForge.AgentWriteRequest = {...};```@@ -109,9 +109,9 @@ for await (const item of response) {This SDK supports direct imports of subpackage clients, which allows JavaScript bundlers to tree-shake and include only the imported subpackage code. This results in much smaller bundle sizes.```typescript-import { AuthClient } from 'trueforge/auth';+import { AgentsClient } from 'trueforge/agents';-const client = new AuthClient({...});+const client = new AgentsClient({...});```### Additional Headersdiff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex be118f369..b56c1c05e 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -29,6 +29,17 @@},"default": "./dist/cjs/serialization/index.js"},+ "./agents": {+ "import": {+ "types": "./dist/esm/api/resources/agents/exports.d.mts",+ "default": "./dist/esm/api/resources/agents/exports.mjs"+ },+ "require": {+ "types": "./dist/cjs/api/resources/agents/exports.d.ts",+ "default": "./dist/cjs/api/resources/agents/exports.js"+ },+ "default": "./dist/cjs/api/resources/agents/exports.js"+ },"./auth": {"import": {"types": "./dist/esm/api/resources/auth/exports.d.mts",diff --git a/packages/sdk/pnpm-lock.yaml b/packages/sdk/pnpm-lock.yamlindex beaeab47c..2fb00e120 100644--- a/packages/sdk/pnpm-lock.yaml+++ b/packages/sdk/pnpm-lock.yaml@@ -718,8 +718,8 @@ packages:resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}engines: {node: '>=12'}- resolution: {integrity: sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==}+ resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==}engines: {node: ^10 || ^12 || >=14}@@ -1536,7 +1536,7 @@ snapshots:dependencies:nanoid: 3.3.17picocolors: 1.1.1@@ -1670,7 +1670,7 @@ snapshots:dependencies:lightningcss: 1.33.0picomatch: 4.0.5- postcss: 8.5.25+ postcss: 8.5.26rolldown: 1.2.3tinyglobby: 0.2.17optionalDependencies:diff --git a/packages/sdk/reference.md b/packages/sdk/reference.mdindex 677489b7b..c8dcc3fa0 100644--- a/packages/sdk/reference.md+++ b/packages/sdk/reference.md@@ -1,4 +1,266 @@# Reference+## Agents+<details><summary><code>client.agents.<a href="/src/api/resources/agents/client/Client.ts">list</a>() -> TrueForge.ListAgentsResponse</code></summary>+<dl>+<dd>++#### 📝 Description++<dl>+<dd>++<dl>+<dd>++All configured agents for the tenant.+</dd>+</dl>+</dd>+</dl>++#### 🔌 Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.agents.list();++```+</dd>+</dl>+</dd>+</dl>++#### ⚙️ Parameters++<dl>+<dd>++<dl>+<dd>++**requestOptions:** `AgentsClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>+++</dd>+</dl>+</details>++<details><summary><code>client.agents.<a href="/src/api/resources/agents/client/Client.ts">create</a>({ ...params }) -> TrueForge.CreateAgentResponse</code></summary>+<dl>+<dd>++#### 📝 Description++<dl>+<dd>++<dl>+<dd>++Creates an agent and allocates an immutable id. Fails if `name` is already taken. Name cannot be changed later.+</dd>+</dl>+</dd>+</dl>++#### 🔌 Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.agents.create({+ model: {+ name: "name"+ },+ name: "name"+});++```+</dd>+</dl>+</dd>+</dl>++#### ⚙️ Parameters++<dl>+<dd>++<dl>+<dd>++**request:** `TrueForge.AgentWriteRequest`++</dd>+</dl>++<dl>+<dd>++**requestOptions:** `AgentsClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>+++</dd>+</dl>+</details>++<details><summary><code>client.agents.<a href="/src/api/resources/agents/client/Client.ts">get</a>(agent_id) -> TrueForge.GetAgentResponse</code></summary>+<dl>+<dd>++#### 📝 Description++<dl>+<dd>++<dl>+<dd>++Fetch a configured agent by immutable id.+</dd>+</dl>+</dd>+</dl>++#### 🔌 Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.agents.get("agent_id");++```+</dd>+</dl>+</dd>+</dl>++#### ⚙️ Parameters++<dl>+<dd>++<dl>+<dd>++**agent_id:** `string` — Immutable agent identifier.++</dd>+</dl>++<dl>+<dd>++**requestOptions:** `AgentsClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>+++</dd>+</dl>+</details>++<details><summary><code>client.agents.<a href="/src/api/resources/agents/client/Client.ts">update</a>(name, { ...params }) -> TrueForge.PutAgentResponse</code></summary>+<dl>+<dd>++#### 📝 Description++<dl>+<dd>++<dl>+<dd>++Replaces the AgentSpec for an existing agent keyed by immutable `name`.+</dd>+</dl>+</dd>+</dl>++#### 🔌 Usage++<dl>+<dd>++<dl>+<dd>++```typescript+await client.agents.update("name", {+ model: {+ name: "name"+ }+});++```+</dd>+</dl>+</dd>+</dl>++#### ⚙️ Parameters++<dl>+<dd>++<dl>+<dd>++**name:** `string` — Immutable unique agent name within the tenant.++</dd>+</dl>++<dl>+<dd>++**request:** `TrueForge.UpdateAgentRequest`++</dd>+</dl>++<dl>+<dd>++**requestOptions:** `AgentsClient.RequestOptions`++</dd>+</dl>+</dd>+</dl>+++</dd>+</dl>+</details>+## Auth<details><summary><code>client.auth.<a href="/src/api/resources/auth/client/Client.ts">logout</a>() -> void</code></summary><dl>@@ -425,7 +687,7 @@ await client.models.list();<dl><dd>-List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.+List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.</dd></dl></dd>@@ -488,7 +750,7 @@ await client.sessions.list();<dl><dd>-Create a session holding an inline agent spec. Turns are executed against this spec.+Create a session with `agent` as either `{ type: "value", agent_spec }` (draft) or `{ type: "ref", agent_id }` (named). Named sessions resolve the live agent on each turn.</dd></dl></dd>@@ -504,10 +766,9 @@ Create a session holding an inline agent spec. Turns are executed against this s```typescriptawait client.sessions.create({- agentSpec: {- model: {- name: "name"- }+ agent: {+ agentId: "agent_id",+ type: "ref"}});@@ -683,7 +944,7 @@ await client.sessions.delete("session_id");<dl><dd>-Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.+Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.</dd></dl></dd>diff --git a/packages/sdk/src/Client.ts b/packages/sdk/src/Client.tsindex c8d5a9fac..dd368becc 100644--- a/packages/sdk/src/Client.ts+++ b/packages/sdk/src/Client.ts@@ -1,5 +1,6 @@// This file was auto-generated by Fern from our API Definition.+import { AgentsClient } from "./api/resources/agents/client/Client.js";import { AuthClient } from "./api/resources/auth/client/Client.js";import { McpServersClient } from "./api/resources/mcpServers/client/Client.js";import { ModelsClient } from "./api/resources/models/client/Client.js";@@ -19,6 +20,7 @@ export declare namespace TrueForge {export class TrueForge {protected readonly _options: NormalizedClientOptions<TrueForge.Options>;+ protected _agents: AgentsClient | undefined;protected _auth: AuthClient | undefined;protected _server: ServerClient | undefined;protected _mcpServers: McpServersClient | undefined;@@ -31,6 +33,10 @@ export class TrueForge {this._options = normalizeClientOptions(options);}+ public get agents(): AgentsClient {+ return (this._agents ??= new AgentsClient(this._options));+ }+public get auth(): AuthClient {return (this._auth ??= new AuthClient(this._options));}diff --git a/packages/sdk/src/api/errors/ConflictError.ts b/packages/sdk/src/api/errors/ConflictError.tsnew file mode 100644index 000000000..a035639fa--- /dev/null+++ b/packages/sdk/src/api/errors/ConflictError.ts@@ -0,0 +1,24 @@+// This file was auto-generated by Fern from our API Definition.++import type * as core from "../../core/index.js";+import * as errors from "../../errors/index.js";+import type * as TrueForge from "../index.js";++export class ConflictError extends errors.TrueForgeError {+ public declare readonly body: TrueForge.RequestErrorResponse;++ constructor(body: TrueForge.RequestErrorResponse, rawResponse?: core.RawResponse) {+ super({+ message: "ConflictError",+ statusCode: 409,+ body: body,+ rawResponse: rawResponse,+ });+ Object.setPrototypeOf(this, new.target.prototype);+ if (Error.captureStackTrace) {+ Error.captureStackTrace(this, this.constructor);+ }++ this.name = "ConflictError";+ }+}diff --git a/packages/sdk/src/api/errors/index.ts b/packages/sdk/src/api/errors/index.tsindex 5d65048fb..a527471c6 100644--- a/packages/sdk/src/api/errors/index.ts+++ b/packages/sdk/src/api/errors/index.ts@@ -1,5 +1,6 @@export * from "./BadGatewayError.js";export * from "./BadRequestError.js";+export * from "./ConflictError.js";export * from "./InternalServerError.js";export * from "./NotFoundError.js";export * from "./PreconditionFailedError.js";diff --git a/packages/sdk/src/api/resources/agents/client/Client.ts b/packages/sdk/src/api/resources/agents/client/Client.tsnew file mode 100644index 000000000..854fe273c--- /dev/null+++ b/packages/sdk/src/api/resources/agents/client/Client.ts@@ -0,0 +1,399 @@+// This file was auto-generated by Fern from our API Definition.++import type { BaseClientOptions, BaseRequestOptions } from "../../../../BaseClient.js";+import { type NormalizedClientOptions, normalizeClientOptions } from "../../../../BaseClient.js";+import { mergeHeaders } from "../../../../core/headers.js";+import * as core from "../../../../core/index.js";+import { mergeAdditionalBodyParameters } from "../../../../core/requestBody.js";+import { handleNonStatusCodeError } from "../../../../errors/handleNonStatusCodeError.js";+import * as errors from "../../../../errors/index.js";+import * as serializers from "../../../../serialization/index.js";+import * as TrueForge from "../../../index.js";++export declare namespace AgentsClient {+ export type Options = BaseClientOptions;++ export interface RequestOptions extends BaseRequestOptions {}+}++export class AgentsClient {+ protected readonly _options: NormalizedClientOptions<AgentsClient.Options>;++ constructor(options: AgentsClient.Options) {+ this._options = normalizeClientOptions(options);+ }++ /**+ * All configured agents for the tenant.+ *+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.agents.list()+ */+ public list(requestOptions?: AgentsClient.RequestOptions): core.HttpResponsePromise<TrueForge.ListAgentsResponse> {+ return core.HttpResponsePromise.fromPromise(this.__list(requestOptions));+ }++ private async __list(+ requestOptions?: AgentsClient.RequestOptions,+ ): Promise<core.WithRawResponse<TrueForge.ListAgentsResponse>> {+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/agents",+ ),+ method: "GET",+ headers: _headers,+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.ListAgentsResponse.parseOrThrow(_response.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ rawResponse: _response.rawResponse,+ };+ }++ if (_response.error.reason === "status-code") {+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }++ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/agents");+ }++ /**+ * Creates an agent and allocates an immutable id. Fails if `name` is already taken. Name cannot be changed later.+ *+ * @param {TrueForge.AgentWriteRequest} request+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link TrueForge.BadRequestError}+ * @throws {@link TrueForge.ConflictError}+ * @throws {@link TrueForge.UnprocessableEntityError}+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.agents.create({+ * model: {+ * name: "name"+ * },+ * name: "name"+ * })+ */+ public create(+ request: TrueForge.AgentWriteRequest,+ requestOptions?: AgentsClient.RequestOptions,+ ): core.HttpResponsePromise<TrueForge.CreateAgentResponse> {+ return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions));+ }++ private async __create(+ request: TrueForge.AgentWriteRequest,+ requestOptions?: AgentsClient.RequestOptions,+ ): Promise<core.WithRawResponse<TrueForge.CreateAgentResponse>> {+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ "api/v1/agents",+ ),+ method: "POST",+ headers: _headers,+ contentType: "application/json",+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ requestType: "json",+ body: mergeAdditionalBodyParameters(+ serializers.AgentWriteRequest.jsonOrThrow(request, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ omitUndefined: true,+ }),+ requestOptions?.additionalBodyParameters,+ ),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.CreateAgentResponse.parseOrThrow(_response.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ rawResponse: _response.rawResponse,+ };+ }++ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 400:+ throw new TrueForge.BadRequestError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 409:+ throw new TrueForge.ConflictError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 422:+ throw new TrueForge.UnprocessableEntityError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ default:+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }++ return handleNonStatusCodeError(_response.error, _response.rawResponse, "POST", "/api/v1/agents");+ }++ /**+ * Fetch a configured agent by immutable id.+ *+ * @param {string} agent_id - Immutable agent identifier.+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link TrueForge.NotFoundError}+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.agents.get("agent_id")+ */+ public get(+ agent_id: string,+ requestOptions?: AgentsClient.RequestOptions,+ ): core.HttpResponsePromise<TrueForge.GetAgentResponse> {+ return core.HttpResponsePromise.fromPromise(this.__get(agent_id, requestOptions));+ }++ private async __get(+ agent_id: string,+ requestOptions?: AgentsClient.RequestOptions,+ ): Promise<core.WithRawResponse<TrueForge.GetAgentResponse>> {+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ `api/v1/agents/${core.url.encodePathParam(agent_id)}`,+ ),+ method: "GET",+ headers: _headers,+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.GetAgentResponse.parseOrThrow(_response.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ rawResponse: _response.rawResponse,+ };+ }++ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 404:+ throw new TrueForge.NotFoundError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ default:+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }++ return handleNonStatusCodeError(_response.error, _response.rawResponse, "GET", "/api/v1/agents/{agent_id}");+ }++ /**+ * Replaces the AgentSpec for an existing agent keyed by immutable `name`.+ *+ * @param {string} name - Immutable unique agent name within the tenant.+ * @param {TrueForge.UpdateAgentRequest} request+ * @param {AgentsClient.RequestOptions} requestOptions - Request-specific configuration.+ *+ * @throws {@link TrueForge.BadRequestError}+ * @throws {@link TrueForge.NotFoundError}+ * @throws {@link TrueForge.UnprocessableEntityError}+ * @throws {@link errors.TrueForgeError}+ * @throws {@link errors.TrueForgeTimeoutError}+ *+ * @example+ * await client.agents.update("name", {+ * model: {+ * name: "name"+ * }+ * })+ */+ public update(+ name: string,+ request: TrueForge.UpdateAgentRequest,+ requestOptions?: AgentsClient.RequestOptions,+ ): core.HttpResponsePromise<TrueForge.PutAgentResponse> {+ return core.HttpResponsePromise.fromPromise(this.__update(name, request, requestOptions));+ }++ private async __update(+ name: string,+ request: TrueForge.UpdateAgentRequest,+ requestOptions?: AgentsClient.RequestOptions,+ ): Promise<core.WithRawResponse<TrueForge.PutAgentResponse>> {+ const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers, requestOptions?.headers);+ const _response = await (this._options.fetcher ?? core.fetcher)({+ url: core.url.join(+ (await core.Supplier.get(this._options.baseUrl)) ??+ (await core.Supplier.get(this._options.environment)),+ `api/v1/agents/${core.url.encodePathParam(name)}`,+ ),+ method: "PUT",+ headers: _headers,+ contentType: "application/json",+ queryString: core.url.queryBuilder().mergeAdditional(requestOptions?.queryParams).build(),+ requestType: "json",+ body: mergeAdditionalBodyParameters(+ serializers.UpdateAgentRequest.jsonOrThrow(request, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ omitUndefined: true,+ }),+ requestOptions?.additionalBodyParameters,+ ),+ timeoutMs: (requestOptions?.timeoutInSeconds ?? this._options?.timeoutInSeconds ?? 60) * 1000,+ maxRetries: requestOptions?.maxRetries ?? this._options?.maxRetries,+ abortSignal: requestOptions?.abortSignal,+ fetchFn: this._options?.fetch,+ logging: this._options.logging,+ });+ if (_response.ok) {+ return {+ data: serializers.PutAgentResponse.parseOrThrow(_response.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ rawResponse: _response.rawResponse,+ };+ }++ if (_response.error.reason === "status-code") {+ switch (_response.error.statusCode) {+ case 400:+ throw new TrueForge.BadRequestError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 404:+ throw new TrueForge.NotFoundError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ case 422:+ throw new TrueForge.UnprocessableEntityError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );+ default:+ throw new errors.TrueForgeError({+ statusCode: _response.error.statusCode,+ body: _response.error.body,+ rawResponse: _response.rawResponse,+ });+ }+ }++ return handleNonStatusCodeError(_response.error, _response.rawResponse, "PUT", "/api/v1/agents/{name}");+ }+}diff --git a/packages/sdk/src/api/resources/agents/client/index.ts b/packages/sdk/src/api/resources/agents/client/index.tsnew file mode 100644index 000000000..195f9aa8a--- /dev/null+++ b/packages/sdk/src/api/resources/agents/client/index.ts@@ -0,0 +1 @@+export * from "./requests/index.js";diff --git a/packages/sdk/src/api/resources/agents/client/requests/AgentWriteRequest.ts b/packages/sdk/src/api/resources/agents/client/requests/AgentWriteRequest.tsnew file mode 100644index 000000000..5a1c4cdef--- /dev/null+++ b/packages/sdk/src/api/resources/agents/client/requests/AgentWriteRequest.ts@@ -0,0 +1,16 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../../../index.js";++/**+ * @example+ * {+ * model: {+ * name: "name"+ * },+ * name: "name"+ * }+ */+export interface AgentWriteRequest extends TrueForge.AgentSpec {+ name: TrueForge.ResourceName;+}diff --git a/packages/sdk/src/api/resources/agents/client/requests/UpdateAgentRequest.ts b/packages/sdk/src/api/resources/agents/client/requests/UpdateAgentRequest.tsnew file mode 100644index 000000000..3e3e1408c--- /dev/null+++ b/packages/sdk/src/api/resources/agents/client/requests/UpdateAgentRequest.ts@@ -0,0 +1,22 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../../../index.js";++/**+ * @example+ * {+ * model: {+ * name: "name"+ * }+ * }+ */+export interface UpdateAgentRequest {+ config?: TrueForge.RuntimeConfig;+ instructions?: string;+ mcpServers?: TrueForge.McpServer[];+ messages?: TrueForge.AgentSpecUserMessage[];+ model: TrueForge.AgentSpecModel;+ responseFormat?: TrueForge.ResponseFormat;+ skills?: TrueForge.SkillNameRef[];+ variables?: Record<string, string>;+}diff --git a/packages/sdk/src/api/resources/agents/client/requests/index.ts b/packages/sdk/src/api/resources/agents/client/requests/index.tsnew file mode 100644index 000000000..1f894cb37--- /dev/null+++ b/packages/sdk/src/api/resources/agents/client/requests/index.ts@@ -0,0 +1,2 @@+export type { AgentWriteRequest } from "./AgentWriteRequest.js";+export type { UpdateAgentRequest } from "./UpdateAgentRequest.js";diff --git a/packages/sdk/src/api/resources/agents/exports.ts b/packages/sdk/src/api/resources/agents/exports.tsnew file mode 100644index 000000000..b468a638b--- /dev/null+++ b/packages/sdk/src/api/resources/agents/exports.ts@@ -0,0 +1,4 @@+// This file was auto-generated by Fern from our API Definition.++export { AgentsClient } from "./client/Client.js";+export * from "./client/index.js";diff --git a/packages/sdk/src/api/resources/agents/index.ts b/packages/sdk/src/api/resources/agents/index.tsnew file mode 100644index 000000000..914b8c3c7--- /dev/null+++ b/packages/sdk/src/api/resources/agents/index.ts@@ -0,0 +1 @@+export * from "./client/index.js";diff --git a/packages/sdk/src/api/resources/index.ts b/packages/sdk/src/api/resources/index.tsindex f708829ee..32797cdef 100644--- a/packages/sdk/src/api/resources/index.ts+++ b/packages/sdk/src/api/resources/index.ts@@ -1,3 +1,5 @@+export * from "./agents/client/requests/index.js";+export * as agents from "./agents/index.js";export * as auth from "./auth/index.js";export * from "./mcpServers/client/requests/index.js";export * as mcpServers from "./mcpServers/index.js";diff --git a/packages/sdk/src/api/resources/sessions/client/Client.ts b/packages/sdk/src/api/resources/sessions/client/Client.tsindex 9d6d6ca52..ef54289a5 100644--- a/packages/sdk/src/api/resources/sessions/client/Client.ts+++ b/packages/sdk/src/api/resources/sessions/client/Client.ts@@ -24,7 +24,7 @@ export class SessionsClient {}/**- * List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.+ * List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.** @param {TrueForge.ListSessionsRequest} request* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.@@ -44,7 +44,7 @@ export class SessionsClient {async (request: TrueForge.ListSessionsRequest,): Promise<core.WithRawResponse<TrueForge.ListSessionsResponse>> => {- const { limit = 10, order, pageToken, startTimestamp, endTimestamp } = request;+ const { limit = 10, order, pageToken, startTimestamp, endTimestamp, agentId } = request;const _queryParams: Record<string, unknown> = {limit,order:@@ -59,6 +59,7 @@ export class SessionsClient {page_token: pageToken,start_timestamp: startTimestamp != null ? startTimestamp?.toISOString() : undefined,end_timestamp: endTimestamp != null ? endTimestamp?.toISOString() : undefined,+ agent_id: agentId,};const _headers: core.Fetcher.Args["headers"] = mergeHeaders(this._options?.headers,@@ -134,22 +135,22 @@ export class SessionsClient {}/**- * Create a session holding an inline agent spec. Turns are executed against this spec.+ * Create a session with `agent` as either `{ type: "value", agent_spec }` (draft) or `{ type: "ref", agent_id }` (named). Named sessions resolve the live agent on each turn.** @param {TrueForge.CreateSessionRequest} request* @param {SessionsClient.RequestOptions} requestOptions - Request-specific configuration.** @throws {@link TrueForge.BadRequestError}+ * @throws {@link TrueForge.NotFoundError}* @throws {@link TrueForge.UnprocessableEntityError}* @throws {@link errors.TrueForgeError}* @throws {@link errors.TrueForgeTimeoutError}** @example* await client.sessions.create({- * agentSpec: {- * model: {- * name: "name"- * }+ * agent: {+ * agentId: "agent_id",+ * type: "ref"* }* })*/@@ -217,6 +218,17 @@ export class SessionsClient {}),_response.rawResponse,);+ case 404:+ throw new TrueForge.NotFoundError(+ serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {+ unrecognizedObjectKeys: "passthrough",+ allowUnrecognizedUnionMembers: true,+ allowUnrecognizedEnumValues: true,+ skipValidation: true,+ breadcrumbsPrefix: ["response"],+ }),+ _response.rawResponse,+ );case 422:throw new TrueForge.UnprocessableEntityError(serializers.RequestErrorResponse.parseOrThrow(_response.error.body, {@@ -375,7 +387,7 @@ export class SessionsClient {}/**- * Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.+ * Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.** @param {string} session_id - Session identifier.* @param {TrueForge.UpdateSessionRequest} requestdiff --git a/packages/sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.tsindex f0d6c2904..e104606e2 100644--- a/packages/sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts+++ b/packages/sdk/src/api/resources/sessions/client/requests/CreateSessionRequest.ts@@ -5,13 +5,12 @@ import type * as TrueForge from "../../../../index.js";/*** @example* {- * agentSpec: {- * model: {- * name: "name"- * }+ * agent: {+ * agentId: "agent_id",+ * type: "ref"* }* }*/export interface CreateSessionRequest {- agentSpec: TrueForge.AgentSpec;+ agent: TrueForge.SessionAgent;}diff --git a/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.tsindex 3a31c7e5d..c839e37f2 100644--- a/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts+++ b/packages/sdk/src/api/resources/sessions/client/requests/ListSessionsRequest.ts@@ -17,4 +17,6 @@ export interface ListSessionsRequest {startTimestamp?: Date;/** Inclusive upper bound on `created_at` (ISO-8601 / RFC 3339). */endTimestamp?: Date;+ /** When set, only sessions bound to this agent id are returned. */+ agentId?: string;}diff --git a/packages/sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts b/packages/sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.tsindex c5d8bedcd..b026e8030 100644--- a/packages/sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts+++ b/packages/sdk/src/api/resources/sessions/client/requests/UpdateSessionRequest.ts@@ -7,5 +7,5 @@ import type * as TrueForge from "../../../../index.js";* {}*/export interface UpdateSessionRequest {- agentSpec?: TrueForge.AgentSpec;+ agent?: TrueForge.SessionAgentValue;}diff --git a/packages/sdk/src/api/types/Agent.ts b/packages/sdk/src/api/types/Agent.tsnew file mode 100644index 000000000..43c9ef2c1--- /dev/null+++ b/packages/sdk/src/api/types/Agent.ts@@ -0,0 +1,13 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++/**+ * Agent Definition+ */+export interface Agent extends TrueForge.AgentSpec {+ /** Immutable server-generated agent identifier. */+ id: string;+ /** Immutable unique agent name within the tenant. */+ name: string;+}diff --git a/packages/sdk/src/api/types/CreateAgentResponse.ts b/packages/sdk/src/api/types/CreateAgentResponse.tsnew file mode 100644index 000000000..726309082--- /dev/null+++ b/packages/sdk/src/api/types/CreateAgentResponse.ts@@ -0,0 +1,7 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface CreateAgentResponse {+ data: TrueForge.Agent;+}diff --git a/packages/sdk/src/api/types/GetAgentResponse.ts b/packages/sdk/src/api/types/GetAgentResponse.tsnew file mode 100644index 000000000..c8273a7d5--- /dev/null+++ b/packages/sdk/src/api/types/GetAgentResponse.ts@@ -0,0 +1,7 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface GetAgentResponse {+ data: TrueForge.Agent;+}diff --git a/packages/sdk/src/api/types/ListAgentsResponse.ts b/packages/sdk/src/api/types/ListAgentsResponse.tsnew file mode 100644index 000000000..31819069c--- /dev/null+++ b/packages/sdk/src/api/types/ListAgentsResponse.ts@@ -0,0 +1,7 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface ListAgentsResponse {+ data: TrueForge.Agent[];+}diff --git a/packages/sdk/src/api/types/PutAgentResponse.ts b/packages/sdk/src/api/types/PutAgentResponse.tsnew file mode 100644index 000000000..4f7912db4--- /dev/null+++ b/packages/sdk/src/api/types/PutAgentResponse.ts@@ -0,0 +1,7 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface PutAgentResponse {+ data: TrueForge.Agent;+}diff --git a/packages/sdk/src/api/types/Session.ts b/packages/sdk/src/api/types/Session.tsindex 01e518cc6..9139df9ab 100644--- a/packages/sdk/src/api/types/Session.ts+++ b/packages/sdk/src/api/types/Session.ts@@ -3,7 +3,7 @@import type * as TrueForge from "../index.js";export interface Session {- agentSpec: TrueForge.AgentSpec;+ agent: TrueForge.SessionAgent;createdAt: string;id: string;title: string | null;diff --git a/packages/sdk/src/api/types/SessionAgent.ts b/packages/sdk/src/api/types/SessionAgent.tsnew file mode 100644index 000000000..c6e454add--- /dev/null+++ b/packages/sdk/src/api/types/SessionAgent.ts@@ -0,0 +1,5 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export type SessionAgent = TrueForge.SessionAgentRef | TrueForge.SessionAgentValue;diff --git a/packages/sdk/src/api/types/SessionAgentRef.ts b/packages/sdk/src/api/types/SessionAgentRef.tsnew file mode 100644index 000000000..f140732b3--- /dev/null+++ b/packages/sdk/src/api/types/SessionAgentRef.ts@@ -0,0 +1,6 @@+// This file was auto-generated by Fern from our API Definition.++export interface SessionAgentRef {+ agentId: string;+ type: "ref";+}diff --git a/packages/sdk/src/api/types/SessionAgentValue.ts b/packages/sdk/src/api/types/SessionAgentValue.tsnew file mode 100644index 000000000..c3e9caefa--- /dev/null+++ b/packages/sdk/src/api/types/SessionAgentValue.ts@@ -0,0 +1,8 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../index.js";++export interface SessionAgentValue {+ agentSpec: TrueForge.AgentSpec;+ type: "value";+}diff --git a/packages/sdk/src/api/types/index.ts b/packages/sdk/src/api/types/index.tsindex fcbbb3349..1763a2c2d 100644--- a/packages/sdk/src/api/types/index.ts+++ b/packages/sdk/src/api/types/index.ts@@ -1,4 +1,5 @@export * from "./ActionRequiredEvent.js";+export * from "./Agent.js";export * from "./AgentInfo.js";export * from "./AgentParent.js";export * from "./AgentSpec.js";@@ -30,6 +31,7 @@ export * from "./ConfiguredMcpServer.js";export * from "./ConfiguredMcpServerAuth.js";export * from "./ContextManagementConfig.js";export * from "./ContextManagementConfigCompaction.js";+export * from "./CreateAgentResponse.js";export * from "./DaytonaSandboxProvider.js";export * from "./DaytonaSandboxProviderAuth.js";export * from "./DynamicSubAgentsConfig.js";@@ -37,6 +39,7 @@ export * from "./ExtendedChunkDeltaToolCall.js";export * from "./FileContent.js";export * from "./FinishReason.js";export * from "./GenerativeUiConfig.js";+export * from "./GetAgentResponse.js";export * from "./GetCapabilitiesResponse.js";export * from "./GetCapabilitiesResponseData.js";export * from "./GetCapabilitiesResponseDataSandbox.js";@@ -50,6 +53,7 @@ export * from "./GetSessionResponse.js";export * from "./GetSkillCatalogResponse.js";export * from "./GetTurnResponse.js";export * from "./LargeToolResponseConfig.js";+export * from "./ListAgentsResponse.js";export * from "./ListAvailableMcpServersResponse.js";export * from "./ListAvailableSkillsResponse.js";export * from "./ListConfiguredSkillsResponse.js";@@ -93,6 +97,7 @@ export * from "./ModelProperties.js";export * from "./ModelProvider.js";export * from "./ModelProviderAuth.js";export * from "./PreviousTurnIdInput.js";+export * from "./PutAgentResponse.js";export * from "./PutMcpServerResponse.js";export * from "./PutModelProviderResponse.js";export * from "./PutSandboxProviderResponse.js";@@ -114,6 +119,9 @@ export * from "./SandboxNetworkPolicyAuthInjectItem.js";export * from "./SandboxNetworkPolicyAuthInjectItemAuthData.js";export * from "./SandboxNetworkPolicyAuthInjectItemMatch.js";export * from "./Session.js";+export * from "./SessionAgent.js";+export * from "./SessionAgentRef.js";+export * from "./SessionAgentValue.js";export * from "./SessionEvent.js";export * from "./SessionEventItem.js";export * from "./SkillManifest.js";diff --git a/packages/sdk/src/serialization/resources/agents/client/index.ts b/packages/sdk/src/serialization/resources/agents/client/index.tsnew file mode 100644index 000000000..195f9aa8a--- /dev/null+++ b/packages/sdk/src/serialization/resources/agents/client/index.ts@@ -0,0 +1 @@+export * from "./requests/index.js";diff --git a/packages/sdk/src/serialization/resources/agents/client/requests/AgentWriteRequest.ts b/packages/sdk/src/serialization/resources/agents/client/requests/AgentWriteRequest.tsnew file mode 100644index 000000000..38b47a79a--- /dev/null+++ b/packages/sdk/src/serialization/resources/agents/client/requests/AgentWriteRequest.ts@@ -0,0 +1,22 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../../../../api/index.js";+import * as core from "../../../../../core/index.js";+import type * as serializers from "../../../../index.js";+import { AgentSpec } from "../../../../types/AgentSpec.js";+import { ResourceName } from "../../../../types/ResourceName.js";++export const AgentWriteRequest: core.serialization.Schema<+ serializers.AgentWriteRequest.Raw,+ TrueForge.AgentWriteRequest+> = core.serialization+ .object({+ name: ResourceName,+ })+ .extend(AgentSpec);++export declare namespace AgentWriteRequest {+ export interface Raw extends AgentSpec.Raw {+ name: ResourceName.Raw;+ }+}diff --git a/packages/sdk/src/serialization/resources/agents/client/requests/UpdateAgentRequest.ts b/packages/sdk/src/serialization/resources/agents/client/requests/UpdateAgentRequest.tsnew file mode 100644index 000000000..b765c1076--- /dev/null+++ b/packages/sdk/src/serialization/resources/agents/client/requests/UpdateAgentRequest.ts@@ -0,0 +1,38 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../../../../api/index.js";+import * as core from "../../../../../core/index.js";+import type * as serializers from "../../../../index.js";+import { AgentSpecModel } from "../../../../types/AgentSpecModel.js";+import { AgentSpecUserMessage } from "../../../../types/AgentSpecUserMessage.js";+import { McpServer } from "../../../../types/McpServer.js";+import { ResponseFormat } from "../../../../types/ResponseFormat.js";+import { RuntimeConfig } from "../../../../types/RuntimeConfig.js";+import { SkillNameRef } from "../../../../types/SkillNameRef.js";++export const UpdateAgentRequest: core.serialization.Schema<+ serializers.UpdateAgentRequest.Raw,+ TrueForge.UpdateAgentRequest+> = core.serialization.object({+ config: RuntimeConfig.optional(),+ instructions: core.serialization.string().optional(),+ mcpServers: core.serialization.property("mcp_servers", core.serialization.list(McpServer).optional()),+ messages: core.serialization.list(AgentSpecUserMessage).optional(),+ model: AgentSpecModel,+ responseFormat: core.serialization.property("response_format", ResponseFormat.optional()),+ skills: core.serialization.list(SkillNameRef).optional(),+ variables: core.serialization.record(core.serialization.string(), core.serialization.string()).optional(),+});++export declare namespace UpdateAgentRequest {+ export interface Raw {+ config?: RuntimeConfig.Raw | null;+ instructions?: string | null;+ mcp_servers?: McpServer.Raw[] | null;+ messages?: AgentSpecUserMessage.Raw[] | null;+ model: AgentSpecModel.Raw;+ response_format?: ResponseFormat.Raw | null;+ skills?: SkillNameRef.Raw[] | null;+ variables?: Record<string, string> | null;+ }+}diff --git a/packages/sdk/src/serialization/resources/agents/client/requests/index.ts b/packages/sdk/src/serialization/resources/agents/client/requests/index.tsnew file mode 100644index 000000000..548a9fc6f--- /dev/null+++ b/packages/sdk/src/serialization/resources/agents/client/requests/index.ts@@ -0,0 +1,2 @@+export { AgentWriteRequest } from "./AgentWriteRequest.js";+export { UpdateAgentRequest } from "./UpdateAgentRequest.js";diff --git a/packages/sdk/src/serialization/resources/agents/index.ts b/packages/sdk/src/serialization/resources/agents/index.tsnew file mode 100644index 000000000..914b8c3c7--- /dev/null+++ b/packages/sdk/src/serialization/resources/agents/index.ts@@ -0,0 +1 @@+export * from "./client/index.js";diff --git a/packages/sdk/src/serialization/resources/index.ts b/packages/sdk/src/serialization/resources/index.tsindex c639ea5e0..843403a46 100644--- a/packages/sdk/src/serialization/resources/index.ts+++ b/packages/sdk/src/serialization/resources/index.ts@@ -1,3 +1,5 @@+export * from "./agents/client/requests/index.js";+export * as agents from "./agents/index.js";export * from "./sessions/client/requests/index.js";export * as sessions from "./sessions/index.js";export * as settings from "./settings/index.js";diff --git a/packages/sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts b/packages/sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.tsindex 892c2f328..362ccc2ba 100644--- a/packages/sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts+++ b/packages/sdk/src/serialization/resources/sessions/client/requests/CreateSessionRequest.ts@@ -3,17 +3,17 @@import type * as TrueForge from "../../../../../api/index.js";import * as core from "../../../../../core/index.js";import type * as serializers from "../../../../index.js";-import { AgentSpec } from "../../../../types/AgentSpec.js";+import { SessionAgent } from "../../../../types/SessionAgent.js";export const CreateSessionRequest: core.serialization.Schema<serializers.CreateSessionRequest.Raw,TrueForge.CreateSessionRequest> = core.serialization.object({- agentSpec: core.serialization.property("agent_spec", AgentSpec),+ agent: SessionAgent,});export declare namespace CreateSessionRequest {export interface Raw {- agent_spec: AgentSpec.Raw;+ agent: SessionAgent.Raw;}}diff --git a/packages/sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts b/packages/sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.tsindex 9a98d5a7d..cf3169919 100644--- a/packages/sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts+++ b/packages/sdk/src/serialization/resources/sessions/client/requests/UpdateSessionRequest.ts@@ -3,17 +3,17 @@import type * as TrueForge from "../../../../../api/index.js";import * as core from "../../../../../core/index.js";import type * as serializers from "../../../../index.js";-import { AgentSpec } from "../../../../types/AgentSpec.js";+import { SessionAgentValue } from "../../../../types/SessionAgentValue.js";export const UpdateSessionRequest: core.serialization.Schema<serializers.UpdateSessionRequest.Raw,TrueForge.UpdateSessionRequest> = core.serialization.object({- agentSpec: core.serialization.property("agent_spec", AgentSpec.optional()),+ agent: SessionAgentValue.optional(),});export declare namespace UpdateSessionRequest {export interface Raw {- agent_spec?: AgentSpec.Raw | null;+ agent?: SessionAgentValue.Raw | null;}}diff --git a/packages/sdk/src/serialization/types/Agent.ts b/packages/sdk/src/serialization/types/Agent.tsnew file mode 100644index 000000000..52f8cc7e8--- /dev/null+++ b/packages/sdk/src/serialization/types/Agent.ts@@ -0,0 +1,20 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { AgentSpec } from "./AgentSpec.js";++export const Agent: core.serialization.ObjectSchema<serializers.Agent.Raw, TrueForge.Agent> = core.serialization+ .object({+ id: core.serialization.string(),+ name: core.serialization.string(),+ })+ .extend(AgentSpec);++export declare namespace Agent {+ export interface Raw extends AgentSpec.Raw {+ id: string;+ name: string;+ }+}diff --git a/packages/sdk/src/serialization/types/CreateAgentResponse.ts b/packages/sdk/src/serialization/types/CreateAgentResponse.tsnew file mode 100644index 000000000..633d4cb5b--- /dev/null+++ b/packages/sdk/src/serialization/types/CreateAgentResponse.ts@@ -0,0 +1,19 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { Agent } from "./Agent.js";++export const CreateAgentResponse: core.serialization.ObjectSchema<+ serializers.CreateAgentResponse.Raw,+ TrueForge.CreateAgentResponse+> = core.serialization.object({+ data: Agent,+});++export declare namespace CreateAgentResponse {+ export interface Raw {+ data: Agent.Raw;+ }+}diff --git a/packages/sdk/src/serialization/types/GetAgentResponse.ts b/packages/sdk/src/serialization/types/GetAgentResponse.tsnew file mode 100644index 000000000..b1bff3987--- /dev/null+++ b/packages/sdk/src/serialization/types/GetAgentResponse.ts@@ -0,0 +1,19 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { Agent } from "./Agent.js";++export const GetAgentResponse: core.serialization.ObjectSchema<+ serializers.GetAgentResponse.Raw,+ TrueForge.GetAgentResponse+> = core.serialization.object({+ data: Agent,+});++export declare namespace GetAgentResponse {+ export interface Raw {+ data: Agent.Raw;+ }+}diff --git a/packages/sdk/src/serialization/types/ListAgentsResponse.ts b/packages/sdk/src/serialization/types/ListAgentsResponse.tsnew file mode 100644index 000000000..15018a96a--- /dev/null+++ b/packages/sdk/src/serialization/types/ListAgentsResponse.ts@@ -0,0 +1,19 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { Agent } from "./Agent.js";++export const ListAgentsResponse: core.serialization.ObjectSchema<+ serializers.ListAgentsResponse.Raw,+ TrueForge.ListAgentsResponse+> = core.serialization.object({+ data: core.serialization.list(Agent),+});++export declare namespace ListAgentsResponse {+ export interface Raw {+ data: Agent.Raw[];+ }+}diff --git a/packages/sdk/src/serialization/types/PutAgentResponse.ts b/packages/sdk/src/serialization/types/PutAgentResponse.tsnew file mode 100644index 000000000..4465fc9b6--- /dev/null+++ b/packages/sdk/src/serialization/types/PutAgentResponse.ts@@ -0,0 +1,19 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { Agent } from "./Agent.js";++export const PutAgentResponse: core.serialization.ObjectSchema<+ serializers.PutAgentResponse.Raw,+ TrueForge.PutAgentResponse+> = core.serialization.object({+ data: Agent,+});++export declare namespace PutAgentResponse {+ export interface Raw {+ data: Agent.Raw;+ }+}diff --git a/packages/sdk/src/serialization/types/Session.ts b/packages/sdk/src/serialization/types/Session.tsindex a2898c358..30759710a 100644--- a/packages/sdk/src/serialization/types/Session.ts+++ b/packages/sdk/src/serialization/types/Session.ts@@ -3,11 +3,11 @@import type * as TrueForge from "../../api/index.js";import * as core from "../../core/index.js";import type * as serializers from "../index.js";-import { AgentSpec } from "./AgentSpec.js";+import { SessionAgent } from "./SessionAgent.js";export const Session: core.serialization.ObjectSchema<serializers.Session.Raw, TrueForge.Session> =core.serialization.object({- agentSpec: core.serialization.property("agent_spec", AgentSpec),+ agent: SessionAgent,createdAt: core.serialization.property("created_at", core.serialization.string()),id: core.serialization.string(),title: core.serialization.string().nullable(),@@ -16,7 +16,7 @@ export const Session: core.serialization.ObjectSchema<serializers.Session.Raw, Texport declare namespace Session {export interface Raw {- agent_spec: AgentSpec.Raw;+ agent: SessionAgent.Raw;created_at: string;id: string;title?: string | null;diff --git a/packages/sdk/src/serialization/types/SessionAgent.ts b/packages/sdk/src/serialization/types/SessionAgent.tsnew file mode 100644index 000000000..299c20015--- /dev/null+++ b/packages/sdk/src/serialization/types/SessionAgent.ts@@ -0,0 +1,14 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { SessionAgentRef } from "./SessionAgentRef.js";+import { SessionAgentValue } from "./SessionAgentValue.js";++export const SessionAgent: core.serialization.Schema<serializers.SessionAgent.Raw, TrueForge.SessionAgent> =+ core.serialization.undiscriminatedUnion([SessionAgentRef, SessionAgentValue]);++export declare namespace SessionAgent {+ export type Raw = SessionAgentRef.Raw | SessionAgentValue.Raw;+}diff --git a/packages/sdk/src/serialization/types/SessionAgentRef.ts b/packages/sdk/src/serialization/types/SessionAgentRef.tsnew file mode 100644index 000000000..6544c055c--- /dev/null+++ b/packages/sdk/src/serialization/types/SessionAgentRef.ts@@ -0,0 +1,20 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";++export const SessionAgentRef: core.serialization.ObjectSchema<+ serializers.SessionAgentRef.Raw,+ TrueForge.SessionAgentRef+> = core.serialization.object({+ agentId: core.serialization.property("agent_id", core.serialization.string()),+ type: core.serialization.stringLiteral("ref"),+});++export declare namespace SessionAgentRef {+ export interface Raw {+ agent_id: string;+ type: "ref";+ }+}diff --git a/packages/sdk/src/serialization/types/SessionAgentValue.ts b/packages/sdk/src/serialization/types/SessionAgentValue.tsnew file mode 100644index 000000000..eae372748--- /dev/null+++ b/packages/sdk/src/serialization/types/SessionAgentValue.ts@@ -0,0 +1,21 @@+// This file was auto-generated by Fern from our API Definition.++import type * as TrueForge from "../../api/index.js";+import * as core from "../../core/index.js";+import type * as serializers from "../index.js";+import { AgentSpec } from "./AgentSpec.js";++export const SessionAgentValue: core.serialization.ObjectSchema<+ serializers.SessionAgentValue.Raw,+ TrueForge.SessionAgentValue+> = core.serialization.object({+ agentSpec: core.serialization.property("agent_spec", AgentSpec),+ type: core.serialization.stringLiteral("value"),+});++export declare namespace SessionAgentValue {+ export interface Raw {+ agent_spec: AgentSpec.Raw;+ type: "value";+ }+}diff --git a/packages/sdk/src/serialization/types/index.ts b/packages/sdk/src/serialization/types/index.tsindex fcbbb3349..1763a2c2d 100644--- a/packages/sdk/src/serialization/types/index.ts+++ b/packages/sdk/src/serialization/types/index.ts@@ -1,4 +1,5 @@export * from "./ActionRequiredEvent.js";+export * from "./Agent.js";export * from "./AgentInfo.js";export * from "./AgentParent.js";export * from "./AgentSpec.js";@@ -30,6 +31,7 @@ export * from "./ConfiguredMcpServer.js";export * from "./ConfiguredMcpServerAuth.js";export * from "./ContextManagementConfig.js";export * from "./ContextManagementConfigCompaction.js";+export * from "./CreateAgentResponse.js";export * from "./DaytonaSandboxProvider.js";export * from "./DaytonaSandboxProviderAuth.js";export * from "./DynamicSubAgentsConfig.js";@@ -37,6 +39,7 @@ export * from "./ExtendedChunkDeltaToolCall.js";export * from "./FileContent.js";export * from "./FinishReason.js";export * from "./GenerativeUiConfig.js";+export * from "./GetAgentResponse.js";export * from "./GetCapabilitiesResponse.js";export * from "./GetCapabilitiesResponseData.js";export * from "./GetCapabilitiesResponseDataSandbox.js";@@ -50,6 +53,7 @@ export * from "./GetSessionResponse.js";export * from "./GetSkillCatalogResponse.js";export * from "./GetTurnResponse.js";export * from "./LargeToolResponseConfig.js";+export * from "./ListAgentsResponse.js";export * from "./ListAvailableMcpServersResponse.js";export * from "./ListAvailableSkillsResponse.js";export * from "./ListConfiguredSkillsResponse.js";@@ -93,6 +97,7 @@ export * from "./ModelProperties.js";export * from "./ModelProvider.js";export * from "./ModelProviderAuth.js";export * from "./PreviousTurnIdInput.js";+export * from "./PutAgentResponse.js";export * from "./PutMcpServerResponse.js";export * from "./PutModelProviderResponse.js";export * from "./PutSandboxProviderResponse.js";@@ -114,6 +119,9 @@ export * from "./SandboxNetworkPolicyAuthInjectItem.js";export * from "./SandboxNetworkPolicyAuthInjectItemAuthData.js";export * from "./SandboxNetworkPolicyAuthInjectItemMatch.js";export * from "./Session.js";+export * from "./SessionAgent.js";+export * from "./SessionAgentRef.js";+export * from "./SessionAgentValue.js";export * from "./SessionEvent.js";export * from "./SessionEventItem.js";export * from "./SkillManifest.js";diff --git a/packages/sdk/tests/wire/agents.test.ts b/packages/sdk/tests/wire/agents.test.tsnew file mode 100644index 000000000..5b0f7ceff--- /dev/null+++ b/packages/sdk/tests/wire/agents.test.ts@@ -0,0 +1,447 @@+// This file was auto-generated by Fern from our API Definition.++import * as TrueForgeTypes from "../../src/api/index";+import { TrueForge } from "../../src/Client";+import { mockServerPool } from "../mock-server/MockServerPool";++describe("AgentsClient", () => {+ test("list", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ const rawResponseBody = {+ data: [+ {+ instructions: "instructions",+ mcp_servers: [{ name: "name" }],+ messages: [{ content: "content", type: "user.message" }],+ model: { name: "name" },+ response_format: { type: "json_object" },+ skills: [{ name: "name" }],+ variables: { key: "value" },+ id: "id",+ name: "name",+ },+ ],+ };++ server.mockEndpoint().get("/api/v1/agents").respondWith().statusCode(200).jsonBody(rawResponseBody).build();++ const response = await client.agents.list();+ expect(response).toEqual({+ data: [+ {+ instructions: "instructions",+ mcpServers: [+ {+ name: "name",+ },+ ],+ messages: [+ {+ content: "content",+ type: "user.message",+ },+ ],+ model: {+ name: "name",+ },+ responseFormat: {+ type: "json_object",+ },+ skills: [+ {+ name: "name",+ },+ ],+ variables: {+ key: "value",+ },+ id: "id",+ name: "name",+ },+ ],+ });+ });++ test("create (1)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { model: { name: "name" }, name: "name" };+ const rawResponseBody = {+ data: {+ config: { iteration_limit: 1, sandbox: { enabled: true } },+ instructions: "instructions",+ mcp_servers: [{ name: "name" }],+ messages: [{ content: "content", type: "user.message" }],+ model: { name: "name" },+ response_format: { type: "json_object" },+ skills: [{ name: "name" }],+ variables: { key: "value" },+ id: "id",+ name: "name",+ },+ };++ server+ .mockEndpoint()+ .post("/api/v1/agents")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(200)+ .jsonBody(rawResponseBody)+ .build();++ const response = await client.agents.create({+ model: {+ name: "name",+ },+ name: "name",+ });+ expect(response).toEqual({+ data: {+ config: {+ iterationLimit: 1,+ sandbox: {+ enabled: true,+ },+ },+ instructions: "instructions",+ mcpServers: [+ {+ name: "name",+ },+ ],+ messages: [+ {+ content: "content",+ type: "user.message",+ },+ ],+ model: {+ name: "name",+ },+ responseFormat: {+ type: "json_object",+ },+ skills: [+ {+ name: "name",+ },+ ],+ variables: {+ key: "value",+ },+ id: "id",+ name: "name",+ },+ });+ });++ test("create (2)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { name: "xy", model: { name: "x" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/agents")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(400)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.agents.create({+ name: "xy",+ model: {+ name: "x",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);+ });++ test("create (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { name: "xy", model: { name: "x" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/agents")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(409)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.agents.create({+ name: "xy",+ model: {+ name: "x",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.ConflictError);+ });++ test("create (4)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { name: "xy", model: { name: "x" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/agents")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(422)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.agents.create({+ name: "xy",+ model: {+ name: "x",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);+ });++ test("get (1)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ const rawResponseBody = {+ data: {+ config: { iteration_limit: 1, sandbox: { enabled: true } },+ instructions: "instructions",+ mcp_servers: [{ name: "name" }],+ messages: [{ content: "content", type: "user.message" }],+ model: { name: "name" },+ response_format: { type: "json_object" },+ skills: [{ name: "name" }],+ variables: { key: "value" },+ id: "id",+ name: "name",+ },+ };++ server+ .mockEndpoint()+ .get("/api/v1/agents/agent_id")+ .respondWith()+ .statusCode(200)+ .jsonBody(rawResponseBody)+ .build();++ const response = await client.agents.get("agent_id");+ expect(response).toEqual({+ data: {+ config: {+ iterationLimit: 1,+ sandbox: {+ enabled: true,+ },+ },+ instructions: "instructions",+ mcpServers: [+ {+ name: "name",+ },+ ],+ messages: [+ {+ content: "content",+ type: "user.message",+ },+ ],+ model: {+ name: "name",+ },+ responseFormat: {+ type: "json_object",+ },+ skills: [+ {+ name: "name",+ },+ ],+ variables: {+ key: "value",+ },+ id: "id",+ name: "name",+ },+ });+ });++ test("get (2)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });++ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .get("/api/v1/agents/agent_id")+ .respondWith()+ .statusCode(404)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.agents.get("agent_id");+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);+ });++ test("update (1)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { model: { name: "name" } };+ const rawResponseBody = {+ data: {+ config: { iteration_limit: 1, sandbox: { enabled: true } },+ instructions: "instructions",+ mcp_servers: [{ name: "name" }],+ messages: [{ content: "content", type: "user.message" }],+ model: { name: "name" },+ response_format: { type: "json_object" },+ skills: [{ name: "name" }],+ variables: { key: "value" },+ id: "id",+ name: "name",+ },+ };++ server+ .mockEndpoint()+ .put("/api/v1/agents/name")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(200)+ .jsonBody(rawResponseBody)+ .build();++ const response = await client.agents.update("name", {+ model: {+ name: "name",+ },+ });+ expect(response).toEqual({+ data: {+ config: {+ iterationLimit: 1,+ sandbox: {+ enabled: true,+ },+ },+ instructions: "instructions",+ mcpServers: [+ {+ name: "name",+ },+ ],+ messages: [+ {+ content: "content",+ type: "user.message",+ },+ ],+ model: {+ name: "name",+ },+ responseFormat: {+ type: "json_object",+ },+ skills: [+ {+ name: "name",+ },+ ],+ variables: {+ key: "value",+ },+ id: "id",+ name: "name",+ },+ });+ });++ test("update (2)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { model: { name: "x" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .put("/api/v1/agents/name")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(400)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.agents.update("name", {+ model: {+ name: "x",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.BadRequestError);+ });++ test("update (3)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { model: { name: "x" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .put("/api/v1/agents/name")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(404)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.agents.update("name", {+ model: {+ name: "x",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);+ });++ test("update (4)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { model: { name: "x" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .put("/api/v1/agents/name")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(422)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.agents.update("name", {+ model: {+ name: "x",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);+ });+});diff --git a/packages/sdk/tests/wire/sessions.test.ts b/packages/sdk/tests/wire/sessions.test.tsindex 23a3a2d28..002902329 100644--- a/packages/sdk/tests/wire/sessions.test.ts+++ b/packages/sdk/tests/wire/sessions.test.ts@@ -12,7 +12,7 @@ describe("SessionsClient", () => {const rawResponseBody = {data: [{- agent_spec: { model: { name: "name" } },+ agent: { agent_id: "agent_id", type: "ref" },created_at: "created_at",id: "id",title: "title",@@ -33,10 +33,9 @@ describe("SessionsClient", () => {const expected = {data: [{- agentSpec: {- model: {- name: "name",- },+ agent: {+ agentId: "agent_id",+ type: "ref",},createdAt: "created_at",id: "id",@@ -74,18 +73,10 @@ describe("SessionsClient", () => {test("create (1)", async () => {const server = mockServerPool.createServer();const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });- const rawRequestBody = { agent_spec: { model: { name: "name" } } };+ const rawRequestBody = { agent: { agent_id: "agent_id", type: "ref" } };const rawResponseBody = {data: {- agent_spec: {- instructions: "instructions",- mcp_servers: [{ name: "name" }],- messages: [{ content: "content", type: "user.message" }],- model: { name: "name" },- response_format: { type: "json_object" },- skills: [{ name: "name" }],- variables: { key: "value" },- },+ agent: { agent_id: "agent_id", type: "ref" },created_at: "created_at",id: "id",title: "title",@@ -103,41 +94,16 @@ describe("SessionsClient", () => {.build();const response = await client.sessions.create({- agentSpec: {- model: {- name: "name",- },+ agent: {+ agentId: "agent_id",+ type: "ref",},});expect(response).toEqual({data: {- agentSpec: {- instructions: "instructions",- mcpServers: [- {- name: "name",- },- ],- messages: [- {- content: "content",- type: "user.message",- },- ],- model: {- name: "name",- },- responseFormat: {- type: "json_object",- },- skills: [- {- name: "name",- },- ],- variables: {- key: "value",- },+ agent: {+ agentId: "agent_id",+ type: "ref",},createdAt: "created_at",id: "id",@@ -150,7 +116,7 @@ describe("SessionsClient", () => {test("create (2)", async () => {const server = mockServerPool.createServer();const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });- const rawRequestBody = { agent_spec: { model: { name: "x" } } };+ const rawRequestBody = { agent: { agent_id: "x", type: "ref" } };const rawResponseBody = { error: { message: "message" } };server@@ -164,10 +130,9 @@ describe("SessionsClient", () => {await expect(async () => {return await client.sessions.create({- agentSpec: {- model: {- name: "x",- },+ agent: {+ agentId: "x",+ type: "ref",},});}).rejects.toThrow(TrueForgeTypes.BadRequestError);@@ -176,7 +141,32 @@ describe("SessionsClient", () => {test("create (3)", async () => {const server = mockServerPool.createServer();const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });- const rawRequestBody = { agent_spec: { model: { name: "x" } } };+ const rawRequestBody = { agent: { agent_id: "x", type: "ref" } };+ const rawResponseBody = { error: { message: "message" } };++ server+ .mockEndpoint()+ .post("/api/v1/sessions")+ .jsonBody(rawRequestBody)+ .respondWith()+ .statusCode(404)+ .jsonBody(rawResponseBody)+ .build();++ await expect(async () => {+ return await client.sessions.create({+ agent: {+ agentId: "x",+ type: "ref",+ },+ });+ }).rejects.toThrow(TrueForgeTypes.NotFoundError);+ });++ test("create (4)", async () => {+ const server = mockServerPool.createServer();+ const client = new TrueForge({ maxRetries: 0, baseUrl: server.baseUrl });+ const rawRequestBody = { agent: { agent_id: "x", type: "ref" } };const rawResponseBody = { error: { message: "message" } };server@@ -190,10 +180,9 @@ describe("SessionsClient", () => {await expect(async () => {return await client.sessions.create({- agentSpec: {- model: {- name: "x",- },+ agent: {+ agentId: "x",+ type: "ref",},});}).rejects.toThrow(TrueForgeTypes.UnprocessableEntityError);@@ -205,15 +194,7 @@ describe("SessionsClient", () => {const rawResponseBody = {data: {- agent_spec: {- instructions: "instructions",- mcp_servers: [{ name: "name" }],- messages: [{ content: "content", type: "user.message" }],- model: { name: "name" },- response_format: { type: "json_object" },- skills: [{ name: "name" }],- variables: { key: "value" },- },+ agent: { agent_id: "agent_id", type: "ref" },created_at: "created_at",id: "id",title: "title",@@ -232,33 +213,9 @@ describe("SessionsClient", () => {const response = await client.sessions.get("session_id");expect(response).toEqual({data: {- agentSpec: {- instructions: "instructions",- mcpServers: [- {- name: "name",- },- ],- messages: [- {- content: "content",- type: "user.message",- },- ],- model: {- name: "name",- },- responseFormat: {- type: "json_object",- },- skills: [- {- name: "name",- },- ],- variables: {- key: "value",- },+ agent: {+ agentId: "agent_id",+ type: "ref",},createdAt: "created_at",id: "id",@@ -303,15 +260,7 @@ describe("SessionsClient", () => {const rawRequestBody = {};const rawResponseBody = {data: {- agent_spec: {- instructions: "instructions",- mcp_servers: [{ name: "name" }],- messages: [{ content: "content", type: "user.message" }],- model: { name: "name" },- response_format: { type: "json_object" },- skills: [{ name: "name" }],- variables: { key: "value" },- },+ agent: { agent_id: "agent_id", type: "ref" },created_at: "created_at",id: "id",title: "title",@@ -331,33 +280,9 @@ describe("SessionsClient", () => {const response = await client.sessions.update("session_id");expect(response).toEqual({data: {- agentSpec: {- instructions: "instructions",- mcpServers: [- {- name: "name",- },- ],- messages: [- {- content: "content",- type: "user.message",- },- ],- model: {- name: "name",- },- responseFormat: {- type: "json_object",- },- skills: [- {- name: "name",- },- ],- variables: {- key: "value",- },+ agent: {+ agentId: "agent_id",+ type: "ref",},createdAt: "created_at",id: "id",diff --git a/packages/server/scripts/write-openapi.ts b/packages/server/scripts/write-openapi.tsindex 563d9fcc9..3b48e2804 100644--- a/packages/server/scripts/write-openapi.ts+++ b/packages/server/scripts/write-openapi.ts@@ -16,6 +16,7 @@ import { McpCatalog } from '../src/catalog/McpCatalog';import { ModelCatalog } from '../src/catalog/ModelCatalog';import { SandboxCatalog } from '../src/catalog/SandboxCatalog';import { SkillCatalog } from '../src/catalog/SkillCatalog';+import { SqliteAgentStore } from '../src/db/sqlite/agent-store/SqliteAgentStore';import { createSqliteDb } from '../src/db/sqlite/client';import { SqliteMcpServerStore } from '../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';import { SqliteModelProviderStore } from '../src/db/sqlite/model-provider-store/SqliteModelProviderStore';@@ -57,6 +58,7 @@ const app = createServerApp({skillStore: new SqliteSkillStore(db),sandboxCatalog: SandboxCatalog.load(),sandboxProviderStore: new SqliteSandboxProviderStore(db),+ agentStore: new SqliteAgentStore(db),sessionStore,sessions: new Sessions({ sessionStore }),activeTurns: new ActiveTurnRegistry(),diff --git a/packages/server/src/apis/agents.ts b/packages/server/src/apis/agents.tsnew file mode 100644index 000000000..d57160fc0--- /dev/null+++ b/packages/server/src/apis/agents.ts@@ -0,0 +1,99 @@+/**+ * DB-backed agent registry API (mounted at /api/v1/agents).+ */+import { OpenAPIHono, type RouteHandler } from '@hono/zod-openapi';+import type { AgentSpec } from '@truefoundry/utils-core/agent-session';+import { AgentNameConflictError, type AgentRecord, type IAgentStore } from '../db/agentStore';+import type { IMcpServerStore } from '../db/mcpServerStore';+import type { IModelProviderStore } from '../db/modelProviderStore';+import type { ISandboxProviderStore } from '../db/sandboxProviderStore';+import type { ISkillStore } from '../db/skillStore';+import { createAgentRoute, getAgentRoute, listAgentsRoute, putAgentRoute } from '../routes/agentRoutes';+import { validateAgentSpec } from '../runtime/sessionResources';+import { toAgentManifest, type Agent, type AgentWriteRequest } from '../schemas/agent';+import { TENANT_ID } from './sessions';++export interface AgentsRouterDeps {+ agentStore: IAgentStore;+ modelProviderStore: IModelProviderStore;+ mcpServerStore: IMcpServerStore;+ skillStore: ISkillStore;+ sandboxProviderStore: ISandboxProviderStore;+}++/** Wire view: identity columns plus AgentSpec fields flattened. */+function toWireAgent(record: AgentRecord): Agent {+ return {+ id: record.id,+ name: record.name,+ ...record.manifest,+ };+}++async function validateManifest({ spec, deps }: { spec: AgentSpec; deps: AgentsRouterDeps }): Promise<AgentSpec> {+ await validateAgentSpec({+ spec,+ tenant_id: TENANT_ID,+ modelProviderStore: deps.modelProviderStore,+ mcpServerStore: deps.mcpServerStore,+ skillStore: deps.skillStore,+ sandboxProviderStore: deps.sandboxProviderStore,+ });+ return spec;+}++export function createAgentsRouter(deps: AgentsRouterDeps) {+ const listHandler: RouteHandler<typeof listAgentsRoute> = async c => {+ const records = await deps.agentStore.listAgents(TENANT_ID);+ return c.json({ data: records.map(toWireAgent) }, 200);+ };++ const createHandler: RouteHandler<typeof createAgentRoute> = async c => {+ const body: AgentWriteRequest = c.req.valid('json');+ const manifest = await validateManifest({ spec: toAgentManifest(body), deps });+ try {+ const record = await deps.agentStore.createAgent({+ tenant_id: TENANT_ID,+ name: body.name,+ manifest,+ });+ return c.json({ data: toWireAgent(record) }, 200);+ } catch (error) {+ if (error instanceof AgentNameConflictError) {+ return c.json({ error: { message: error.message } }, 409);+ }+ throw error;+ }+ };++ const getHandler: RouteHandler<typeof getAgentRoute> = async c => {+ const { agent_id: agentId } = c.req.valid('param');+ const record = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, id: agentId });+ if (record === undefined) {+ return c.json({ error: { message: `Agent not found: ${agentId}` } }, 404);+ }+ return c.json({ data: toWireAgent(record) }, 200);+ };++ const putHandler: RouteHandler<typeof putAgentRoute> = async c => {+ const { name } = c.req.valid('param');+ const body = c.req.valid('json');+ const manifest = await validateManifest({ spec: body, deps });+ const record = await deps.agentStore.updateAgent({+ tenant_id: TENANT_ID,+ name,+ manifest,+ });+ if (record === undefined) {+ return c.json({ error: { message: `Agent not found: ${name}` } }, 404);+ }+ return c.json({ data: toWireAgent(record) }, 200);+ };++ const router = new OpenAPIHono();+ router.openapi(listAgentsRoute, listHandler);+ router.openapi(createAgentRoute, createHandler);+ router.openapi(getAgentRoute, getHandler);+ router.openapi(putAgentRoute, putHandler);+ return router;+}diff --git a/packages/server/src/apis/sessions.ts b/packages/server/src/apis/sessions.tsindex c6b42e49b..fda647ba7 100644--- a/packages/server/src/apis/sessions.ts+++ b/packages/server/src/apis/sessions.ts@@ -6,6 +6,7 @@ import type { ISessionStore, SessionRecord, Sessions } from '@truefoundry/utils-import {CancellationReason,SessionStoreConflictError,+ SessionStoreInvariantError,SessionStoreNotFoundError,} from '@truefoundry/utils-core/agent-session';import type {@@ -18,6 +19,7 @@ import type { RedisClientType } from 'redis';import { ulid } from 'ulid';import { z } from 'zod';import configuration from '../config';+import type { IAgentStore } from '../db/agentStore';import type { IMcpServerStore } from '../db/mcpServerStore';import type { IModelProviderStore } from '../db/modelProviderStore';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';@@ -53,7 +55,7 @@ type CancelPeerBody = z.infer<typeof CancelPeerBodySchema>;export function toWireSession(record: SessionRecord): Session {return {id: record.session_id,- agent_spec: record.agent_spec,+ agent: record.agent,title: record.title,created_at: record.created_at.toISOString(),updated_at: record.updated_at.toISOString(),@@ -67,6 +69,7 @@ export interface SessionsRouterDeps {modelProviderStore: IModelProviderStore;mcpServerStore: IMcpServerStore;skillStore: ISkillStore;+ agentStore: IAgentStore;sandboxProviderStore: ISandboxProviderStore;redis?: RedisClientType | undefined;requestReplyRouter: RequestReplyRouter;@@ -184,8 +187,23 @@ export async function cancelSessionTurn(export function createSessionsRouter(deps: SessionsRouterDeps) {const createSessionHandler: RouteHandler<typeof createSessionRoute> = async c => {const body = c.req.valid('json');+ const sessionId = ulid().toLowerCase();++ if (body.agent.type === 'ref') {+ const agent = await deps.agentStore.getAgent({ tenant_id: TENANT_ID, id: body.agent.agent_id });+ if (agent === undefined) {+ return c.json({ error: { message: `Agent not found: ${body.agent.agent_id}` } }, 404);+ }+ const session = await deps.sessions.create({+ tenant_id: TENANT_ID,+ session_id: sessionId,+ agent: body.agent,+ });+ return c.json({ data: toWireSession(session.record) }, 201);+ }+await validateAgentSpec({- spec: body.agent_spec,+ spec: body.agent.agent_spec,tenant_id: TENANT_ID,modelProviderStore: deps.modelProviderStore,mcpServerStore: deps.mcpServerStore,@@ -194,8 +212,8 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {});const session = await deps.sessions.create({tenant_id: TENANT_ID,- session_id: ulid().toLowerCase(),- agent_spec: body.agent_spec,+ session_id: sessionId,+ agent: body.agent,});return c.json({ data: toWireSession(session.record) }, 201);};@@ -218,9 +236,11 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {const updateSessionHandler: RouteHandler<typeof updateSessionRoute> = async c => {const { session_id: sessionId } = c.req.valid('param');const body = c.req.valid('json');- if (body.agent_spec) {+ // Draft (value) sessions may replace their inline agent; named (ref) sessions+ // cannot — the store rejects that with SessionStoreInvariantError → 400 below.+ if (body.agent !== undefined) {await validateAgentSpec({- spec: body.agent_spec,+ spec: body.agent.agent_spec,tenant_id: TENANT_ID,modelProviderStore: deps.modelProviderStore,mcpServerStore: deps.mcpServerStore,@@ -232,13 +252,16 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {await deps.sessionStore.updateSession({tenant_id: TENANT_ID,session_id: sessionId,- agent_spec: body.agent_spec,+ agent: body.agent,title: undefined,});} catch (error) {if (error instanceof SessionStoreNotFoundError) {return c.json({ error: { message: `Session not found: ${sessionId}` } }, 404);}+ if (error instanceof SessionStoreInvariantError) {+ return c.json({ error: { message: error.message } }, 400);+ }throw error;}const record = await deps.sessionStore.getSession({ tenant_id: TENANT_ID, session_id: sessionId });@@ -252,6 +275,7 @@ export function createSessionsRouter(deps: SessionsRouterDeps) {const query = c.req.valid('query');try {const { data, pagination } = await deps.sessionStore.listSessions({+ agent_id: query.agent_id,tenant_id: TENANT_ID,limit: query.limit,order: query.order,diff --git a/packages/server/src/apis/turns.ts b/packages/server/src/apis/turns.tsindex 693bee6ca..a8efb3e09 100644--- a/packages/server/src/apis/turns.ts+++ b/packages/server/src/apis/turns.ts@@ -20,13 +20,13 @@ import {isFileContentPart,McpConnectionError,VercelAILLM,- type VercelAIProviderConfig,} from '@truefoundry/utils-core/core';import type { Context } from 'hono';import { HTTPException } from 'hono/http-exception';import { streamSSE } from 'hono/streaming';import type { Logger } from 'winston';import configuration from '../config';+import type { IAgentStore } from '../db/agentStore';import type { IMcpServerStore } from '../db/mcpServerStore';import type { IModelProviderStore } from '../db/modelProviderStore';import type { ISandboxProviderStore } from '../db/sandboxProviderStore';@@ -70,6 +70,7 @@ export interface TurnsRouterDeps {mcpServerStore: IMcpServerStore;tokenStore: IOAuthTokenStore;skillStore: ISkillStore;+ agentStore: IAgentStore;/** Resumable live turn-event transport: create-turn writes, subscribe polls. */eventSubscriptions: EventSubscriptionRegistry<TurnStreamingEvent>;sandboxProviderStore: ISandboxProviderStore;@@ -77,26 +78,36 @@ export interface TurnsRouterDeps {}/**- * TurnResourceResolver requires a sync llm factory; preload the session model- * config so the factory stays sync while the store read stays async.+ * Builds the per-turn resolver. Agent / MCP / sandbox / LLM lookups are wired+ * the same way: async factories over the corresponding stores.*/function createTurnResolver(deps: {mcpServerStore: IMcpServerStore;tokenStore: IOAuthTokenStore;skillStore: ISkillStore;sandboxProviderStore: ISandboxProviderStore;+ agentStore: IAgentStore;+ modelProviderStore: IModelProviderStore;logger: Logger;signal: AbortSignal;- modelName: string;- providerConfig: VercelAIProviderConfig;}): TurnResourceResolver {- const { mcpServerStore, tokenStore, skillStore, sandboxProviderStore, logger, signal, modelName, providerConfig } =- deps;+ const {+ mcpServerStore,+ tokenStore,+ skillStore,+ sandboxProviderStore,+ agentStore,+ modelProviderStore,+ logger,+ signal,+ } = deps;return new TurnResourceResolver({- llm: name => {- if (name !== modelName) {- throw new Error(`Model not registered: ${name}`);- }+ llm: async name => {+ const providerConfig = await getModelProviderConfig({+ tenant_id: TENANT_ID,+ name,+ store: modelProviderStore,+ });return new VercelAILLM({providerConfig,logger,@@ -146,6 +157,13 @@ function createTurnResolver(deps: {tenantName: TENANT_ID,});},+ agent: async agentId => {+ const record = await agentStore.getAgent({ tenant_id: TENANT_ID, id: agentId });+ if (record === undefined) {+ throw new HTTPException(422, { message: `Agent not found: ${agentId}` });+ }+ return record.manifest;+ },logger,});}@@ -299,21 +317,15 @@ export function createTurnsRouter(deps: TurnsRouterDeps) {}const abortController = new AbortController();- const modelName = session.agent_spec.model.name;- const providerConfig = await getModelProviderConfig({- tenant_id: TENANT_ID,- name: modelName,- store: deps.modelProviderStore,- });const resolver = createTurnResolver({mcpServerStore: deps.mcpServerStore,tokenStore: deps.tokenStore,skillStore: deps.skillStore,sandboxProviderStore: deps.sandboxProviderStore,+ agentStore: deps.agentStore,+ modelProviderStore: deps.modelProviderStore,logger: deps.logger,signal: abortController.signal,- modelName,- providerConfig,});// First turn only: derive the title from the first user message. The storediff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 322502dfd..c19e16f1a 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -7,6 +7,7 @@ import type { Context } from 'hono';import { HTTPException } from 'hono/http-exception';import type { RedisClientType } from 'redis';import type { Logger } from 'winston';+import { createAgentsRouter } from './apis/agents';import { createAuthRouter } from './apis/auth';import { createCapabilitiesRouter } from './apis/capabilities';import { createMcpOAuthRouter } from './apis/mcpOAuth';@@ -20,6 +21,7 @@ import type { McpCatalog } from './catalog/McpCatalog';import type { ModelCatalog } from './catalog/ModelCatalog';import type { SandboxCatalog } from './catalog/SandboxCatalog';import type { SkillCatalog } from './catalog/SkillCatalog';+import type { IAgentStore } from './db/agentStore';import type { IMcpServerStore } from './db/mcpServerStore';import type { IModelProviderStore } from './db/modelProviderStore';import type { ISandboxProviderStore } from './db/sandboxProviderStore';@@ -32,7 +34,8 @@ const openApiDocConfig = {openapi: '3.1.0',info: {title: 'Agent Server',- description: 'Agent server with DB-backed sessions, settings catalogs, and model/MCP/skill providers.',+ description:+ 'Agent server with DB-backed sessions, agent registry, settings catalogs, and model/MCP/skill providers.',version: '0.1.0',},};@@ -56,6 +59,7 @@ export interface ServerDeps {tokenStore: IOAuthTokenStore;skillStore: ISkillStore;sandboxProviderStore: ISandboxProviderStore;+ agentStore: IAgentStore;sessionStore: ISessionStore;sessions: Sessions;activeTurns: ActiveTurnRegistry;@@ -94,6 +98,16 @@ export function createServerApp(deps: ServerDeps) {}),);app.route('/api/v1/skills', createAvailableSkillsRouter(deps.skillStore));+ app.route(+ '/api/v1/agents',+ createAgentsRouter({+ agentStore: deps.agentStore,+ modelProviderStore: deps.modelProviderStore,+ mcpServerStore: deps.mcpServerStore,+ skillStore: deps.skillStore,+ sandboxProviderStore: deps.sandboxProviderStore,+ }),+ );app.route('/api/v1/settings',createSettingsRouter({@@ -118,6 +132,7 @@ export function createServerApp(deps: ServerDeps) {modelProviderStore: deps.modelProviderStore,mcpServerStore: deps.mcpServerStore,skillStore: deps.skillStore,+ agentStore: deps.agentStore,sandboxProviderStore: deps.sandboxProviderStore,redis: deps.redis,requestReplyRouter: deps.requestReplyRouter,@@ -133,6 +148,7 @@ export function createServerApp(deps: ServerDeps) {mcpServerStore: deps.mcpServerStore,tokenStore: deps.tokenStore,skillStore: deps.skillStore,+ agentStore: deps.agentStore,eventSubscriptions: deps.eventSubscriptions,sandboxProviderStore: deps.sandboxProviderStore,logger: deps.logger,diff --git a/packages/server/src/db/agentStore.ts b/packages/server/src/db/agentStore.tsnew file mode 100644index 000000000..8655b836c--- /dev/null+++ b/packages/server/src/db/agentStore.ts@@ -0,0 +1,57 @@+/**+ * DB-backed configured agents: one row per agent per tenant,+ * immutable ULID `id`, unique immutable `name` within a tenant, plus a Zod-validated+ * `AgentSpec` jsonb document.+ * Implementations: PostgresAgentStore and SqliteAgentStore.+ */+import type { AgentSpec } from '@truefoundry/utils-core/agent-session';+import type { ResourceName } from '../schemas/common';++export interface AgentRecord {+ id: string;+ tenant_id: string;+ name: ResourceName;+ manifest: AgentSpec;+ /** ISO-8601 UTC instant. */+ created_at: string;+ /** ISO-8601 UTC instant. */+ updated_at: string;+}++/** Look up by immutable id or unique name within a tenant. */+export type GetAgentInput = { tenant_id: string } & ({ id: string } | { name: string });++export interface CreateAgentInput {+ tenant_id: string;+ name: ResourceName;+ manifest: AgentSpec;+}++/** Replace manifest for an existing agent keyed by immutable name. */+export interface UpdateAgentInput {+ tenant_id: string;+ name: ResourceName;+ manifest: AgentSpec;+}++/** Unique `(tenant_id, name)` violation on create. */+export class AgentNameConflictError extends Error {+ readonly tenant_id: string;+ readonly agent_name: string;++ constructor({ tenant_id, name }: { tenant_id: string; name: string }, options?: ErrorOptions) {+ super(`Agent name already exists: ${name}`, options);+ this.name = 'AgentNameConflictError';+ this.tenant_id = tenant_id;+ this.agent_name = name;+ }+}++export interface IAgentStore {+ listAgents(tenantId: string): Promise<AgentRecord[]>;+ getAgent(input: GetAgentInput): Promise<AgentRecord | undefined>;+ /** Inserts a new agent with a generated ULID. Throws AgentNameConflictError on name clash. */+ createAgent(input: CreateAgentInput): Promise<AgentRecord>;+ /** Replaces `manifest` for an existing name. Returns undefined if missing. */+ updateAgent(input: UpdateAgentInput): Promise<AgentRecord | undefined>;+}diff --git a/packages/server/src/db/postgres/agent-store/PostgresAgentStore.ts b/packages/server/src/db/postgres/agent-store/PostgresAgentStore.tsnew file mode 100644index 000000000..5a44740c6--- /dev/null+++ b/packages/server/src/db/postgres/agent-store/PostgresAgentStore.ts@@ -0,0 +1,90 @@+import type { Kysely, Selectable } from 'kysely';+import { ulid } from 'ulid';+import {+ AgentNameConflictError,+ type AgentRecord,+ type CreateAgentInput,+ type GetAgentInput,+ type IAgentStore,+ type UpdateAgentInput,+} from '../../agentStore';+import { isUniqueViolation } from '../client';+import { json, now } from '../sqlExpressions';+import type { AgentTable, Database } from '../types';++function toRecord(row: Selectable<AgentTable>): AgentRecord {+ return {+ id: row.id,+ tenant_id: row.tenant_id,+ name: row.name,+ manifest: row.manifest,+ created_at: row.created_at.toISOString(),+ updated_at: row.updated_at.toISOString(),+ };+}++export class PostgresAgentStore implements IAgentStore {+ readonly #db: Kysely<Database>;++ constructor(db: Kysely<Database>) {+ this.#db = db;+ }++ async listAgents(tenantId: string): Promise<AgentRecord[]> {+ const rows = await this.#db+ .selectFrom('agent')+ .selectAll()+ .where('tenant_id', '=', tenantId)+ .orderBy('name')+ .execute();+ return rows.map(toRecord);+ }++ async getAgent(input: GetAgentInput): Promise<AgentRecord | undefined> {+ let query = this.#db.selectFrom('agent').selectAll().where('tenant_id', '=', input.tenant_id);+ if ('id' in input) {+ query = query.where('id', '=', input.id);+ } else {+ query = query.where('name', '=', input.name);+ }+ const row = await query.executeTakeFirst();+ return row === undefined ? undefined : toRecord(row);+ }++ async createAgent(input: CreateAgentInput): Promise<AgentRecord> {+ try {+ const row = await this.#db+ .insertInto('agent')+ .values({+ id: ulid().toLowerCase(),+ tenant_id: input.tenant_id,+ name: input.name,+ manifest: json(input.manifest),+ created_at: now(),+ updated_at: now(),+ })+ .returningAll()+ .executeTakeFirstOrThrow();+ return toRecord(row);+ } catch (error) {+ if (isUniqueViolation(error)) {+ throw new AgentNameConflictError({ tenant_id: input.tenant_id, name: input.name }, { cause: error });+ }+ throw error;+ }+ }++ async updateAgent(input: UpdateAgentInput): Promise<AgentRecord | undefined> {+ const row = await this.#db+ .updateTable('agent')+ .set({+ manifest: json(input.manifest),+ updated_at: now(),+ })+ .where('tenant_id', '=', input.tenant_id)+ .where('name', '=', input.name)+ .returningAll()+ .executeTakeFirst();+ return row === undefined ? undefined : toRecord(row);+ }+}diff --git a/packages/server/src/db/postgres/migrations/20260810_000001_agent.ts b/packages/server/src/db/postgres/migrations/20260810_000001_agent.tsnew file mode 100644index 000000000..64434ac45--- /dev/null+++ b/packages/server/src/db/postgres/migrations/20260810_000001_agent.ts@@ -0,0 +1,57 @@+import { sql, type Kysely } from 'kysely';++/**+ * Agent registry + session agent binding.+ *+ * - `agent`: immutable application-generated `id` (ULID) as PK; natural lookup+ * key is UNIQUE (tenant_id, name). Spec lives in Zod-validated `manifest` jsonb+ * (same pattern as mcp_server).+ * - `session`: agent_id XOR agent_spec. Existing rows keep inline agent_spec with+ * agent_id NULL.+ */+export async function up(db: Kysely<unknown>): Promise<void> {+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);+ await db.schema+ .createTable('agent')+ .addColumn('id', 'text', col => col.notNull())+ .addColumn('tenant_id', 'text', col => col.notNull())+ .addColumn('name', 'text', col => col.notNull())+ .addColumn('manifest', 'jsonb', col => col.notNull())+ .addColumn('created_at', 'timestamptz', col => col.notNull())+ .addColumn('updated_at', 'timestamptz', col => col.notNull())+ .addPrimaryKeyConstraint('agent_pkey', ['id'])+ .execute();++ await db.schema.createIndex('agent_tenant_name_idx').on('agent').columns(['tenant_id', 'name']).unique().execute();++ await db.schema.alterTable('session').addColumn('agent_id', 'text').execute();++ await sql`ALTER TABLE session ALTER COLUMN agent_spec DROP NOT NULL`.execute(db);++ await sql`+ ALTER TABLE session+ ADD CONSTRAINT session_agent_xor_check+ CHECK (+ (agent_id IS NOT NULL AND agent_spec IS NULL)+ OR (agent_id IS NULL AND agent_spec IS NOT NULL)+ )+ `.execute(db);++ await sql`+ CREATE INDEX session_agent_id_idx+ ON session (tenant_id, agent_id)+ WHERE agent_id IS NOT NULL+ `.execute(db);+}++export async function down(db: Kysely<unknown>): Promise<void> {+ await sql`SET LOCAL lock_timeout = '5s'`.execute(db);+ await sql`DROP INDEX IF EXISTS session_agent_id_idx`.execute(db);+ await sql`ALTER TABLE session DROP CONSTRAINT IF EXISTS session_agent_xor_check`.execute(db);+ await sql`+ DELETE FROM session WHERE agent_spec IS NULL+ `.execute(db);+ await sql`ALTER TABLE session ALTER COLUMN agent_spec SET NOT NULL`.execute(db);+ await db.schema.alterTable('session').dropColumn('agent_id').execute();+ await db.schema.dropTable('agent').ifExists().cascade().execute();+}diff --git a/packages/server/src/db/postgres/session-store/queries/sessions.ts b/packages/server/src/db/postgres/session-store/queries/sessions.tsindex 5918df240..d7dbee61d 100644--- a/packages/server/src/db/postgres/session-store/queries/sessions.ts+++ b/packages/server/src/db/postgres/session-store/queries/sessions.ts@@ -1,3 +1,4 @@+import type { AgentSpec } from '@truefoundry/utils-core/agent-session';import type { SessionRecord } from '@truefoundry/utils-core/agent-session/models/SessionRecord';import type {CreateSessionInput,@@ -13,6 +14,7 @@ import {SessionStoreInvariantError,} from '@truefoundry/utils-core/agent-session/store/SessionStoreErrors';import { sql, type Kysely } from 'kysely';+import { sessionAgentFromColumns, sessionAgentToColumns } from '../../../sessionAgentColumns';import { json } from '../../sqlExpressions';import type { Database } from '../../types';@@ -46,7 +48,8 @@ function parseSessionCustom(value: Record<string, unknown> | null): SessionCustofunction mapRowToSessionRecord(row: {tenant_id: string;session_id: string;- agent_spec: ProtoSessionRecord['agent_spec'];+ agent_id: string | null;+ agent_spec: AgentSpec | null;title: string | null;last_turn_id: string | null;custom: Record<string, unknown> | null;@@ -57,7 +60,11 @@ function mapRowToSessionRecord(row: {return {tenant_id: row.tenant_id,session_id: row.session_id,- agent_spec: row.agent_spec,+ agent: sessionAgentFromColumns({+ session_id: row.session_id,+ agent_id: row.agent_id,+ agent_spec: row.agent_spec,+ }),title: row.title,last_turn_id: row.last_turn_id,custom: parseSessionCustom(row.custom),@@ -68,6 +75,7 @@ function mapRowToSessionRecord(row: {}export async function createSession(db: Kysely<Database>, input: CreateSessionInput<SessionCustom>): Promise<void> {+ const columns = sessionAgentToColumns(input.agent);const nowMs = Date.now();try {@@ -76,7 +84,8 @@ export async function createSession(db: Kysely<Database>, input: CreateSessionIn.values({tenant_id: input.tenant_id,session_id: input.session_id,- agent_spec: json(input.agent_spec),+ agent_id: columns.agent_id,+ agent_spec: columns.agent_spec !== null ? json(columns.agent_spec) : null,title: null,custom: input.custom !== null ? json(input.custom) : null,created_at: new Date(nowMs),@@ -119,20 +128,30 @@ export async function getSession(}export async function updateSession(db: Kysely<Database>, input: UpdateSessionInput<SessionCustom>): Promise<void> {- const agentSpec = input.agent_spec;+ const agent = input.agent;const title = input.title;+ if (agent !== undefined) {+ const existing = await getSession(db, { tenant_id: input.tenant_id, session_id: input.session_id });+ if (existing === undefined) {+ throw new SessionNotFoundError(input.session_id);+ }+ if (existing.agent.type === 'ref') {+ throw new SessionStoreInvariantError(`Session ${input.session_id} is named; agent cannot be updated`);+ }+ }+const result = await db.updateTable('session').set({updated_at: sql<Date>`now()`,last_activity_timestamp_ms: Date.now(),})- .$if(agentSpec !== undefined, qb => {- if (agentSpec === undefined) {+ .$if(agent !== undefined, qb => {+ if (agent === undefined) {return qb;}- return qb.set({ agent_spec: json(agentSpec) });+ return qb.set({ agent_spec: json(agent.agent_spec) });}).$if(title !== undefined, qb => {if (title === undefined) {@@ -164,6 +183,9 @@ export async function listSessions(let query = db.selectFrom('session').selectAll().where('tenant_id', '=', input.tenant_id);+ if (input.agent_id !== undefined) {+ query = query.where('agent_id', '=', input.agent_id);+ }if (input.start_timestamp !== undefined) {query = query.where('created_at', '>=', input.start_timestamp);}diff --git a/packages/server/src/db/postgres/types.ts b/packages/server/src/db/postgres/types.tsindex f0f05bede..4d1783184 100644--- a/packages/server/src/db/postgres/types.ts+++ b/packages/server/src/db/postgres/types.ts@@ -46,10 +46,15 @@ export interface SessionTable {/** key */session_id: string;/**- * top: big + immutable-in-practice (updateSession patch only);- * TOAST pointer rides through per-turn tip bumps untouched+ * Named registry binding; XOR with `agent_spec`+ * (CHECK session_agent_xor_check).*/- agent_spec: JSONColumnType<AgentSpec, AgentSpec, AgentSpec>;+ agent_id: string | null;+ /**+ * Inline draft binding; XOR with `agent_id`.+ * TOAST pointer rides through per-turn tip bumps when present.+ */+ agent_spec: JSONColumnType<AgentSpec, AgentSpec | null, AgentSpec | null> | null;/*** top: list-displayed, independently patched; first-write-wins* (COALESCE) targets it directly@@ -329,6 +334,22 @@ export interface SandboxProviderTable {updated_at: Date;}+/**+ * Configured agents — immutable ULID `id` PK; UNIQUE immutable (tenant_id, name).+ * PRIMARY KEY (id)+ */+export interface AgentTable {+ /** application-generated (ulid); never re-derived from tenant_id/name */+ id: string;+ tenant_id: string;+ /** immutable natural uniqueness target within a tenant */+ name: string;+ /** AgentSpec document; replaced whole on every upsert */+ manifest: JSONColumnType<AgentSpec, AgentSpec, AgentSpec>;+ created_at: Date;+ updated_at: Date;+}+/*** PRIMARY KEY (id)* UNIQUE (tenant_id, name) — the natural lookup key.@@ -393,8 +414,8 @@ export interface OAuthPendingAuthorizationTable {* `thread_capability_state` take small bounded HOT-friendly updates; the two logs* are pure insert. Nothing ever rewrites a large value except the array concat* itself — the documented, bounded cost of the raw-array model. `model_provider`,- * `skill`, `sandbox_provider`, `mcp_server`, and the two `oauth_*` tables are- * low-write, low-volume (one row per tenant/resource, or short-lived).+ * `skill`, `sandbox_provider`, `agent`, `mcp_server`, and the two `oauth_*` tables+ * are low-write, low-volume (one row per tenant/resource, or short-lived).** Canonical Kysely database.*/@@ -408,6 +429,7 @@ export interface Database {model_provider: ModelProviderTable;skill: SkillTable;sandbox_provider: SandboxProviderTable;+ agent: AgentTable;mcp_server: McpServerTable;oauth_token: OAuthTokenTable;oauth_pending_authorization: OAuthPendingAuthorizationTable;diff --git a/packages/server/src/db/sessionAgentColumns.ts b/packages/server/src/db/sessionAgentColumns.tsnew file mode 100644index 000000000..0aab5b784--- /dev/null+++ b/packages/server/src/db/sessionAgentColumns.ts@@ -0,0 +1,29 @@+import type { AgentSpec, SessionAgent } from '@truefoundry/utils-core/agent-session';++/** Flatten domain agent for SQL session columns (XOR pair). */+export function sessionAgentToColumns(agent: SessionAgent): {+ agent_id: string | null;+ agent_spec: AgentSpec | null;+} {+ if (agent.type === 'ref') {+ return { agent_id: agent.agent_id, agent_spec: null };+ }+ return { agent_id: null, agent_spec: agent.agent_spec };+}++/** Rebuild domain agent from SQL session columns. */+export function sessionAgentFromColumns(input: {+ session_id: string;+ agent_id: string | null;+ agent_spec: AgentSpec | null;+}): SessionAgent {+ if (input.agent_id !== null && input.agent_spec === null) {+ return { type: 'ref', agent_id: input.agent_id };+ }+ if (input.agent_id === null && input.agent_spec !== null) {+ return { type: 'value', agent_spec: input.agent_spec };+ }+ throw new Error(+ `Session ${input.session_id} has invalid agent binding (exactly one of agent_id or agent_spec required)`,+ );+}diff --git a/packages/server/src/db/sqlite/agent-store/SqliteAgentStore.ts b/packages/server/src/db/sqlite/agent-store/SqliteAgentStore.tsnew file mode 100644index 000000000..6d7df87ad--- /dev/null+++ b/packages/server/src/db/sqlite/agent-store/SqliteAgentStore.ts@@ -0,0 +1,89 @@+import type { AgentSpec } from '@truefoundry/utils-core/agent-session';+import type { ExpressionBuilder, Kysely } from 'kysely';+import { ulid } from 'ulid';+import {+ AgentNameConflictError,+ type AgentRecord,+ type CreateAgentInput,+ type GetAgentInput,+ type IAgentStore,+ type UpdateAgentInput,+} from '../../agentStore';+import { isUniqueViolation } from '../client';+import { jsonbBind, jsonText, nowIso } from '../sqlExpressions';+import type { Database } from '../types';++/** Column list projecting the JSONB manifest as parsed JSON (see JSON_RESULT_COLUMNS). */+function recordColumns(eb: ExpressionBuilder<Database, 'agent'>) {+ return [+ 'id' as const,+ 'tenant_id' as const,+ 'name' as const,+ jsonText<AgentSpec>(eb.ref('manifest')).as('manifest'),+ 'created_at' as const,+ 'updated_at' as const,+ ];+}++export class SqliteAgentStore implements IAgentStore {+ readonly #db: Kysely<Database>;++ constructor(db: Kysely<Database>) {+ this.#db = db;+ }++ async listAgents(tenantId: string): Promise<AgentRecord[]> {+ return await this.#db+ .selectFrom('agent')+ .select(recordColumns)+ .where('tenant_id', '=', tenantId)+ .orderBy('name')+ .execute();+ }++ async getAgent(input: GetAgentInput): Promise<AgentRecord | undefined> {+ let query = this.#db.selectFrom('agent').select(recordColumns).where('tenant_id', '=', input.tenant_id);+ if ('id' in input) {+ query = query.where('id', '=', input.id);+ } else {+ query = query.where('name', '=', input.name);+ }+ return await query.executeTakeFirst();+ }++ async createAgent(input: CreateAgentInput): Promise<AgentRecord> {+ const timestamp = nowIso();+ try {+ return await this.#db+ .insertInto('agent')+ .values({+ id: ulid().toLowerCase(),+ tenant_id: input.tenant_id,+ name: input.name,+ manifest: jsonbBind(input.manifest),+ created_at: timestamp,+ updated_at: timestamp,+ })+ .returning(recordColumns)+ .executeTakeFirstOrThrow();+ } catch (error) {+ if (isUniqueViolation(error)) {+ throw new AgentNameConflictError({ tenant_id: input.tenant_id, name: input.name }, { cause: error });+ }+ throw error;+ }+ }++ async updateAgent(input: UpdateAgentInput): Promise<AgentRecord | undefined> {+ return await this.#db+ .updateTable('agent')+ .set({+ manifest: jsonbBind(input.manifest),+ updated_at: nowIso(),+ })+ .where('tenant_id', '=', input.tenant_id)+ .where('name', '=', input.name)+ .returning(recordColumns)+ .executeTakeFirst();+ }+}diff --git a/packages/server/src/db/sqlite/migrations/20260810_000001_agent.ts b/packages/server/src/db/sqlite/migrations/20260810_000001_agent.tsnew file mode 100644index 000000000..d4e2a1bd6--- /dev/null+++ b/packages/server/src/db/sqlite/migrations/20260810_000001_agent.ts@@ -0,0 +1,147 @@+import { sql, type Kysely } from 'kysely';++/**+ * Agent registry + session agent binding for SQLite.+ *+ * - `agent`: mirrors Postgres (manifest is BLOB SQLite JSONB; timestamps ISO TEXT).+ * - `session`: agent_id XOR agent_spec. STRICT cannot drop NOT NULL in place —+ * rebuild the session table. Foreign keys are disabled for the swap; child+ * rows keep matching session_id values.+ */+export async function up(db: Kysely<unknown>): Promise<void> {+ await sql`+ CREATE TABLE agent (+ id TEXT NOT NULL,+ tenant_id TEXT NOT NULL,+ name TEXT NOT NULL,+ manifest BLOB NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ PRIMARY KEY (id),+ UNIQUE (tenant_id, name)+ ) STRICT+ `.execute(db);++ await sql`PRAGMA foreign_keys = OFF`.execute(db);++ await sql`+ CREATE TABLE session_new (+ tenant_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ agent_id TEXT,+ agent_spec BLOB,+ title TEXT,+ last_turn_id TEXT,+ custom BLOB,+ last_activity_timestamp_ms INTEGER NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ PRIMARY KEY (session_id),+ CHECK (+ (agent_id IS NOT NULL AND agent_spec IS NULL)+ OR (agent_id IS NULL AND agent_spec IS NOT NULL)+ )+ ) STRICT+ `.execute(db);++ await sql`+ INSERT INTO session_new (+ tenant_id,+ session_id,+ agent_id,+ agent_spec,+ title,+ last_turn_id,+ custom,+ last_activity_timestamp_ms,+ created_at,+ updated_at+ )+ SELECT+ tenant_id,+ session_id,+ NULL,+ agent_spec,+ title,+ last_turn_id,+ custom,+ last_activity_timestamp_ms,+ created_at,+ updated_at+ FROM session+ `.execute(db);++ await sql`DROP TABLE session`.execute(db);+ await sql`ALTER TABLE session_new RENAME TO session`.execute(db);++ await sql`+ CREATE INDEX session_list_idx+ ON session (tenant_id, created_at, session_id)+ `.execute(db);++ await sql`+ CREATE INDEX session_agent_id_idx+ ON session (tenant_id, agent_id)+ WHERE agent_id IS NOT NULL+ `.execute(db);++ await sql`PRAGMA foreign_keys = ON`.execute(db);+}++export async function down(db: Kysely<unknown>): Promise<void> {+ await sql`PRAGMA foreign_keys = OFF`.execute(db);++ await sql`DELETE FROM session WHERE agent_spec IS NULL`.execute(db);++ await sql`+ CREATE TABLE session_old (+ tenant_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ agent_spec BLOB NOT NULL,+ title TEXT,+ last_turn_id TEXT,+ custom BLOB,+ last_activity_timestamp_ms INTEGER NOT NULL,+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ PRIMARY KEY (session_id)+ ) STRICT+ `.execute(db);++ await sql`+ INSERT INTO session_old (+ tenant_id,+ session_id,+ agent_spec,+ title,+ last_turn_id,+ custom,+ last_activity_timestamp_ms,+ created_at,+ updated_at+ )+ SELECT+ tenant_id,+ session_id,+ agent_spec,+ title,+ last_turn_id,+ custom,+ last_activity_timestamp_ms,+ created_at,+ updated_at+ FROM session+ `.execute(db);++ await sql`DROP TABLE session`.execute(db);+ await sql`ALTER TABLE session_old RENAME TO session`.execute(db);++ await sql`+ CREATE INDEX session_list_idx+ ON session (tenant_id, created_at, session_id)+ `.execute(db);++ await sql`PRAGMA foreign_keys = ON`.execute(db);++ await sql`DROP TABLE IF EXISTS agent`.execute(db);+}diff --git a/packages/server/src/db/sqlite/session-store/queries/sessions.ts b/packages/server/src/db/sqlite/session-store/queries/sessions.tsindex 447432c52..9f7c3140e 100644--- a/packages/server/src/db/sqlite/session-store/queries/sessions.ts+++ b/packages/server/src/db/sqlite/session-store/queries/sessions.ts@@ -14,6 +14,7 @@ import {SessionStoreInvariantError,} from '@truefoundry/utils-core/agent-session/store/SessionStoreErrors';import { sql, type Kysely } from 'kysely';+import { sessionAgentFromColumns, sessionAgentToColumns } from '../../../sessionAgentColumns';import { isUniqueViolation } from '../../client';import { jsonbBind, jsonText, nowIso } from '../../sqlExpressions';import type { Database } from '../../types';@@ -38,7 +39,8 @@ function parseSessionCustom(value: Record<string, unknown> | null): SessionCustofunction mapRowToSessionRecord(row: {tenant_id: string;session_id: string;- agent_spec: AgentSpec;+ agent_id: string | null;+ agent_spec: AgentSpec | null;title: string | null;last_turn_id: string | null;custom: Record<string, unknown> | null;@@ -49,7 +51,11 @@ function mapRowToSessionRecord(row: {return {tenant_id: row.tenant_id,session_id: row.session_id,- agent_spec: row.agent_spec,+ agent: sessionAgentFromColumns({+ session_id: row.session_id,+ agent_id: row.agent_id,+ agent_spec: row.agent_spec,+ }),title: row.title,last_turn_id: row.last_turn_id,custom: parseSessionCustom(row.custom),@@ -59,7 +65,23 @@ function mapRowToSessionRecord(row: {};}+function sessionSelectColumns() {+ return [+ 'tenant_id' as const,+ 'session_id' as const,+ 'agent_id' as const,+ jsonText<AgentSpec | null>(sql.ref('agent_spec')).as('agent_spec'),+ 'title' as const,+ 'last_turn_id' as const,+ jsonText<Record<string, unknown> | null>(sql.ref('custom')).as('custom'),+ 'created_at' as const,+ 'updated_at' as const,+ 'last_activity_timestamp_ms' as const,+ ];+}+export async function createSession(db: Kysely<Database>, input: CreateSessionInput<SessionCustom>): Promise<void> {+ const columns = sessionAgentToColumns(input.agent);const now = nowIso();try {@@ -68,7 +90,8 @@ export async function createSession(db: Kysely<Database>, input: CreateSessionIn.values({tenant_id: input.tenant_id,session_id: input.session_id,- agent_spec: jsonbBind(input.agent_spec),+ agent_id: columns.agent_id,+ agent_spec: columns.agent_spec !== null ? jsonbBind(columns.agent_spec) : null,title: null,custom: input.custom !== null ? jsonbBind(input.custom) : null,created_at: now,@@ -98,17 +121,7 @@ export async function getSession(): Promise<ProtoSessionRecord | undefined> {const row = await db.selectFrom('session')- .select([- 'tenant_id',- 'session_id',- jsonText<AgentSpec>(sql.ref('agent_spec')).as('agent_spec'),- 'title',- 'last_turn_id',- jsonText<Record<string, unknown> | null>(sql.ref('custom')).as('custom'),- 'created_at',- 'updated_at',- 'last_activity_timestamp_ms',- ])+ .select(sessionSelectColumns).where('tenant_id', '=', input.tenant_id).where('session_id', '=', input.session_id).executeTakeFirst();@@ -121,9 +134,19 @@ export async function getSession(}export async function updateSession(db: Kysely<Database>, input: UpdateSessionInput<SessionCustom>): Promise<void> {- const agentSpec = input.agent_spec;+ const agent = input.agent;const title = input.title;+ if (agent !== undefined) {+ const existing = await getSession(db, { tenant_id: input.tenant_id, session_id: input.session_id });+ if (existing === undefined) {+ throw new SessionNotFoundError(input.session_id);+ }+ if (existing.agent.type === 'ref') {+ throw new SessionStoreInvariantError(`Session ${input.session_id} is named; agent cannot be updated`);+ }+ }+let qb = db.updateTable('session').set({@@ -133,8 +156,8 @@ export async function updateSession(db: Kysely<Database>, input: UpdateSessionIn.where('tenant_id', '=', input.tenant_id).where('session_id', '=', input.session_id);- if (agentSpec !== undefined) {- qb = qb.set({ agent_spec: jsonbBind(agentSpec) });+ if (agent !== undefined) {+ qb = qb.set({ agent_spec: jsonbBind(agent.agent_spec) });}if (title !== undefined) {qb = qb.set({ title });@@ -159,21 +182,11 @@ export async function listSessions(const offset = decodeOffsetPageToken(input.page_token);const order = input.order ?? 'desc';- let query = db- .selectFrom('session')- .select([- 'tenant_id',- 'session_id',- jsonText<AgentSpec>(sql.ref('agent_spec')).as('agent_spec'),- 'title',- 'last_turn_id',- jsonText<Record<string, unknown> | null>(sql.ref('custom')).as('custom'),- 'created_at',- 'updated_at',- 'last_activity_timestamp_ms',- ])- .where('tenant_id', '=', input.tenant_id);+ let query = db.selectFrom('session').select(sessionSelectColumns).where('tenant_id', '=', input.tenant_id);+ if (input.agent_id !== undefined) {+ query = query.where('agent_id', '=', input.agent_id);+ }if (input.start_timestamp !== undefined) {query = query.where('created_at', '>=', input.start_timestamp.toISOString());}diff --git a/packages/server/src/db/sqlite/types.ts b/packages/server/src/db/sqlite/types.tsindex b95d1fc47..a31ddc638 100644--- a/packages/server/src/db/sqlite/types.ts+++ b/packages/server/src/db/sqlite/types.ts@@ -48,7 +48,10 @@ type JsonbColumn<T extends object | null> = JSONColumnType<T, T | string, T | stexport interface SessionTable {tenant_id: string;session_id: string;- agent_spec: JsonbColumn<AgentSpec>;+ /** Named registry binding; XOR with `agent_spec`. */+ agent_id: string | null;+ /** Inline draft binding; XOR with `agent_id`. */+ agent_spec: JsonbColumn<AgentSpec> | null;title: string | null;last_turn_id: string | null;custom: JsonbColumn<Record<string, unknown>> | null;@@ -181,6 +184,22 @@ export interface SandboxProviderTable {updated_at: string;}+/**+ * Configured agents — mirrors the Postgres `agent` table.+ * PRIMARY KEY (id); UNIQUE (tenant_id, name).+ */+export interface AgentTable {+ /** application-generated (ulid); never re-derived from tenant_id/name */+ id: string;+ tenant_id: string;+ /** natural uniqueness target within a tenant */+ name: string;+ /** AgentSpec document; replaced whole on every upsert */+ manifest: JsonbColumn<AgentSpec>;+ created_at: string;+ updated_at: string;+}+/*** PRIMARY KEY (id)* UNIQUE (tenant_id, name) — the natural lookup key;@@ -240,6 +259,7 @@ export interface Database {model_provider: ModelProviderTable;skill: SkillTable;sandbox_provider: SandboxProviderTable;+ agent: AgentTable;mcp_server: McpServerTable;oauth_token: OAuthTokenTable;oauth_pending_authorization: OAuthPendingAuthorizationTable;diff --git a/packages/server/src/main.ts b/packages/server/src/main.tsindex dcf8c9075..b4c45ded7 100644--- a/packages/server/src/main.ts+++ b/packages/server/src/main.ts@@ -41,6 +41,7 @@ import { ModelCatalog } from './catalog/ModelCatalog';import { SandboxCatalog } from './catalog/SandboxCatalog';import { SkillCatalog } from './catalog/SkillCatalog';import { type DistributedServerConfiguration } from './config';+import type { IAgentStore } from './db/agentStore';import type { IMcpServerStore } from './db/mcpServerStore';import type { IModelProviderStore } from './db/modelProviderStore';import type { ISandboxProviderStore } from './db/sandboxProviderStore';@@ -58,6 +59,7 @@ interface ServerPersistence {tokenStore: IOAuthTokenStore;skillStore: ISkillStore;sandboxProviderStore: ISandboxProviderStore;+ agentStore: IAgentStore;destroyDb: () => Promise<void>;redis: RedisClientType | undefined;}@@ -79,6 +81,7 @@ async function createStandalonePersistence(options: {import('./db/sqlite/token-store/SqliteOAuthTokenStore'),import('./db/sqlite/skill-store/SqliteSkillStore'),import('./db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore'),+ import('./db/sqlite/agent-store/SqliteAgentStore'),]),]);const [@@ -88,6 +91,7 @@ async function createStandalonePersistence(options: {{ SqliteOAuthTokenStore },{ SqliteSkillStore },{ SqliteSandboxProviderStore },+ { SqliteAgentStore },] = sqliteStores;const db = createSqliteDb(sqlitePath);@@ -102,6 +106,7 @@ async function createStandalonePersistence(options: {tokenStore: new SqliteOAuthTokenStore(db),skillStore: new SqliteSkillStore(db),sandboxProviderStore: new SqliteSandboxProviderStore(db),+ agentStore: new SqliteAgentStore(db),destroyDb: () => db.destroy(),redis: undefined,};@@ -133,6 +138,7 @@ async function createDistributedPersistence(options: {import('./db/postgres/token-store/PostgresOAuthTokenStore'),import('./db/postgres/skill-store/PostgresSkillStore'),import('./db/postgres/sandbox-provider-store/PostgresSandboxProviderStore'),+ import('./db/postgres/agent-store/PostgresAgentStore'),]),]);const [@@ -142,6 +148,7 @@ async function createDistributedPersistence(options: {{ PostgresOAuthTokenStore },{ PostgresSkillStore },{ PostgresSandboxProviderStore },+ { PostgresAgentStore },] = postgresStores;const db = createDb({@@ -161,6 +168,7 @@ async function createDistributedPersistence(options: {tokenStore: new PostgresOAuthTokenStore(db),skillStore: new PostgresSkillStore(db),sandboxProviderStore: new PostgresSandboxProviderStore(db),+ agentStore: new PostgresAgentStore(db),destroyDb: () => db.destroy(),redis: await connectRedis({ url: redisUrl, logger }),};@@ -181,6 +189,7 @@ try {tokenStore,skillStore,sandboxProviderStore,+ agentStore,destroyDb,redis,} = configuration.STANDALONE@@ -201,6 +210,7 @@ try {tokenStore,skillStore,sandboxProviderStore,+ agentStore,sessionStore,sessions: new Sessions({ sessionStore }),activeTurns,diff --git a/packages/server/src/routes/agentRoutes.ts b/packages/server/src/routes/agentRoutes.tsnew file mode 100644index 000000000..ef29b9576--- /dev/null+++ b/packages/server/src/routes/agentRoutes.ts@@ -0,0 +1,136 @@+/**+ * Agent registry route definitions (mounted at /api/v1/agents).+ * Handlers are registered in apis/agents.ts.+ */+import { createRoute, z } from '@hono/zod-openapi';+import {+ AgentWriteRequestSchema,+ CreateAgentResponseSchema,+ GetAgentResponseSchema,+ ListAgentsResponseSchema,+ PutAgentResponseSchema,+ UpdateAgentRequestSchema,+} from '../schemas/agent';+import { NameSchema } from '../schemas/common';+import { RequestErrorResponseSchema } from '../schemas/errors';++const AGENTS_TAG = 'Agents';++export const AgentIdParamsSchema = z.object({+ agent_id: z.string().min(1).max(64).describe('Immutable agent identifier.'),+});++export const AgentNameParamsSchema = z.object({+ name: NameSchema.describe('Immutable unique agent name within the tenant.'),+});++export const listAgentsRoute = createRoute({+ method: 'get',+ path: '/',+ tags: [AGENTS_TAG],+ summary: 'List agents',+ description: 'All configured agents for the tenant.',+ 'x-fern-sdk-group-name': ['agents'],+ 'x-fern-sdk-method-name': 'list',+ responses: {+ 200: {+ content: { 'application/json': { schema: ListAgentsResponseSchema } },+ description: 'All configured agents.',+ },+ },+});++export const createAgentRoute = createRoute({+ method: 'post',+ path: '/',+ tags: [AGENTS_TAG],+ summary: 'Create an agent',+ description:+ 'Creates an agent and allocates an immutable id. Fails if `name` is already taken. Name cannot be changed later.',+ 'x-fern-sdk-group-name': ['agents'],+ 'x-fern-sdk-method-name': 'create',+ request: {+ body: {+ content: { 'application/json': { schema: AgentWriteRequestSchema } },+ required: true,+ },+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: CreateAgentResponseSchema } },+ description: 'The created agent.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request body or unknown model/MCP/skill refs.',+ },+ 409: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'An agent with this name already exists.',+ },+ 422: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description:+ 'The agent spec is valid but requires a capability this server does not provide (e.g. sandbox or skills).',+ },+ },+});++export const getAgentRoute = createRoute({+ method: 'get',+ path: '/{agent_id}',+ tags: [AGENTS_TAG],+ summary: 'Get an agent',+ description: 'Fetch a configured agent by immutable id.',+ 'x-fern-sdk-group-name': ['agents'],+ 'x-fern-sdk-method-name': 'get',+ request: {+ params: AgentIdParamsSchema,+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: GetAgentResponseSchema } },+ description: 'The agent.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Agent not found.',+ },+ },+});++export const putAgentRoute = createRoute({+ method: 'put',+ path: '/{name}',+ tags: [AGENTS_TAG],+ summary: 'Update an agent',+ description: 'Replaces the AgentSpec for an existing agent keyed by immutable `name`.',+ 'x-fern-sdk-group-name': ['agents'],+ 'x-fern-sdk-method-name': 'update',+ request: {+ params: AgentNameParamsSchema,+ body: {+ content: { 'application/json': { schema: UpdateAgentRequestSchema } },+ required: true,+ },+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: PutAgentResponseSchema } },+ description: 'The saved agent.',+ },+ 400: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Invalid request body or unknown model/MCP/skill refs.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Agent not found.',+ },+ 422: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description:+ 'The agent spec is valid but requires a capability this server does not provide (e.g. sandbox or skills).',+ },+ },+});diff --git a/packages/server/src/routes/sessionRoutes.ts b/packages/server/src/routes/sessionRoutes.tsindex 8a56341e6..06602c750 100644--- a/packages/server/src/routes/sessionRoutes.ts+++ b/packages/server/src/routes/sessionRoutes.ts@@ -27,7 +27,8 @@ export const createSessionRoute = createRoute({path: '/',tags: [SESSIONS_TAG],summary: 'Create a session',- description: 'Create a session holding an inline agent spec. Turns are executed against this spec.',+ description:+ 'Create a session with `agent` as either `{ type: "value", agent_spec }` (draft) or `{ type: "ref", agent_id }` (named). Named sessions resolve the live agent on each turn.','x-fern-sdk-group-name': ['sessions'],'x-fern-sdk-method-name': 'create',request: {@@ -45,6 +46,10 @@ export const createSessionRoute = createRoute({content: { 'application/json': { schema: RequestErrorResponseSchema } },description: 'Invalid request body.',},+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Named `agent_id` not found.',+ },422: {content: { 'application/json': { schema: RequestErrorResponseSchema } },description:@@ -99,7 +104,8 @@ export const updateSessionRoute = createRoute({path: '/{session_id}',tags: [SESSIONS_TAG],summary: 'Update a session',- description: "Update a session's inline agent spec. An empty body is a valid no-op that refreshes `updated_at`.",+ description:+ 'Update a draft session by replacing `agent` with a value arm. Named (ref) sessions reject agent updates. An empty body is a valid no-op that refreshes `updated_at`.','x-fern-sdk-group-name': ['sessions'],'x-fern-sdk-method-name': 'update',request: {@@ -116,7 +122,7 @@ export const updateSessionRoute = createRoute({},400: {content: { 'application/json': { schema: RequestErrorResponseSchema } },- description: 'Invalid request body.',+ description: 'Invalid request body, or named session rejected an agent update.',},404: {content: { 'application/json': { schema: RequestErrorResponseSchema } },@@ -136,7 +142,7 @@ export const listSessionsRoute = createRoute({tags: [SESSIONS_TAG],summary: 'List sessions',description:- 'List sessions (newest first by default), token-paginated. Pass `page_token` to fetch the next page, keeping the other query params constant.',+ 'List sessions (newest first by default), token-paginated. Optional `agent_id` filters to sessions bound to that named agent. Pass `page_token` to fetch the next page, keeping the other query params constant.','x-fern-sdk-group-name': ['sessions'],'x-fern-sdk-method-name': 'list','x-fern-pagination': TOKEN_PAGINATION,diff --git a/packages/server/src/routes/turnRoutes.ts b/packages/server/src/routes/turnRoutes.tsindex 7afef5ef1..574e908a2 100644--- a/packages/server/src/routes/turnRoutes.ts+++ b/packages/server/src/routes/turnRoutes.ts@@ -146,7 +146,7 @@ Use \`previous_turn_id\` to chain to the session's last turn (defaults to \`auto422: {content: { 'application/json': { schema: RequestErrorResponseSchema } },description:- 'The session is valid but a required resource is no longer available (e.g. model, MCP server, skill, or sandbox provider).',+ 'The session is valid but a required resource is no longer available (e.g. named agent, model, MCP server, skill, or sandbox provider).',},},});diff --git a/packages/server/src/schemas/agent.ts b/packages/server/src/schemas/agent.tsnew file mode 100644index 000000000..c4129c7be--- /dev/null+++ b/packages/server/src/schemas/agent.ts@@ -0,0 +1,38 @@+/**+ * Configured agent domain + wire schemas: identity columns plus an AgentSpec+ * manifest document. AgentSpec remains owned by harness; this module only adds+ * registry identity (`id`, `name`).+ */+import { z } from '@hono/zod-openapi';+import { AgentSpecSchema, type AgentSpec } from '@truefoundry/utils-core/agent-session';+import { NameSchema } from './common';++/** Create body: unique immutable `name` plus full AgentSpec. `id` is never client-supplied. */+export const AgentWriteRequestSchema = AgentSpecSchema.extend({+ name: NameSchema,+}).openapi('AgentWriteRequest');++/** Update body: full AgentSpec replacement. Name is the path key and is immutable. */+export const UpdateAgentRequestSchema = AgentSpecSchema.openapi('UpdateAgentRequest');++/** List/get/create/update response item: immutable `id`, unique immutable `name`, and AgentSpec fields. */+export const AgentSchema = AgentSpecSchema.extend({+ id: z.string().min(1).describe('Immutable server-generated agent identifier.'),+ name: NameSchema.describe('Immutable unique agent name within the tenant.'),+}).openapi('Agent');++export const CreateAgentResponseSchema = z.object({ data: AgentSchema }).openapi('CreateAgentResponse');+export const PutAgentResponseSchema = z.object({ data: AgentSchema }).openapi('PutAgentResponse');+export const ListAgentsResponseSchema = z.object({ data: z.array(AgentSchema) }).openapi('ListAgentsResponse');+export const GetAgentResponseSchema = z.object({ data: AgentSchema }).openapi('GetAgentResponse');++export type AgentWriteRequest = z.infer<typeof AgentWriteRequestSchema>;+export type UpdateAgentRequest = z.infer<typeof UpdateAgentRequestSchema>;+export type Agent = z.infer<typeof AgentSchema>;++/** Strip registry identity; remaining fields are the persisted AgentSpec document. */+export function toAgentManifest(request: AgentWriteRequest): AgentSpec {+ const { name, ...manifest } = request;+ void name;+ return manifest;+}diff --git a/packages/server/src/schemas/session.ts b/packages/server/src/schemas/session.tsindex adbbeb6b1..9a543e2f9 100644--- a/packages/server/src/schemas/session.ts+++ b/packages/server/src/schemas/session.ts@@ -42,6 +42,7 @@ export const ListSessionsRequestQuerySchema = zend_timestamp: IsoTimestampQueryParam.optional().describe('Inclusive upper bound on `created_at` (ISO-8601 / RFC 3339).',),+ agent_id: z.string().min(1).optional().describe('When set, only sessions bound to this agent id are returned.'),}).openapi('ListSessionsRequestQuery');diff --git a/packages/server/tests/db/agentStoreContractSuite.ts b/packages/server/tests/db/agentStoreContractSuite.tsnew file mode 100644index 000000000..afc9c7a23--- /dev/null+++ b/packages/server/tests/db/agentStoreContractSuite.ts@@ -0,0 +1,126 @@+/**+ * Backend-agnostic behavioural contract for IAgentStore.+ * Runs under jest against a fresh store per test (see backend test files).+ */+import { AgentSpecSchema, type AgentSpec } from '@truefoundry/utils-core/agent-session';+import { AgentNameConflictError, type IAgentStore } from '../../src/db/agentStore';++const TENANT = 'default';++function manifest(overrides: Partial<AgentSpec> = {}): AgentSpec {+ return AgentSpecSchema.parse({+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'Be helpful.',+ ...overrides,+ });+}++const ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;++export function runAgentStoreContractSuite(getStore: () => IAgentStore): void {+ it('createAgent allocates an id and round-trips the manifest', async () => {+ const store = getStore();+ const created = await store.createAgent({+ tenant_id: TENANT,+ name: 'research',+ manifest: manifest(),+ });++ expect(created.tenant_id).toBe(TENANT);+ expect(created.name).toBe('research');+ expect(created.id.length).toBeGreaterThan(0);+ expect(created.manifest).toEqual(manifest());+ expect(created.created_at).toMatch(ISO_UTC);+ expect(created.updated_at).toBe(created.created_at);++ const byName = await store.getAgent({ tenant_id: TENANT, name: 'research' });+ expect(byName).toEqual(created);++ const byId = await store.getAgent({ tenant_id: TENANT, id: created.id });+ expect(byId).toEqual(created);+ });++ it('getAgent returns undefined for unknown id or name', async () => {+ const store = getStore();+ expect(await store.getAgent({ tenant_id: TENANT, id: 'missing' })).toBeUndefined();+ expect(await store.getAgent({ tenant_id: TENANT, name: 'missing' })).toBeUndefined();+ });++ it('updateAgent by name replaces manifest but keeps id, name, and created_at', async () => {+ const store = getStore();+ const created = await store.createAgent({+ tenant_id: TENANT,+ name: 'research',+ manifest: manifest(),+ });++ const replacement = manifest({ instructions: 'Updated instructions.' });+ const updated = await store.updateAgent({+ tenant_id: TENANT,+ name: 'research',+ manifest: replacement,+ });++ expect(updated).toEqual(+ expect.objectContaining({+ id: created.id,+ name: 'research',+ manifest: replacement,+ created_at: created.created_at,+ }),+ );+ expect(updated).toBeDefined();+ if (updated === undefined) {+ throw new Error('expected updateAgent to return a record');+ }+ expect(Date.parse(updated.updated_at)).toBeGreaterThanOrEqual(Date.parse(created.updated_at));++ expect(await store.getAgent({ tenant_id: TENANT, name: 'research' })).toEqual(updated);+ });++ it('updateAgent returns undefined for unknown names', async () => {+ const store = getStore();+ expect(+ await store.updateAgent({+ tenant_id: TENANT,+ name: 'missing',+ manifest: manifest(),+ }),+ ).toBeUndefined();+ });++ it('createAgent throws AgentNameConflictError on name clash', async () => {+ const store = getStore();+ await store.createAgent({ tenant_id: TENANT, name: 'research', manifest: manifest() });++ await expect(+ store.createAgent({ tenant_id: TENANT, name: 'research', manifest: manifest() }),+ ).rejects.toBeInstanceOf(AgentNameConflictError);+ });++ it('listAgents returns only the tenant, ordered by name', async () => {+ const store = getStore();+ await store.createAgent({ tenant_id: TENANT, name: 'zeta', manifest: manifest() });+ await store.createAgent({+ tenant_id: TENANT,+ name: 'alpha',+ manifest: manifest({ instructions: 'Alpha agent.' }),+ });+ await store.createAgent({ tenant_id: 'other-tenant', name: 'research', manifest: manifest() });++ const agents = await store.listAgents(TENANT);+ expect(agents.map(agent => agent.name)).toEqual(['alpha', 'zeta']);+ expect(agents.every(agent => agent.tenant_id === TENANT)).toBe(true);+ });++ it('getAgent by id is tenant-scoped', async () => {+ const store = getStore();+ const created = await store.createAgent({+ tenant_id: TENANT,+ name: 'research',+ manifest: manifest(),+ });++ expect(await store.getAgent({ tenant_id: 'other-tenant', id: created.id })).toBeUndefined();+ });+}diff --git a/packages/server/tests/db/postgres/agent-store/contract.test.ts b/packages/server/tests/db/postgres/agent-store/contract.test.tsnew file mode 100644index 000000000..6bec7045c--- /dev/null+++ b/packages/server/tests/db/postgres/agent-store/contract.test.ts@@ -0,0 +1,35 @@+import { sql } from 'kysely';++import { PostgresAgentStore } from '../../../../src/db/postgres/agent-store/PostgresAgentStore';+import { runAgentStoreContractSuite } from '../../agentStoreContractSuite';+import { createPostgresTestDatabase, type PostgresTestDatabase } from '../testDatabase';++const describePg = process.env['PG_STORE_TESTS_ENABLED'] === '1' ? describe : describe.skip;++describePg('PostgresAgentStore (IAgentStore contract)', () => {+ let env: PostgresTestDatabase | undefined;++ beforeAll(async () => {+ env = await createPostgresTestDatabase();+ if (env === undefined) {+ throw new Error('Postgres test environment unavailable despite globalSetup probe');+ }+ }, 120_000);++ afterAll(async () => {+ await env?.teardown();+ });++ beforeEach(async () => {+ if (env !== undefined) {+ await sql`TRUNCATE TABLE agent CASCADE`.execute(env.db);+ }+ });++ runAgentStoreContractSuite(() => {+ if (env === undefined) {+ throw new Error('Postgres test environment not initialized');+ }+ return new PostgresAgentStore(env.db);+ });+});diff --git a/packages/server/tests/db/sqlite/agent-store/contract.test.ts b/packages/server/tests/db/sqlite/agent-store/contract.test.tsnew file mode 100644index 000000000..88fe1a387--- /dev/null+++ b/packages/server/tests/db/sqlite/agent-store/contract.test.ts@@ -0,0 +1,17 @@+import { SqliteAgentStore } from '../../../../src/db/sqlite/agent-store/SqliteAgentStore';+import { runAgentStoreContractSuite } from '../../agentStoreContractSuite';+import { createSqliteTestDatabase, type SqliteTestDatabase } from '../testDatabase';++describe('SqliteAgentStore (IAgentStore contract)', () => {+ let env: SqliteTestDatabase;++ beforeEach(async () => {+ env = await createSqliteTestDatabase();+ }, 120_000);++ afterEach(async () => {+ await env?.teardown();+ });++ runAgentStoreContractSuite(() => new SqliteAgentStore(env.db));+});diff --git a/packages/server/tests/unit/apis/agents.test.ts b/packages/server/tests/unit/apis/agents.test.tsnew file mode 100644index 000000000..ace5cddd2--- /dev/null+++ b/packages/server/tests/unit/apis/agents.test.ts@@ -0,0 +1,114 @@+import { createAgentsRouter } from '../../../src/apis/agents';+import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';+import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';+import { createSqliteDb } from '../../../src/db/sqlite/client';+import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';+import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';+import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';+import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';++const modelProviderBody = {+ type: 'anthropic' as const,+ name: 'anthropic',+ auth: { api_key: 'sk-ant-secret' },+ models: [+ {+ model_id: 'claude-sonnet-4-6',+ name: 'claude-sonnet-4-6',+ properties: { context_length: 200000, max_output_tokens: 32768 },+ },+ ],+};++const writeBody = {+ name: 'research',+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'Be helpful.',+};++const updateBody = {+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'Updated instructions.',+};++function jsonInit(method: string, body: unknown): RequestInit {+ return {+ method,+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ };+}++describe('agents router', () => {+ let router: ReturnType<typeof createAgentsRouter>;++ beforeAll(async () => {+ const db = createSqliteDb(':memory:');+ await migrateSqliteToLatest(db);+ const modelProviderStore = new SqliteModelProviderStore(db);+ await modelProviderStore.upsertProvider({+ tenant_id: 'default',+ name: modelProviderBody.name,+ manifest: {+ type: modelProviderBody.type,+ auth: modelProviderBody.auth,+ models: modelProviderBody.models,+ },+ });+ router = createAgentsRouter({+ agentStore: new SqliteAgentStore(db),+ modelProviderStore,+ mcpServerStore: new SqliteMcpServerStore(db),+ skillStore: new SqliteSkillStore(db),+ sandboxProviderStore: new SqliteSandboxProviderStore(db),+ });+ });++ it('POST returns a flattened Agent; PUT by immutable name keeps the same id', async () => {+ const created = await router.request('/', jsonInit('POST', writeBody));+ expect(created.status).toBe(200);+ const createdJson = (await created.json()) as {+ data: { id: string; name: string; model: { name: string }; instructions?: string };+ };+ // HTTP wire flattens store.manifest onto the response; id is allocated server-side.+ expect(createdJson.data.id.length).toBeGreaterThan(0);+ expect(createdJson.data).toMatchObject({+ name: 'research',+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'Be helpful.',+ });++ const updated = await router.request('/research', jsonInit('PUT', updateBody));+ expect(updated.status).toBe(200);+ const updatedJson = (await updated.json()) as {+ data: { id: string; name: string; instructions?: string };+ };+ expect(updatedJson.data.id).toBe(createdJson.data.id);+ expect(updatedJson.data.instructions).toBe('Updated instructions.');+ });++ it('GET returns 404 for unknown ids; PUT returns 404 for unknown names', async () => {+ const get = await router.request('/missing-agent-id');+ expect(get.status).toBe(404);++ const put = await router.request('/missing-agent', jsonInit('PUT', updateBody));+ expect(put.status).toBe(404);+ });++ it('POST rejects invalid bodies, unknown models, and duplicate names', async () => {+ const badName = await router.request('/', jsonInit('POST', { ...writeBody, name: 'Not A Name' }));+ expect(badName.status).toBe(400);++ const unknownModel = await router.request(+ '/',+ jsonInit('POST', { ...writeBody, name: 'other', model: { name: 'missing/model' } }),+ );+ expect(unknownModel.status).toBe(422);++ const first = await router.request('/', jsonInit('POST', { ...writeBody, name: 'alpha' }));+ expect(first.status).toBe(200);++ const clash = await router.request('/', jsonInit('POST', { ...writeBody, name: 'alpha' }));+ expect(clash.status).toBe(409);+ });+});diff --git a/packages/server/tests/unit/apis/deletedSessionCrud.test.ts b/packages/server/tests/unit/apis/deletedSessionCrud.test.tsindex 42f87783d..1638b934b 100644--- a/packages/server/tests/unit/apis/deletedSessionCrud.test.ts+++ b/packages/server/tests/unit/apis/deletedSessionCrud.test.ts@@ -6,6 +6,7 @@ import { createLogger } from 'winston';import { createSessionsRouter, TENANT_ID } from '../../../src/apis/sessions';import { createTurnsRouter } from '../../../src/apis/turns';import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';+import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';import { createSqliteDb } from '../../../src/db/sqlite/client';import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';@@ -28,6 +29,7 @@ describe('public CRUD after session deletion', () => {const mcpServerStore = new SqliteMcpServerStore(db);const tokenStore = new SqliteOAuthTokenStore(db);const skillStore = new SqliteSkillStore(db);+ const agentStore = new SqliteAgentStore(db);const sandboxProviderStore = new SqliteSandboxProviderStore(db);const app = new OpenAPIHono();@@ -40,6 +42,7 @@ describe('public CRUD after session deletion', () => {modelProviderStore,mcpServerStore,skillStore,+ agentStore,sandboxProviderStore,redis: createClient(),requestReplyRouter: new RequestReplyRouter(),@@ -55,6 +58,7 @@ describe('public CRUD after session deletion', () => {mcpServerStore,tokenStore,skillStore,+ agentStore,eventSubscriptions: new EventSubscriptionRegistry(undefined),sandboxProviderStore,logger: createLogger({ silent: true }),@@ -64,10 +68,13 @@ describe('public CRUD after session deletion', () => {await sessionStore.createSession({tenant_id: TENANT_ID,session_id: 's1',- agent_spec: AgentSpecSchema.parse({- model: { name: 'test-provider/test-model' },- instructions: 'test',- }),+ agent: {+ type: 'value',+ agent_spec: AgentSpecSchema.parse({+ model: { name: 'test-provider/test-model' },+ instructions: 'test',+ }),+ },custom: null,});expect((await app.request('/s1', { method: 'DELETE' })).status).toBe(204);diff --git a/packages/server/tests/unit/apis/sessionHttp.test.ts b/packages/server/tests/unit/apis/sessionHttp.test.tsnew file mode 100644index 000000000..6dca87fa4--- /dev/null+++ b/packages/server/tests/unit/apis/sessionHttp.test.ts@@ -0,0 +1,163 @@+import { OpenAPIHono } from '@hono/zod-openapi';+import { AgentSpecSchema, Sessions } from '@truefoundry/utils-core/agent-session';+import { RequestReplyRouter } from '@truefoundry/utils-core/request-reply';+import { createClient } from 'redis';+import { createSessionsRouter, TENANT_ID } from '../../../src/apis/sessions';+import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';+import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';+import { createSqliteDb } from '../../../src/db/sqlite/client';+import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';+import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';+import { SqliteSandboxProviderStore } from '../../../src/db/sqlite/sandbox-provider-store/SqliteSandboxProviderStore';+import { SqliteSessionStore } from '../../../src/db/sqlite/session-store/SqliteSessionStore';+import { SqliteSkillStore } from '../../../src/db/sqlite/skill-store/SqliteSkillStore';+import { ActiveTurnRegistry } from '../../../src/runtime/activeTurns';++const draftSpec = AgentSpecSchema.parse({+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'draft',+});++function jsonInit(method: string, body: unknown): RequestInit {+ return {+ method,+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ };+}++describe('sessions HTTP agent binding', () => {+ let app: OpenAPIHono;+ let agentStore: SqliteAgentStore;++ beforeEach(async () => {+ const db = createSqliteDb(':memory:');+ await migrateSqliteToLatest(db);+ const sessionStore = new SqliteSessionStore(db);+ const sessions = new Sessions({ sessionStore });+ const modelProviderStore = new SqliteModelProviderStore(db);+ const mcpServerStore = new SqliteMcpServerStore(db);+ const skillStore = new SqliteSkillStore(db);+ const sandboxProviderStore = new SqliteSandboxProviderStore(db);+ agentStore = new SqliteAgentStore(db);++ await modelProviderStore.upsertProvider({+ tenant_id: TENANT_ID,+ name: 'anthropic',+ manifest: {+ type: 'anthropic',+ auth: { api_key: 'sk-ant-secret' },+ models: [+ {+ model_id: 'claude-sonnet-4-6',+ name: 'claude-sonnet-4-6',+ properties: { context_length: 200000, max_output_tokens: 32768 },+ },+ ],+ },+ });++ app = new OpenAPIHono();+ app.route(+ '/',+ createSessionsRouter({+ sessions,+ sessionStore,+ activeTurns: new ActiveTurnRegistry(),+ modelProviderStore,+ mcpServerStore,+ skillStore,+ agentStore,+ sandboxProviderStore,+ redis: createClient(),+ requestReplyRouter: new RequestReplyRouter(),+ }),+ );+ });++ it('creates a draft session from a value agent', async () => {+ const res = await app.request('/', jsonInit('POST', { agent: { type: 'value', agent_spec: draftSpec } }));+ expect(res.status).toBe(201);+ const json = (await res.json()) as {+ data: { id: string; agent: { type: string; agent_spec?: { instructions?: string } } };+ };+ expect(json.data.agent.type).toBe('value');+ expect(json.data.agent.agent_spec?.instructions).toBe('draft');+ });++ it('returns 404 when creating a session for an unknown agent_id', async () => {+ const missing = await app.request('/', jsonInit('POST', { agent: { type: 'ref', agent_id: 'does-not-exist' } }));+ expect(missing.status).toBe(404);+ });++ it('creates a named ref session and filters list by agent_id', async () => {+ const agent = await agentStore.createAgent({+ tenant_id: TENANT_ID,+ name: 'named-agent',+ manifest: AgentSpecSchema.parse({+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'from-registry',+ }),+ });++ const created = await app.request('/', jsonInit('POST', { agent: { type: 'ref', agent_id: agent.id } }));+ expect(created.status).toBe(201);+ const json = (await created.json()) as {+ data: { id: string; agent: { type: string; agent_id?: string } };+ };+ expect(json.data.agent).toEqual({ type: 'ref', agent_id: agent.id });++ const listed = await app.request(`/?agent_id=${encodeURIComponent(agent.id)}`);+ expect(listed.status).toBe(200);+ const listJson = (await listed.json()) as {+ data: Array<{ id: string; agent: { type: string; agent_id?: string } }>;+ };+ expect(listJson.data.every(row => row.agent.type === 'ref' && row.agent.agent_id === agent.id)).toBe(true);+ expect(listJson.data.some(row => row.id === json.data.id)).toBe(true);+ });++ it('rejects PATCH agent on a session bound by agent_id', async () => {+ const agent = await agentStore.createAgent({+ tenant_id: TENANT_ID,+ name: 'named-agent',+ manifest: AgentSpecSchema.parse({+ model: { name: 'anthropic/claude-sonnet-4-6' },+ instructions: 'from-registry',+ }),+ });++ const created = await app.request('/', jsonInit('POST', { agent: { type: 'ref', agent_id: agent.id } }));+ expect(created.status).toBe(201);+ const json = (await created.json()) as { data: { id: string } };++ const patchNamed = await app.request(+ `/${json.data.id}`,+ jsonInit('PATCH', { agent: { type: 'value', agent_spec: { ...draftSpec, instructions: 'nope' } } }),+ );+ expect(patchNamed.status).toBe(400);+ });++ it('allows PATCH agent_spec on draft sessions', async () => {+ const created = await app.request('/', jsonInit('POST', { agent: { type: 'value', agent_spec: draftSpec } }));+ expect(created.status).toBe(201);+ const { data } = (await created.json()) as { data: { id: string } };++ const patched = await app.request(+ `/${data.id}`,+ jsonInit('PATCH', { agent: { type: 'value', agent_spec: { ...draftSpec, instructions: 'updated' } } }),+ );+ expect(patched.status).toBe(200);+ const patchedJson = (await patched.json()) as {+ data: { agent: { type: string; agent_spec?: { instructions?: string } } };+ };+ expect(patchedJson.data.agent.agent_spec?.instructions).toBe('updated');+ });++ it('rejects create bodies that mix ref and value agent fields', async () => {+ const both = await app.request(+ '/',+ jsonInit('POST', { agent: { type: 'ref', agent_id: 'x', agent_spec: draftSpec } }),+ );+ expect(both.status).toBe(400);+ });+});diff --git a/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts b/packages/server/tests/unit/apis/turnStreamAfterDelete.test.tsindex 6324d8336..7e04699cd 100644--- a/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts+++ b/packages/server/tests/unit/apis/turnStreamAfterDelete.test.ts@@ -4,6 +4,7 @@ import { AgentSpecSchema, TurnNotFoundError } from '@truefoundry/utils-core/agenimport { createLogger } from 'winston';import { createTurnsRouter } from '../../../src/apis/turns';import { migrateSqliteToLatest } from '../../../src/db/migrateSqlite';+import { SqliteAgentStore } from '../../../src/db/sqlite/agent-store/SqliteAgentStore';import { createSqliteDb } from '../../../src/db/sqlite/client';import { SqliteMcpServerStore } from '../../../src/db/sqlite/mcp-server-store/SqliteMcpServerStore';import { SqliteModelProviderStore } from '../../../src/db/sqlite/model-provider-store/SqliteModelProviderStore';@@ -42,11 +43,16 @@ describe('turn SSE after session deletion', () => {},});+ const agentSpec = AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } });const sessions = {get: () =>Promise.resolve({- agent_spec: AgentSpecSchema.parse({ model: { name: 'test-provider/test-model' } }),- record: { last_turn_id: null },+ agent_spec: agentSpec,+ record: {+ session_id: 's1',+ last_turn_id: null,+ agent: { type: 'value', agent_spec: agentSpec },+ },createTurn: () =>Promise.resolve({id: 'turn-gone',@@ -68,6 +74,7 @@ describe('turn SSE after session deletion', () => {mcpServerStore: new SqliteMcpServerStore(db),tokenStore: new SqliteOAuthTokenStore(db),skillStore: new SqliteSkillStore(db),+ agentStore: new SqliteAgentStore(db),eventSubscriptions: new EventSubscriptionRegistry(undefined),sandboxProviderStore: new SqliteSandboxProviderStore(db),logger,