agent-neckbeard 1.1.26 → 1.1.28
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.
- package/CHANGELOG.md +18 -0
- package/README.md +53 -459
- package/dist/build.cjs +5560 -0
- package/dist/build.d.cts +80 -0
- package/dist/build.d.ts +80 -0
- package/dist/build.js +17 -0
- package/dist/chunk-JF5YPOBY.js +4339 -0
- package/dist/chunk-KG6SJM74.js +97 -0
- package/dist/chunk-M3FISP7J.js +377 -0
- package/dist/chunk-M7XNBKG4.js +346 -0
- package/dist/cli.cjs +5606 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +75 -0
- package/dist/index.cjs +1572 -149
- package/dist/index.d.cts +338 -6
- package/dist/index.d.ts +338 -6
- package/dist/index.js +36 -3272
- package/dist/{invoke-client-YKWOTQWG.js → invoke-client-P2CPBYTF.js} +2 -41
- package/dist/serve-Dan1HQKN.d.cts +89 -0
- package/dist/serve-Dan1HQKN.d.ts +89 -0
- package/dist/serve.cjs +337 -0
- package/dist/serve.d.cts +1 -0
- package/dist/serve.d.ts +1 -0
- package/dist/serve.js +8 -0
- package/docs/AGENT.md +173 -0
- package/docs/DAYTONA.md +56 -0
- package/docs/DOCKER.md +7 -7
- package/docs/E2B.md +11 -0
- package/docs/LEGACY.md +335 -0
- package/docs/MODAL.md +29 -13
- package/docs/SUPERVISOR.md +2 -2
- package/package.json +43 -3
- package/dist/chunk-6GCQOKYI.js +0 -48
package/docs/AGENT.md
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# Agents from Prebuilt Images
|
|
2
|
+
|
|
3
|
+
An agent runs a Pi session from a container image you build ahead of time, usually in CI. The image holds everything the agent needs: OS packages, Python and npm dependencies, skills, and the agent itself. Starting a sandbox installs and uploads nothing, so a cold start is the provider's sandbox start plus the agent process start.
|
|
4
|
+
|
|
5
|
+
This replaces `LegacyBundledAgent`, which bundles the agent's code on the host and uploads it, its dependencies, and its local directories at every deploy. That class still works and is deprecated.
|
|
6
|
+
|
|
7
|
+
## Defining an agent
|
|
8
|
+
|
|
9
|
+
`defineAgent()` describes an agent once, in one module: its image, its sandbox, and its Pi session. Your process imports it to start sandboxes and run turns; `neckbeard build` bundles the same module as the image's entry point, which serves the session.
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
// src/agent.ts
|
|
13
|
+
import { defineAgent } from "agent-neckbeard";
|
|
14
|
+
import type { JsonAgentSessionEvent } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
|
|
16
|
+
export const myAgent = defineAgent<JsonAgentSessionEvent>({
|
|
17
|
+
name: "my-agent", // the image is ghcr.io/acme/my-agent:<tag>
|
|
18
|
+
registry: "ghcr.io/acme",
|
|
19
|
+
sandbox: { provider: "modal", cpu: 2, memoryMiB: 4096, regions: ["us-east"], registrySecret: "ghcr" },
|
|
20
|
+
envs: () => ({ OPENAI_API_KEY: process.env.OPENAI_API_KEY }),
|
|
21
|
+
maxTurnDurationMs: 2 * 60 * 60 * 1000, // optional: ends a turn that runs longer as failed
|
|
22
|
+
pi: {
|
|
23
|
+
model: "openai/gpt-6.1-sol",
|
|
24
|
+
thinkingLevel: "high",
|
|
25
|
+
tools: ["read", "bash", "grep", "ls"],
|
|
26
|
+
systemPrompt: "You are ...",
|
|
27
|
+
cwd: "workspace",
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`sandbox` and `envs` may be functions, read the first time the host needs them, so the image, which never calls them, needs none of the host's configuration. Pass Pi's `JsonAgentSessionEvent` to type the events; neckbeard's own declarations don't reference Pi's, so a package that only runs turns needn't install Pi.
|
|
33
|
+
|
|
34
|
+
`pi` creates the session in the sandbox, which needs Pi's Node.js 22.19 or later (`PiSessionConfig` in [`src/define.ts`](../src/define.ts)):
|
|
35
|
+
|
|
36
|
+
- `model` as `provider/model`, with `thinkingLevel` and the built-in `tools` to enable. The model's credential comes from the sandbox's environment, such as `OPENAI_API_KEY`.
|
|
37
|
+
- `systemPrompt` replaces Pi's. Pi's agent directory is `~/agent/.pi`, and its skills are the image's `/app/.agents/skills` (`SKILLS_DIR`) only: no extensions, prompt templates, or context files are loaded from the sandbox.
|
|
38
|
+
- `cwd`, relative to the sandbox user's home unless absolute (default `workspace`), is created before the session and exported as `NECKBEARD_CWD`, so the agent's scripts can find it.
|
|
39
|
+
- `persist` keeps the conversation in `~/agent/.pi/sessions/<sessionId>.jsonl`, for the `sessionId` passed to `start()`, so a restarted runtime, or a sandbox restored from a copy of that file, continues it. `sessionFilePath(homeDir, sessionId)` gives the path for copying it out and back. Otherwise the conversation lives in memory as long as the sandbox.
|
|
40
|
+
|
|
41
|
+
For a session that config can't express, pass `createSession` instead of `pi`, returning anything with Pi's `subscribe`, `prompt`, and `abort`, and optionally `afterTurn()`, which runs once each turn's outcome is known, before its `end` record and outside its deadline, as to send traces; an abort that arrives meanwhile changes nothing. Keep it bounded, since it delays the `end` record. A definition needs exactly one of them.
|
|
42
|
+
|
|
43
|
+
### Tracing
|
|
44
|
+
|
|
45
|
+
A `pi` agent traces its turns in [Braintrust](https://www.braintrust.dev) when its sandbox has `BRAINTRUST_API_KEY` and `BRAINTRUST_PROJECT_NAME`. Pass them in `envs`, and add `braintrust` `>=3.44.0 <4.0.0`, an optional peer dependency, to the agent's package's `dependencies` (not `devDependencies`), so `neckbeard build` installs it in the image, shared with any imports of it in the agent's own code; the build fails on a version outside that range, which can't trace Pi 1.x:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
envs: () => ({
|
|
49
|
+
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
|
|
50
|
+
BRAINTRUST_API_KEY: process.env.BRAINTRUST_API_KEY,
|
|
51
|
+
BRAINTRUST_PROJECT_NAME: "my-agent",
|
|
52
|
+
}),
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Each turn is a trace of Pi's prompt, its model calls, and its tool calls, sent once its outcome is known: before its `end` record, so a sandbox deleted right after a turn loses nothing, and outside `maxTurnDurationMs`, so sending it can't fail the turn. Tracing never fails a turn: a trace that can't be sent within 10 seconds, or a Braintrust that can't start, is reported with `console.warn` and the agent runs on. The key turns tracing on: without it, tracing is off, so an agent can name its project and run untraced wherever no key is configured, as in local development. A key without a project name is a mistake: the first `start()` warns on the host, the sandbox warns in its own log, and the agent runs untraced.
|
|
56
|
+
|
|
57
|
+
A sandbox with a network allowlist must allow `www.braintrust.dev`, where Braintrust logs in, and the organization's API host, by default `api.braintrust.dev`.
|
|
58
|
+
|
|
59
|
+
### Image names
|
|
60
|
+
|
|
61
|
+
A host runs `<registry>/<name>:<tag>`, where the tag is the first of these set: `NECKBEARD_IMAGE_TAG`, then the commit its platform deployed, from the variables [Sentry reads](https://github.com/getsentry/sentry-javascript/blob/develop/packages/core/src/utils/commitEnv.ts) for the same purpose (`GITHUB_SHA`, `CI_COMMIT_SHA`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA`, `RAILWAY_GIT_COMMIT_SHA`, `HEROKU_SLUG_COMMIT` and others; `resolveImageTag()`). So CI tags each image with its commit, and a deployed host runs the image of its own commit, without configuration; set `NECKBEARD_IMAGE_TAG` where no commit is known, as in local development: `master` follows each push on Daytona and E2B, but Modal keeps a tag's first contents, so a Modal agent needs a commit's tag. The tag is the commit rather than a hash of the image's contents because a host doesn't have the build context to hash. `image` instead of `registry` names a full image reference, and `imageRef(tag?)` returns the image a host would run. A definition without either fails, and a host that can't find a tag fails when it first starts a sandbox.
|
|
62
|
+
|
|
63
|
+
## Building and pushing the image
|
|
64
|
+
|
|
65
|
+
From the agent's package, after logging in to the registry:
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
npx neckbeard push src/agent.ts [--export <name>] [--tag <tag>]... [--cache] [--dry-run]
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
`push` writes the image's build context, as `neckbeard build` does, to a temporary directory it removes afterwards, so the package needn't ignore it, and builds it for `linux/amd64`, which every provider runs, with the package's `sandbox/Dockerfile` (`build.dockerfile`) and `docker build`, tagged `<registry>/<name>:<tag>` for each `--tag` (default: `resolveImageTag()`, so `GITHUB_SHA` in a GitHub workflow). It then pushes each tag, and readies each for its provider: on Daytona it builds the tag's snapshot, on E2B its template, again even when one exists, since a tag such as `master` may now name new contents, and deletes older ones, keeping three in all and never one this push built (`prepare({ refresh: true })` and `gc({ keep: 3, alsoKeep })`), so no sandbox start waits on a build. Modal pulls the image itself, and [keeps a tag's contents once pulled](https://modal.com/docs/guide/sandboxes#separating-image-builds-from-sandbox-creation), so a reused tag such as `master` can't be refreshed there: a Modal host should run an immutable tag, as a deployed host running its commit does, and `push` says so for each later tag of a Modal agent. That needs the provider's credentials, such as `DAYTONA_API_KEY`, and whatever the definition's `sandbox` function reads. `--cache` builds with `docker buildx`, reusing and updating layers cached in the registry under the image's `buildcache` tag. `--dry-run` builds without pushing or preparing, as for a pull request. `--export` picks the agent when the module exports several; by default it is the default export or the module's only agent. `pushAgent()` from `agent-neckbeard/build` does the same. A workflow:
|
|
72
|
+
|
|
73
|
+
```yaml
|
|
74
|
+
- uses: docker/setup-buildx-action@v3
|
|
75
|
+
- uses: docker/login-action@v3
|
|
76
|
+
with: { registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}" }
|
|
77
|
+
- run: npx neckbeard push src/agent.ts --tag ${{ github.sha }} --tag latest --cache ${{ github.event_name == 'pull_request' && '--dry-run' || '' }}
|
|
78
|
+
working-directory: packages/my-agent
|
|
79
|
+
env: { DAYTONA_API_KEY: "${{ secrets.DAYTONA_API_KEY }}" }
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`neckbeard build src/agent.ts [--export <name>] [--out dist-sandbox]` writes only the build context, for inspecting it. It replaces `dist-sandbox/`, or `--out`, with three things. It refuses an output directory that holds the package or its module, or that is not empty and was not written by an earlier build.
|
|
83
|
+
|
|
84
|
+
- `agent.mjs`: the module, bundled with an entry point that calls the agent's `serve()`. Pi's packages (`@earendil-works/*`), Braintrust for a `pi` agent whose package depends on it, the host-only provider SDKs, and each package in the definition's `build.external` stay out of the bundle, for ones that load native modules or wasm or otherwise must be installed. The build loads the module on the host to read its definition, so its top level must not need the image.
|
|
85
|
+
- `package.json`: those packages, each pinned to the version its importer resolves, as Node will in the image. The build fails when the bundle imports one package at two versions.
|
|
86
|
+
- `.agents/skills/`: the package's own skills from `skills/`, plus the third-party skills its `skills-lock.json` pins. It restores those with the [skills CLI](https://www.npmjs.com/package/skills) (`skills@1.8.1`, run as `experimental_install --frozen-lockfile`), which fetches each at its locked commit and fails unless its files match the lock's hash. That CLI is an optional dependency that needs Node.js 22.20 or later, so a package with a `skills-lock.json` must be built on such a Node; the rest of the package keeps its wider Node range.
|
|
87
|
+
|
|
88
|
+
Commit `skills/` and `skills-lock.json`, never the third-party skills' files. To add or update one, run `npx skills@1.8.1 add <owner>/<repo>#<full commit SHA> --skill <name> --copy` in the package, review what it fetched, commit the lock, and delete the `.agents` it wrote. The build fails when a lock entry's `ref` is not a full commit SHA, since the lock records the ref as typed; when a skill is in both `skills/` and the lock; when a skill directory has no `SKILL.md`; or when a skill holds a symbolic link that is absolute or points outside the skill, since it would not resolve in the image. Links inside a skill are copied as they are.
|
|
89
|
+
|
|
90
|
+
The build fetches over the network, but `docker build` then sees only local files. A Dockerfile puts the bundle in `/app` with its unbundled dependencies and skills:
|
|
91
|
+
|
|
92
|
+
```dockerfile
|
|
93
|
+
FROM python:3.14-slim-trixie
|
|
94
|
+
COPY --from=node:22-trixie-slim /usr/local/bin/node /usr/local/bin/node
|
|
95
|
+
COPY --from=node:22-trixie-slim /usr/local/lib/node_modules /usr/local/lib/node_modules
|
|
96
|
+
RUN ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm
|
|
97
|
+
RUN apt-get update && apt-get install -y --no-install-recommends bash ca-certificates curl \
|
|
98
|
+
&& rm -rf /var/lib/apt/lists/*
|
|
99
|
+
WORKDIR /app
|
|
100
|
+
COPY package.json ./
|
|
101
|
+
RUN npm install --omit=dev
|
|
102
|
+
COPY agent.mjs ./
|
|
103
|
+
COPY .agents /app/.agents
|
|
104
|
+
CMD ["node", "/app/agent.mjs"]
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The runtime listens on `NECKBEARD_PORT`, which the host sets, or 8080, and sends Pi's events in the JSON form Pi's JSON and RPC modes write: a `message_update` carries only its delta, not the cumulative message. The image needs Bash for file and command access through `SandboxClient`. Never bake secrets into it: pass them as `envs`, or as turn `env`.
|
|
108
|
+
|
|
109
|
+
## The host
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { getPiTurnResult } from "agent-neckbeard";
|
|
113
|
+
import { myAgent } from "./agent";
|
|
114
|
+
|
|
115
|
+
const sandboxId = await myAgent.start({ sessionId });
|
|
116
|
+
for await (const record of myAgent.prompt(sandboxId, {
|
|
117
|
+
turnId: runId,
|
|
118
|
+
message: "Summarize the data room.",
|
|
119
|
+
env: { API_TOKEN: shortLivedToken },
|
|
120
|
+
})) {
|
|
121
|
+
if (record.type === "event") store(record.seq, record.event);
|
|
122
|
+
else console.log(record.outcome, record.error);
|
|
123
|
+
}
|
|
124
|
+
await myAgent.kill(sandboxId);
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Every method takes the sandbox ID, so a host process that restarts, or another one, can drive a sandbox the first one started.
|
|
128
|
+
|
|
129
|
+
| Method | Does |
|
|
130
|
+
|---|---|
|
|
131
|
+
| `start({ envs, sessionId, signal })` | Prepares the image for the provider if needed, creates a sandbox whose main process is the image's runtime, waits until it answers, returns the sandbox ID. `sessionId` is the sandbox's `NECKBEARD_SESSION_ID`, which names a persisted session's file. A start that fails or is cancelled deletes its sandbox; if that fails too, it throws `DeploymentError` with the `sandboxId` to `kill()` |
|
|
132
|
+
| `prompt(sandboxId, { turnId, message, env }, { after, signal })` | Starts a turn and yields its records until its `end` record. A `turnId` the runtime already has resumes that turn instead of running it again |
|
|
133
|
+
| `run(sandboxId, turn, { onRecord, signal })` | Runs a turn to its end, passing each record to `onRecord`, and returns the last assistant message's text; throws `ExecutionError` when the turn doesn't complete. Calling it again with the same `turnId` resumes the turn and replays its records from the start, so store them keyed by `seq` |
|
|
134
|
+
| `events(sandboxId, turnId, { after, signal })` | Resumes a turn's records after `after`. Throws `TurnLostError` when the runtime no longer has the turn |
|
|
135
|
+
| `abort(sandboxId, turnId)` | Stops the turn; its stream ends with an `aborted` record |
|
|
136
|
+
| `health`, `waitForIdle` | Whether a turn is running |
|
|
137
|
+
| `sandbox(sandboxId)` | A `SandboxClient` for files and commands, for staging inputs or reading results |
|
|
138
|
+
| `kill(sandboxId)` | Deletes the sandbox without starting it. One that is gone counts as deleted; any other failure throws, so cleanup can be retried, since a Daytona sandbox without `autoDeleteInterval` never expires |
|
|
139
|
+
| `prepare({ refresh })` | Creates the Daytona snapshot or E2B template if missing, or replaces one an earlier attempt left failed, or with `refresh` builds it again, within `prepareTimeoutMs` (30 minutes) and the caller's `signal`; does nothing on Modal |
|
|
140
|
+
| `gc({ keep, alsoKeep })` | Deletes this agent's older Daytona snapshots or E2B templates (exactly `nb-<name>-<hash>`, so not another agent's whose name starts with this one's), keeping the newest `keep`, and never the current one or those named in `alsoKeep` |
|
|
141
|
+
|
|
142
|
+
The first call builds the agent's `Agent` for the image `imageRef()` names; `forImage(image)` returns one for another image. `new Agent({ name, image, sandbox, envs })` takes the same options for an image built some other way, and `serve({ createSession })` from `agent-neckbeard/serve` serves a session from an entry point you write yourself.
|
|
143
|
+
|
|
144
|
+
`getPiTurnResult(records)` reads how a turn ended: completed with its last assistant message's text when the records include the `end` record, the turn ended normally, and the model stopped on its own; otherwise an error, including for records that stop before the `end` record.
|
|
145
|
+
|
|
146
|
+
`signal` stops reading a stream, never the turn: a host that stops or restarts leaves the turn running, and the next `prompt` or `events` call resumes it. Use `abort()` to stop a turn. A stream that drops reconnects on its own from the last record, and fails after `reconnectTimeoutMs` (two minutes) without a healthy connection. A connection is healthy while bytes arrive: records, the comment the runtime sends as a stream opens, or its heartbeat every 15 seconds. A connection that sends nothing for that long is abandoned, including one the server accepts and never answers, so keep `reconnectTimeoutMs` above 15 seconds. An `Agent` prepares once and reuses the result, until a start fails to create its sandbox, as when a newer release's `gc()` deleted its snapshot; the next start then prepares again. `start()` and `waitForIdle()` bound each health check by their own deadlines, and a malformed `/health` body is an error, never an idle runtime. A whole record that is invalid fails the stream with `ExecutionError` rather than being retried, while a record cut off by a dropped connection is read again after reconnecting.
|
|
147
|
+
|
|
148
|
+
## Providers
|
|
149
|
+
|
|
150
|
+
| Provider | How the image becomes a sandbox | Private images |
|
|
151
|
+
|---|---|---|
|
|
152
|
+
| Modal | Pulled directly; the runtime is the sandbox's command | `registrySecret` names a Modal Secret with `REGISTRY_USERNAME` and `REGISTRY_PASSWORD` |
|
|
153
|
+
| Daytona | `prepare()` creates a snapshot named `nb-<name>-<hash>` with the runtime as its entrypoint | Add the registry once in the Daytona dashboard |
|
|
154
|
+
| E2B | `prepare()` builds a template named `nb-<name>-<hash>`; `start()` launches the runtime as a background command, because a template's start command runs once at build time without each sandbox's environment | `registry: { username, password }`, used only when building the template |
|
|
155
|
+
|
|
156
|
+
The hash covers the image reference, the command (Daytona), and the resources, so equal inputs share a snapshot or template and `prepare()` is a lookup. `neckbeard push` runs `prepare()` after pushing the image so no sandbox waits on a build; in our live tests a first build took 20 to 45 seconds, and a sandbox start after it about 2.5 seconds. It then runs `gc()` to delete older ones. Docker is not supported by `Agent` yet.
|
|
157
|
+
|
|
158
|
+
## Turn protocol
|
|
159
|
+
|
|
160
|
+
`serve()` speaks protocol version 2 over HTTP, behind each provider's endpoint auth (`TURN_PROTOCOL_VERSION`; types in `src/turn-protocol.ts`).
|
|
161
|
+
|
|
162
|
+
- `GET /health` returns `{ ok, protocolVersion, busy, turnId }`. `busy` stays true until the turn's prompt has returned and its `env` is restored, which can be after its `end` record, as when an event fails to convert and the prompt is still stopping. `start()` rejects a runtime with another protocol version.
|
|
163
|
+
- `POST /turns` with `{ turnId, message, env? }` starts a turn and returns 202. A known `turnId`, the current or previous turn, returns 200 without starting anything; another turn while one is busy returns 409. `env` is set in `process.env` for the turn and restored after it.
|
|
164
|
+
- `GET /turns/:turnId/events?after=<seq>` opens with an SSE comment, streams the turn's records after `seq`, then live records with a heartbeat comment every 15 seconds, and closes after the `end` record. A reader already past the end of an ended turn gets the `end` record again, so it can tell the turn ended from a dropped stream. Unknown turns return 404.
|
|
165
|
+
- `POST /turns/:turnId/abort` returns 202 and aborts the session's prompt. Pi waits for a running tool before its prompt returns, so a turn that is aborted, or exceeds `maxTurnDurationMs` (which counts from the turn's start, creating the session included), and hasn't stopped within `serve()`'s `abortGraceMs` (10 seconds) gets its end record anyway. `busy` stays true until the prompt does return.
|
|
166
|
+
|
|
167
|
+
A record is `{ seq, type: "event", event }` or `{ seq, type: "end", outcome: "completed" | "aborted" | "failed", error? }`. `seq` starts at 0 for each turn and increases by one, and the runtime serializes each record when it is written, so a replay of a `seq` sends exactly what streamed live, and a host can store records keyed by `seq` and ignore repeats. The runtime keeps the current and previous turns in memory. A runtime that restarts, or a replaced sandbox, loses them, and a resume then fails with `TurnLostError`.
|
|
168
|
+
|
|
169
|
+
## Limits
|
|
170
|
+
|
|
171
|
+
- The session runs in the runtime process: if the agent crashes the process, the turn is lost and the provider's sandbox usually ends with it.
|
|
172
|
+
- One turn runs at a time per sandbox.
|
|
173
|
+
- `Agent` supports Pi-style sessions only. Other runtimes would get their own class.
|
package/docs/DAYTONA.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Daytona Provider
|
|
2
|
+
|
|
3
|
+
Daytona runs `Agent`, `SandboxClient`, and the deprecated `LegacyBundledAgent`. Set `DAYTONA_API_KEY` on the host, or pass `apiKey` in the sandbox config.
|
|
4
|
+
|
|
5
|
+
## Images and snapshots
|
|
6
|
+
|
|
7
|
+
Daytona starts sandboxes from snapshots. `Agent.prepare()` turns the agent's registry image into a snapshot named `nb-<name>-<hash>`, where the hash covers the image, the start command, and `resources` (`{ cpu, memory, disk }`, vCPUs and GiB), and waits until it can start sandboxes. Run it from CI after pushing the image; `start()` otherwise creates a missing snapshot itself, which takes minutes. `gc({ keep })` deletes this agent's older snapshots. To pull a private image, add its registry once in the Daytona dashboard. For `SandboxClient` and `LegacyBundledAgent`, `sandbox.template` names an existing snapshot, such as `daytona-small`.
|
|
8
|
+
|
|
9
|
+
## Network policy
|
|
10
|
+
|
|
11
|
+
Daytona sandboxes can also receive network policy options supported by the Daytona SDK. Use `domainAllowList` for domains and wildcard domains, or `networkAllowList` for comma-separated CIDR ranges:
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
new Agent({
|
|
15
|
+
name: "my-agent",
|
|
16
|
+
image: "ghcr.io/acme/my-agent:<commit>",
|
|
17
|
+
sandbox: { provider: "daytona", domainAllowList: "api.openai.com,*.example.com" },
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Set `networkBlockAll: true` only when you want to block all outbound network access. Daytona rejects `networkBlockAll: true` combined with non-empty allow lists.
|
|
22
|
+
|
|
23
|
+
Modal sandboxes accept the same three options in the same shape. Modal's domain allow list only passes HTTPS, so see [Modal network policy](MODAL.md#network-policy).
|
|
24
|
+
|
|
25
|
+
## Lifecycle
|
|
26
|
+
|
|
27
|
+
`autoStopInterval` and `autoDeleteInterval` set the sandbox's Daytona lifecycle, in whole minutes, when the sandbox is created; reconnecting to an existing sandbox does not change them. Daytona stops a sandbox after `autoStopInterval` minutes without activity (`0` disables auto-stop; omitting it keeps Daytona's default, 15 minutes for standard sandbox classes) and deletes it `autoDeleteInterval` minutes after it stops (`0` deletes it immediately; `-1`, the default, never auto-deletes it). `new Agent()` rejects values that are not whole minutes.
|
|
28
|
+
|
|
29
|
+
## SandboxClient
|
|
30
|
+
|
|
31
|
+
Use `SandboxClient` when host code needs provider-neutral filesystem or command access without running an agent invocation, such as staging documents into a sandbox before an agent runs or pulling artifacts out afterward:
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { SandboxClient } from "agent-neckbeard";
|
|
35
|
+
|
|
36
|
+
const sandbox = await SandboxClient.create({
|
|
37
|
+
provider: "daytona",
|
|
38
|
+
template: "daytona-small",
|
|
39
|
+
domainAllowList: "*.example.com",
|
|
40
|
+
autoDeleteInterval: 30,
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
const documentsDir = `${sandbox.paths.homeDir}/documents`;
|
|
44
|
+
await sandbox.makeDir(documentsDir);
|
|
45
|
+
await sandbox.writeFile(`${documentsDir}/input.txt`, "hello");
|
|
46
|
+
const result = await sandbox.runCommand("ls documents", {
|
|
47
|
+
cwd: sandbox.paths.homeDir,
|
|
48
|
+
timeoutMs: 60_000,
|
|
49
|
+
});
|
|
50
|
+
const bytes = await sandbox.readFileBytes(`${documentsDir}/input.txt`);
|
|
51
|
+
await sandbox.kill();
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Paths and HTTP
|
|
55
|
+
|
|
56
|
+
Daytona resolves the sandbox user's home directory at runtime (`/home/daytona` on default snapshots), so use `sandbox.paths.homeDir` rather than a fixed path. Neckbeard reaches a sandbox's server through a Daytona preview link and sends its preview token as the `DAYTONA_SANDBOX_AUTH_KEY` query parameter; callers only store the sandbox ID.
|
package/docs/DOCKER.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Docker Provider
|
|
2
2
|
|
|
3
|
-
The Docker provider runs the same agent runtime in a container on a local Docker daemon. It is supported by both `
|
|
3
|
+
The Docker provider runs the same agent runtime in a container on a local Docker daemon. It is supported by both `LegacyBundledAgent` and `SandboxClient` and needs only the `docker` CLI on the host `PATH`; there is no SDK dependency and no credential.
|
|
4
4
|
|
|
5
5
|
**It is a development and evaluation provider, not an isolation boundary.** E2B, Daytona, and Modal place untrusted agent tool calls inside a provider-operated microVM or gVisor sandbox. A Docker container shares the host kernel and runs here as root. Use it to iterate locally, to run evals next to local services on a compose network, and in CI. Do not use it to contain untrusted input in production, and note that the primary serverless consumers (Vercel Functions, Trigger.dev) have no Docker daemon at all.
|
|
6
6
|
|
|
@@ -30,17 +30,17 @@ All settings except `provider` are optional:
|
|
|
30
30
|
|
|
31
31
|
| Setting | Default | Meaning |
|
|
32
32
|
| --- | --- | --- |
|
|
33
|
-
| `template` | `node:22-bookworm` | Debian-compatible image. `
|
|
33
|
+
| `template` | `node:22-bookworm` | Debian-compatible image. `LegacyBundledAgent` requires Node.js and npm in it |
|
|
34
34
|
| `network` | Docker default bridge | Existing Docker network to join, such as a compose project network, so the agent can reach sibling services by name |
|
|
35
35
|
| `platform` | Daemon native | Image platform such as `linux/amd64` |
|
|
36
36
|
| `timeoutMs` | `3600000` | Fixed container lifetime in multiples of `1000` milliseconds, up to `86400000` (24 hours). The container exits and removes itself afterwards |
|
|
37
37
|
| `cpu` | Unlimited | Positive finite `--cpus` limit |
|
|
38
38
|
| `memoryMiB` | Unlimited | Positive integer `--memory` limit |
|
|
39
39
|
|
|
40
|
-
Use the same settings in
|
|
40
|
+
Use the same settings in a `LegacyBundledAgent`. Switching an existing agent between a cloud provider and Docker is a change to `sandbox` only:
|
|
41
41
|
|
|
42
42
|
```typescript
|
|
43
|
-
const agent = new
|
|
43
|
+
const agent = new LegacyBundledAgent({
|
|
44
44
|
sandbox: { provider: 'docker', network: 'my-eval_default' },
|
|
45
45
|
// sourceFile, inputSchema, session, dependencies, localDirectories, etc.
|
|
46
46
|
});
|
|
@@ -54,15 +54,15 @@ On Apple Silicon the default container is `linux/arm64`, while Neckbeard filters
|
|
|
54
54
|
|
|
55
55
|
## Attaching to an existing container
|
|
56
56
|
|
|
57
|
-
`SandboxClient.connect` accepts a container ID or name (kept verbatim as the handle `id`, so `
|
|
57
|
+
`SandboxClient.connect` accepts a container ID or name (kept verbatim as the handle `id`, so `LegacyBundledAgent.run(..., { sandboxId })` and `createSession({ sandboxId })` accept names and short IDs too), including containers this provider did not create, such as a service an eval harness or compose file already started:
|
|
58
58
|
|
|
59
59
|
```typescript
|
|
60
60
|
const sandbox = await SandboxClient.connect({ provider: 'docker', sandboxId: 'my-eval-main-1' });
|
|
61
61
|
```
|
|
62
62
|
|
|
63
|
-
Containers created by this provider carry the label `agent-neckbeard.managed=true`. **`destroy()` and `
|
|
63
|
+
Containers created by this provider carry the label `agent-neckbeard.managed=true`. **`destroy()` and `LegacyBundledAgent.kill()` remove only labeled containers.** For any other container they are a no-op: the container and its host tunnel are left in place for its owner and for other handles in the process. An attached container must be running, Debian-compatible, and able to run commands as root.
|
|
64
64
|
|
|
65
|
-
`
|
|
65
|
+
`LegacyBundledAgent.deploy()` always creates its own container; deploying an agent into a container owned by another tool is not supported yet. `LegacyBundledAgent.run(..., { sandboxId })` and `createSession({ sandboxId })` reconnect to a container that an earlier `deploy()` prepared. To put a deployed agent next to compose services, pass the compose network as `network` instead.
|
|
66
66
|
|
|
67
67
|
## HTTP access
|
|
68
68
|
|
package/docs/E2B.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# E2B Provider
|
|
2
|
+
|
|
3
|
+
E2B runs `Agent`, `SandboxClient`, and the deprecated `LegacyBundledAgent`. Set `E2B_API_KEY` on the host, or pass `apiKey` in the sandbox config. The E2B SDK sets the package's minimum host Node.js version; see [host requirements](CONSUMER_ENVIRONMENTS.md#host-requirements).
|
|
4
|
+
|
|
5
|
+
## Images and templates
|
|
6
|
+
|
|
7
|
+
E2B starts sandboxes from templates. `Agent.prepare()` builds a template named `nb-<name>-<hash>` from the agent's registry image, unless that template already has a ready build (it waits out a build in progress, builds again after a failed one, and builds after a grace period of a quarter of `prepareTimeoutMs`, at most a minute, when a registered build never starts), and `gc({ keep })` deletes this agent's older ones. To pull a private image, pass `sandbox.registry: { username, password }`; E2B uses it only while building the template. A template's start command cannot receive per-sandbox environment, so `Agent` starts the runtime as a background command after the sandbox starts. `cpuCount` and `memoryMB` size the sandbox, and `timeoutMs` sets its lifetime. For `SandboxClient` and `LegacyBundledAgent`, `sandbox.template` names an existing template, such as `code-interpreter-v1`.
|
|
8
|
+
|
|
9
|
+
## Lifetime, paths, and HTTP
|
|
10
|
+
|
|
11
|
+
`SandboxClient.create()` accepts `timeoutMs`, and E2B is the provider that supports `setTimeout()` to extend a running sandbox's lifetime; other providers throw `ConfigurationError`. The home directory is `/home/user`. Neckbeard sends E2B's traffic token as the `e2b-traffic-access-token` header; callers only store the sandbox ID.
|
package/docs/LEGACY.md
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
# Legacy API (deprecated)
|
|
2
|
+
|
|
3
|
+
> **Deprecated.** Everything on this page is deprecated: `LegacyBundledAgent`, its structured tasks and attached sessions, `dependencies`, `files`, `localDirectories`, `claudeDir`, the `mode` property, the Next.js helpers, and the durable-session supervisor. It will be deleted once Tupelo's `cim-agent`, `valuation-agent`, and `deal-qualification-agent` have moved to the image-based `Agent` (see the [README](../README.md) and [AGENT.md](AGENT.md)). It still works, and it receives fixes but no new features.
|
|
4
|
+
|
|
5
|
+
`LegacyBundledAgent` bundles your agent's code on the host and, at every deploy, uploads it with the embedded runtime server, installs its dependencies, and copies its local directories into the sandbox. Its usage patterns:
|
|
6
|
+
|
|
7
|
+
- Structured tasks: an agent runs once per background task and returns one validated output (Structured Tasks below).
|
|
8
|
+
- Attached sessions: a caller-owned session emits typed progress frames while work runs (Attached Sessions below).
|
|
9
|
+
- Durable sessions: an opt-in generated supervisor owns Pi inside Daytona and reconnects outward to a long-lived gateway (Durable Sessions below).
|
|
10
|
+
|
|
11
|
+
`SandboxClient`, which these also use, is not deprecated; see the README.
|
|
12
|
+
|
|
13
|
+
`LegacyBundledAgent.kind` reports `"task"` or `"session"`. The older `mode: "run" | "stream"` property remains as a deprecated compatibility surface.
|
|
14
|
+
|
|
15
|
+
## Legacy Bundled Agents
|
|
16
|
+
|
|
17
|
+
You write an agent:
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { LegacyBundledAgent } from "agent-neckbeard";
|
|
21
|
+
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
22
|
+
import { z } from "zod";
|
|
23
|
+
|
|
24
|
+
const agent = new LegacyBundledAgent({
|
|
25
|
+
sandbox: {
|
|
26
|
+
provider: "e2b",
|
|
27
|
+
template: "code-interpreter-v1",
|
|
28
|
+
},
|
|
29
|
+
inputSchema: z.object({ topic: z.string() }),
|
|
30
|
+
outputSchema: z.object({
|
|
31
|
+
title: z.string(),
|
|
32
|
+
summary: z.string(),
|
|
33
|
+
keyPoints: z.array(z.string()),
|
|
34
|
+
}),
|
|
35
|
+
envs: {
|
|
36
|
+
ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
|
|
37
|
+
},
|
|
38
|
+
run: async (input) => {
|
|
39
|
+
for await (const message of query({
|
|
40
|
+
prompt: `Research "${input.topic}" and return JSON`,
|
|
41
|
+
options: { maxTurns: 10 },
|
|
42
|
+
})) {
|
|
43
|
+
if (message.type === "result") {
|
|
44
|
+
return JSON.parse(message.result ?? "{}");
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
throw new Error("Claude did not return a result");
|
|
48
|
+
},
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const sandboxId = await agent.deploy();
|
|
52
|
+
const result = await agent.run({ topic: "TypeScript generics" }, { sandboxId });
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`deploy()` bundles your agent, uploads `agent.mjs` and the embedded runtime server to the sandbox, starts `node server.mjs`, waits for `/health`, and returns the sandbox ID.
|
|
56
|
+
|
|
57
|
+
`run()` validates input locally, POSTs it to the sandbox server, reads SSE harness events, validates the final output, and returns the existing `{ ok, executionId, output | error }` result shape.
|
|
58
|
+
|
|
59
|
+
By default, the package infers the file to bundle from the `new LegacyBundledAgent(...)` call stack. In frameworks that bundle server code before runtime, set `sourceFile` to the real agent module so `deploy()` does not rebundle a framework output chunk:
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
new LegacyBundledAgent({
|
|
63
|
+
sourceFile: path.resolve(process.cwd(), "packages/my-agent/src/agent.ts"),
|
|
64
|
+
// ...
|
|
65
|
+
});
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
When the right path differs between environments (for example a monorepo dev server versus a deployed worker), `resolveAgentSourceFile(candidates, { errorMessage })` returns the first candidate path that exists and falls back to the bundled agent module when running inside the sandbox.
|
|
69
|
+
|
|
70
|
+
For Next.js/Vercel-style deployments, keep `agent-neckbeard` external to the server bundle and make sure the referenced source file is included in the production artifact:
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
// next.config.ts
|
|
74
|
+
import { withNeckbeardNextConfig } from "agent-neckbeard";
|
|
75
|
+
|
|
76
|
+
const nextConfig = withNeckbeardNextConfig(
|
|
77
|
+
{
|
|
78
|
+
// your existing Next config
|
|
79
|
+
outputFileTracingIncludes: {
|
|
80
|
+
// Include every localDirectories source tree used by deploy().
|
|
81
|
+
"/api/my-agent": ["./packages/my-agent/.agents/**/*"],
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
routeGlob: "/api/my-agent",
|
|
86
|
+
sourceFiles: ["./packages/my-agent/src/agent.ts"],
|
|
87
|
+
},
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
export default nextConfig;
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
The helper traces files imported by those source entries by default, including package entry metadata that `deploy()` needs when it rebundles the agent at runtime. It preserves and merges existing `outputFileTracingIncludes`, such as the `.agents/**/*` entry above. A `localDirectories.source` is read by the deployed process, so its complete tree must be included in the production function artifact. Set `outputFileTracingRoot` when the agent source or local directory is outside the app root.
|
|
94
|
+
|
|
95
|
+
This repo tests that shape locally with `npm run test:compat:next`, which builds and runs a Dockerized Next App Router fixture without pushing to Vercel. The fixture also checks the runtime env contract, Node major, and traced standalone files so source-level tests do not mask deployment artifact problems.
|
|
96
|
+
|
|
97
|
+
## Setup
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
npm install agent-neckbeard
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
export E2B_API_KEY=your-key
|
|
105
|
+
export DAYTONA_API_KEY=your-key
|
|
106
|
+
export ANTHROPIC_API_KEY=your-key
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Pick the sandbox backend explicitly with `sandbox.provider`. The public `sandbox.template` field maps to an E2B template or a Daytona snapshot.
|
|
110
|
+
|
|
111
|
+
Daytona network policy (`networkBlockAll`, `networkAllowList`, `domainAllowList`) and lifecycle (`autoStopInterval`, `autoDeleteInterval`) settings go in `sandbox` as described in [DAYTONA.md](DAYTONA.md):
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
new LegacyBundledAgent({
|
|
115
|
+
sandbox: {
|
|
116
|
+
provider: "daytona",
|
|
117
|
+
template: "daytona-small",
|
|
118
|
+
domainAllowList: "*.example.com",
|
|
119
|
+
},
|
|
120
|
+
// ...
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
Modal sandboxes accept the same network options in the same shape; see [Modal network policy](MODAL.md#network-policy).
|
|
125
|
+
|
|
126
|
+
## Structured Tasks
|
|
127
|
+
|
|
128
|
+
Use `run` when each invocation should produce one validated output:
|
|
129
|
+
|
|
130
|
+
```typescript
|
|
131
|
+
new LegacyBundledAgent({
|
|
132
|
+
sandbox: {
|
|
133
|
+
provider: "e2b",
|
|
134
|
+
template: "code-interpreter-v1",
|
|
135
|
+
},
|
|
136
|
+
inputSchema: z.object({ prompt: z.string() }),
|
|
137
|
+
outputSchema: z.object({ answer: z.string() }),
|
|
138
|
+
run: async (input, ctx) => {
|
|
139
|
+
ctx.logger.info(`Handling ${ctx.executionId}`);
|
|
140
|
+
return { answer: input.prompt.toUpperCase() };
|
|
141
|
+
},
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
The `run` handler receives a context object with `executionId`, `AbortSignal`, environment variables, sandbox paths, and a logger:
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
run: async (input, ctx) => {
|
|
149
|
+
const notesPath = `${ctx.sandbox.homeDir}/data/notes.txt`;
|
|
150
|
+
const cwd = ctx.sandbox.agentDir;
|
|
151
|
+
// ...
|
|
152
|
+
};
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Use `ctx.sandbox.homeDir` and `ctx.sandbox.agentDir` instead of hardcoding `/home/user` if you want the same agent code to work on both providers.
|
|
156
|
+
|
|
157
|
+
Structured-task agents fit background workflows (Hatchet tasks, Trigger.dev jobs, queue workers). The usual shape is one sandbox per task:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
const sandboxId = await agent.deploy({ fresh: true });
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
const result = await agent.run(input, { sandboxId });
|
|
164
|
+
if (!result.ok) throw result.error;
|
|
165
|
+
return result.output;
|
|
166
|
+
} finally {
|
|
167
|
+
await agent.kill(sandboxId);
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
`deploy({ fresh: true })` keeps concurrent tasks from sharing one cached sandbox; see Reusing Sandboxes for the caching behavior.
|
|
172
|
+
|
|
173
|
+
The current 1.x structured-task configuration intentionally remains flat: top-level `outputSchema` and `run` define the task, and `agent.run()` executes it. Neither use of `run` is deprecated. A future API revision may introduce a noun-oriented `task: { outputSchema, handler }` configuration to parallel `session`, with a compatibility period for the current shape; no such change is scheduled.
|
|
174
|
+
|
|
175
|
+
## Attached Sessions
|
|
176
|
+
|
|
177
|
+
Use `session.handler` when you want progress frames while the sandbox work is still running, such as relaying tool calls and assistant text to a UI or event log:
|
|
178
|
+
|
|
179
|
+
```typescript
|
|
180
|
+
const agent = new LegacyBundledAgent({
|
|
181
|
+
sandbox: {
|
|
182
|
+
provider: "daytona",
|
|
183
|
+
template: "daytona-small",
|
|
184
|
+
},
|
|
185
|
+
inputSchema: z.object({ prompt: z.string() }),
|
|
186
|
+
session: {
|
|
187
|
+
frameSchema: z.object({
|
|
188
|
+
type: z.enum(["status", "token", "done"]),
|
|
189
|
+
text: z.string().optional(),
|
|
190
|
+
}),
|
|
191
|
+
handler: async ({ input, emit }) => {
|
|
192
|
+
await emit({ type: "status", text: `Starting ${input.prompt}` });
|
|
193
|
+
await emit({ type: "token", text: "hello" });
|
|
194
|
+
await emit({ type: "done" });
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
const sandboxId = await agent.deploy();
|
|
200
|
+
try {
|
|
201
|
+
const session = await agent.createSession({ sandboxId });
|
|
202
|
+
try {
|
|
203
|
+
for await (const frame of session.prompt({ prompt: "hi" })) {
|
|
204
|
+
console.log(frame);
|
|
205
|
+
}
|
|
206
|
+
} finally {
|
|
207
|
+
await session.close();
|
|
208
|
+
}
|
|
209
|
+
} finally {
|
|
210
|
+
await agent.kill(sandboxId);
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
An attached session is a local handle over the sandbox HTTP/SSE runtime. It supports sequential `prompt()` calls, one active turn at a time, `stop()` for the active turn, and `close()` for the local handle. Closing it does not destroy the reusable sandbox. Pass `{ signal }` to `createSession()` to bind the complete local session lifetime to an external abort signal. A turn's iterator completes only after the runtime reports that the handler finished; a stream that ends early throws `ExecutionError`, and a turn cancelled by `stop()`, `close()`, or the session signal rejects with that cancellation reason. The runtime runs one handler at a time, so starting a turn while an earlier handler is still running throws `RuntimeBusyError`. A cancelled turn rejects at once while its handler may keep running in the sandbox until it notices the cancellation; call `agent.waitForIdle({ sandboxId })` before reading what the handler writes, such as a transcript, or starting the next turn.
|
|
215
|
+
|
|
216
|
+
The previous `server: { frameSchema, handler }` configuration remains as a deprecated alias for `session`. Likewise, `invoke(input, options)` remains as a deprecated compatibility wrapper: it creates one attached session, streams one prompt, and closes the local handle afterward.
|
|
217
|
+
|
|
218
|
+
## Reusing Sandboxes
|
|
219
|
+
|
|
220
|
+
Persist the sandbox ID if another process needs to call the same running sandbox server:
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
const sandboxId = await agent.deploy();
|
|
224
|
+
await saveSandboxId(sandboxId);
|
|
225
|
+
|
|
226
|
+
// Later:
|
|
227
|
+
const savedSandboxId = await loadSandboxId();
|
|
228
|
+
const result = await agent.run(
|
|
229
|
+
{ topic: "hello" },
|
|
230
|
+
{ sandboxId: savedSandboxId },
|
|
231
|
+
);
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
Neckbeard rehydrates the sandbox endpoint and provider traffic token from the sandbox ID using the configured provider SDK. E2B traffic tokens are sent as the `e2b-traffic-access-token` header. Daytona preview tokens are sent as the `DAYTONA_SANDBOX_AUTH_KEY` query parameter. Consumers only need to store the sandbox ID and configure the same provider/API key in the process that reconnects.
|
|
235
|
+
|
|
236
|
+
`deploy()` caches the sandbox on the agent instance and returns the cached ID on later calls. Use `deploy({ fresh: true })` to provision a new sandbox without touching the instance cache, which is useful when one agent instance serves concurrent runs that each need their own sandbox. The caller owns the returned sandbox ID: pass it to `run()`/`createSession()` and `kill()` it explicitly.
|
|
237
|
+
|
|
238
|
+
### Environment Changes with Reused Sandboxes
|
|
239
|
+
|
|
240
|
+
`envs` are applied when Neckbeard creates the sandbox and starts the sandbox server. If the host app was missing a required value such as `ANTHROPIC_API_KEY` when the sandbox was created, the sandbox can remain healthy but unauthenticated even after you fix the host environment and redeploy the app.
|
|
241
|
+
|
|
242
|
+
Updating Vercel, Render, or 1Password environment variables does not mutate already-running sandboxes. Kill the old sandbox or deploy a fresh one and replace the persisted sandbox ID. Consumers that keep long-lived sandbox IDs should treat authentication failures such as `Not logged in` or `Please run /login` as a signal to discard the sandbox after verifying the host environment is now correct.
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
## Configuration
|
|
246
|
+
|
|
247
|
+
The configuration types are exported: `AgentConfig` (a union of `RunAgentConfig` for structured tasks and `SessionAgentConfig` for sessions), `SandboxConfig` (`E2BSandboxConfig`, `DaytonaSandboxConfig`, `ModalSandboxConfig`, `DockerSandboxConfig`), `OsDependencies`, `BuildOptions`, `FileDownload`, and `LocalDirectoryUpload`, all in [`src/index.ts`](../src/index.ts). Their fields:
|
|
248
|
+
|
|
249
|
+
- `sandbox`: the provider and its options. `template` is an E2B template or a Daytona snapshot.
|
|
250
|
+
- `inputSchema`, plus `outputSchema` and `run` for a structured task, or `session: { frameSchema, handler, port? }` for a session agent. `session.port` is the in-sandbox HTTP server's port, 3000 by default.
|
|
251
|
+
- `maxDuration`: seconds an invocation may run, 300 by default.
|
|
252
|
+
- `sourceFile`: the module to bundle, described above.
|
|
253
|
+
- `dependencies`: `{ apt?: string[], commands?: string[] }`, APT packages to install and shell commands to run in the sandbox during `deploy()`. None by default.
|
|
254
|
+
- `files` (`{ url, path }[]`), `localDirectories`, `claudeDir` (deprecated), `envs`, and `build` (`{ external?: string[], autoDetectExternal?: boolean }`), described below.
|
|
255
|
+
|
|
256
|
+
The `files` option downloads files into the sandbox before the server starts. Relative paths resolve from the sandbox home directory: `/home/user` on E2B and the sandbox user's home on Daytona (`/home/daytona` on default snapshots).
|
|
257
|
+
|
|
258
|
+
`LocalDirectoryUpload` is exported by the package and has this shape:
|
|
259
|
+
|
|
260
|
+
```typescript
|
|
261
|
+
interface LocalDirectoryUpload {
|
|
262
|
+
source: string;
|
|
263
|
+
destination: string;
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
`localDirectories` recursively copies consumer-selected local directories beneath `ctx.sandbox.agentDir` during `deploy()`. Relative sources resolve from the deploying process's current working directory; absolute sources are also supported. Nested paths and dotfiles are included, text and binary files retain their exact bytes, and parent directories are created as needed. Empty directories are not preserved. The files go up as one gzipped tar archive that the sandbox extracts with `tar`, so the image needs `tar` and `gzip`; files land with mode 0644.
|
|
268
|
+
|
|
269
|
+
Each `destination` is relative to the sandbox agent directory. For example, this Pi-oriented configuration produces `<sandbox agentDir>/.agents/skills/...` on both E2B and Daytona:
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
const agent = new LegacyBundledAgent({
|
|
273
|
+
localDirectories: [
|
|
274
|
+
{
|
|
275
|
+
source: "./packages/my-agent/.agents",
|
|
276
|
+
destination: ".agents",
|
|
277
|
+
},
|
|
278
|
+
],
|
|
279
|
+
// ...structured-task or session-agent configuration
|
|
280
|
+
});
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
Copying skills to `.agents/skills` does not guarantee that Pi or another harness will discover them automatically. If the harness working directory is elsewhere, pass `${ctx.sandbox.agentDir}/.agents/skills` to it as an explicit skill path. Neckbeard does not detect harnesses or change their discovery and trust settings.
|
|
284
|
+
|
|
285
|
+
Before creating a sandbox, Neckbeard validates and enumerates every local upload. A source must exist and be a directory. `localDirectories` rejects symbolic links anywhere in a source tree, with the local path in the error. Empty destinations, `.`, absolute destinations, traversal outside the agent directory, and duplicate sandbox targets are rejected with `ConfigurationError`; this includes collisions with another entry or with `claudeDir`.
|
|
286
|
+
|
|
287
|
+
For Next.js/Vercel and other bundled deployment environments, ensure each source tree is present in the runtime artifact. Include it with `withNeckbeardNextConfig` as shown above, with raw `outputFileTracingIncludes`, or with the equivalent artifact-inclusion setting for the host framework.
|
|
288
|
+
|
|
289
|
+
`claudeDir` is deprecated but remains functional for backward compatibility. It uploads the contents of a local `.claude` directory to `<sandbox agentDir>/.claude`, preserving existing Claude Agent SDK behavior. Replace it with an explicit `localDirectories` mapping:
|
|
290
|
+
|
|
291
|
+
```typescript
|
|
292
|
+
const agent = new LegacyBundledAgent({
|
|
293
|
+
localDirectories: [
|
|
294
|
+
{
|
|
295
|
+
source: "./my-project/.claude",
|
|
296
|
+
destination: ".claude",
|
|
297
|
+
},
|
|
298
|
+
],
|
|
299
|
+
// ...agent configuration
|
|
300
|
+
});
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
The `envs` option passes environment variables to the sandbox. Undefined values are filtered out:
|
|
304
|
+
|
|
305
|
+
```typescript
|
|
306
|
+
const agent = new LegacyBundledAgent({
|
|
307
|
+
sandbox: {
|
|
308
|
+
provider: "e2b",
|
|
309
|
+
template: "code-interpreter-v1",
|
|
310
|
+
},
|
|
311
|
+
envs: {
|
|
312
|
+
ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
|
|
313
|
+
MY_API_KEY: process.env.MY_API_KEY,
|
|
314
|
+
},
|
|
315
|
+
// ...
|
|
316
|
+
});
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
Some packages cannot be bundled because they spawn child processes or have native modules. The Claude Agent SDK is like this. These packages are automatically marked external and installed with npm in the sandbox. The `build` option tunes this: `build.external` adds package globs to mark external, and `build.autoDetectExternal: false` disables the native-module auto-detection.
|
|
320
|
+
|
|
321
|
+
## Cleanup
|
|
322
|
+
|
|
323
|
+
A successfully deployed sandbox remains caller-owned and runs until you kill it or the provider's lifetime settings expire it. If `deploy()` creates a sandbox but fails before returning its ID, Neckbeard reclaims that incomplete deployment so it does not leak an unreachable provider resource. Kill every successfully deployed sandbox, as in the workflow example above. `kill()` accepts a sandbox ID. If omitted, it kills the sandbox cached on the agent instance.
|
|
324
|
+
|
|
325
|
+
## Errors
|
|
326
|
+
|
|
327
|
+
All errors extend `NeckbeardError`. `ConfigurationError` covers invalid agent config, missing provider API keys, and provider features a sandbox does not support. `DeploymentError` covers sandbox creation, dependency install, and runtime server startup failures. After a runtime-server health-check failure, the two built-in startup paths include bounded best-effort captured logs when available, redact credential-named configured environment values and configured values of at least eight characters (including a possible tail-boundary fragment), and preserve the original health error if the diagnostic read fails or exceeds its local deadline. `ValidationError` wraps input/output schema failures with the parser error as `cause`. `ExecutionError` represents agent handler failures.
|
|
328
|
+
|
|
329
|
+
`run()` never throws; it returns `{ ok: false, error }`. Attached `session.prompt()` throws. The deprecated `invoke()` wrapper preserves that throwing behavior.
|
|
330
|
+
|
|
331
|
+
## Durable Sessions
|
|
332
|
+
|
|
333
|
+
> **Deprecated.** The durable-session supervisor is no longer maintained and will be removed in a future major release. Attached sessions (`LegacyBundledAgent.createSession()`) remain supported, but they are not durable: a turn stops when its caller disconnects, and nothing is replayed.
|
|
334
|
+
|
|
335
|
+
`agent-neckbeard/supervisor` runs a persistent sandbox process that owns Pi while a separate gateway and lifecycle worker may restart independently. `createDurableSessionArtifact()` builds it and `deployDurableSessionArtifact()` boots it in a Daytona sandbox. [SUPERVISOR.md](SUPERVISOR.md) documents it completely: the launch contract and an example, the attempt credential, `beforeRelease`, cancellation and unavailable-generation errors, the Daytona target and terminal helpers, the 64 MiB session history ceiling, the gateway protocol, and the deprecated `createPiSupervisorArtifact()` and `deploySupervisorArtifact()` aliases.
|