The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Add GET agent code-snippets for TypeScript SDK samples (#475)
Bhavesh Patela60f4c261593
diff --git a/.changeset/agent-code-snippets.md b/.changeset/agent-code-snippets.mdnew file mode 100644index 000000000..fb10d7eff--- /dev/null+++ b/.changeset/agent-code-snippets.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge": patch+---++Add GET /api/v1/agents/{agent_id}/code-snippets with TypeScript TrueForge SDK stream and non-stream samples.diff --git a/.github/fern/openapi/openapi.json b/.github/fern/openapi/openapi.jsonindex 3f3b7202f..8ba3cb9fc 100644--- a/.github/fern/openapi/openapi.json+++ b/.github/fern/openapi/openapi.json@@ -4426,6 +4426,118 @@"x-fern-sdk-method-name": "update"}},+ "/api/v1/agents/{agent_id}/code-snippets": {+ "get": {+ "description": "TypeScript TrueForge SDK samples (stream and non-stream) for creating a session and turn against this agent.",+ "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": {+ "properties": {+ "data": {+ "additionalProperties": false,+ "properties": {+ "base_url": {+ "description": "Origin to pass as the TrueForge SDK `baseUrl`.",+ "format": "uri",+ "type": "string"+ },+ "snippets": {+ "items": {+ "additionalProperties": false,+ "properties": {+ "icon": {+ "format": "uri",+ "type": "string"+ },+ "label_name": {+ "minLength": 1,+ "type": "string"+ },+ "language": {+ "minLength": 1,+ "type": "string"+ },+ "sample_code": {+ "additionalProperties": false,+ "properties": {+ "non_stream": {+ "description": "SDK sample that creates a turn without streaming.",+ "type": "string"+ },+ "stream": {+ "description": "SDK sample that streams turn events.",+ "type": "string"+ }+ },+ "required": [+ "stream",+ "non_stream"+ ],+ "type": "object"+ }+ },+ "required": [+ "label_name",+ "language",+ "icon",+ "sample_code"+ ],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": [+ "base_url",+ "snippets"+ ],+ "type": "object"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ }+ }+ },+ "description": "TypeScript SDK samples and the origin to use as `baseUrl`."+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Agent not found."+ }+ },+ "summary": "Get agent SDK code snippets",+ "tags": [+ "Agents"+ ],+ "x-excluded": true,+ "x-fern-ignore": true+ }+ },"/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.",diff --git a/docs/openapi.json b/docs/openapi.jsonindex 3f3b7202f..8ba3cb9fc 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -4426,6 +4426,118 @@"x-fern-sdk-method-name": "update"}},+ "/api/v1/agents/{agent_id}/code-snippets": {+ "get": {+ "description": "TypeScript TrueForge SDK samples (stream and non-stream) for creating a session and turn against this agent.",+ "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": {+ "properties": {+ "data": {+ "additionalProperties": false,+ "properties": {+ "base_url": {+ "description": "Origin to pass as the TrueForge SDK `baseUrl`.",+ "format": "uri",+ "type": "string"+ },+ "snippets": {+ "items": {+ "additionalProperties": false,+ "properties": {+ "icon": {+ "format": "uri",+ "type": "string"+ },+ "label_name": {+ "minLength": 1,+ "type": "string"+ },+ "language": {+ "minLength": 1,+ "type": "string"+ },+ "sample_code": {+ "additionalProperties": false,+ "properties": {+ "non_stream": {+ "description": "SDK sample that creates a turn without streaming.",+ "type": "string"+ },+ "stream": {+ "description": "SDK sample that streams turn events.",+ "type": "string"+ }+ },+ "required": [+ "stream",+ "non_stream"+ ],+ "type": "object"+ }+ },+ "required": [+ "label_name",+ "language",+ "icon",+ "sample_code"+ ],+ "type": "object"+ },+ "type": "array"+ }+ },+ "required": [+ "base_url",+ "snippets"+ ],+ "type": "object"+ }+ },+ "required": [+ "data"+ ],+ "type": "object"+ }+ }+ },+ "description": "TypeScript SDK samples and the origin to use as `baseUrl`."+ },+ "404": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/RequestErrorResponse"+ }+ }+ },+ "description": "Agent not found."+ }+ },+ "summary": "Get agent SDK code snippets",+ "tags": [+ "Agents"+ ],+ "x-excluded": true,+ "x-fern-ignore": true+ }+ },"/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.",diff --git a/packages/trueforge/src/apis/agentCodeSnippets.ts b/packages/trueforge/src/apis/agentCodeSnippets.tsnew file mode 100644index 000000000..316fbe941--- /dev/null+++ b/packages/trueforge/src/apis/agentCodeSnippets.ts@@ -0,0 +1,35 @@+import type { AgentCodeSnippets } from '../schemas/agent';+import { typescriptNonStreamTemplate, typescriptStreamTemplate } from './codesnippet-templates/typescript';++const TYPESCRIPT_ICON = 'https://assets.production.truefoundry.com/typescript.svg';++function renderSnippetTemplate(template: string, vars: { agentName: string; baseUrl: string }): string {+ const literals: Record<string, string> = {+ agentName: JSON.stringify(vars.agentName),+ baseUrl: JSON.stringify(vars.baseUrl),+ };+ return template.replaceAll(/\{\{(\w+)\}\}/g, (match, key: string) => {+ const value = literals[key];+ if (value === undefined) {+ throw new Error(`Unknown snippet template placeholder ${match}`);+ }+ return value;+ });+}++export function buildAgentCodeSnippets(input: { agentName: string; baseUrl: string }): AgentCodeSnippets {+ return {+ base_url: input.baseUrl,+ snippets: [+ {+ label_name: 'TypeScript',+ language: 'typescript',+ icon: TYPESCRIPT_ICON,+ sample_code: {+ stream: renderSnippetTemplate(typescriptStreamTemplate, input),+ non_stream: renderSnippetTemplate(typescriptNonStreamTemplate, input),+ },+ },+ ],+ };+}diff --git a/packages/trueforge/src/apis/agents.ts b/packages/trueforge/src/apis/agents.tsindex 90255201e..bf1daf9a6 100644--- a/packages/trueforge/src/apis/agents.ts+++ b/packages/trueforge/src/apis/agents.ts@@ -12,12 +12,14 @@ import type { WithTransaction } from '../db/transaction';import {createAgentRoute,deleteAgentRoute,+ getAgentCodeSnippetsRoute,getAgentRoute,listAgentsRoute,putAgentRoute,} from '../routes/agentRoutes';import { validateAgentSpec } from '../runtime/sessionResources';import { type Agent, type CreateAgentRequest } from '../schemas/agent';+import { buildAgentCodeSnippets } from './agentCodeSnippets';import { TENANT_ID } from './sessions';export interface AgentsRouterDeps<TTransaction> {@@ -89,6 +91,23 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransacreturn c.json({ data: toWireAgent(record) }, 200);};+ const getCodeSnippetsHandler: RouteHandler<typeof getAgentCodeSnippetsRoute> = 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: buildAgentCodeSnippets({+ agentName: record.name,+ baseUrl: new URL(c.req.url).origin,+ }),+ },+ 200,+ );+ };+const deleteHandler: RouteHandler<typeof deleteAgentRoute> = async c => {const { agent_id: agentId } = c.req.valid('param');await deps.agentStore.deleteAgent({ tenant_id: TENANT_ID, id: agentId });@@ -113,6 +132,7 @@ export function createAgentsRouter<TTransaction>(deps: AgentsRouterDeps<TTransacconst router = new OpenAPIHono();router.openapi(listAgentsRoute, listHandler);router.openapi(createAgentRoute, createHandler);+ router.openapi(getAgentCodeSnippetsRoute, getCodeSnippetsHandler);router.openapi(getAgentRoute, getHandler);router.openapi(deleteAgentRoute, deleteHandler);router.openapi(putAgentRoute, putHandler);diff --git a/packages/trueforge/src/apis/codesnippet-templates/typescript.ts b/packages/trueforge/src/apis/codesnippet-templates/typescript.tsnew file mode 100644index 000000000..cd52ec1fc--- /dev/null+++ b/packages/trueforge/src/apis/codesnippet-templates/typescript.ts@@ -0,0 +1,55 @@+export const typescriptStreamTemplate = `// npm install @truefoundry/trueforge-sdk+import { TrueForge, TrueForgeApi, isEventDelta, mergeEventDelta } from "@truefoundry/trueforge-sdk";++const client = new TrueForge({+ baseUrl: {{baseUrl}},+ timeoutInSeconds: 600,+});++const { data: session } = await client.sessions.create({+ agent: { name: {{agentName}} },+});++const events = new Map<string, TrueForgeApi.TurnStreamingEvent>();+let turnId: string | undefined;+let lastSequenceNumber = 0;++const stream = await client.sessions.createTurnStream(session.id, {+ input: [{ type: "user.message", content: "Hello!" }],+});++for await (const { data: event, id } of stream.withMetadata()) {+ if (id != null) lastSequenceNumber = Number(id);+ if (event.type === "turn.created") turnId = event.turnId;+ if (isEventDelta(event)) {+ const base = events.get(event.id);+ if (base) mergeEventDelta(base, event);+ } else {+ events.set(event.id, event);+ }+ if (event.type === "turn.done") console.log("status:", event.state.status);+}+`;++export const typescriptNonStreamTemplate = `// npm install @truefoundry/trueforge-sdk+import { TrueForge } from "@truefoundry/trueforge-sdk";++const client = new TrueForge({+ baseUrl: {{baseUrl}},+ timeoutInSeconds: 600,+});++const { data: session } = await client.sessions.create({+ agent: { name: {{agentName}} },+});++const { data: turn } = await client.sessions.createTurn(session.id, {+ input: [{ type: "user.message", content: "Hello!" }],+});++console.log(turn.id, turn.state);++// Turn may still be running. Call getTurn to read a later state.+const { data: latest } = await client.sessions.getTurn(session.id, turn.id);+console.log(latest.state);+`;diff --git a/packages/trueforge/src/routes/agentRoutes.ts b/packages/trueforge/src/routes/agentRoutes.tsindex b859ef342..6655e433b 100644--- a/packages/trueforge/src/routes/agentRoutes.ts+++ b/packages/trueforge/src/routes/agentRoutes.ts@@ -6,6 +6,7 @@ import { createRoute, z } from '@hono/zod-openapi';import {CreateAgentRequestSchema,DeleteAgentResponseSchema,+ GetAgentCodeSnippetsResponseSchema,GetAgentResponseSchema,ListAgentsResponseSchema,UpdateAgentRequestSchema,@@ -73,6 +74,30 @@ export const createAgentRoute = createRoute({},});+export const getAgentCodeSnippetsRoute = createRoute({+ method: 'get',+ path: '/{agent_id}/code-snippets',+ tags: [OpenApiTag.AGENTS],+ summary: 'Get agent SDK code snippets',+ description:+ 'TypeScript TrueForge SDK samples (stream and non-stream) for creating a session and turn against this agent.',+ 'x-fern-ignore': true,+ 'x-excluded': true,+ request: {+ params: AgentIdParamsSchema,+ },+ responses: {+ 200: {+ content: { 'application/json': { schema: GetAgentCodeSnippetsResponseSchema } },+ description: 'TypeScript SDK samples and the origin to use as `baseUrl`.',+ },+ 404: {+ content: { 'application/json': { schema: RequestErrorResponseSchema } },+ description: 'Agent not found.',+ },+ },+});+export const getAgentRoute = createRoute({method: 'get',path: '/{agent_id}',diff --git a/packages/trueforge/src/schemas/agent.ts b/packages/trueforge/src/schemas/agent.tsindex b8db5a0e0..e5ad277c4 100644--- a/packages/trueforge/src/schemas/agent.ts+++ b/packages/trueforge/src/schemas/agent.ts@@ -37,6 +37,32 @@ export const GetAgentResponseSchema = z.object({ data: AgentSchema }).openapi('Gexport const ListAgentsResponseSchema = z.object({ data: z.array(AgentSchema) }).openapi('ListAgentsResponse');export const DeleteAgentResponseSchema = z.object({}).openapi('DeleteAgentResponse');+export const AgentCodeSnippetSampleCodeSchema = z+ .object({+ stream: z.string().describe('SDK sample that streams turn events.'),+ non_stream: z.string().describe('SDK sample that creates a turn without streaming.'),+ })+ .strict();++export const AgentCodeSnippetSchema = z+ .object({+ label_name: z.string().min(1),+ language: z.string().min(1),+ icon: z.url(),+ sample_code: AgentCodeSnippetSampleCodeSchema,+ })+ .strict();++export const AgentCodeSnippetsSchema = z+ .object({+ base_url: z.url().describe('Origin to pass as the TrueForge SDK `baseUrl`.'),+ snippets: z.array(AgentCodeSnippetSchema),+ })+ .strict();++export const GetAgentCodeSnippetsResponseSchema = z.object({ data: AgentCodeSnippetsSchema });+export type CreateAgentRequest = z.infer<typeof CreateAgentRequestSchema>;export type UpdateAgentRequest = z.infer<typeof UpdateAgentRequestSchema>;export type Agent = z.infer<typeof AgentSchema>;+export type AgentCodeSnippets = z.infer<typeof AgentCodeSnippetsSchema>;diff --git a/packages/trueforge/tests/unit/apis/agents.test.ts b/packages/trueforge/tests/unit/apis/agents.test.tsindex 185db7fc1..f1adefb7f 100644--- a/packages/trueforge/tests/unit/apis/agents.test.ts+++ b/packages/trueforge/tests/unit/apis/agents.test.ts@@ -120,6 +120,20 @@ describe('agents router', () => {const put = await router.request('/missing-agent-id', jsonInit('PUT', updateBody));expect(put.status).toBe(404);++ const snippets = await router.request('/missing-agent-id/code-snippets');+ expect(snippets.status).toBe(404);+ });++ it('GET code-snippets returns snippets for an existing agent', async () => {+ const created = await router.request('/', jsonInit('POST', { ...writeBody, name: 'snippet-bot' }));+ expect(created.status).toBe(201);+ const createdJson = (await created.json()) as { data: WireAgent };++ const response = await router.request(`/${createdJson.data.id}/code-snippets`);+ expect(response.status).toBe(200);+ const body = (await response.json()) as { data: { snippets: unknown[] } };+ expect(body.data.snippets.length).toBeGreaterThan(0);});it('DELETE removes an agent by id and is idempotent', async () => {