agent-neckbeard 1.1.18 → 1.1.20

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,37 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ## 1.1.20 - 2026-08-25
6
+
7
+ - Wait for Daytona sandbox deletion to complete during deployment cleanup.
8
+
9
+ ## 1.1.19 - 2026-08-11
10
+
11
+ - Make implicit source detection independent of the package checkout directory name, including nested consumer chunks beside a bundled SDK, clean up newly created sandboxes when deployment fails after provider creation, refresh the E2B and Daytona runtime dependencies, and align the advertised host Node.js range with E2B (`>=20.18.1 <21 || >=22`). Intentionally move esbuild from 0.24 to 0.28.2 despite its breaking-version boundaries: 0.25 removes the development-server exposure described by GHSA-67mh-4wv8-2f99, 0.28 verifies fallback-downloaded npm binaries, and 0.28.2 carries subsequent bundler correctness fixes. The packaged Next fixture exercises the synchronous tracing path and the live provider suites exercise asynchronous deployment bundling with the upgraded line.
12
+ - Add `Agent.createSession()` as the primary attached-session API with sequential prompts, active-turn cancellation, and explicit local close; add `kind: "task" | "session"`, and retain `mode` plus `invoke()` as deprecated compatibility surfaces.
13
+ - Name the gateway-owned APIs `createDurableSessionArtifact()` and `deployDurableSessionArtifact()` while preserving the previous supervisor function names as deprecated aliases.
14
+ - Add `createDaytonaSupervisorSandboxTarget()` for already-connected Daytona sandboxes and `validateDurableSessionDeploymentEnvironment()` for provider-I/O-free launch preflight; classify only provider-confirmed cancellation through credential-safe `SupervisorLaunchCancelledError` with stable code `NECKBEARD_SUPERVISOR_LAUNCH_CANCELLED`, while leaving uncertain cleanup retryable on the same attempt and adopting a release that already won.
15
+ - Require exact live-generation proof before replacement-capable release or adoption returns a handle; keep exact completed generations same-attempt retryable, and classify started-but-unavailable generations through `SupervisorReleasedGenerationUnavailableError` with stable code `NECKBEARD_SUPERVISOR_RELEASED_GENERATION_UNAVAILABLE`.
16
+ - Add the opt-in `agent-neckbeard/supervisor` subpath with a versioned in-process `@earendil-works/pi-coding-agent` SDK artifact, outbound resumable WebSocket protocol, attempt fencing, disk-backed event replay and command deduplication, verified signed-URL attachment materialization, normalized turn lifecycle, heartbeat/reconnect handling, and idempotent active-turn recovery.
17
+ - Expose `SandboxClient.startDetachedCommand()`, `readSessionLogs()`, and `stopSession()` for persistent runtime boot and reconciliation, pass provider-owned detached handles intact to follow-up operations, and retain deprecated string overloads for legacy identities.
18
+ - Harden the durable supervisor with a single execution gate, atomic terminal arbitration, semantic command fingerprints, ordered per-socket intake, transmitted-only acknowledgements, byte-bounded replay, crash-safe acknowledged-history compaction, event-first outcome recovery, deep credential redaction, and PID-birth-fenced Daytona process cleanup.
19
+ - Bound raw gateway intake and pending command gaps, validate persisted event variants, make command attachments immutable and crash-durable, constrain all durable reasons and sandbox paths, coalesce Pi deltas with bounded memory, and terminalize accepted work during graceful shutdown.
20
+ - Make attached-session close callers share one teardown Promise and make Daytona detached stop wait through birth-fenced TERM/KILL escalation before resolving.
21
+ - Make E2B and Daytona detached launches adopt a stable hashed launch record, persist identity before an optional release callback, atomically arbitrate release versus cancellation, confirm started state across response loss, preserve compound shell commands, and revalidate PID birth before every descendant scan and signal.
22
+ - Make legacy E2B PID-handle stop require provider not-found or inventory confirmation that the numeric leader disappeared, while retaining its documented non-birth-fenced compatibility limits.
23
+ - Move durable attempt storage behind a runtime-2 revision pointer that blocks older runtimes, fsync newly created directory entries, fail closed on corrupt active-turn markers, install the generated default Pi dependency graph with `npm ci` under a clean environment and neutral npm configuration, suppress raw provider/install diagnostics, require a matching lock for custom Pi coordinates, and reject non-Daytona supervisor targets before sandbox mutation.
24
+ - Bound all repeated supervisor identifiers and raw Pi-event traversal, cancel attachment response bodies on every failure path, reuse attached-session connections, make reconnect/startup waits cancellable, and share shell/error/package-manifest policies across host and embedded runtimes.
25
+ - Restart an exited released durable supervisor on the same attempt under generation and environment-revision fencing, require canonical 256-bit random attempt credentials before using them as revision keys, verify and repair marked dependency installs, establish trusted no-symlink install paths before upload, reject unsafe or oversized journal/control leaves, migrate genuine runtime-1 full-history journals, retain Pi resource-root identity, rotate detached output into independently read, bounded 8 MiB best-effort diagnostic tails with descriptor-bound optimistic marker reads, V1 compatibility, quiescent crash recovery, identity-revalidated reads, and keep stopped-turn command bookkeeping bounded.
26
+ - Remove detached-log `flock` coordination entirely: V1/V2 readers use bounded marker-before/read/marker-after checks, revalidate the launch identity before returning, and may return stale or empty diagnostics or lose an unpublished crash fragment. Inert legacy lock leaves remain for rolling-reader compatibility. The independent generation `flock` remains only for launch, decision, and replacement control, and bootstrap still uses `flock` because a provider timeout can overlap a shared `npm ci`. Detached logs never determine transcript, lifecycle, ownership, completion, or acknowledgement state.
27
+ - Keep public `readSessionLogs()` raw for valid-text compatibility and require callers to treat its result as sensitive diagnostic data because Neckbeard does not persist a historical secret dictionary. Reject invalid UTF-8 envelopes before decoding can expand an accepted 8 MiB byte stream. The two built-in runtime-startup `DeploymentError` paths instead redact credential-named configured environment values and configured values of at least eight characters, suppress tail-boundary fragments, re-bound sanitized diagnostics to 8 MiB, and fail empty after a one-second diagnostic-read deadline; Mission Control has no log-read caller. Keep generic detached prepare/release/cancel/stop errors fixed and bounded so provider SDK diagnostics cannot echo launch environment values, transport generic caller variables through the same bounded anonymous-descriptor boundary so lifecycle preparation and the permanent reaper use only a fixed clean environment, neutralize provider-shell startup controls before E2B's login shell can inspect that composite, and preserve the generic runtime's provider-home `HOME` default unless the caller overrides it.
28
+ - Bound durable attachment storage across commands and restarts with per-attempt file/byte quotas reconstructed from descriptor-bound published files, recover crash-left temporary links and pending batch markers, and durably roll back only the files owned by a failed command batch.
29
+ - Keep detached FIFO pumps draining after diagnostic capture failure so log corruption cannot terminate the target; make a permanent Python subreaper publish `started` before spawning pumps or user code, reap adopted descendants through `ECHILD`, and fsync an exact completion proof before a started V3 generation can stop or be replaced. Reclaim an absent exact pre-`started` leader because no workload could have launched, and fail closed for exited started PROCESS_V2 records that lack this proof.
30
+ - Validate the public `createSession()` JavaScript options boundary with native `AbortSignal` branding, reject oversized timer delays and semantically invalid persisted token/cost/PID fields, enforce append-only command outcome transitions during recovery, and randomize atomic control-file temporary names across crashes.
31
+ - Make a bootstrap graph marker attest to the complete installed payload: record a bounded deterministic no-follow `node_modules` manifest, fsync installed files and directories before atomically publishing it, verify it through the retained install-directory descriptor on marked retries, and repair deleted, truncated, unsafe, or mismatched trees under the existing installer `flock`.
32
+ - Add explicit managed-handle `disposeSessionArtifacts()` plus narrow raw-Daytona supervisor stop/disposal helpers. Terminal cleanup now preserves stop and log-read compatibility until an exact, idempotent destructive step removes an exactly quiescent started generation or a safely unstarted one with its intact descriptor-bound empty pre-start proof, together with its crash-recovery, diagnostic, and generation-lock artifacts. Crash-left replacement retirement is removed only after its intact identity and proof match the exact handle; mismatched, partial, or unsafe state fails closed. Raw-Daytona terminal control depends only on command execution rather than launch-only path discovery, and every retry revalidates external ownership before provider I/O.
33
+ - Bound each attempt's Pi JSONL history to a hard 64 MiB ceiling with a final synchronous 56 MiB prompt/steer admission check, reject oversized or legacy restart files before SDK parsing or migration, require the pinned Pi manager's append-only state, serialize and descriptor-write each pending JSONL line exactly once, terminally latch every persistence failure after Pi's in-memory mutation, refuse unexpected private full rewrites before they write, and revalidate the canonical private session leaf before and after terminal file-plus-parent fsync so replacement cannot publish terminal success.
34
+
3
35
  ## 1.1.18 - 2026-08-05
4
36
 
5
37
  - Add harness-neutral `localDirectories` uploads beneath the sandbox agent directory, with recursive byte-preserving copies and deployment preflight validation.
package/README.md CHANGED
@@ -8,25 +8,30 @@ The intent is simple: your production process should not run the agent. The sand
8
8
 
9
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
10
 
11
- The three primary usage patterns:
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
12
 
13
- - Workflows: a run-output agent runs once per background task and returns one validated output (Run-Output Agents below).
14
- - Streaming: a persistent sandbox server emits typed progress frames while work runs (Streaming Agents below).
13
+ The four primary usage patterns:
14
+
15
+ - Structured tasks: an agent runs once per background task and returns one validated output (Structured Tasks below).
16
+ - Attached sessions: a caller-owned session emits typed progress frames while work runs (Attached Sessions below).
15
17
  - Direct sandbox access: `SandboxClient` wraps E2B and Daytona behind one filesystem/command API, no agent required (Direct Sandbox Access below).
18
+ - Durable sessions: an opt-in generated supervisor owns Pi inside Daytona and reconnects outward to a long-lived gateway (Durable Sessions below).
19
+
20
+ `Agent.kind` reports `"task"` or `"session"`. The older `mode: "run" | "stream"` property remains as a deprecated compatibility surface.
16
21
 
17
22
  ## What This Does
18
23
 
19
24
  You write an agent:
20
25
 
21
26
  ```typescript
22
- import { Agent } from 'agent-neckbeard';
23
- import { query } from '@anthropic-ai/claude-agent-sdk';
24
- import { z } from 'zod';
27
+ import { Agent } from "agent-neckbeard";
28
+ import { query } from "@anthropic-ai/claude-agent-sdk";
29
+ import { z } from "zod";
25
30
 
26
31
  const agent = new Agent({
27
32
  sandbox: {
28
- provider: 'e2b',
29
- template: 'code-interpreter-v1',
33
+ provider: "e2b",
34
+ template: "code-interpreter-v1",
30
35
  },
31
36
  inputSchema: z.object({ topic: z.string() }),
32
37
  outputSchema: z.object({
@@ -42,16 +47,16 @@ const agent = new Agent({
42
47
  prompt: `Research "${input.topic}" and return JSON`,
43
48
  options: { maxTurns: 10 },
44
49
  })) {
45
- if (message.type === 'result') {
46
- return JSON.parse(message.result ?? '{}');
50
+ if (message.type === "result") {
51
+ return JSON.parse(message.result ?? "{}");
47
52
  }
48
53
  }
49
- throw new Error('Claude did not return a result');
54
+ throw new Error("Claude did not return a result");
50
55
  },
51
56
  });
52
57
 
53
58
  const sandboxId = await agent.deploy();
54
- const result = await agent.run({ topic: 'TypeScript generics' }, { sandboxId });
59
+ const result = await agent.run({ topic: "TypeScript generics" }, { sandboxId });
55
60
  ```
56
61
 
57
62
  `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.
@@ -62,7 +67,7 @@ By default, the package infers the file to bundle from the `new Agent(...)` call
62
67
 
63
68
  ```typescript
64
69
  new Agent({
65
- sourceFile: path.resolve(process.cwd(), 'packages/my-agent/src/agent.ts'),
70
+ sourceFile: path.resolve(process.cwd(), "packages/my-agent/src/agent.ts"),
66
71
  // ...
67
72
  });
68
73
  ```
@@ -73,18 +78,21 @@ For Next.js/Vercel-style deployments, keep `agent-neckbeard` external to the ser
73
78
 
74
79
  ```typescript
75
80
  // next.config.ts
76
- import { withNeckbeardNextConfig } from 'agent-neckbeard';
77
-
78
- const nextConfig = withNeckbeardNextConfig({
79
- // your existing Next config
80
- outputFileTracingIncludes: {
81
- // Include every localDirectories source tree used by deploy().
82
- '/api/my-agent': ['./packages/my-agent/.agents/**/*'],
81
+ import { withNeckbeardNextConfig } from "agent-neckbeard";
82
+
83
+ const nextConfig = withNeckbeardNextConfig(
84
+ {
85
+ // your existing Next config
86
+ outputFileTracingIncludes: {
87
+ // Include every localDirectories source tree used by deploy().
88
+ "/api/my-agent": ["./packages/my-agent/.agents/**/*"],
89
+ },
83
90
  },
84
- }, {
85
- routeGlob: '/api/my-agent',
86
- sourceFiles: ['./packages/my-agent/src/agent.ts'],
87
- });
91
+ {
92
+ routeGlob: "/api/my-agent",
93
+ sourceFiles: ["./packages/my-agent/src/agent.ts"],
94
+ },
95
+ );
88
96
 
89
97
  export default nextConfig;
90
98
  ```
@@ -112,9 +120,9 @@ Daytona sandboxes can also receive network policy options supported by the Dayto
112
120
  ```typescript
113
121
  new Agent({
114
122
  sandbox: {
115
- provider: 'daytona',
116
- template: 'daytona-small',
117
- domainAllowList: '*.example.com',
123
+ provider: "daytona",
124
+ template: "daytona-small",
125
+ domainAllowList: "*.example.com",
118
126
  },
119
127
  // ...
120
128
  });
@@ -122,15 +130,15 @@ new Agent({
122
130
 
123
131
  Set `networkBlockAll: true` only when you want to block all outbound network access. Daytona rejects `networkBlockAll: true` combined with non-empty allow lists.
124
132
 
125
- ## Run-Output Agents
133
+ ## Structured Tasks
126
134
 
127
135
  Use `run` when each invocation should produce one validated output:
128
136
 
129
137
  ```typescript
130
138
  new Agent({
131
139
  sandbox: {
132
- provider: 'e2b',
133
- template: 'code-interpreter-v1',
140
+ provider: "e2b",
141
+ template: "code-interpreter-v1",
134
142
  },
135
143
  inputSchema: z.object({ prompt: z.string() }),
136
144
  outputSchema: z.object({ answer: z.string() }),
@@ -148,12 +156,12 @@ run: async (input, ctx) => {
148
156
  const notesPath = `${ctx.sandbox.homeDir}/data/notes.txt`;
149
157
  const cwd = ctx.sandbox.agentDir;
150
158
  // ...
151
- }
159
+ };
152
160
  ```
153
161
 
154
162
  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.
155
163
 
156
- Run-output agents fit background workflows (Hatchet tasks, Trigger.dev jobs, queue workers). The usual shape is one sandbox per task:
164
+ Structured-task agents fit background workflows (Hatchet tasks, Trigger.dev jobs, queue workers). The usual shape is one sandbox per task:
157
165
 
158
166
  ```typescript
159
167
  const sandboxId = await agent.deploy({ fresh: true });
@@ -169,38 +177,50 @@ try {
169
177
 
170
178
  `deploy({ fresh: true })` keeps concurrent tasks from sharing one cached sandbox; see Reusing Sandboxes for the caching behavior.
171
179
 
172
- ## Streaming Agents
180
+ 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.
181
+
182
+ ## Attached Sessions
173
183
 
174
- Use `server.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:
184
+ 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:
175
185
 
176
186
  ```typescript
177
187
  const agent = new Agent({
178
188
  sandbox: {
179
- provider: 'daytona',
180
- template: 'daytona-small',
189
+ provider: "daytona",
190
+ template: "daytona-small",
181
191
  },
182
192
  inputSchema: z.object({ prompt: z.string() }),
183
- server: {
193
+ session: {
184
194
  frameSchema: z.object({
185
- type: z.enum(['status', 'token', 'done']),
195
+ type: z.enum(["status", "token", "done"]),
186
196
  text: z.string().optional(),
187
197
  }),
188
198
  handler: async ({ input, emit }) => {
189
- await emit({ type: 'status', text: `Starting ${input.prompt}` });
190
- await emit({ type: 'token', text: 'hello' });
191
- await emit({ type: 'done' });
199
+ await emit({ type: "status", text: `Starting ${input.prompt}` });
200
+ await emit({ type: "token", text: "hello" });
201
+ await emit({ type: "done" });
192
202
  },
193
203
  },
194
204
  });
195
205
 
196
206
  const sandboxId = await agent.deploy();
197
-
198
- for await (const frame of agent.invoke({ prompt: 'hi' }, { sandboxId })) {
199
- console.log(frame);
207
+ try {
208
+ const session = await agent.createSession({ sandboxId });
209
+ try {
210
+ for await (const frame of session.prompt({ prompt: "hi" })) {
211
+ console.log(frame);
212
+ }
213
+ } finally {
214
+ await session.close();
215
+ }
216
+ } finally {
217
+ await agent.kill(sandboxId);
200
218
  }
201
219
  ```
202
220
 
203
- Internally, streaming uses Server-Sent Events from the sandbox `/invoke` endpoint. Neckbeard wraps user frames in harness events so errors, completion, and run-output results are handled consistently. `invoke()` also accepts an abort signal for host-side cancellation: `agent.invoke(input, { sandboxId, signal })`.
221
+ 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.
222
+
223
+ 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.
204
224
 
205
225
  ## Reusing Sandboxes
206
226
 
@@ -212,12 +232,15 @@ await saveSandboxId(sandboxId);
212
232
 
213
233
  // Later:
214
234
  const savedSandboxId = await loadSandboxId();
215
- const result = await agent.run({ topic: 'hello' }, { sandboxId: savedSandboxId });
235
+ const result = await agent.run(
236
+ { topic: "hello" },
237
+ { sandboxId: savedSandboxId },
238
+ );
216
239
  ```
217
240
 
218
241
  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.
219
242
 
220
- `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()`/`invoke()` and `kill()` it explicitly.
243
+ `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.
221
244
 
222
245
  ### Environment Changes with Reused Sandboxes
223
246
 
@@ -230,19 +253,19 @@ Updating Vercel, Render, or 1Password environment variables does not mutate alre
230
253
  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:
231
254
 
232
255
  ```typescript
233
- import { SandboxClient } from 'agent-neckbeard';
256
+ import { SandboxClient } from "agent-neckbeard";
234
257
 
235
258
  const sandbox = await SandboxClient.create({
236
- provider: 'daytona',
237
- template: 'daytona-small',
238
- domainAllowList: '*.example.com',
259
+ provider: "daytona",
260
+ template: "daytona-small",
261
+ domainAllowList: "*.example.com",
239
262
  autoDeleteInterval: 30,
240
263
  });
241
264
 
242
265
  const documentsDir = `${sandbox.paths.homeDir}/documents`;
243
266
  await sandbox.makeDir(documentsDir);
244
- await sandbox.writeFile(`${documentsDir}/input.txt`, 'hello');
245
- const result = await sandbox.runCommand('ls documents', {
267
+ await sandbox.writeFile(`${documentsDir}/input.txt`, "hello");
268
+ const result = await sandbox.runCommand("ls documents", {
246
269
  cwd: sandbox.paths.homeDir,
247
270
  timeoutMs: 60_000,
248
271
  });
@@ -250,7 +273,88 @@ const bytes = await sandbox.readFileBytes(`${documentsDir}/input.txt`);
250
273
  await sandbox.kill();
251
274
  ```
252
275
 
253
- Reconnect to an existing sandbox with `SandboxClient.connect({ provider, sandboxId })`. `create()` accepts provider-specific lifetime options: `timeoutMs` on E2B and `autoDeleteInterval` in minutes on Daytona (`-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`.
276
+ 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`.
277
+
278
+ `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.
279
+
280
+ 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.
281
+
282
+ 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.
283
+
284
+ 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.
285
+
286
+ 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.
287
+
288
+ 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.
289
+
290
+ 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.
291
+
292
+ ## Durable Sessions
293
+
294
+ Use `agent-neckbeard/supervisor` when a persistent sandbox process should own Pi while a separate gateway and lifecycle worker may restart independently:
295
+
296
+ ```typescript
297
+ import { SandboxClient } from "agent-neckbeard";
298
+ import {
299
+ createDurableSessionArtifact,
300
+ deployDurableSessionArtifact,
301
+ } from "agent-neckbeard/supervisor";
302
+
303
+ const sandbox = await SandboxClient.connect({ provider: "daytona", sandboxId });
304
+ const artifact = createDurableSessionArtifact({
305
+ sessionId,
306
+ runId,
307
+ attemptId,
308
+ gatewayUrl: "wss://gateway.example.com/v1/supervisor",
309
+ installDir: `${sandbox.paths.homeDir}/.neckbeard/runtime/${attemptId}`,
310
+ stateDurabilityAnchor: sandbox.paths.homeDir,
311
+ stateDir: `${sandbox.paths.homeDir}/.neckbeard/sessions/${sessionId}`,
312
+ workspaceDir: sandbox.paths.workDir,
313
+ pi: {
314
+ provider: "anthropic",
315
+ model: "claude-sonnet-4-5",
316
+ providerCredentialEnv: "ANTHROPIC_API_KEY",
317
+ },
318
+ });
319
+
320
+ const supervisorProcess = await deployDurableSessionArtifact(
321
+ sandbox,
322
+ artifact,
323
+ {
324
+ envs: {
325
+ NECKBEARD_SUPERVISOR_CREDENTIAL: attemptCredential,
326
+ ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
327
+ },
328
+ beforeRelease: async (prepared) => {
329
+ await persistSandboxProcess(prepared);
330
+ },
331
+ },
332
+ );
333
+
334
+ // During terminal reconciliation, load the identity persisted above, stop the
335
+ // exact fenced process, then apply the application's sandbox deletion policy.
336
+ try {
337
+ const persistedProcess = await loadSandboxProcess();
338
+ await sandbox.stopSession(persistedProcess);
339
+ await sandbox.disposeSessionArtifacts(persistedProcess);
340
+ } finally {
341
+ await sandbox.kill();
342
+ }
343
+ ```
344
+
345
+ `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.
346
+
347
+ 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.
348
+
349
+ 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 0.83 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.
350
+
351
+ For that cancellation outcome, `JSON.parse(JSON.stringify(error))` retains the public `name` and `code`. Arbitrary error serializers are not part of the contract.
352
+
353
+ 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.
354
+
355
+ The previous `createPiSupervisorArtifact()` and `deploySupervisorArtifact()` exports remain as deprecated aliases.
356
+
357
+ See [`docs/SUPERVISOR.md`](docs/SUPERVISOR.md) for the complete launch and gateway protocol contract.
254
358
 
255
359
  ## Configuration
256
360
 
@@ -280,11 +384,11 @@ new Agent({
280
384
  external?: string[],
281
385
  autoDetectExternal?: boolean,
282
386
  },
283
- // Run-output agents require:
387
+ // Structured-task agents require:
284
388
  outputSchema: ZodSchema,
285
389
  run: (input, ctx) => Promise<output>,
286
- // Streaming agents require this instead of outputSchema/run:
287
- server: {
390
+ // Session agents require this instead of outputSchema/run:
391
+ session: {
288
392
  port?: number,
289
393
  frameSchema: ZodSchema,
290
394
  handler: ({ input, ctx, signal, emit }) => Promise<void>,
@@ -311,11 +415,11 @@ Each `destination` is relative to the sandbox agent directory. For example, this
311
415
  const agent = new Agent({
312
416
  localDirectories: [
313
417
  {
314
- source: './packages/my-agent/.agents',
315
- destination: '.agents',
418
+ source: "./packages/my-agent/.agents",
419
+ destination: ".agents",
316
420
  },
317
421
  ],
318
- // ...run-output or streaming agent configuration
422
+ // ...structured-task or session-agent configuration
319
423
  });
320
424
  ```
321
425
 
@@ -331,8 +435,8 @@ For Next.js/Vercel and other bundled deployment environments, ensure each source
331
435
  const agent = new Agent({
332
436
  localDirectories: [
333
437
  {
334
- source: './my-project/.claude',
335
- destination: '.claude',
438
+ source: "./my-project/.claude",
439
+ destination: ".claude",
336
440
  },
337
441
  ],
338
442
  // ...agent configuration
@@ -344,8 +448,8 @@ The `envs` option passes environment variables to the sandbox. Undefined values
344
448
  ```typescript
345
449
  const agent = new Agent({
346
450
  sandbox: {
347
- provider: 'e2b',
348
- template: 'code-interpreter-v1',
451
+ provider: "e2b",
452
+ template: "code-interpreter-v1",
349
453
  },
350
454
  envs: {
351
455
  ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY,
@@ -359,13 +463,13 @@ Some packages cannot be bundled because they spawn child processes or have nativ
359
463
 
360
464
  ## Cleanup
361
465
 
362
- Neckbeard never kills a sandbox on its own; sandboxes run until you kill them or the provider's lifetime settings expire them. Kill every sandbox you deploy, as in the workflow example above. `kill()` accepts a sandbox ID. If omitted, it kills the sandbox cached on the agent instance.
466
+ 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.
363
467
 
364
468
  ## Errors
365
469
 
366
- 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, and includes captured server logs when the health check fails. `ValidationError` wraps input/output schema failures with the parser error as `cause`. `ExecutionError` represents agent handler failures.
470
+ 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.
367
471
 
368
- `run()` never throws; it returns `{ ok: false, error }`. `invoke()` throws.
472
+ `run()` never throws; it returns `{ ok: false, error }`. Attached `session.prompt()` throws. The deprecated `invoke()` wrapper preserves that throwing behavior.
369
473
 
370
474
  ## Testing
371
475
 
@@ -0,0 +1,21 @@
1
+ // src/serialized-error.ts
2
+ function isSerializedError(value) {
3
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
4
+ const candidate = value;
5
+ return typeof candidate.message === "string" && (candidate.name === void 0 || typeof candidate.name === "string") && (candidate.stack === void 0 || typeof candidate.stack === "string");
6
+ }
7
+ function serializeError(error) {
8
+ if (error instanceof Error) {
9
+ return {
10
+ name: error.name,
11
+ message: error.message,
12
+ ...error.stack === void 0 ? {} : { stack: error.stack }
13
+ };
14
+ }
15
+ return { message: String(error) };
16
+ }
17
+
18
+ export {
19
+ isSerializedError,
20
+ serializeError
21
+ };