> ## Documentation Index
> Fetch the complete documentation index at: https://docs.declaw.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript API builder

> Agent scaffolds an Express API, compiles with tsc, runs it as a background process, and hits it with curl.

## Use case

Verify that an agent can author and run TypeScript code end to
end: write sources, install deps, compile, start a long-running
server, smoke-test it with curl — all inside a Node 20 sandbox.

## Template

`node` — Node 20, npm, TypeScript, tsc on PATH. No pip, no Python.

## Run it

```bash theme={null}
export DECLAW_API_KEY=dcl_...
export DECLAW_DOMAIN=api.declaw.ai
export OPENAI_API_KEY=sk-...

python cookbook/examples/openai-agents-typescript-api/main.py
```

## Security policy

```python theme={null}
SecurityPolicy(
    injection_defense=InjectionDefenseConfig(enabled=True, sensitivity="medium", domains=["api.openai.com"]),
    network=NetworkPolicy(
        allow_out=[
            "api.openai.com",
            "registry.npmjs.org",
            "*.npmjs.org",       # pattern: any npm mirror subdomain
        ],
    ),
)
```

The server the agent writes binds to `127.0.0.1` inside the VM and
is only reachable with curl from within the same sandbox —
outbound network policy doesn't need to allow it because nothing
outside the VM is trying to reach it.

## Env isolation

```python theme={null}
envs={"API_PORT": "8081", "SERVICE_NAME": "declaw-demo-api"}
```

The generated `server.ts` reads both from `process.env`, so
rotating the port or service name is a client-side config change,
not a prompt rewrite.

## What the agent does

1. `mkdir -p /workspace/api && cd /workspace/api`.
2. Write `server.ts` reading `process.env.API_PORT` and
   `process.env.SERVICE_NAME`.
3. `npm init -y && npm i express && npm i -D typescript @types/node @types/express`.
4. `npx tsc` to compile.
5. Start the server in background: `node server.js >server.log 2>&1 &`.
6. `sleep 1 && curl http://127.0.0.1:$API_PORT/health`.
7. Return the JSON plus `tail -n 10 server.log`.

## Why background processes matter

`session._inner._sbx.run_command("... &")` returns when the shell
forks — the server keeps running in the sandbox. The same session
can then hit it with a second `run_command("curl ...")`. This is
the same pattern you'd use for testing any long-running service
(databases, workers, APIs) against an agent-driven client.

## Full source

See `cookbook/examples/openai-agents-typescript-api/main.py` in the repo.
