# Golem Multi Instance Agent TS

> Golem Multi Instance Agent TS is an Agent Skill for agent building published in the golemcloud/golem repository on GitHub: a SKILL.md instruction file an AI agent can load to do this task.

Using phantom agents in TypeScript to create multiple agent instances with the same constructor parameters. Use when the user needs multiple distinct agents sharing constructor values, or asks about phantom agents, phantom IDs, getPhantom/newPhantom, or multi-instance agents in TypeScript.

- Skill name: `golem-multi-instance-agent-ts`
- Category: [Agent Building](https://www.openparable.com/skill/agent-building/1)
- Source: https://github.com/golemcloud/golem/blob/HEAD/golem-skills/skills/ts/golem-multi-instance-agent-ts/SKILL.md
- Repository: golemcloud/golem (1,605 GitHub stars when collected)

## SKILL.md

# Phantom Agents in TypeScript

Phantom agents allow creating **multiple distinct agent instances** that share the same identity (`id` record) values. Normally, an agent is uniquely identified by its `id` record — addressing it with the same id values always reaches the same agent. Phantom agents add an extra **phantom ID** (a UUID) to the identity, so you can have many independent instances with identical id values.

## Agent ID Format

A phantom agent's ID appends the phantom UUID in square brackets:

```
agent-type(param1, param2)[a09f61a8-677a-40ea-9ebe-437a0df51749]
```

A non-phantom agent ID has no bracket suffix:

```
agent-type(param1, param2)
```

## Creating and Addressing Phantom Agents (RPC)

You address another agent with a typed RPC client built from its `defineAgent` definition via `clientFor(Def)`. The returned factory takes the id record and an **optional phantom UUID**:

```typescript
clientFor(Def)(id)                       // non-phantom: same agent for the same id
clientFor(Def)(id, phantomUuid)          // phantom: addressed by id + a specific UUID
clientFor(Def)(id, phantomUuid, config)  // + per-call non-secret config overrides (config-on-RPC)
clientFor(Def).newPhantom(id, config?)    // new phantom with a generated UUID
```

| Call | Description |
|--------|-------------|
| `client(id)` | Get or create a **non-phantom** agent identified solely by its id record |
| `client.newPhantom(id)` | Create a **new phantom** agent and return `{ client, phantomId }` |
| `client(id, savedUuid)` | Get or create a phantom agent with a **specific** UUID |
| `client(id, undefined, { foo })` | Override the target's non-secret config for this call (secrets stay host-provisioned) |

Each method on the client has, besides the awaited call: `.trigger(input)` (fire-and-forget) and `.schedule(at, input) → CancellationToken`. Cancel an awaited invocation with the normal call shape's trailing `{ signal }` option: `method(input, { signal })`, or `method({ signal })` for a method with no input.

### Example

```typescript
import { z } from 'zod';
import { defineAgent, method, clientFor, Uuid } from '@golemcloud/golem-ts-sdk';

export const Counter = defineAgent({
    name: 'Counter',
    id: { name: z.string() },
    methods: { increment: method({ input: {}, returns: z.number() }) },
});

Counter.implement({
    init: () => ({ count: 0 }),
    methods: {
        increment() {
            this.count += 1;
            return this.count;
        },
    },
});

// --- In another agent, using the RPC client factory: ---
const counters = clientFor(Counter);

// Non-phantom: always the same agent for the same name
const shared = counters({ name: 'shared' });
await shared.increment();

// New phantom: the factory returns the client and its generated UUID.
const { client: phantom1, phantomId: phantomId1 } = counters.newPhantom({
    name: 'shared',
});
const { client: phantom2 } = counters.newPhantom({ name: 'shared' });
// phantom1 and phantom2 are different agents, both with name="shared"

// Reconnect to an existing phantom by its UUID.
const samePhantom = counters({ name: 'shared' }, phantomId1);

// A persisted UUID string can be restored later.
const restoredPhantom = counters(
    { name: 'shared' },
    Uuid.parse(savedUuidString),
);
```

Persist the phantom UUID yourself (as a string via `uuid.toString()`, reparsed with `Uuid.parse(...)`) whenever you need to reach the same phantom instance again later.

## Querying the Phantom ID from Inside an Agent

A handler can check its own phantom ID via `this.getPhantomId()`:

```typescript
export const MyAgent = defineAgent({
    name: 'MyAgent',
    id: { name: z.string() },
    methods: { whoAmI: method({ input: {}, returns: z.string() }) },
});

MyAgent.implement({
    init: () => ({}),
    methods: {
        whoAmI() {
            const phantom = this.getPhantomId(); // Uuid | undefined
            return phantom
                ? `I am a phantom agent with ID: ${phantom.toString()}`
                : 'I am a regular agent';
        },
    },
});
```

## HTTP-Mounted Phantom Agents

When an agent is mounted as an HTTP endpoint, set `phantomAgent: true` in the mount options to make every incoming HTTP request create a **new phantom instance** automatically:

```typescript
import { http } from '@golemcloud/golem-ts-sdk';

export const RequestHandler = defineAgent({
    name: 'RequestHandler',
    id: { name: z.string() },
    http: http.mount('/api/{name}', { phantomAgent: true }),
    methods: { /* ... */ },
});
```

Each HTTP request will be handled by a fresh agent instance with its own phantom ID, even though all instances share the same id values.

## Key Points

- Phantom agents are **fully durable** — they persist just like regular agents.
- The phantom ID is a standard UUID; prefer `client.newPhantom(id)` for a fresh one, and use `Uuid.parse(str)` to restore a saved one or `Uuid.generate()` when the caller must choose the ID itself.
- Reaching a phantom with the same UUID and id values always returns the same agent (idempotent).
- Phantom and non-phantom agents with the same id values are **different agents** — they do not share state.

---

Source: https://www.openparable.com/skill/agent-building/golem-multi-instance-agent-ts (OpenParable). Cite the canonical URL above.
