# Temporal

> The xmemory Temporal plugin — durable agent memory as replay-safe Temporal Activities, in Python and TypeScript.

Canonical page: https://xmemory.ai/temporal/

[Temporal](https://docs.temporal.io/) runs long-lived, crash-proof workflows; xmemory stores durable, schema-grounded memory your agents can recall across runs, users, and services. The **xmemory Temporal plugin** wires the two together so a memory read or write becomes a replay-safe Temporal Activity — added to your Worker with a single line.

It ships in two languages that mirror each other:

- **Python** — [`xmemory-temporal`](https://pypi.org/project/xmemory-temporal/) on PyPI ([source](https://github.com/xmemory-ai/xmemory-temporal))
- **TypeScript** — [`@xmemory/temporal`](https://www.npmjs.com/package/@xmemory/temporal) on npm ([source](https://github.com/xmemory-ai/xmemory-temporal-ts))

> An agent's memory is exactly the state you don't want to lose when a worker crashes mid-turn. Putting xmemory behind Temporal makes a memory write a durable step: it survives process death, redeploys, and rolling upgrades, and Temporal — not your code — owns its retries and timeouts.

## What you get

- **Memory as Activities.** `read`, `write`, `write_async` + `write_status` run as Activities, so all network I/O stays out of Workflow code and Workflows replay deterministically.
- **A durable write.** `write_durable(text)` enqueues a write and polls it to completion from the Workflow, so a multi-minute extraction survives worker restarts — the poll state lives in Workflow history, not a worker process.
- **A near-zero-diff migration.** The Workflow-side handle mirrors the plain xmemory client, so agent code that already calls `inst.read(...)` / `inst.write(...)` keeps working — it just dispatches to an Activity.
- **Temporal-owned retries.** xmemory errors map to typed `ApplicationFailure`s with retryable / non-retryable verdicts (see below), so you tune `RetryPolicy` against stable error-type strings.
- **Opt-in auto-capture** of Activity results into memory, via an Activity interceptor that never touches the replay path.

## Prerequisites

- Python 3.10+ with `temporalio` 1.30+, or Node.js 22.12+ with the `@temporalio/*` 1.20 packages
- A local Temporal dev server or a Temporal Cloud namespace
- An xmemory API key and cluster

Start a local Temporal server with the [Temporal CLI](https://docs.temporal.io/cli):

```bash
temporal server start-dev
```

Set your xmemory API key:

```bash
export XMEM_API_KEY="your-xmemory-api-key"
```

Install the plugin:

```bash
# Python
pip install xmemory-temporal pyyaml

# TypeScript
npm install @xmemory/temporal
```

## Create an xmemory instance

xmemory stores information in typed *instances*. An agent can author the [XMD schema](https://xmemory.ai/xmd/)
directly or describe the intended memory and let xmemory generate it, then create an instance from
the result. Choose primary keys the agent will naturally restate in text—a person's full name, or a
literal `customer_id` / `interaction_id` you supply—so writes can update the same record when
xmemory extracts the same key.

```python
import os

import yaml
from xmemory import SchemaType, XmemoryClient

with XmemoryClient(api_key=os.environ["XMEM_API_KEY"]) as client:
    cluster_id = client.admin.list_clusters()[0].id

    schema = client.admin.generate_schema(
        cluster_id,
        (
            "Track customer-support memory. Customers are identified by customer_id. "
            "Support interactions are identified by interaction_id and record the "
            "message, recalled context, response, and outcome. Make customer_id and "
            "interaction_id primary keys so repeated writes update the same records."
        ),
    )

    instance = client.admin.create_instance(
        cluster_id=cluster_id,
        name="temporal-support-memory",
        schema_text=yaml.dump(schema.data_schema, allow_unicode=True),
        schema_type=SchemaType.YML,
    )
    print(instance.id)
```

Run it once and save the printed instance id:

```bash
export XMEM_INSTANCE_ID="the-returned-instance-id"
```

You can also create and manage instances in the [xmemory console](https://console.xmemory.ai/). See the [Python SDK guide](https://xmemory.ai/python/) for other schema and instance-management options.

## Quickstart — Python

Register the plugin on the **Client**; the Worker inherits it automatically.

```python
from temporalio.client import Client
from temporalio.worker import Worker
from xmemory_temporal import XmemoryConfig, XmemoryPlugin

from workflows import CustomerSupportWorkflow

config = XmemoryConfig(instance_id="<your-instance-id>")  # reads XMEM_API_KEY from the env
plugin = XmemoryPlugin(config)

client = await Client.connect("localhost:7233", plugins=[plugin])
# The Worker inherits the client's plugins automatically — do NOT pass it again here.
worker = Worker(client, task_queue="xmemory-support", workflows=[CustomerSupportWorkflow])
await worker.run()
```

Inside the Workflow, `xmemory_for_workflow()` returns a handle whose methods dispatch to Activities:

```python
from temporalio import workflow

with workflow.unsafe.imports_passed_through():
    from xmemory_temporal import xmemory_for_workflow

@workflow.defn
class CustomerSupportWorkflow:
    @workflow.run
    async def run(self, customer_id: str, interaction_id: str, message: str) -> str:
        mem = xmemory_for_workflow()

        # A memory store has no ambient "current user" — name whom the fact is
        # about, then recall by that name (or pass scope= to bind to a record).
        context = await mem.read(f"What should support know about {customer_id}?")

        # ... handle the request (put any LLM call in its own Activity) ...
        response = f"Interaction {interaction_id} recorded for {customer_id}."

        # A durable write: enqueue + poll to completion, surviving worker restarts.
        await mem.write_durable(
            f"interaction_id: {interaction_id}. customer_id: {customer_id}. "
            f"message: {message}. response: {response}. status: completed."
        )
        return str(context.reader_result)  # reader_result is Any
```

## Quickstart — TypeScript

Register the plugin on the **Worker** (the TS plugin is a `WorkerPlugin`; the client does not carry it).

```ts

const plugin = new XmemoryPlugin({ instanceId: '<your-instance-id>' }); // reads XMEM_API_KEY
const connection = await NativeConnection.connect({ address: 'localhost:7233' });
const worker = await Worker.create({
  connection,
  taskQueue: 'xmemory-support',
  workflowsPath: require.resolve('./workflows'),
  plugins: [plugin],
});
await worker.run();
```

```ts
// workflows.ts

export async function customerSupportWorkflow(
  customerId: string,
  interactionId: string,
  message: string,
): Promise<unknown> {
  const mem = xmemoryForWorkflow();

  const context = await mem.read(`What should support know about ${customerId}?`);
  const response = `Interaction ${interactionId} recorded for ${customerId}.`;

  await mem.writeDurable(
    `interaction_id: ${interactionId}. customer_id: ${customerId}. ` +
      `message: ${message}. response: ${response}. status: completed.`,
  );
  return context.readerResult;
}
```

Workflow code imports from **`@xmemory/temporal/workflow`**, not the package root. That subpath reaches no Activity code and no xmemory client, so Temporal's Workflow bundler accepts it. The root entry loads the plugin and the client, so it belongs in Worker setup only.

> **Register the plugin once, never twice.** In Python, put it on the Client (the Worker inherits it) — passing it to both registers the Activities twice and fails with *"More than one activity named xmemory_read"*. In TypeScript, put it on the Worker. Use one plugin instance per Worker.

## Durable writes

An xmemory extraction can take minutes. `write_durable` enqueues the write and then polls its status **from the Workflow**, so the wait is a Temporal timer in server-side history rather than a blocked activity slot:

```python
status = await mem.write_durable(text, max_wait=timedelta(minutes=15))
```
```ts
const status = await mem.writeDurable(text, { maxWaitMs: 15 * 60_000 });
```

Because the poll loop lives in Workflow history, you can redeploy the worker fleet mid-write and nothing is lost — the loop resumes on the new worker and completes. Under the time-skipping test environment a 15-minute write runs in milliseconds, because Temporal fast-forwards the timers. For the fire-and-forget pattern (kick off several writes, keep talking, join before the turn ends), `write_async_start()` and `write_status()` are public too.

## Timeouts

**The Workflow owns every activity budget.** `xmemory_for_workflow()` sets each call's `start_to_close_timeout`, and the Activity derives its xmemory client timeout from the deadline Temporal actually assigned it — always a margin below, so the client gives up first and you get an attributable xmemory error rather than an opaque Temporal activity timeout.

```python
mem = xmemory_for_workflow(
    read_timeout=timedelta(seconds=60),   # a long read on a large instance
    write_timeout=timedelta(minutes=5),
)
```
```ts
const mem = xmemoryForWorkflow({ readTimeout: '60s', writeTimeout: '5m' });
```

Because the client timeout is *derived* rather than configured separately, the two can never disagree: lowering a Workflow's budget lowers the client's with it. The defaults are 120s for reads, 180s for writes, and 30s for the enqueue and each status poll; the gap between the activity deadline and the client timeout is the one knob that stays worker-side (`client_margin_seconds` / `clientMarginMs`).

## Replay safety and idempotency

Two things keep memory operations correct under retries and replay:

- **Replay never re-issues an operation.** All I/O is in Activities; Workflow code only schedules Activities and sleeps. Temporal replays Workflow code but never re-runs a completed Activity, so a replay never repeats a memory read or write. The test suite proves this with a forced-replay (`max_cached_workflows=0`) side-effects test.
- **Writes default to at-most-once.** Write Activities default to `maximum_attempts=1`, so your Workflow decides whether a write is retried; give records keys the text states literally, such as `customer_id`. Reads and status-polls (idempotent) retry generously.

**Structured writes are the reliable way to make a write retryable.** Pass explicit mutations instead of free text and the primary key is one you supply, so nothing is extracted and re-applying the write is deterministic:

```python
mem = xmemory_for_workflow(write_retry_policy=RetryPolicy(maximum_attempts=3))
await mem.write(structured_mutations=[
    {"object_mutation": {"object_type": "Customer",
                         "update": {"key": {"customer_id": "c-1"}, "values": {"tier": "gold"}}}}
])
```
```ts
const mem = xmemoryForWorkflow({ writeRetryPolicy: { maximumAttempts: 3 } });
await mem.write('', {
  structuredMutations: [
    { object_mutation: { object_type: 'Customer', update: { key: { customerId: 'c-1' }, values: { tier: 'gold' } } } },
  ],
});
```

An object mutation is a `create`, `update`, or `delete` and carries the key explicitly, so a retry addresses the same row instead of forking a new one. An object `update` in particular re-applies identically. Relations can be created, updated, or deleted through explicit endpoints.

For text writes, opt into retries only when your primary keys are literal identifiers that appear verbatim in the text, such as a `customer_id` you supply, so the extractor has no room to normalise them differently on a second pass. That is a convention you have to keep, not something the API enforces.

[**Scoped writes**](https://xmemory.ai/api/#scoped-writes) in the xmemory API bind a text write to a record you name up front, but the plugin's write methods do not take a `scope`; only `read` does. Through the plugin, use structured mutations when a write has to be retryable.

This is why the support example above builds its write text from literal `customer_id` / `interaction_id` values — with those as schema primary keys, opting into retries is safe.

## Error handling

xmemory errors become `ApplicationFailure`s with stable `type` strings you can match in a `RetryPolicy` (`non_retryable_error_types=[...]` / `nonRetryableErrorTypes`). The mapping is derived from the server's own error codes:

| xmemory condition | `type` | Retryable? |
|---|---|---|
| transport error / timeout / HTTP ≥ 500 / 408 | `XmemoryServerError` / `XmemoryUnavailable` | yes |
| `RATE_LIMITED` (429) | `XmemoryRateLimited` | yes — honors `Retry-After` |
| `QUOTA_EXCEEDED` + daily | `XmemoryDailyQuotaExceeded` | yes (long backoff) |
| `QUOTA_EXCEEDED` + monthly | `XmemoryMonthlyQuotaExceeded` | no |
| `QUOTA_EXCEEDED` (kind unknown) | `XmemoryQuotaExceeded` | no |
| `UNAUTHORIZED` / `FORBIDDEN` | `XmemoryAuthFailed` | no |
| `NOT_FOUND` | `XmemoryNotFound` | no |
| validation / conflict / schema-evolution rejections | `XmemoryBadRequest` / `XmemorySchemaRejected` | no |
| Activities registered without the plugin | `XmemoryNotBound` | no |
| an Activity scheduled with neither close timeout | `XmemoryNoDeadline` | no |
| durable-write options that cannot be honored (TypeScript) | `XmemoryBadOptions` | no |
| an unrecognized code | `XmemoryUnknown` | Python: yes · TypeScript: follows the HTTP status |

Plus three raised by the durable-write loop from a polled `write_status`, all non-retryable: `XmemoryWriteFailed` (the queued write reported `failed`), `XmemoryWriteNotFound` (the write id was not found), and `XmemoryWriteTimeout` (polling exceeded `max_wait`).

An unrecognized error code never raises — a stricter client that crashed on a newer server's code would break during rolling deploys. Python retries it. TypeScript decides from the HTTP status: 5xx, 408, 429 and a missing status are retried, and any other 4xx is terminal.

## Credentials and privacy

The config holds the **name** of the environment variable that supplies the API key (`XMEM_API_KEY` by default), never the key itself — so nothing secret is serialized into Activity arguments, which Temporal persists in the clear. Pass the key in-process instead with `XmemoryPlugin(config, api_key=...)` / `new XmemoryPlugin(config, { apiKey })` if you prefer.

**Your memory text and queries, however, *are* in history.** The query you `read` and the text you `write` are Activity inputs, and the error mapping keeps raw transport strings out of failure *messages* — but the inputs themselves, and the `reader_result`, are persisted to cleartext Temporal history and shown in the Web UI. If your memory text is sensitive, install a Temporal **Payload Codec** to encrypt payloads at the edge — the plugin deliberately does not impose one, since a codec applies namespace-wide to every payload, not just xmemory's.

## Auto-capture (opt-in)

Instead of writing memory explicitly, you can capture the results of your own Activities into memory automatically:

```python
from xmemory_temporal import AutoCaptureConfig, XmemoryPlugin

plugin = XmemoryPlugin(
    config,
    auto_capture=AutoCaptureConfig(
        project=lambda activity_name, result: summarize(result),  # return None to skip
        sample_rate=0.25,
    ),
)
```

Off by default. It runs as an **Activity** interceptor (outside the replay path), requires a `project` function that decides what — if anything — to remember, samples to bound fan-out, and never fails the wrapped Activity if a capture write errors. Capture is an enqueue (`write_async`) bounded by a short timeout, so it can never slow the wrapped Activity past its `start_to_close`. It skips any Activity whose name starts with `xmemory_`, and never captures Queries.

## Production checklist

- Register the plugin once (Python: on the Client; TypeScript: on the Worker), one instance per Worker.
- Prefer `write_durable` when a later step needs the write to land; use `read` for recall.
- Keep write retries off unless your primary keys are literal identifiers present verbatim in the text.
- Match `RetryPolicy(non_retryable_error_types=...)` to the typed error strings above.
- Set activity budgets on `xmemory_for_workflow()` — raise them for long reads or large writes rather than leaving a call to time out.
- Return only the minimum recalled context — Activity results are recorded in Workflow history.
- Install a Payload Codec if memory text is sensitive.
- Keep Temporal and xmemory credentials in a secret manager, never in Workflow arguments.

The plugin source lives on GitHub — [xmemory-temporal](https://github.com/xmemory-ai/xmemory-temporal) (Python) and [xmemory-temporal-ts](https://github.com/xmemory-ai/xmemory-temporal-ts) (TypeScript). For the underlying client APIs, see the [Python](https://xmemory.ai/python/) and [TypeScript](https://xmemory.ai/typescript/) SDK guides. For the raw tool surface, see the [MCP](https://xmemory.ai/mcp/) guide.
