# Temporal Continuity: AI Coding Integration Guide

This guide is intended for developers using an AI coding assistant to integrate the **Temporal Continuity** hosted service into an application.

## What to install

Use the supported TypeScript SDK, **not** an MCP adapter. Choose one integration path:

**Standard Temporal Continuity SDK**

```bash
npm install temporal-continuity
```

**Temporal Continuity + TC-Fast** for durable local conversation history and separate canonical publication:

```bash
npm install temporal-continuity tc-fast
```

TC-Fast is an optional companion to the same hosted API and uses the same Temporal Continuity credentials and relationship identities.

Requirements: a Node.js application with a server-side runtime, a Temporal Continuity developer account, an API key, and the organization, project, and environment identifiers from the developer console.

## Server-side configuration

Configure these values in the application's server environment (for local development, use a git-ignored environment file):

```dotenv
TEMPORAL_CONTINUITY_API_KEY=your_api_key
TEMPORAL_CONTINUITY_BASE_URL=https://api.rscapex.com
TEMPORAL_CONTINUITY_ORGANIZATION_ID=your_organization_id
TEMPORAL_CONTINUITY_PROJECT_ID=your_project_id
TEMPORAL_CONTINUITY_ENVIRONMENT_ID=your_environment_id
```

Never expose the API key in browser bundles, client components, logs, or a repository.

## Initialize the SDK

```ts
import { RMS } from "temporal-continuity";

export const rms = new RMS({
  apiKey: process.env.TEMPORAL_CONTINUITY_API_KEY,
  baseUrl: process.env.TEMPORAL_CONTINUITY_BASE_URL,
  organizationId: process.env.TEMPORAL_CONTINUITY_ORGANIZATION_ID,
  projectId: process.env.TEMPORAL_CONTINUITY_PROJECT_ID,
  environmentId: process.env.TEMPORAL_CONTINUITY_ENVIRONMENT_ID,
});
```

Run this code only on the server.

## Standard SDK conversation lifecycle

Temporal continuity must be part of the application's **deterministic request lifecycle**, not an optional model-selected tool call.

1. Authenticate the application's user and resolve their authorized, stable relationship identity. Do not create a new relationship on every turn.
2. Before cognition, load the relationship's authorized context with the SDK or use the supported provider-neutral composition pathway.
3. Supply the retrieved context to the chosen cognition provider in a controlled, auditable way.
4. Record the interaction through the supported contribution/composition pathway. Confirm persistence and capture its receipt before treating the turn as committed.
5. Handle retries using stable idempotency keys. Reuse a key only for a retry of the same operation.
6. Test session clearing, process restart, returning users, provider changes, duplicate requests, and failed commits. Do not silently claim a turn was persisted when the commit failed.

For a managed user, the SDK supports provider-neutral composition with an application-supplied cognition callback:

```ts
await rms.compose({
  userId,
  content: "Remember that I prefer concise answers.",
  idempotencyKey: crypto.randomUUID(),
  cognition: async projection => invokeRegisteredCognition(projection),
});
```

`userId` must be the stable, provisioned application user identifier; `invokeRegisteredCognition` is **your application's** provider integration, not a function supplied by the SDK. Adapt the callback to the actual provider and SDK response contracts.

## Optional TC-Fast conversation lifecycle

Choose TC-Fast when your application should return the generated response after **durable local acceptance**, then publish the completed human/AI pair to canonical Temporal Continuity separately.

The `tc-fast` package supplies `TCFast` and durable storage adapters for SQLite, PostgreSQL (including Supabase) and Firestore. Your application supplies the cognition callback and operates the delivery schedule.

### Select durable storage

Choose an adapter that fits the application:

| Storage | Import | Setup |
|---|---|---|
| SQLite | `tc-fast/sqlite` | Persistent SQLite database; install `better-sqlite3` or use supported Node 22+ `node:sqlite` |
| PostgreSQL / Supabase | `tc-fast/postgres` | Existing server-side PostgreSQL pool; apply the `tc-fast/postgres.sql` migration |
| Firestore | `tc-fast/firestore` | Firebase Admin Firestore and the required indexes |

For the SQLite example:

```bash
npm install better-sqlite3
```

### Integrate TC-Fast on the server

Use the `rms` client initialized above and an existing enrolled `userId` and `relationshipId`. The code below illustrates the conversation handler and delivery worker. Supply your application's actual cognition-provider function.

```ts
import { randomUUID } from "node:crypto";
import Database from "better-sqlite3";
import { TCFast } from "tc-fast";
import { createSQLiteStorage } from "tc-fast/sqlite";
import { rms } from "./temporal-continuity-client";

const db = new Database("./working-history.sqlite");
const storage = createSQLiteStorage({ db, scope: rms.scope });

export const fast = new TCFast({
  tc: rms,
  storage,
  cognition: async projection => {
    const result = await invokeRegisteredCognition(projection);
    return {
      text: result.text,
      provider: result.provider,
      model: result.model,
      invocationId: result.invocationId,
      ...(result.responseId ? { responseId: result.responseId } : {}),
    };
  },
});

// From your authenticated conversation handler:
export async function replyWithContinuity(
  userId: string,
  relationshipId: string,
  content: string,
  idempotencyKey: string,
) {
  return fast.converse({ userId, relationshipId, content, idempotencyKey });
}

// From a scheduled server worker, and again on startup:
export async function publishPendingConversations() {
  return fast.drain({ limit: 20 });
}
```

Generate and retain an idempotency key for each new conversation turn (for example, `randomUUID()` when accepting a new request). Use the **same** key on retries of that turn. The provider callback receives the authorized Temporal Continuity projection combined with recently accepted local history.

`fast.converse()` returns `responseText`, `acceptance: "durable"` and a `canonical` status of `"pending"` or `"published"`. The application can return `responseText` after the storage adapter confirms acceptance. `fast.drain()` publishes pending pairs through the hosted service, records canonical receipts, and returns counts of attempted, published and failed deliveries.

Call `drain()` on application startup and from an independently scheduled worker. Persist and monitor pending pairs so failed delivery can resume after a restart.

### Canonical publication endpoint

```http
POST https://api.rscapex.com/v1/relationships/{relationshipId}/conversation-pairs
```

`fast.drain()` calls this endpoint through the existing `RMS` client. For direct API callers, the request requires a Temporal Continuity Bearer credential with `contributions:write` authorization, the appropriate relationship permissions, and an `Idempotency-Key` header. The JSON body supplies `organizationId`, `projectId`, `environmentId`, `userId`, `human.content`, and `ai` with `content`, `provider`, `model`, `invocationId` and optional `responseId`.

A successful HTTP 200 response includes `completed: true`, `canonical: "published"`, `relationshipId`, `conversationId`, `humanContributionId`, `aiContributionId` and `responseText`. Reuse the identical idempotency key and pair content for publication retries.

Temporal Continuity remains authoritative for canonical contributions, relational memory and Continuity Credit enforcement.

### Instructions to give your AI coding assistant for TC-Fast

> Integrate the published `temporal-continuity` and `tc-fast` packages into my application's **server-side** conversation lifecycle. First inspect the current authentication, enrolled user identity, relationship resolution, cognition provider, database and deployment scheduler. Reuse one authorized relationship identity for each user. Select and configure a durable TC-Fast storage adapter appropriate to the existing database. Construct `TCFast` with the existing `RMS` client, the storage adapter and our provider callback. Route new turns through `fast.converse()` with stable idempotency keys; return its durably accepted `responseText`. Set up `fast.drain()` on startup and on a recurring worker schedule to publish pending conversation pairs and persist canonical receipts. Verify continuity across restart, provider changes, duplicate requests, retry failures and recovery. Keep Temporal Continuity credentials server-side. Do not add an MCP adapter, invent SDK methods, or replace the hosted continuity service. Show all changed files and executable tests. Consult the public package documentation and current API reference.

## Instructions to give your AI coding assistant

**Standard SDK prompt:**

> Integrate the `temporal-continuity` TypeScript SDK into my application's server-side conversation lifecycle. First inspect my existing authentication, user identity, conversation handler, and cognition provider integration. Reuse authorized relationship identities. Hydrate context before cognition and ensure contribution persistence is confirmed after each turn, using supported SDK operations and idempotency. Keep credentials server-side. Do not introduce an MCP integration or model-optional memory tool calls. Show the files changed, the error-handling behavior, and tests proving continuity across sessions, retries, and provider changes. Do not invent SDK methods; consult the current SDK reference.

## References

- [TypeScript SDK quickstart](/developers/typescript)
- [SDK methods and API routes](/developers/reference)
- [Developer console](/console/enroll)
- [TC-Fast on npm](https://www.npmjs.com/package/tc-fast)
- [Installation and optional TC-Fast API](/console/install)

**Scope:** Both paths integrate with the hosted Temporal Continuity service. The standard path commits turns through the SDK composition workflow; the optional TC-Fast path durably accepts local conversation pairs and publishes them using the hosted API.
