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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.28 - 2026-11-13
4
+
5
+ - Add `Agent`, which runs a Pi agent from a prebuilt container image, and `serve()` from the new `agent-neckbeard/serve` entry point, which the image runs as its main process around its Pi session, calling the session's optional `afterTurn()` before each turn's end record and outside its deadline. Starting a sandbox installs and uploads nothing, and `kill()` throws when a provider fails to delete a sandbox that still exists, so cleanup can be retried. Turns carry a caller-chosen `turnId` and per-turn `env`, stream numbered records of Pi's JSON events, keep running when the host disconnects, and resume from any record; retrying a start never runs a turn twice. Modal pulls the image directly; `prepare()` turns it into a Daytona snapshot or E2B template, and `gc()` deletes older ones. See `docs/AGENT.md`.
6
+ - **Breaking:** rename the previous `Agent` to `LegacyBundledAgent` and deprecate it, along with `resolveAgentSourceFile`, `withNeckbeardNextConfig`, and `AgentConfig`. Its bundled sandbox code must import `LegacyBundledAgent`.
7
+ - Add `getPiTurnResult(records)`, which reads how a Pi turn ended from its records, and reports a turn as completed only once its records include the `end` record.
8
+ - Add `SandboxClient.getServerEndpoint(port)`, and Modal `command` and `registrySecret` options for `SandboxClient.create()`.
9
+ - Add `defineAgent()`, which describes an agent once, in the module both the host and the image load: its image, its sandbox, and its Pi session from config (`model`, `thinkingLevel`, `tools`, `systemPrompt`, `cwd`, `persist`) or a `createSession` of its own. On the host it has `Agent`'s methods and `run()`, which runs a turn to its end and returns its text; in the image, `serve()`. A host runs the image `<registry>/<name>:<tag>`, with the tag from `NECKBEARD_IMAGE_TAG` or the commit its platform deployed, such as `RENDER_GIT_COMMIT` (`resolveImageTag()`). A Pi session's working directory is exported as `NECKBEARD_CWD`, and `start({ sessionId })` names a persisted session's file. See `docs/AGENT.md#defining-an-agent`. Pi is an optional peer dependency, `>=1.3.0 <2.0.0`; a `pi` agent's image installs the version its package resolves. A `pi` agent traces its turns in Braintrust when its sandbox has `BRAINTRUST_API_KEY` and `BRAINTRUST_PROJECT_NAME`; `braintrust` is an optional peer dependency. See `docs/AGENT.md#tracing`.
10
+ - Add `neckbeard push`, and `pushAgent()` from `agent-neckbeard/build`, which build an agent's image with its Dockerfile from a temporary build context, push it, and build each pushed tag's Daytona snapshot or E2B template again, so a reused tag such as `master` gets its new contents, deleting all but the newest three older ones. `--cache` uses a registry build cache, and `--dry-run` only builds.
11
+ - Add `neckbeard build`, and `buildAgent()` from the new `agent-neckbeard/build` entry point, which write the build context of an agent defined with `defineAgent()`: the bundled module with an entry point that serves it, a `package.json` pinning the packages left external, and `.agents/skills` with the package's own `skills/` plus the third-party skills its `skills-lock.json` pins. Those are restored with the skills CLI (`skills@1.8.1`, a new optional dependency that needs Node.js 22.20 or later, which a build with a lock then needs too) under `--frozen-lockfile`, so each is fetched at its locked commit and verified against the lock's hash. The build fails on a lock entry not pinned to a full commit SHA or a skill in both places. See `docs/AGENT.md#building-and-pushing-the-image`.
12
+ - Rewrite the README around `defineAgent()`, `neckbeard push`, and `SandboxClient`. The deprecated API's documentation moves to `docs/LEGACY.md`, Daytona and E2B get their own docs, and the host requirements move to `docs/CONSUMER_ENVIRONMENTS.md`.
13
+
14
+ ## 1.1.27 - 2026-11-09
15
+
16
+ - Upload `localDirectories` (and `claudeDir`) as one gzipped tar archive extracted with the sandbox's `tar`, instead of one provider call per file and directory. A 138-file skills directory took about two minutes to upload to a distant Modal sandbox. Images now need `tar` and `gzip`, and uploaded files have mode 0644.
17
+ - Accept `regions` in Modal sandbox config and pass it to sandbox creation. Modal otherwise places a sandbox in any region worldwide.
18
+ - Accept Daytona's `networkBlockAll`, `networkAllowList`, and `domainAllowList` in Modal sandbox config, in the same shape, mapped to Modal's outbound network policy. Modal's domain allow list only passes HTTPS, so with one set the image's apt sources are switched to HTTPS. See `docs/MODAL.md#network-policy`.
19
+ - Link a Modal image's `node`, `npm`, and `npx` into `/usr/local/bin` when they resolve elsewhere, such as an nvm install, so the runtime's fixed `PATH` finds them. Images like `daytonaio/sandbox:*-slim` failed their health check before.
20
+
3
21
  ## 1.1.26 - 2026-11-03
4
22
 
5
23
  - Make the runtime wait up to 10 seconds for an aborted handler to stop before emitting the terminal `error` event, so the event marks the end of the handler's work. The host's `run()` timeout allows for that grace period.
package/README.md CHANGED
@@ -2,508 +2,102 @@
2
2
 
3
3
  # neckbeard
4
4
 
5
- Neckbeard deploys your agent code into an E2B, Daytona, or Modal sandbox and runs it behind a small persistent HTTP server inside that sandbox.
5
+ Neckbeard runs a [Pi](https://github.com/earendil-works/pi) agent in a Daytona, Modal, or E2B sandbox from a container image you build ahead of time, and streams its turns back to your code. Your production process never runs the agent: it starts a sandbox, sends each turn to the agent over a private endpoint, and reads Pi's events as they happen. A sandbox starts with nothing to install or upload, a turn keeps running if your process restarts, and its stream resumes where it left off. Use it when an agent needs its own filesystem, shell, and tools, from a Hatchet worker, a Trigger.dev task, or a Vercel Function (see [consumer environments](docs/CONSUMER_ENVIRONMENTS.md)).
6
6
 
7
- The intent is simple: your production process should not run the agent. The sandbox runs the agent, keeps its filesystem/process state, and exposes a private `/invoke` endpoint that neckbeard calls for each turn.
7
+ ## An agent package
8
8
 
9
- This is designed to work from short-lived request handlers and long-running workers, including Vercel Functions, Hatchet workers, and Trigger.dev tasks. See `docs/CONSUMER_ENVIRONMENTS.md` before changing lifecycle, timeout, streaming, or cleanup behavior for those environments.
10
-
11
- The host package requires Node.js `>=20.18.1 <21 || >=22`, matching the supported range of its E2B runtime dependency. Its esbuild runtime dependency requires Linux kernel 3.2 or later or macOS 12 or later on those platforms.
12
-
13
- The Modal provider additionally requires host Node.js 22+ and `MODAL_TOKEN_ID` / `MODAL_TOKEN_SECRET` (or SDK profile credentials). Start with `sandbox: { provider: 'modal' }`; optional settings include `appName`, registry-image `template`, `environment`, `timeoutMs`, `cpu`, and `memoryMiB`. Modal uses private Connect Token HTTP auth and the shared managed detached controller. See [Modal configuration, limits, and live tests](docs/MODAL.md).
14
-
15
- For local development, evals, and CI there is also `sandbox: { provider: 'docker' }`, which needs only the `docker` CLI and can join a compose network via `network`. It is not an isolation boundary and is not meant for production. See [Docker provider](docs/DOCKER.md).
16
-
17
- The Modal adapter forces root, including for custom images. Claude Agent SDK consumers opting into `bypassPermissions` must explicitly forward `IS_SANDBOX: '1'` through `Agent.envs` for Claude's root-user check; Neckbeard does not enable this or bypass permissions by default. See the [Claude-on-Modal guide and example](docs/MODAL.md#claude-permissions-under-root) for the security implications and tested workaround.
18
-
19
- The four primary usage patterns:
20
-
21
- - Structured tasks: an agent runs once per background task and returns one validated output (Structured Tasks below).
22
- - Attached sessions: a caller-owned session emits typed progress frames while work runs (Attached Sessions below).
23
- - Direct sandbox access: `SandboxClient` wraps E2B, Daytona, and Modal behind one filesystem/command API, no agent required (Direct Sandbox Access below).
24
- - Durable sessions (deprecated): an opt-in generated supervisor owns Pi inside Daytona and reconnects outward to a long-lived gateway (Durable Sessions below).
25
-
26
- `Agent.kind` reports `"task"` or `"session"`. The older `mode: "run" | "stream"` property remains as a deprecated compatibility surface.
27
-
28
- ## What This Does
29
-
30
- You write an agent:
31
-
32
- ```typescript
33
- import { Agent } from "agent-neckbeard";
34
- import { query } from "@anthropic-ai/claude-agent-sdk";
35
- import { z } from "zod";
36
-
37
- const agent = new Agent({
38
- sandbox: {
39
- provider: "e2b",
40
- template: "code-interpreter-v1",
41
- },
42
- inputSchema: z.object({ topic: z.string() }),
43
- outputSchema: z.object({
44
- title: z.string(),
45
- summary: z.string(),
46
- keyPoints: z.array(z.string()),
47
- }),
48
- envs: {
49
- ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
50
- },
51
- run: async (input) => {
52
- for await (const message of query({
53
- prompt: `Research "${input.topic}" and return JSON`,
54
- options: { maxTurns: 10 },
55
- })) {
56
- if (message.type === "result") {
57
- return JSON.parse(message.result ?? "{}");
58
- }
59
- }
60
- throw new Error("Claude did not return a result");
61
- },
62
- });
63
-
64
- const sandboxId = await agent.deploy();
65
- const result = await agent.run({ topic: "TypeScript generics" }, { sandboxId });
66
- ```
67
-
68
- `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.
69
-
70
- `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.
71
-
72
- By default, the package infers the file to bundle from the `new Agent(...)` 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:
73
-
74
- ```typescript
75
- new Agent({
76
- sourceFile: path.resolve(process.cwd(), "packages/my-agent/src/agent.ts"),
77
- // ...
78
- });
79
9
  ```
80
-
81
- 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.
82
-
83
- 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:
84
-
85
- ```typescript
86
- // next.config.ts
87
- import { withNeckbeardNextConfig } from "agent-neckbeard";
88
-
89
- const nextConfig = withNeckbeardNextConfig(
90
- {
91
- // your existing Next config
92
- outputFileTracingIncludes: {
93
- // Include every localDirectories source tree used by deploy().
94
- "/api/my-agent": ["./packages/my-agent/.agents/**/*"],
95
- },
96
- },
97
- {
98
- routeGlob: "/api/my-agent",
99
- sourceFiles: ["./packages/my-agent/src/agent.ts"],
100
- },
101
- );
102
-
103
- export default nextConfig;
10
+ my-agent/
11
+ src/agent.ts # defineAgent(): the image, the sandbox, and the Pi session, used by both your process and the image
12
+ skills/ # skills you wrote, committed
13
+ skills-lock.json # third-party skills, pinned to commits (npx skills@1.8.1 add <repo>#<sha> --skill <name> --copy)
14
+ sandbox/Dockerfile # OS and Python packages; copies in what neckbeard build writes
104
15
  ```
105
16
 
106
- 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.
107
-
108
- 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.
109
-
110
- ## Setup
111
-
112
- ```bash
113
- npm install agent-neckbeard
114
- ```
17
+ ## Quickstart
115
18
 
116
19
  ```bash
117
- export E2B_API_KEY=your-key
118
- export DAYTONA_API_KEY=your-key
119
- export ANTHROPIC_API_KEY=your-key
20
+ npm install agent-neckbeard @earendil-works/pi-coding-agent
120
21
  ```
121
22
 
122
- Pick the sandbox backend explicitly with `sandbox.provider`. The public `sandbox.template` field maps to an E2B template or a Daytona snapshot.
123
-
124
- 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:
23
+ `src/agent.ts` defines the agent once. In the image it serves its Pi session, which lives as long as the sandbox, so each turn remembers the earlier ones; in your process it starts sandboxes and runs turns.
125
24
 
126
25
  ```typescript
127
- new Agent({
128
- sandbox: {
129
- provider: "daytona",
130
- template: "daytona-small",
131
- domainAllowList: "*.example.com",
132
- },
133
- // ...
134
- });
135
- ```
136
-
137
- Set `networkBlockAll: true` only when you want to block all outbound network access. Daytona rejects `networkBlockAll: true` combined with non-empty allow lists.
138
-
139
- `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).
140
-
141
- ## Structured Tasks
142
-
143
- Use `run` when each invocation should produce one validated output:
26
+ import { defineAgent } from "agent-neckbeard";
27
+ import type { JsonAgentSessionEvent } from "@earendil-works/pi-coding-agent";
144
28
 
145
- ```typescript
146
- new Agent({
147
- sandbox: {
148
- provider: "e2b",
149
- template: "code-interpreter-v1",
150
- },
151
- inputSchema: z.object({ prompt: z.string() }),
152
- outputSchema: z.object({ answer: z.string() }),
153
- run: async (input, ctx) => {
154
- ctx.logger.info(`Handling ${ctx.executionId}`);
155
- return { answer: input.prompt.toUpperCase() };
156
- },
29
+ export const myAgent = defineAgent<JsonAgentSessionEvent>({
30
+ name: "my-agent",
31
+ registry: "ghcr.io/acme", // the image is ghcr.io/acme/my-agent:<commit>
32
+ sandbox: { provider: "daytona", resources: { cpu: 2, memory: 4, disk: 8 } },
33
+ envs: () => ({ OPENAI_API_KEY: process.env.OPENAI_API_KEY }),
34
+ pi: { model: "openai/gpt-6.1-sol", tools: ["read", "bash", "grep", "ls"], systemPrompt: "You are a helpful agent." },
157
35
  });
158
36
  ```
159
37
 
160
- The `run` handler receives a context object with `executionId`, `AbortSignal`, environment variables, sandbox paths, and a logger:
161
-
162
- ```typescript
163
- run: async (input, ctx) => {
164
- const notesPath = `${ctx.sandbox.homeDir}/data/notes.txt`;
165
- const cwd = ctx.sandbox.agentDir;
166
- // ...
167
- };
168
- ```
169
-
170
- 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.
171
-
172
- Structured-task agents fit background workflows (Hatchet tasks, Trigger.dev jobs, queue workers). The usual shape is one sandbox per task:
173
-
174
- ```typescript
175
- const sandboxId = await agent.deploy({ fresh: true });
176
-
177
- try {
178
- const result = await agent.run(input, { sandboxId });
179
- if (!result.ok) throw result.error;
180
- return result.output;
181
- } finally {
182
- await agent.kill(sandboxId);
183
- }
184
- ```
185
-
186
- `deploy({ fresh: true })` keeps concurrent tasks from sharing one cached sandbox; see Reusing Sandboxes for the caching behavior.
187
-
188
- 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.
189
-
190
- ## Attached Sessions
191
-
192
- 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:
193
-
194
- ```typescript
195
- const agent = new Agent({
196
- sandbox: {
197
- provider: "daytona",
198
- template: "daytona-small",
199
- },
200
- inputSchema: z.object({ prompt: z.string() }),
201
- session: {
202
- frameSchema: z.object({
203
- type: z.enum(["status", "token", "done"]),
204
- text: z.string().optional(),
205
- }),
206
- handler: async ({ input, emit }) => {
207
- await emit({ type: "status", text: `Starting ${input.prompt}` });
208
- await emit({ type: "token", text: "hello" });
209
- await emit({ type: "done" });
210
- },
211
- },
212
- });
213
-
214
- const sandboxId = await agent.deploy();
215
- try {
216
- const session = await agent.createSession({ sandboxId });
217
- try {
218
- for await (const frame of session.prompt({ prompt: "hi" })) {
219
- console.log(frame);
220
- }
221
- } finally {
222
- await session.close();
223
- }
224
- } finally {
225
- await agent.kill(sandboxId);
226
- }
227
- ```
228
-
229
- 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.
230
-
231
- 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.
232
-
233
- ## Reusing Sandboxes
234
-
235
- Persist the sandbox ID if another process needs to call the same running sandbox server:
236
-
237
- ```typescript
238
- const sandboxId = await agent.deploy();
239
- await saveSandboxId(sandboxId);
240
-
241
- // Later:
242
- const savedSandboxId = await loadSandboxId();
243
- const result = await agent.run(
244
- { topic: "hello" },
245
- { sandboxId: savedSandboxId },
246
- );
247
- ```
248
-
249
- 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.
250
-
251
- `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.
252
-
253
- ### Environment Changes with Reused Sandboxes
254
-
255
- `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.
38
+ `neckbeard push`, run from CI, bundles it with Pi's `package.json` and installs `skills/` and the locked skills into the image's build context, builds the image with `sandbox/Dockerfile` ([example](docs/AGENT.md#building-and-pushing-the-image)), pushes it tagged with the commit, and creates its Daytona snapshot:
256
39
 
257
- 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.
258
-
259
- ## Direct Sandbox Access
260
-
261
- 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:
262
-
263
- ```typescript
264
- import { SandboxClient } from "agent-neckbeard";
265
-
266
- const sandbox = await SandboxClient.create({
267
- provider: "daytona",
268
- template: "daytona-small",
269
- domainAllowList: "*.example.com",
270
- autoDeleteInterval: 30,
271
- });
272
-
273
- const documentsDir = `${sandbox.paths.homeDir}/documents`;
274
- await sandbox.makeDir(documentsDir);
275
- await sandbox.writeFile(`${documentsDir}/input.txt`, "hello");
276
- const result = await sandbox.runCommand("ls documents", {
277
- cwd: sandbox.paths.homeDir,
278
- timeoutMs: 60_000,
279
- });
280
- const bytes = await sandbox.readFileBytes(`${documentsDir}/input.txt`);
281
- await sandbox.kill();
40
+ ```bash
41
+ npx neckbeard push src/agent.ts --tag $GITHUB_SHA
282
42
  ```
283
43
 
284
- Reconnect to an existing sandbox with `SandboxClient.connect({ provider, sandboxId })`. `create()` accepts provider-specific lifetime options: `timeoutMs` on E2B, plus `autoStopInterval` and `autoDeleteInterval` on Daytona. Daytona measures `autoDeleteInterval` from when the sandbox stops; `-1`, the default, disables auto-delete. `sandbox.paths` exposes the same provider-neutral paths agents receive as `ctx.sandbox`. E2B supports `setTimeout()` for sandbox lifetime extension; providers without that lifecycle primitive throw a `ConfigurationError`.
285
-
286
- `SandboxClient.startDetachedCommand()`, `readSessionLogs()`, `stopSession()`, and `disposeSessionArtifacts()` expose provider background-process primitives. Pass the complete opaque handle returned by `startDetachedCommand()` to every follow-up API; deprecated string overloads remain only for persisted handles from older releases and native provider sessions, while artifact disposal accepts managed current handles only. Detached prepare, release, cancellation, stop, and disposal failures use fixed bounded messages rather than reproducing provider output or SDK request options, which can contain launch environment values. Caller `envs` are serialized into one bounded internal provider value instead of becoming active variables in the lifecycle preparation shell. Before an SDK-selected outer shell starts (including E2B's login Bash), every control request supplies a trusted `PATH`, `TMPDIR`, and `LANG`, an inaccessible `HOME`, and neutral Bash/sh startup and xtrace controls. Preparation and the permanent reaper then run under fixed `PATH`, `HOME`, `TMPDIR`, and `LANG` values. A generic launch validates and erases the anonymous handoff descriptor before applying caller variables only to the requested `/bin/sh` payload; its payload `HOME` defaults to `sandbox.paths.homeDir` for compatibility, while an explicit caller `HOME` wins. Supervisor mode passes the descriptor to runtime entry for its existing strict hydration.
287
-
288
- Captured stdout and stderr are bounded, best-effort diagnostics only. Neckbeard reads them internally only in the two generic HTTP runtime startup paths, after a health check has already failed, to enrich the resulting `DeploymentError`; those paths give the diagnostic read a one-second local deadline, ignore a diagnostic failure, and redact every credential-named configured environment value plus configured values of at least eight characters before including available output. Redaction also suppresses the possible leading credential fragment created when a native provider tail begins inside a configured value, and the fully formatted internal diagnostic is bounded again to 8 MiB after sanitization. Shorter generic settings are not automatically redacted. A capture/append/rotation/marker failure disables further storage for that stream while its pump continues draining the FIFO, so diagnostic failure cannot remove the pipe reader or terminate the target with `EPIPE`. The durable supervisor and Mission Control never use these bytes as transcript, lifecycle, ownership, completion, or acknowledgement state. The public `readSessionLogs(handle)` API deliberately preserves raw captured output for compatibility: Neckbeard does not persist a historical secret dictionary that could reliably sanitize it, so callers must treat the result as sensitive diagnostic data and avoid exposing or retaining it without their own redaction. It reads stdout and stderr independently, so the returned pair is not one atomic cross-stream snapshot and the streams may represent different instants. Each returned stream contains at most the newest 8 MiB accepted by its read, including deprecated native-provider results. The detached envelope accepts only strict UTF-8; binary or otherwise invalid text fails closed to empty diagnostics instead of expanding through replacement characters beyond that byte bound. Legacy Daytona log leaves are bound to owner-only single-link descriptors before their bounded read.
289
-
290
- For the V2 capture protocol, each writer brackets a chunk append or rotation with atomically replaced `ROTATING` and `STABLE` generation markers. A reader makes a bounded number of optimistic marker-before/read/marker-after attempts. On each attempt it opens the current and optional previous segments, validates their owner-only single-link regular-file paths, binds the read to those descriptors, and accepts the payload only if the marker is unchanged. That check is a best-effort race detector, not a public guarantee of an atomic or perfectly coherent diagnostic snapshot. A concurrent writer or unsafe, malformed, or unstable state can make the read fail closed and return empty diagnostics; even a successful read may be stale relative to output still buffered in the pipe, and a process or sandbox crash can lose a final fragment that was never published. Recovery from a V2 `ROTATING` marker or a current segment missing after an interrupted current-to-previous rename occurs only when the current PROCESS_V3 lifecycle record proves quiescence through its exact completion marker. An older started PROCESS_V2 record has no equivalent proof and may therefore fail diagnostic recovery. An interrupted legacy rotation fails closed because its copy/truncate phases are ambiguous. Persisted V1 `STABLE` markers retain the compatible bounded double-marker reader without requiring `flock`, with the same descriptor-to-path validation. Current readers and writers do not take a per-stream log `flock`; empty legacy `.snapshot.lock` leaves may still be created solely for older readers during a rolling upgrade, but current code treats them as inert compatibility artifacts.
291
-
292
- A replacement-capable generation independently requires util-linux `flock` for its outer launch, decision, and replacement fence. Optional `disposeSessionArtifacts()` also requires `flock` for its destructive generation fence. Generic permanent launch, stop, and diagnostic log reads do not require it; a generic launch needs `flock` only if the caller later requests disposal. Stop remains exact-handle and PID-birth fenced without taking that lock. Diagnostic log reads do not acquire it either, even when its compatibility leaf exists: they identity-check the generation and bind each bounded read to validated file descriptors, but a concurrent retirement or replacement may make the sample stale or fail. Pass a stable `launchId` to make a retry adopt the same prepared process, and use `beforeRelease(prepared)` to durably persist its complete process handle before the command may run. The callback must be idempotent because a later caller may adopt the launch. Neckbeard hashes `launchId` before using it in sandbox paths and binds adoption to a URL-free hash of the command, working directory, and environment names; environment values are never written to the lifecycle markers or command string. Those values are therefore immutable for one `launchId`: rotate credentials or any other value by minting a replacement attempt and launch ID.
293
-
294
- E2B and Daytona publish an atomic release-or-cancel decision, wait for a durable started confirmation, and return only after release is confirmed. New detached launch and stop paths require Python 3 with Linux `prctl` and pidfd support. After validating the exact setsid leader, the permanent Python wrapper enables `PR_SET_CHILD_SUBREAPER`, durably publishes `started`, and only then spawns the diagnostic pumps and original payload through `sh -c`. A lost provider response can therefore adopt the same process without launching a duplicate. If an internal restart-capable leader dies before `started`, its absence proves that no logger or user workload was spawned and a locked retry can reclaim that incomplete generation. Once `started` exists, the wrapper remains the exact session leader, adopts orphaned descendants, waits through `ECHILD` (including its log pumps), writes a descriptor-bound exact completion marker, fsyncs it, and exits. Stop preserves that wrapper, opens a stable pidfd for each captured-session candidate before checking and signaling it, and reports success only after exact leader absence plus the completion proof. A descendant that creates a new session is not signaled; if the subreaper is still waiting for it, stop fails within its bounded deadline instead of falsely reporting quiescence. An exited started PROCESS_V2 record predates this proof and fails closed for current stop or replacement rather than claiming exact termination. Pre-V2 native handles retain their explicitly weaker compatibility behavior. Legacy `e2b:<pid>` handles cannot prove process birth or descendant ownership: their compatibility stop sends at most one provider signal and resolves only after E2B confirms the PID was already absent or its running-command inventory confirms that the numeric PID disappeared. It never signals that PID again while polling. These APIs are additive and do not change `runCommand()` behavior.
295
-
296
- Generic `startDetachedCommand()` launch IDs remain permanently bound to their first released generation, even after a short command exits. Durable supervisor deployment adds an internal recovery policy: once the PROCESS_V3 subreaper has published its exact completion proof (or an exact unstarted leader is absent), reconciliation may replace that dead generation on the same attempt. Lifecycle controls remain generation-fenced. Diagnostic reads do not take that fence: they check identity before capture and again before returning, so a normal concurrent replacement race fails empty instead of returning the replacement generation, while the broader snapshot remains explicitly best-effort rather than atomic.
297
-
298
- An application that reuses a sandbox can bound retained lifecycle state and diagnostics by calling `stopSession(handle)`, optionally reading final logs, and then calling `disposeSessionArtifacts(handle)`. Stop and log behavior are unchanged until that explicit destructive step. Disposal accepts an exact managed PROCESS_V3 generation only after either its exact leader is absent or no longer matches, no safe `started` marker exists, and the descriptor-bound quiescent leaf is still exactly empty, proving the workload never launched, or its exact `started` and completion markers both validate. It removes the exact launch directory, its identity-derived disposal recovery directory, any intact launch-key replacement-retirement directory that proves the same exact generation, and finally the generation lock. A mismatched, partial, or unsafe replacement-retirement directory fails closed instead of risking successor state. Disposal is idempotent when those exact artifacts are already absent. Absence during disposal is never process-exit evidence: callers must persist and retry stop confirmation first. After disposal, reads return no retained logs, stop can no longer prove the old generation, and the same stable `launchId` may create a new generation. Do not race generic same-`launchId` start with disposal; durable supervisor start and disposal share the generation lock, but lifecycle ownership still belongs in the calling control plane.
299
-
300
- ## Durable Sessions
301
-
302
- > **Deprecated.** The durable-session supervisor is no longer maintained and will be removed in a future major release. Attached sessions (`Agent.createSession()`) remain supported, but they are not durable: a turn stops when its caller disconnects, and nothing is replayed.
303
-
304
- Use `agent-neckbeard/supervisor` when a persistent sandbox process should own Pi while a separate gateway and lifecycle worker may restart independently:
44
+ Then run a turn from your process. A host deployed from the same commit runs that commit's image: it finds the commit in `GITHUB_SHA`, `RENDER_GIT_COMMIT`, `VERCEL_GIT_COMMIT_SHA` and the like, or `NECKBEARD_IMAGE_TAG` ([image names](docs/AGENT.md#image-names)).
305
45
 
306
46
  ```typescript
307
- import { SandboxClient } from "agent-neckbeard";
308
- import {
309
- createDurableSessionArtifact,
310
- deployDurableSessionArtifact,
311
- } from "agent-neckbeard/supervisor";
312
-
313
- const sandbox = await SandboxClient.connect({ provider: "daytona", sandboxId });
314
- const artifact = createDurableSessionArtifact({
315
- sessionId,
316
- runId,
317
- attemptId,
318
- gatewayUrl: "wss://gateway.example.com/v1/supervisor",
319
- installDir: `${sandbox.paths.homeDir}/.neckbeard/runtime/${attemptId}`,
320
- stateDurabilityAnchor: sandbox.paths.homeDir,
321
- stateDir: `${sandbox.paths.homeDir}/.neckbeard/sessions/${sessionId}`,
322
- workspaceDir: sandbox.paths.workDir,
323
- pi: {
324
- provider: "anthropic",
325
- model: "claude-sonnet-4-5",
326
- providerCredentialEnv: "ANTHROPIC_API_KEY",
327
- },
328
- });
47
+ import { myAgent } from "./agent";
329
48
 
330
- const supervisorProcess = await deployDurableSessionArtifact(
331
- sandbox,
332
- artifact,
333
- {
334
- envs: {
335
- NECKBEARD_SUPERVISOR_CREDENTIAL: attemptCredential,
336
- ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
337
- },
338
- beforeRelease: async (prepared) => {
339
- await persistSandboxProcess(prepared);
340
- },
341
- },
342
- );
343
-
344
- // During terminal reconciliation, load the identity persisted above, stop the
345
- // exact fenced process, then apply the application's sandbox deletion policy.
49
+ const sandboxId = await myAgent.start();
346
50
  try {
347
- const persistedProcess = await loadSandboxProcess();
348
- await sandbox.stopSession(persistedProcess);
349
- await sandbox.disposeSessionArtifacts(persistedProcess);
51
+ const text = await myAgent.run(sandboxId, { turnId: "run-1", message: "What is in my home directory?" }, {
52
+ onRecord: (record) => {}, // stream these to your UI as they arrive
53
+ });
54
+ console.log(text);
350
55
  } finally {
351
- await sandbox.kill();
56
+ await myAgent.kill(sandboxId);
352
57
  }
353
58
  ```
354
59
 
355
- `createDaytonaSupervisorSandboxTarget()` adapts an already-connected `@daytona/sdk` sandbox to the same narrow deployment contract without taking ownership of that sandbox. Its optional `beforeMutation` hook revalidates external lifecycle ownership before path discovery, staging, bootstrap, each prepare request, and every cleanup/adoption request that lacks an exact returned identity; release authorization remains the `beforeRelease` callback, and release or cleanup of a captured exact identity deliberately bypasses the hook so the single-winner launch decision can finish after ownership changes. If any identity-less ownership check fails after an uncertain provider request, the stale caller issues no later cancellation or adoption request against the deterministic launch, leaving it same-attempt retryable by the current owner. Terminal reconcilers with the raw Daytona SDK can call `stopDaytonaSupervisorSession(daytonaSandbox, persistedProcess, { beforeMutation })`, optionally retain their own final diagnostics before that boundary, then call `disposeDaytonaSupervisorSessionArtifacts(...)`. Those explicit terminal helpers depend only on Daytona's command transport, without launch-only HOME or working-directory discovery, and re-run `beforeMutation` immediately before every stop/disposal provider request and retry; a lost claim authorizes no later provider I/O. `validateDurableSessionDeploymentEnvironment()` exposes the same credential and bounded-environment preflight that `deployDurableSessionArtifact()` performs before sandbox I/O.
356
-
357
- The artifact uses `attemptId` as its stable launch identity. The attempt credential must be an opaque 256-bit CSPRNG token encoded as canonical unpadded base64url (43 characters), matching Mission Control's credential generator; arbitrary passwords are rejected. Persist the sandbox ID and prepared process identity in the idempotent `beforeRelease` callback; returning from that callback is the authorization for the process to run. Replacing an exited generation invokes the callback with a new exact identity, which must replace the prior persisted identity; stale handles remain exactly fenced for stop, while diagnostic reads use before/after identity checks and may fail empty during replacement. A revision keyed by that high-entropy credential binds every replacement generation to the canonical launch environment without placing a dictionary-checkable value hash in lifecycle state, so rotating any value requires a replacement attempt instead of silently relaunching the old attempt with new credentials or configuration. A persistence failure is reported through the fixed, credential-safe `Supervisor prepared identity persistence failed.` message unless subsequent cleanup confirms that cancellation won. A confirmed cancellation proves the prepared generation cannot run and instead throws `SupervisorLaunchCancelledError` with stable code `NECKBEARD_SUPERVISOR_LAUNCH_CANCELLED`; its enumerable `name` and `code` remain usable when serialization preserves enumerable fields. A lost cleanup response is not classified as cancelled and remains safe to retry with the same attempt. If release already won, cancellation adopts the released identity instead of reporting a cancelled outcome. Terminal reconciliation must stop that persisted process identity and either delete the sandbox explicitly, as above, or apply an explicitly configured provider stop/delete policy. The supervisor embeds the pinned `@earendil-works/pi-coding-agent` SDK in-process, uses an outbound resumable WebSocket, attempt fencing, monotonic event IDs, a fsynced disk outbox, cumulative acknowledgments, command write-ahead deduplication, verified attachment materialization, normalized turn lifecycle, turn-boundary steering, heartbeat/reconnect, and idempotent interrupted-turn recovery. Its Daytona snapshot must provide Node.js 22.19.0 or newer. The artifact uploads graph-addressed staging files, then under one sandbox `flock` verifies their hashes, atomically publishes and fsyncs the final runtime/config/dependency files, and runs `npm ci`. After npm's graph and version checks, bootstrap creates a deterministic bounded manifest of every directory, regular file, and safe relative symlink in `node_modules`; it fsyncs regular files and directories bottom-up before atomically publishing and fsyncing that manifest, then re-verifies the finals and publishes the fsynced graph marker. The bootstrap lock remains necessary because a provider timeout does not prove the remote `npm ci` stopped; a retry may overlap the same shared installation. Bootstrap runs with an empty inherited environment, neutral npm user/global configuration, and no project `.npmrc`; failures expose only a bounded exit-code summary, never raw provider or install output. A marked retry skips `npm ci` only after verifying the final files and exact dependency graph plus a descriptor-bound read and full recomputation of the installed-tree manifest. An absent, malformed, unsafe, oversized, or content-mismatched manifest enters the existing locked repair path, while another graph fails without replacing it. Custom Pi coordinates require a caller-supplied matching credential-free lock. Credentials are never embedded in generated files or install commands; the gateway credential is removed before Pi loads, and the provider credential is moved into Pi's in-memory model runtime before tools run.
60
+ ## Sessions and events
358
61
 
359
- Each attempt's Pi JSONL history has a hard 64 MiB ceiling. Startup rejects a larger file or a legacy session version before the SDK parses or migrates it, and new prompts or steers are refused at 56 MiB so an already accepted turn has 8 MiB of logical headroom. Admission finishes with a synchronous retained-descriptor size check immediately before the Pi side effect. The pinned Pi 1.3.0 manager must remain in the append-only state established by the explicit session-file open; the guard serializes each pending JSONL line once, refuses a line that would cross the ceiling, writes those exact bytes through the retained descriptor, and verifies the exact size delta afterward. An unexpected private full-rewrite state fails before any write instead of estimating Pi's private in-memory history. Empty-file initialization is the only supported open-time rewrite; non-empty history must already use Pi session format version 3. Any append guard or postcondition failure terminally fails the attempt because Pi advances its in-memory tree before calling the persistence hook. Terminal history is file-fsynced plus parent-fsynced only while the canonical private leaf still matches the retained descriptor before and after that durability boundary. The 8 MiB margin is budgeting headroom for an accepted turn, not filesystem preallocation or a promise that every future record will fit; terminal/restart facts use the supervisor outbox's separate recovery reserve. Replace the attempt when prompt admission reaches this boundary.
62
+ A sandbox holds one Pi session, and each `prompt()` or `run()` is a turn on it. The turn streams numbered records: `{ seq, type: "event", event }` for each Pi event, in the JSON form Pi's JSON mode writes (a `message_update` carries only its delta), then `{ seq, type: "end", outcome: "completed" | "aborted" | "failed", error? }`. The caller picks `turnId`: prompting again with the same ID resumes that turn instead of running it twice, and a different ID while a turn runs throws `RuntimeBusyError`. Disconnecting does not stop a turn; `myAgent.events(sandboxId, turnId, { after: seq })` resumes its stream, `myAgent.abort(sandboxId, turnId)` stops it, and `myAgent.waitForIdle(sandboxId)` waits until it has. `getPiTurnResult(records)` reads how a turn's records ended. See [AGENT.md](docs/AGENT.md) for the turn protocol.
360
63
 
361
- For that cancellation outcome, `JSON.parse(JSON.stringify(error))` retains the public `name` and `code`. Arbitrary error serializers are not part of the contract.
64
+ ## Tracing
362
65
 
363
- Replacement-capable release and adoption return a released handle only while the exact PROCESS_V3 leader is proven live under the generation lock. Exact completion proof remains safe to retry with the same attempt, allowing the completed generation to be retired and replaced. If an exact `started` marker exists but the leader is dead or ambiguous and no valid exact completion proof exists, deployment instead throws fixed-message `SupervisorReleasedGenerationUnavailableError` with stable code `NECKBEARD_SUPERVISOR_RELEASED_GENERATION_UNAVAILABLE`. The generation may have run, so this is neither cancellation nor transport uncertainty: the caller must fence and confirm termination of the whole sandbox, then create a new attempt or terminally interrupt the run rather than adopt or retry that released generation.
66
+ Give a `pi` agent's `envs` `BRAINTRUST_API_KEY` and `BRAINTRUST_PROJECT_NAME`, add `braintrust` to its package's dependencies, and each turn is traced in that Braintrust project. See [tracing](docs/AGENT.md#tracing).
364
67
 
365
- The previous `createPiSupervisorArtifact()` and `deploySupervisorArtifact()` exports remain as deprecated aliases.
68
+ ## Per-turn credentials
366
69
 
367
- See [`docs/SUPERVISOR.md`](docs/SUPERVISOR.md) for the complete launch and gateway protocol contract.
368
-
369
- ## Configuration
70
+ Secrets never go in the image. The definition's `envs` reach every sandbox, `start({ envs })` one sandbox, and a turn's `env` only that turn: the agent's `process.env` holds it while the turn runs, then it is restored. Use turn `env` for short-lived tokens tied to one user or request:
370
71
 
371
72
  ```typescript
372
- import type { LocalDirectoryUpload } from 'agent-neckbeard';
373
-
374
- new Agent({
375
- sandbox: {
376
- provider: 'e2b' | 'daytona',
377
- template: string,
378
- // Daytona only:
379
- networkBlockAll?: boolean,
380
- networkAllowList?: string,
381
- domainAllowList?: string,
382
- autoStopInterval?: number,
383
- autoDeleteInterval?: number,
384
- },
385
- inputSchema: ZodSchema,
386
- maxDuration?: number,
387
- dependencies?: {
388
- apt?: string[],
389
- commands?: string[],
390
- },
391
- files?: [{ url, path }],
392
- localDirectories?: LocalDirectoryUpload[],
393
- claudeDir?: string, // deprecated; use localDirectories
394
- envs?: Record<string, string | undefined>,
395
- build?: {
396
- external?: string[],
397
- autoDetectExternal?: boolean,
398
- },
399
- // Structured-task agents require:
400
- outputSchema: ZodSchema,
401
- run: (input, ctx) => Promise<output>,
402
- // Session agents require this instead of outputSchema/run:
403
- session: {
404
- port?: number,
405
- frameSchema: ZodSchema,
406
- handler: ({ input, ctx, signal, emit }) => Promise<void>,
407
- },
408
- });
73
+ await myAgent.run(sandboxId, { turnId: "run-2", message: "Sync the account", env: { API_TOKEN: "user-scoped-token" } });
409
74
  ```
410
75
 
411
- 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).
76
+ ## SandboxClient
412
77
 
413
- `LocalDirectoryUpload` is exported by the package and has this shape:
78
+ `SandboxClient` gives provider-neutral file and command access to a sandbox, for staging inputs before a turn and reading results after one. `myAgent.sandbox(sandboxId)` returns one for an agent's sandbox; `SandboxClient.create()` and `SandboxClient.connect({ provider, sandboxId })` work without an agent.
414
79
 
415
80
  ```typescript
416
- interface LocalDirectoryUpload {
417
- source: string;
418
- destination: string;
419
- }
81
+ const sandbox = await myAgent.sandbox(sandboxId);
82
+ await sandbox.writeFile(`${sandbox.paths.homeDir}/input.csv`, "a,b\n1,2\n");
83
+ const { exitCode, stdout } = await sandbox.runCommand("wc -l input.csv", { cwd: sandbox.paths.homeDir, timeoutMs: 30_000 });
420
84
  ```
421
85
 
422
- `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.
423
-
424
- 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:
425
-
426
- ```typescript
427
- const agent = new Agent({
428
- localDirectories: [
429
- {
430
- source: "./packages/my-agent/.agents",
431
- destination: ".agents",
432
- },
433
- ],
434
- // ...structured-task or session-agent configuration
435
- });
436
- ```
437
-
438
- 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.
439
-
440
- 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`.
86
+ Its detached background commands are described in [ARCHITECTURE.md](docs/ARCHITECTURE.md#detached-commands).
441
87
 
442
- 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.
88
+ ## Providers
443
89
 
444
- `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:
445
-
446
- ```typescript
447
- const agent = new Agent({
448
- localDirectories: [
449
- {
450
- source: "./my-project/.claude",
451
- destination: ".claude",
452
- },
453
- ],
454
- // ...agent configuration
455
- });
456
- ```
457
-
458
- The `envs` option passes environment variables to the sandbox. Undefined values are filtered out:
459
-
460
- ```typescript
461
- const agent = new Agent({
462
- sandbox: {
463
- provider: "e2b",
464
- template: "code-interpreter-v1",
465
- },
466
- envs: {
467
- ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
468
- MY_API_KEY: process.env.MY_API_KEY,
469
- },
470
- // ...
471
- });
472
- ```
473
-
474
- 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.
475
-
476
- ## Cleanup
477
-
478
- 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.
479
-
480
- ## Errors
481
-
482
- 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.
483
-
484
- `run()` never throws; it returns `{ ok: false, error }`. Attached `session.prompt()` throws. The deprecated `invoke()` wrapper preserves that throwing behavior.
485
-
486
- ## Testing
487
-
488
- ```bash
489
- npm run check
490
- ```
491
-
492
- The local check runs typecheck, repository lint checks, formatting hygiene checks, unit tests, generated runtime verification, CJS build verification, and package dry-run validation.
493
-
494
- Jest drives both the fast local suite and the live smoke suites. Each live suite automatically skips when its provider key is not set:
495
-
496
- ```bash
497
- npm run test:e2e:e2b
498
- npm run test:e2e:daytona
499
- ```
90
+ | Provider | Runs | Host credentials | Image | Details |
91
+ | --- | --- | --- | --- | --- |
92
+ | Daytona | `Agent`, `SandboxClient` | `DAYTONA_API_KEY` | `neckbeard push` makes a snapshot; add the registry in the Daytona dashboard | [DAYTONA.md](docs/DAYTONA.md) |
93
+ | Modal | `Agent`, `SandboxClient` | `MODAL_TOKEN_ID`, `MODAL_TOKEN_SECRET`; host Node.js 22+ | Pulled directly; `registrySecret` names a Modal Secret | [MODAL.md](docs/MODAL.md) |
94
+ | E2B | `Agent`, `SandboxClient` | `E2B_API_KEY` | `neckbeard push` builds a template; `registry` credentials | [E2B.md](docs/E2B.md) |
95
+ | Docker | `SandboxClient`, not `Agent`; local development only, not an isolation boundary | none | Any local image | [DOCKER.md](docs/DOCKER.md) |
500
96
 
501
- Optional environment variables:
97
+ The host needs Node.js `>=20.18.1 <21 || >=22`; see [host requirements](docs/CONSUMER_ENVIRONMENTS.md#host-requirements). Configuration is typed: `AgentDefinition` and `PiSessionConfig` in [`src/define.ts`](src/define.ts), `AgentOptions`, `AgentSandbox`, `StartOptions`, and `TurnStreamOptions` in [`src/agent.ts`](src/agent.ts), `ServeOptions` in [`src/serve.ts`](src/serve.ts), `BuildAgentOptions` in [`src/build.ts`](src/build.ts), and `SandboxClientCreateOptions` in [`src/index.ts`](src/index.ts).
502
98
 
503
- - `NECKBEARD_E2E_TEMPLATE` to override the default `code-interpreter-v1` test template
504
- - `NECKBEARD_DAYTONA_TEMPLATE` to override the default Daytona smoke snapshot (`daytona-small`)
505
- - `NECKBEARD_E2E_TIMEOUT_MS` to increase the live test timeout for slower environments
99
+ `LegacyBundledAgent`, structured tasks, and the durable-session supervisor are deprecated; see [LEGACY.md](docs/LEGACY.md).
506
100
 
507
- ## License
101
+ ## Development
508
102
 
509
- MIT
103
+ `npm run check` runs the local checks; see [TESTING.md](docs/TESTING.md) for live provider tests. MIT licensed.