> ## Documentation Index
> Fetch the complete documentation index at: https://cognitio-agent.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Continue a conversation

> Close a local session handle and resume the same conversation.

Send a fact, close its session handle, then resume the same transcript and ask the model to recall it. One client keeps the runtime alive through both turns. The complete code is below. You can also [browse the project on GitHub](https://github.com/ozgurugurlu/cognitio-agent-sdk/tree/main/examples/04-session-memory) or [open its JavaScript source](https://github.com/ozgurugurlu/cognitio-agent-sdk/blob/main/examples/04-session-memory/index.mjs).

## 1. Create the project

Use Node.js 22 or newer, npm, and an OpenAI API key with access to `gpt-4.1-mini`. Model requests use your provider account and can incur charges.

```sh theme={null}
mkdir cognitio-memory
cd cognitio-memory
npm init -y
npm install --save-exact cognitio-agent-sdk@2.0.1
```

Keep npm optional dependencies enabled; they include the runtime for your platform. You do not need a separately installed runtime.

## 2. Configure the environment

Create a file named `.env` in this directory:

```dotenv theme={null}
COGNITIO_MODEL=openai/gpt-4.1-mini
OPENAI_API_KEY=replace_with_your_key
```

Replace the placeholder with your key. Add `.env` and `node_modules/` to `.gitignore`. Existing shell environment values take precedence over this file. To use Anthropic instead, set `COGNITIO_MODEL=anthropic/claude-sonnet-4-5` and `ANTHROPIC_API_KEY` to your Anthropic key; the code forwards either provider's credential.

## 3. Create `index.mjs`

```js theme={null}
import { createAgentClient } from "cognitio-agent-sdk"

const model = process.env.COGNITIO_MODEL?.trim() || "openai/gpt-4.1-mini"
const credential = { openai: "OPENAI_API_KEY", anthropic: "ANTHROPIC_API_KEY" }[model.split("/")[0]]
if (!model.includes("/")) throw new Error("Set COGNITIO_MODEL to a provider/model identifier.")
if (credential && (!process.env[credential]?.trim() || process.env[credential] === "replace_with_your_key")) {
  throw new Error(`Set ${credential} in .env or your shell before running this example.`)
}
const providerEnv = Object.fromEntries(
  ["OPENAI_API_KEY", "ANTHROPIC_API_KEY"]
    .filter((name) => process.env[name]?.trim())
    .map((name) => [name, process.env[name]]),
)

// This client owns one isolated runtime. Closing a session handle leaves its
// transcript available here; closing this client removes the isolated state.
const client = await createAgentClient({
  spawn: {
    isolated: true,
    port: 0,
    autoCleanup: true,
    env: { ...providerEnv, COGNITIO_DISABLE_AUTOUPDATE: "1", COGNITIO_DISABLE_LSP_DOWNLOAD: "1" },
    config: { plugin: [], lsp: false, formatter: false, agent: { title: { disable: true } } },
  },
})

try {
  const session = await client.sessions.create({
    title: "Database memory example",
    runtimeConfig: {
      model,
      instructions: "Remember facts from this conversation and answer briefly. Do not call tools.",
      settingSources: [],
      includeEnvironment: false,
      disallowedTools: ["*"],
      maxTurns: 1,
      maxBudgetUsd: 0.03,
    },
  })
  const saved = await session.send("Remember that this project uses PostgreSQL. Reply with Saved.")
  if (saved.subtype !== "success") throw new Error(`First turn failed: ${saved.subtype}`)
  const sessionId = session.id
  await session.close()

  const resumed = await client.sessions.resume(sessionId)
  if (resumed.id !== sessionId) throw new Error("The resumed session ID changed.")
  const recalled = await resumed.send("Which database did I name? Reply only with the database name.")
  if (recalled.subtype !== "success") throw new Error(`Recall failed: ${recalled.subtype}`)
  if (typeof recalled.text !== "string" || !recalled.text.toLowerCase().includes("postgresql")) {
    throw new Error("The resumed conversation did not recall PostgreSQL.")
  }
  console.log(`Resumed the same session: ${sessionId}`)
  console.log(`Remembered database: ${recalled.text.trim()}`)
  await resumed.close()
} finally {
  await client.close()
}
```

## 4. Run it

```sh theme={null}
node --env-file=.env index.mjs
```

A successful run prints:

```text theme={null}
Resumed the same session: ses_...
Remembered database: PostgreSQL
```

The session ID changes on each program run. The script checks that the resumed ID matches the first handle and that the answer mentions PostgreSQL. It throws if either check fails. The program makes two model requests.

## How it works

`session.close()` releases the local handle and callbacks without normally deleting the server transcript. `client.sessions.resume(sessionId)` attaches a new handle while the same client and runtime remain alive.

The application owns this low-level client and closes it in `finally`. Closing it removes the default isolated scratch state. Running the program again starts a new runtime; saving the session ID alone does not preserve the conversation across restarts.

For cross-process persistence, use a [persistent runtime](https://cognitio-agent.mintlify.site/cookbook/remote.md) or explicitly managed local state. Runtime policy and callback registrations must be restored after their process restarts. See [sessions](https://cognitio-agent.mintlify.site/concepts/sessions.md).

`Session.send()` accepts the prompt only. To cancel an active session turn from your application, call `session.interrupt()` on that handle. The session permits one assistant turn per request and uses an estimated \$0.03 budget; provider charges depend on actual usage.

## Use the existing project

If you prefer the [complete GitHub project](https://github.com/ozgurugurlu/cognitio-agent-sdk/tree/main/examples/04-session-memory), copy that directory, run `npm ci`, copy `.env.example` to `.env`, set your key, and run `npm start`. On PowerShell, use `Copy-Item .env.example .env`; in a Unix shell, use `cp .env.example .env`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.