Golem add http endpoint ts

From golemcloud/golem · View interactive version

Golem add http endpoint ts is an AI agent skill from the GitHub repository golemcloud/golem. Exposing a TypeScript Golem agent over HTTP. Use when the user asks to add HTTP endpoints, mount an agent to a URL path, or expose agent methods as a REST API.

How to use this skill

Skill file

Adding HTTP Endpoints to a TypeScript Golem Agent

Overview

Golem agents can be exposed over HTTP using code-first route definitions. This involves:

  1. Adding an http mount to defineAgent(...) with http.mount(...)
  2. Attaching http: http.<verb>(...) endpoints to methods declared with method(...)
  3. Adding an httpApi deployment section to golem.yaml (load the golem-configure-api-domain skill)

Related Skills

| Skill | When to Load |

|---|---|

| golem-http-params-ts | Path/query/header variable mapping, body mapping, supported types, response mapping |

| golem-make-http-request-ts | Making outgoing HTTP requests from agent code, especially when calling other Golem agent endpoints (required for correct JSON body formatting) |

| golem-add-http-auth-ts | Enabling authentication and receiving Principal |

| golem-add-cors-ts | Configuring CORS allowed origins |

| golem-configure-api-domain | Setting up httpApi in golem.yaml, security schemes, domain deployments, and subdomain versus domain choices |

Steps

  1. Add http: http.mount(...) to defineAgent(...)
  2. Add http: http.<verb>(...) to the methods you want to expose
  3. Add httpApi deployment to golem.yaml (see golem-configure-api-domain skill)
  4. Build and deploy

Mount Path

The http field on defineAgent(...) defines the base HTTP path via http.mount(...). Path variables in {braces} map to the agent's id record fields:

import { z } from 'zod';
import { defineAgent, method, http } from '@golemcloud/golem-ts-sdk';

export const TaskAgent = defineAgent({
  name: 'TaskAgent',
  id: { name: z.string() },
  http: http.mount('/api/tasks/{name}'),
  methods: {
    // ...
  },
});

Rules:

The key mount path template is template-literal typed: an ordinary {var} that does not match an id field (or an id field with no matching {var}) is a tsc error, not just a runtime failure. System variables do not count as id fields. Passing a dynamically built (non-literal) string widens to string and defers to the runtime checks.

Required Agent ID Mounts and Creation

Use an ID mount to address an existing durable, non-router agent without constructor inputs in the URL:

http: http.mount('/tasks/{instance}', {
  agentId: http.agentId.path('instance'),
  create: '/tasks/create',
}),

For query addressing, use http.mount('/tasks', { agentId: http.agentId.query('instance'), create: '/tasks/create' }). The ID is required; there is no optional binding or keyed fallback. ID mounts cannot bind constructor fields or combine with phantomAgent or ephemeral mode. The query ID name is reserved from explicit and implicit method query bindings and protocol controls.

create declares a full exact POST path, not a mount suffix, and requires an ID mount. Only literals and system variables are allowed in this path. Send a JSON object with one field per user-supplied constructor parameter, as an endpoint body has one field per method parameter, for example {"name": "first"}; an optional parameter may be left out. Other fields, such as env, config or keyed, are rejected with 400. The new agent has no key. Route authentication does not grant configuration authority. Use authorized operator REST creation or SDK creation for overrides. Creation inherits mount authentication/CORS, waits for the constructor, and returns 201 Created with agentId/agentFingerprint JSON and an ID-mounted Location. Current HTTP callers have no caller scope, even with authentication, so Idempotency-Key is ignored; retries create new unkeyed agents.

ID selection never creates an agent. File serving supports both key and ID mounts but is lookup-only: missing keys and unknown, deleted, wrong-type or wrong-environment IDs return terminal 404, without creation or handler fallback. Missing files on an existing target retain normal mapping fallback.

Endpoint Declaration

Attach an http endpoint to a method with one of the verb builders (http.get, http.post, http.put, http.del, http.patch, or http.custom):

methods: {
  listItems: method({ input: {}, returns: z.array(Item), http: http.get('/items') }),

  createItem: method({
    input: { name: z.string(), count: z.number() },
    returns: Item,
    http: http.post('/items'),
  }),

  updateItem: method({
    input: { id: z.string(), name: z.string() },
    returns: Item,
    http: http.put('/items/{id}'),
  }),

  deleteItem: method({ input: { id: z.string() }, returns: z.void(), http: http.del('/items/{id}') }),

  patchItem: method({
    input: { id: z.string(), patch: PatchData },
    returns: Item,
    http: http.custom('PATCH', '/items/{id}'),
  }),
}

Endpoint paths are relative to the mount path. To expose a method under multiple routes, pass an array: http: [http.get('/items'), http.get('/all')].

For details on how path variables, query parameters, headers, and request bodies map to method inputs, load the golem-http-params-ts skill.

Durable Stream Route Customization

For a method with stream inputs or outputs, pass durableStreams in the endpoint options:

http: http.post('/events', {
  durableStreams: {
    slots: [
      { source: 'input', slot: 'input', name: 'uploads' },
      {
        source: 'output',
        slot: '$result',
        name: 'events',
        contentType: 'application/vnd.example.events',
      },
    ],
    load: {
      maxConcurrentReadersPerStream: 8,
      maxAppendRequestsPerSecondPerStream: 25,
    },
  },
}),

Phantom Agents

On a key mount, set phantomAgent: true to select a fresh unkeyed identity for each HTTP request. Requests can run on separate instances. Identity and lifecycle mode are independent: the default mode is durable; add mode: 'ephemeral' to defineAgent for ephemeral per-request execution. Neither policy can be combined with an ID mount.

export const GatewayAgent = defineAgent({
  name: 'GatewayAgent',
  id: { name: z.string() },
  http: http.mount('/gateway/{name}', { phantomAgent: true }),
  methods: { /* each HTTP request gets its own agent instance */ },
});

Return Type to HTTP Response Mapping

Golem maps a method's returned value to HTTP status codes and response bodies according to the table below. This mapping is currently not configurable. In the TypeScript SDK the return shape is declared by the method's returns schema.

| Returned value / returns schema | HTTP Status | Response Body |

|---|---|---|

| z.void() / no value | 204 No Content | empty |

| any schema T | 200 OK | JSON-serialized T |

| T.nullable() / T.optional() | 200 OK if value, 404 Not Found if null / undefined | JSON T or empty |

| s.option(T) | 200 OK if value, 404 Not Found if undefined | JSON T or empty |

| s.result(ok, err) returning Result.ok / Result.err | 200 OK if Ok, 500 Internal Server Error if Err | JSON ok or JSON err |

| s.result(s.option(T), err) | 200 OK if Result.ok(value), 404 if Result.ok(undefined), 500 if Result.err | JSON T, empty, or JSON err |

| s.unstructuredBinary() | 200 OK (url → 307 redirect) | Raw binary with Content-Type |

| s.unstructuredText() | 200 OK (url → 307 redirect) | text/plain; charset=utf-8 (+ optional Content-Language) |

The value inside an option or Result.ok follows the same rules as a top-level value: s.unstructuredBinary() / s.unstructuredText() wrapped in s.option(...), s.result(..., err), or s.result(s.option(...), err) is sent as the raw body, not as JSON. Use s.option(...) around unstructured markers; zod .nullable() / .optional() wrappers cannot wrap them. A guarded raw download (raw bytes / 404 / JSON error 500):

download: method({
  input: { id: z.string() },
  returns: s.result(s.option(s.unstructuredBinary({ mimeTypes: ['image/png'] })), z.object({ error: z.string() })),
  http: http.get('/files/{id}'),
}),

// Implementation
download({ id }) {
  if (id === 'missing') return Result.ok(undefined); // 404
  if (id === 'pending') return Result.err({ error: 'pending' }); // 500, JSON body
  return Result.ok({ tag: 'inline' as const, val: new Uint8Array([1, 2, 3]), mimeType: 'image/png' }); // 200, raw bytes
},

Complete Example

import { z } from 'zod';
import { defineAgent, method, http, s, Result } from '@golemcloud/golem-ts-sdk';

const Task = z.object({ id: z.string(), title: z.string(), done: z.boolean() });
type Task = z.infer<typeof Task>;

export const TaskAgent = defineAgent({
  name: 'TaskAgent',
  id: { name: z.string() },
  http: http.mount('/task-agents/{name}'),
  methods: {
    getTasks: method({ input: {}, returns: z.array(Task), http: http.get('/tasks') }),
    createTask: method({ input: { title: z.string() }, returns: Task, http: http.post('/tasks') }),
    getTask: method({ input: { id: z.string() }, returns: Task.nullable(), http: http.get('/tasks/{id}') }),
    completeTask: method({
      input: { id: z.string() },
      returns: s.result(Task, z.object({ error: z.string() })),
      http: http.post('/tasks/{id}/complete'),
    }),
  },
});

export const TaskAgentImpl = TaskAgent.implement({
  init: () => ({ tasks: [] as Task[] }),
  methods: {
    getTasks() {
      return this.tasks;
    },
    createTask({ title }) {
      const task: Task = { id: String(this.tasks.length + 1), title, done: false };
      this.tasks.push(task);
      return task;
    },
    getTask({ id }) {
      return this.tasks.find((t) => t.id === id) ?? null;
    },
    completeTask({ id }) {
      const task = this.tasks.find((t) => t.id === id);
      if (!task) return Result.err({ error: 'not found' });
      task.done = true;
      return Result.ok(task);
    },
  },
});
# golem.yaml (add to existing file)
httpApi:
  deployments:
    local:
    - subdomain: my-app  # resolves to my-app.localhost:9006 by default
      agents:
        TaskAgent: {}

Key Constraints

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.