@an-sdk/cli 0.0.7 → 0.0.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,117 @@
1
+ # Next.js Integration
2
+
3
+ `@an-sdk/nextjs` provides a server-side token handler so your `an_sk_` API key never reaches the browser. It also re-exports everything from `@an-sdk/react` for convenience.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @an-sdk/nextjs @an-sdk/react ai @ai-sdk/react
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ ### 1. Set your API key
14
+
15
+ ```env
16
+ # .env.local
17
+ AN_API_KEY=an_sk_your_key_here
18
+ ```
19
+
20
+ Get your API key from [an.dev/agents/dashboard/api](https://an.dev/agents/dashboard/api).
21
+
22
+ ### 2. Create the token route
23
+
24
+ ```ts
25
+ // app/api/an/token/route.ts
26
+ import { createAnTokenHandler } from "@an-sdk/nextjs/server"
27
+
28
+ export const POST = createAnTokenHandler({
29
+ apiKey: process.env.AN_API_KEY!,
30
+ })
31
+ ```
32
+
33
+ ### 3. Use in your page
34
+
35
+ ```tsx
36
+ // app/page.tsx
37
+ "use client"
38
+
39
+ import { useChat } from "@ai-sdk/react"
40
+ import { AnAgentChat, createAnChat } from "@an-sdk/nextjs"
41
+ import "@an-sdk/react/styles.css"
42
+ import { useMemo } from "react"
43
+
44
+ export default function Chat() {
45
+ const chat = useMemo(
46
+ () => createAnChat({
47
+ agent: "your-agent-slug",
48
+ tokenUrl: "/api/an/token",
49
+ }),
50
+ [],
51
+ )
52
+
53
+ const { messages, sendMessage, status, stop, error } = useChat({ chat })
54
+
55
+ return (
56
+ <AnAgentChat
57
+ messages={messages}
58
+ onSend={(msg) =>
59
+ sendMessage({ parts: [{ type: "text", text: msg.content }] })
60
+ }
61
+ status={status}
62
+ onStop={stop}
63
+ error={error}
64
+ />
65
+ )
66
+ }
67
+ ```
68
+
69
+ ## How It Works
70
+
71
+ ```
72
+ Browser Your Next.js Server AN Relay
73
+ | | |
74
+ |-- POST /api/an/token --------->| |
75
+ | |-- POST /v1/tokens -------->|
76
+ | | (with an_sk_ key) |
77
+ | |<-- { token, expiresAt } ---|
78
+ |<-- { token, expiresAt } ------| |
79
+ | |
80
+ |-- POST /v1/chat/:agent ------(with short-lived JWT)------->|
81
+ |<-- streaming response -----(SSE)---------------------------|
82
+ ```
83
+
84
+ The client only receives short-lived JWTs. Your API key stays on the server.
85
+
86
+ ## API
87
+
88
+ ### `createAnTokenHandler(options)`
89
+
90
+ Returns a Next.js `POST` route handler.
91
+
92
+ ```ts
93
+ createAnTokenHandler({
94
+ apiKey: string // Your an_sk_ API key
95
+ relayUrl?: string // Default: "https://relay.an.dev"
96
+ expiresIn?: string // Default: "1h"
97
+ })
98
+ ```
99
+
100
+ ### `exchangeToken(options)`
101
+
102
+ Lower-level function for custom token exchange logic.
103
+
104
+ ```ts
105
+ import { exchangeToken } from "@an-sdk/nextjs/server"
106
+
107
+ const { token, expiresAt } = await exchangeToken({
108
+ apiKey: process.env.AN_API_KEY!,
109
+ relayUrl: "https://relay.an.dev",
110
+ expiresIn: "1h",
111
+ })
112
+ ```
113
+
114
+ ## Entry Points
115
+
116
+ - `@an-sdk/nextjs` — Re-exports everything from `@an-sdk/react` (components, types, `createAnChat`)
117
+ - `@an-sdk/nextjs/server` — Server-only: `createAnTokenHandler`, `exchangeToken`
@@ -0,0 +1,125 @@
1
+ # Node SDK
2
+
3
+ `@an-sdk/node` is a server-side client for the AN API. Use it to manage sandboxes, threads, and tokens programmatically.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @an-sdk/node
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```ts
14
+ import { AnClient } from "@an-sdk/node"
15
+
16
+ const an = new AnClient({
17
+ apiKey: process.env.AN_API_KEY!, // an_sk_...
18
+ })
19
+
20
+ // Create a sandbox for your agent
21
+ const sandbox = await an.sandboxes.create({ agent: "my-agent" })
22
+
23
+ // Create a thread
24
+ const thread = await an.threads.create({
25
+ sandboxId: sandbox.sandboxId,
26
+ name: "Review PR #42",
27
+ })
28
+
29
+ // Generate a short-lived token for browser clients
30
+ const { token, expiresAt } = await an.tokens.create({
31
+ agent: "my-agent",
32
+ expiresIn: "1h",
33
+ })
34
+ ```
35
+
36
+ ## `AnClient`
37
+
38
+ ```ts
39
+ new AnClient({
40
+ apiKey: string // Your an_sk_ API key
41
+ baseUrl?: string // Default: "https://relay.an.dev"
42
+ })
43
+ ```
44
+
45
+ ## Resources
46
+
47
+ ### `client.sandboxes`
48
+
49
+ | Method | Description |
50
+ |--------|-------------|
51
+ | `create({ agent })` | Create a new sandbox for an agent |
52
+ | `get(sandboxId)` | Get sandbox details (status, threads, agent info) |
53
+ | `delete(sandboxId)` | Delete a sandbox |
54
+
55
+ ### `client.threads`
56
+
57
+ | Method | Description |
58
+ |--------|-------------|
59
+ | `list({ sandboxId })` | List all threads in a sandbox |
60
+ | `create({ sandboxId, name? })` | Create a new thread |
61
+ | `get({ sandboxId, threadId })` | Get thread with messages |
62
+ | `delete({ sandboxId, threadId })` | Delete a thread |
63
+
64
+ ### `client.tokens`
65
+
66
+ | Method | Description |
67
+ |--------|-------------|
68
+ | `create({ agent?, userId?, expiresIn? })` | Create a short-lived JWT |
69
+
70
+ Default `expiresIn` is `"1h"`.
71
+
72
+ ## Types
73
+
74
+ ```ts
75
+ interface Sandbox {
76
+ id: string
77
+ sandboxId: string
78
+ status: string
79
+ createdAt: string
80
+ }
81
+
82
+ interface SandboxDetail {
83
+ id: string
84
+ sandboxId: string
85
+ status: string
86
+ error?: string | null
87
+ agent: { slug: string; name: string }
88
+ threads: ThreadSummary[]
89
+ createdAt: string
90
+ updatedAt: string
91
+ }
92
+
93
+ interface ThreadSummary {
94
+ id: string
95
+ name?: string | null
96
+ status: string
97
+ createdAt: string
98
+ }
99
+
100
+ interface Thread {
101
+ id: string
102
+ name?: string | null
103
+ status: string
104
+ messages?: unknown
105
+ createdAt: string
106
+ updatedAt: string
107
+ }
108
+
109
+ interface Token {
110
+ token: string
111
+ expiresAt: string
112
+ }
113
+ ```
114
+
115
+ ## Error Handling
116
+
117
+ All methods throw on non-2xx responses. The error message comes from the API response body when available.
118
+
119
+ ```ts
120
+ try {
121
+ const sandbox = await an.sandboxes.get("nonexistent")
122
+ } catch (err) {
123
+ console.error(err.message) // "Sandbox not found" or similar
124
+ }
125
+ ```
package/docs/07-cli.md ADDED
@@ -0,0 +1,88 @@
1
+ # CLI Reference
2
+
3
+ `@an-sdk/cli` provides the `an` command for deploying agents.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install -g @an-sdk/cli
9
+ # or use npx
10
+ npx @an-sdk/cli <command>
11
+ ```
12
+
13
+ ## Commands
14
+
15
+ ### `an login`
16
+
17
+ Authenticate with the AN platform.
18
+
19
+ ```bash
20
+ npx @an-sdk/cli login
21
+ # Enter your API key: an_sk_...
22
+ # Authenticated as John (team: my-team)
23
+ ```
24
+
25
+ Your key is saved to `~/.an/credentials`.
26
+
27
+ ### `an deploy`
28
+
29
+ Bundle and deploy your agent.
30
+
31
+ ```bash
32
+ npx @an-sdk/cli deploy
33
+ # Bundling src/agent.ts...
34
+ # Bundled (12.3kb)
35
+ # Deploying my-agent...
36
+ # https://api.an.dev/v1/chat/my-agent
37
+ ```
38
+
39
+ The CLI:
40
+ 1. Finds your entry point (see detection order below)
41
+ 2. Bundles your code + dependencies with esbuild
42
+ 3. Deploys to a secure cloud sandbox
43
+ 4. Returns your agent's URL
44
+
45
+ ## Entry Point Detection
46
+
47
+ The CLI looks for your agent file in this order:
48
+
49
+ 1. `src/agent.ts`
50
+ 2. `src/index.ts`
51
+ 3. `agent.ts`
52
+ 4. `index.ts`
53
+
54
+ Your entry file must `export default agent(...)`.
55
+
56
+ ## Project Linking
57
+
58
+ After first deploy, the CLI saves `.an/project.json` in your project directory:
59
+
60
+ ```json
61
+ {
62
+ "agentId": "abc123",
63
+ "slug": "my-agent"
64
+ }
65
+ ```
66
+
67
+ Subsequent deploys update the existing agent.
68
+
69
+ ## Bundling
70
+
71
+ The CLI uses esbuild to bundle your agent code:
72
+
73
+ - Target: Node 22, ESM
74
+ - `@an-sdk/agent` is externalized (provided by the sandbox runtime)
75
+ - All other dependencies are bundled into a single file
76
+
77
+ ## Configuration Files
78
+
79
+ | File | Location | Purpose |
80
+ |------|----------|---------|
81
+ | `~/.an/credentials` | Global | API key (`{ "apiKey": "an_sk_..." }`) |
82
+ | `.an/project.json` | Per-project | Agent ID and slug for redeployment |
83
+
84
+ ## Environment Variables
85
+
86
+ | Variable | Default | Description |
87
+ |----------|---------|-------------|
88
+ | `AN_API_URL` | `https://an.dev/api/v1` | Override API endpoint |
@@ -0,0 +1,88 @@
1
+ # Custom Tool Renderers
2
+
3
+ The `@an-sdk/react` chat UI automatically renders tool calls from your agent. It includes built-in renderers for all standard Claude tools and supports custom renderers for your own tools.
4
+
5
+ ## Built-in Tool Renderers
6
+
7
+ These are rendered automatically when your agent uses standard tools:
8
+
9
+ | Tool | Renderer | Display |
10
+ |------|----------|---------|
11
+ | `Bash` | `BashTool` | Terminal card with command and output |
12
+ | `Edit` | `EditTool` | Diff card with file path and changes |
13
+ | `Write` | `WriteTool` | File creation card |
14
+ | `WebSearch` | `SearchTool` | Search results list |
15
+ | `TodoWrite` | `TodoTool` | Task checklist with progress |
16
+ | `EnterPlanMode` | `PlanTool` | Step list with progress bar |
17
+ | `Task` | `TaskTool` | Sub-agent task with nested tools |
18
+ | `mcp__*` | `McpTool` | MCP tool call with params and output |
19
+ | `thinking` | `ThinkingTool` | Collapsible reasoning block |
20
+ | Other | `GenericTool` | Fallback JSON display |
21
+
22
+ ## Custom Tool Renderers via Slots
23
+
24
+ To render your custom tools differently, use the `slots.ToolRenderer` prop:
25
+
26
+ ```tsx
27
+ import { AnAgentChat, ToolRenderer } from "@an-sdk/react"
28
+ import type { ToolPart } from "@an-sdk/react"
29
+
30
+ function MyToolRenderer(props: { part: ToolPart; status: string }) {
31
+ const { part, status } = props
32
+
33
+ // Handle your custom tool
34
+ if (part.toolInvocation.toolName === "weather") {
35
+ const args = part.toolInvocation.args
36
+ const result = part.toolInvocation.state === "result"
37
+ ? part.toolInvocation.result
38
+ : null
39
+
40
+ return (
41
+ <div className="weather-card">
42
+ <h3>Weather for {args.city}</h3>
43
+ {result ? <p>{result.content[0].text}</p> : <p>Loading...</p>}
44
+ </div>
45
+ )
46
+ }
47
+
48
+ // Fall back to default renderer for standard tools
49
+ return <ToolRenderer part={part} status={status} />
50
+ }
51
+
52
+ <AnAgentChat
53
+ slots={{ ToolRenderer: MyToolRenderer }}
54
+ // ... other props
55
+ />
56
+ ```
57
+
58
+ ## MCP Tool Naming
59
+
60
+ MCP (Model Context Protocol) tools follow the naming pattern `mcp__<server>__<tool>`. The built-in `McpTool` renderer parses this automatically and shows the server name and tool name.
61
+
62
+ ## Tool States
63
+
64
+ Each tool invocation has a state:
65
+
66
+ | State | Meaning |
67
+ |-------|---------|
68
+ | `"call"` | Tool has been called, waiting for execution |
69
+ | `"result"` | Tool has returned a result |
70
+
71
+ During streaming, tools may be in `"call"` state before transitioning to `"result"`.
72
+
73
+ ## CSS Classes
74
+
75
+ All tool renderers have stable CSS class names for custom styling:
76
+
77
+ ```css
78
+ .an-tool-bash { }
79
+ .an-tool-edit { }
80
+ .an-tool-write { }
81
+ .an-tool-search { }
82
+ .an-tool-todo { }
83
+ .an-tool-plan { }
84
+ .an-tool-task { }
85
+ .an-tool-mcp { }
86
+ .an-tool-thinking { }
87
+ .an-tool-generic { }
88
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@an-sdk/cli",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "description": "AN CLI — deploy AI agents",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,9 +8,18 @@
8
8
  },
9
9
  "files": [
10
10
  "dist",
11
+ "docs/**/*",
12
+ "src",
13
+ "!src/**/*.test.ts",
14
+ "AGENTS.md",
11
15
  "README.md"
12
16
  ],
17
+ "directories": {
18
+ "doc": "./docs"
19
+ },
13
20
  "scripts": {
21
+ "prepack": "cp -r ../docs ./docs",
22
+ "postpack": "rm -rf ./docs",
14
23
  "build": "tsup",
15
24
  "dev": "tsx src/index.ts"
16
25
  },
package/src/bundler.ts ADDED
@@ -0,0 +1,63 @@
1
+ import esbuild from "esbuild"
2
+
3
+ export type AgentEntryPoint = { slug: string; entryPoint: string }
4
+
5
+ export async function findAgentEntryPoints(): Promise<AgentEntryPoint[]> {
6
+ const { existsSync, readdirSync, statSync } = await import("fs")
7
+ const { join, basename, extname } = await import("path")
8
+
9
+ if (!existsSync("agents") || !statSync("agents").isDirectory()) {
10
+ throw new Error("No agents/ directory found. See https://an.dev/docs to get started.")
11
+ }
12
+
13
+ const entries: AgentEntryPoint[] = []
14
+ const items = readdirSync("agents")
15
+
16
+ for (const item of items) {
17
+ const fullPath = join("agents", item)
18
+ const stat = statSync(fullPath)
19
+
20
+ if (stat.isDirectory()) {
21
+ for (const indexFile of ["index.ts", "index.js"]) {
22
+ const indexPath = join(fullPath, indexFile)
23
+ if (existsSync(indexPath)) {
24
+ entries.push({ slug: item, entryPoint: indexPath })
25
+ break
26
+ }
27
+ }
28
+ } else if (stat.isFile()) {
29
+ const ext = extname(item)
30
+ if (ext === ".ts" || ext === ".js") {
31
+ entries.push({ slug: basename(item, ext), entryPoint: fullPath })
32
+ }
33
+ }
34
+ }
35
+
36
+ if (entries.length === 0) {
37
+ throw new Error("No agents found in agents/ directory. See https://an.dev/docs to get started.")
38
+ }
39
+
40
+ return entries
41
+ }
42
+
43
+ export async function bundleAgent(entryPoint: string): Promise<Buffer> {
44
+ const result = await esbuild.build({
45
+ entryPoints: [entryPoint],
46
+ bundle: true,
47
+ platform: "node",
48
+ target: "node22",
49
+ format: "esm",
50
+ write: false,
51
+ external: ["@an-sdk/agent"],
52
+ minify: true,
53
+ sourcemap: false,
54
+ })
55
+
56
+ if (result.errors.length > 0) {
57
+ throw new Error(
58
+ `Bundle failed:\n${result.errors.map((e) => e.text).join("\n")}`,
59
+ )
60
+ }
61
+
62
+ return Buffer.from(result.outputFiles[0].contents)
63
+ }
package/src/config.ts ADDED
@@ -0,0 +1,46 @@
1
+ import { readFileSync, writeFileSync, mkdirSync } from "fs"
2
+ import { join } from "path"
3
+ import { homedir } from "os"
4
+
5
+ const AN_DIR = join(homedir(), ".an")
6
+ const CREDENTIALS_PATH = join(AN_DIR, "credentials")
7
+ const PROJECT_PATH = join(process.cwd(), ".an", "project.json")
8
+
9
+ // --- Credentials (global, ~/.an/credentials) ---
10
+
11
+ export function getApiKey(): string | null {
12
+ // Env var takes priority (CI mode)
13
+ if (process.env.AN_API_KEY) return process.env.AN_API_KEY
14
+ try {
15
+ const data = JSON.parse(readFileSync(CREDENTIALS_PATH, "utf-8"))
16
+ return data.apiKey || null
17
+ } catch {
18
+ return null
19
+ }
20
+ }
21
+
22
+ export function saveApiKey(apiKey: string): void {
23
+ mkdirSync(AN_DIR, { recursive: true })
24
+ writeFileSync(CREDENTIALS_PATH, JSON.stringify({ apiKey }, null, 2))
25
+ }
26
+
27
+ // --- Project linking (local, .an/project.json) ---
28
+
29
+ export type ProjectConfig = { projectId: string; projectSlug: string }
30
+
31
+ export function getProject(): ProjectConfig | null {
32
+ try {
33
+ const data = JSON.parse(readFileSync(PROJECT_PATH, "utf-8"))
34
+ // Backward compat: old format had { agentId, slug }
35
+ if (data.projectId && data.projectSlug) return data
36
+ if (data.slug) return { projectId: data.agentId ?? "", projectSlug: data.slug }
37
+ return null
38
+ } catch {
39
+ return null
40
+ }
41
+ }
42
+
43
+ export function saveProject(data: ProjectConfig): void {
44
+ mkdirSync(join(process.cwd(), ".an"), { recursive: true })
45
+ writeFileSync(PROJECT_PATH, JSON.stringify(data, null, 2))
46
+ }