# Getting Started

Install nanocode, then run a first turn from Rust, TypeScript, or the terminal.

## Overview

nanocode is one agent runtime for the Codex and Claude harnesses. Each harness sends its provider's own prompts and tools. The runtime adds Code Mode, subagents, durable sessions, and remote hands, and it runs natively in Rust or as one WebAssembly module in Workers, browsers, and Node.

```mermaid
flowchart LR
  host[Host: Rust, TypeScript, or nc] --> runtime[Nanocode runtime]
  runtime --> codex[Codex harness]
  runtime --> claude[Claude harness]
  codex --> tools[Tools and Code Mode]
  claude --> tools
  runtime --> store[(Session store)]
```

The host builds the runtime and spawns agents. Every agent shares the runtime's tools, subagents, and session store.

## First Turn

Select the surface that matches the project. Each tab installs the SDK and runs one turn against Claude.

#### Rust

Add the facade crate and Tokio. nanocode builds with Rust 1.97 or newer.

```toml title="Cargo.toml"
[dependencies]
# The SDK facade, from the nanocode repository
nanocode = { git = "https://github.com/gakonst/nanocode" }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
```

`ClaudeClient::default()` signs requests with the login that `/login claude` stores, or with an existing Claude Code login.

```rust title="main.rs"
use nanocode::{Claude, ClaudeClient, ClaudeModel, Nanocode};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>>
{
    // 1. Build one runtime with the Claude harness
    let runtime = Nanocode::builder()
        .claude(ClaudeClient::default())
        .build_async()
        .await?;

    // 2. Spawn an agent, keeping its event stream open
    let (agent, _events) = runtime
        .spawn()
        .backend::<Claude>()
        .model(ClaudeModel::Haiku55)
        .build()
        .await?;

    // 3. Send a prompt, then await the finished turn
    let result = agent
        .prompt("Explain durable agents in two sentences.")
        .await?
        .await?;
    println!("{}", result.final_message());

    // 4. Write the session to ~/.nanocode, then stop the runtime
    agent.flush().await?;
    runtime.shutdown().await?;
    Ok(())
}
```

#### TypeScript

The `nanocode-wasm` package is not on npm. Clone it beside the SDK and build the module. The build needs Rust 1.97, the `wasm32-unknown-unknown` target, and Node 22.18 or newer.

```bash
# Build dist/nanocode_wasm.wasm from source
git clone https://github.com/gakonst/nanocode
git clone https://github.com/gakonst/nanocode-wasm
cd nanocode-wasm && npm ci && npm run build
```

Depend on it with `"nanocode-wasm": "file:../nanocode-wasm"`. The host owns storage and credentials: `SqlHost` runs the SDK's SQL, and `dispatch` adds the API key to each model request.

```ts title="host.ts"
import { readFileSync } from 'node:fs'
import { DatabaseSync, type SQLInputValue } from 'node:sqlite'
import {
  AgentRuntime,
  sessionUuid,
  type SqlHost,
  type SqlValue,
} from 'nanocode-wasm'

// 1. Run each operation's statements in one SQLite transaction
const db = new DatabaseSync('agent.sqlite')
const sql: SqlHost = {
  transaction(_kind, _operation, statements) {
    db.exec('BEGIN IMMEDIATE')
    try {
      const rows = statements.map(([query, ...values]) => {
        const statement = db.prepare(query)
        statement.setReturnArrays(true)
        return statement.all(
          ...(values as SQLInputValue[]),
        ) as unknown as SqlValue[][]
      })
      db.exec('COMMIT')
      return rows
    } catch (error) {
      db.exec('ROLLBACK')
      throw error
    }
  },
}

// 2. Instantiate the module and open a Claude session
const module = await WebAssembly.compile(
  readFileSync('node_modules/nanocode-wasm/dist/nanocode_wasm.wasm'),
)
const runtime = await AgentRuntime.instantiate(module, sql, {
  published: () => {},
})
await runtime.open(
  {
    endpoint: 'https://api.anthropic.com/v1/messages',
    provider: 'claude',
    scope: 'owner',
    session_id: sessionUuid(),
    subscription: false,
  },
  {
    dispatch: (request, signal) =>
      fetch(request.endpoint, {
        body: request.body as Uint8Array<ArrayBuffer>,
        headers: [
          ...request.headers,
          ['x-api-key', process.env.ANTHROPIC_API_KEY ?? ''],
        ],
        method: 'POST',
        redirect: 'error',
        signal,
      }),
  },
)

// 3. Queue a turn, then drive it until nothing is pending
await runtime.submit('owner', {
  metadata: {},
  prompt: 'Explain durable agents.',
  request_id: 'turn-1',
})
for (;;) {
  const next = (await runtime.pending('owner'))[0]
  if (!next) break
  const driven = await runtime.drive(next.report.request_id)
  if (driven.retry)
    throw new Error('reopen the runtime from its checkpoint')
  if (driven.waiting)
    await new Promise((resolve) => setTimeout(resolve, 100))
}
console.log((await runtime.turn('owner', 'turn-1'))?.report)
await runtime.dispose()
```

#### CLI

Install the `nanocode` binary from the repository, then link `nc` to it.

```bash
# Install the CLI, then add the nc alias
cargo install --locked --git https://github.com/gakonst/nanocode nanocode-cli
ln -s "$(command -v nanocode)" "$(dirname "$(command -v nanocode)")/nc"
```

Open the terminal interface in a project, sign in once, then type a prompt.

```bash
# Open the interface, then run /login claude or /login codex inside it
nc
```

## Next Steps

- [Agents and Turns](/docs/guides/agents): Build a runtime, spawn agents, and drive turns.

- [Tools](/docs/guides/tools): Offer Rust and TypeScript functions to the model.

- [Events](/docs/guides/events): Stream and read the events a session logs.

- [Durability](/docs/guides/durability): Store sessions and reopen them by ID.
