agent-neckbeard 1.1.17 → 1.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,248 @@
1
+ # Durable Sessions (Sandbox Supervisor)
2
+
3
+ The sandbox supervisor is the implementation of Neckbeard's opt-in durable-session runtime. It is separate from the attached HTTP/SSE session transport: importing `agent-neckbeard/supervisor` does not change `Agent.deploy()`, `run()`, `createSession()`, the deprecated `invoke()` wrapper, or `kill()`.
4
+
5
+ The v1 adapter embeds Pi through `@earendil-works/pi-coding-agent`'s structured SDK. The generated Node runtime connects outward from a Daytona sandbox to a WebSocket gateway, journals durable events before sending them, and lets an accepted Pi turn continue when the gateway or Hatchet worker disconnects.
6
+
7
+ ## Runtime and bootstrap requirements
8
+
9
+ - Node.js 22.19.0 or newer inside the Daytona snapshot. The artifact preflights this exact minimum before dependency mutation and uses Node's built-in WebSocket client.
10
+ - The exact Pi SDK module and version reported by `artifact.requiredRuntimeModules`. The defaults are `@earendil-works/pi-coding-agent` and `0.83.0`, matching Tupelo's SBA financing agent runtime.
11
+ - A persistent sandbox directory for the supervisor journal and Pi session file.
12
+ - A `wss://` gateway. Plain `ws://` is allowed only when `allowInsecureGateway` is explicitly enabled for local development.
13
+ - One attempt-scoped gateway credential containing exactly 32 bytes from a cryptographically secure random generator, encoded as canonical unpadded base64url (43 characters), in the configured environment variable, plus the model credentials Pi needs. It is an opaque token, not a password or arbitrary application string.
14
+
15
+ Runtime configuration rejects timer-backed delays above Node's 2,147,483,647 ms scheduling ceiling, including the reconnect maximum after its positive jitter. This prevents oversized configuration from being clamped to a near-immediate timeout or retry loop.
16
+
17
+ The artifact contains credential-free `package.json`, generated `package-lock.json`, and identical precedence-safe `npm-shrinkwrap.json` files, exact `requiredRuntimeModules`, and a structured `bootstrap` step. Before any provider upload, `deployDurableSessionArtifact()` uses the provider-neutral command capability in a clean environment to create and validate every `installDir` path edge without symlinks. Ancestors must be owned by the sandbox UID or root and may not be group/world-writable unless protected by the sticky bit; the final directory must be sandbox-UID-owned and is forced to `0700`. The preflight opens that directory with `O_NOFOLLOW` and pre-opens every graph-addressed stage as a caller-owned `0600` single-link regular file. A violation fails with the credential-safe preparation exit-code summary before uploads begin. It then uploads the stages, and bootstrap verifies and atomically publishes the final runtime, config, and dependency files without launch credentials. It checks the install exit code before starting the supervisor. For compatibility with the linked structured consumer contract, `bootstrap.command` remains `sh`; `deployDurableSessionArtifact()` validates that contract but does not resolve the name through ambient `PATH`, instead entering through absolute `/usr/bin/env -i` and `/bin/sh` with a fixed path before passing the structured arguments to the constant clean-environment wrapper. The wrapper passes all dynamic values as opaque positional arguments. The resulting bootstrap uses an attempt-scoped clean `HOME`, fixed `PATH`, `/dev/null` global npm configuration, and rejects the install directory's project/user `.npmrc`; raw provider and install output never crosses the deployment error boundary. Other consumers of the structured artifact must provide an equivalently clean interpreter boundary. For the default artifact, the dependency operation inside that clean environment is equivalent to:
18
+
19
+ ```sh
20
+ cd /sandbox/neckbeard/runtime && npm ci --omit=dev --no-audit --no-fund
21
+ ```
22
+
23
+ The package coordinate is validated as a safe npm name plus one exact semantic version; ranges are rejected. Every non-root lock entry must be an ordinary registry package with an exact credential-free HTTPS URL and strict SHA-512 integrity. Credential fields are rejected whether they use bare names or npm's registry/path-scoped form such as `//registry.npmjs.org/:_authToken`. The supported default SDK graph is generated and checked into the package. A custom module/version must supply a matching, credential-free npm lockfileVersion 3 graph through `pi.packageLock`; otherwise artifact construction fails before sandbox mutation. Bootstrap requires the Daytona Linux image's `flock`, whose kernel-owned lock is released automatically if an installer crashes. This lock remains a correctness requirement even though detached log capture no longer uses an inner `flock`: a provider timeout does not prove that the remote `npm ci` stopped, so a retry can overlap the same shared installation. A clean Node wrapper opens the predictable lock with `O_NOFOLLOW` and without truncation, verifies that it is a caller-owned `0600` single-link regular file, and passes that already-open descriptor to `flock`.
24
+
25
+ The locked bootstrap serializes concurrent callers, verifies graph-addressed stages, atomically publishes and fsyncs all final files, and publishes a fsynced pending graph before dependency mutation. After `npm ci`, it requires `npm ls` plus the exact locked-package version check. It then walks the complete installed `node_modules` tree without following links, opening directories and regular files through retained descriptors and matching each canonical path back to the opened device/inode before and after inspection. A deterministic sorted manifest records each relative path, entry kind, permission mode, regular-file size and SHA-256 content hash, or raw relative symlink target. Absolute or lexically escaping symlinks, special files, ownership drift, and observed path/content replacement fail closed. The walk is bounded to 250,000 entries, 4,096 UTF-8 bytes per path or symlink target, 64 MiB of aggregate path/target bytes, 512 MiB per regular file, 2 GiB of regular-file content, and a 64 MiB manifest.
26
+
27
+ Publication order is `npm ci` and graph checks, fsync of every regular file and every installed-tree directory bottom-up, fsync of `installDir`, atomic replacement plus file/directory fsync of the owner-only `0600` installed-tree manifest outside `node_modules`, exact manifest re-verification, final-artifact re-verification, and only then atomic publication and directory fsync of the graph marker. A crash after the manifest but before the marker leaves the pending graph in place, so retry reinstalls and republishes before marking complete. A retry with the same durable marker reopens the canonical manifest leaf through the retained install-directory descriptor and skips `npm ci` only when the final files, dependency graph, manifest shape and bounds, and freshly recomputed installed-tree contents all match. An absent, malformed, unsafe, oversized, or mismatched manifest is repair-needed rather than trusted; the locked `npm ci` path replaces it only after the repaired tree is fully synced. Another graph fails closed so reconciliation cannot replace `node_modules` beneath a live supervisor. The runtime also verifies the SDK's exported `VERSION` before creating a session and fails closed on drift.
28
+
29
+ ## Launch contract
30
+
31
+ Create the artifact in a Hatchet launch task after the sandbox, repository, and runtime dependency are ready:
32
+
33
+ ```ts
34
+ import { SandboxClient } from "agent-neckbeard";
35
+ import {
36
+ DEFAULT_PI_SDK_MODULE,
37
+ DEFAULT_PI_SDK_VERSION,
38
+ createDurableSessionArtifact,
39
+ deployDurableSessionArtifact,
40
+ } from "agent-neckbeard/supervisor";
41
+
42
+ const sandbox = await SandboxClient.connect({ provider: "daytona", sandboxId });
43
+
44
+ const artifact = createDurableSessionArtifact({
45
+ sessionId,
46
+ runId,
47
+ attemptId,
48
+ gatewayUrl: "wss://gateway.example.com/v1/supervisor",
49
+ installDir: `${sandbox.paths.homeDir}/.neckbeard/runtime/${attemptId}`,
50
+ stateDurabilityAnchor: sandbox.paths.homeDir,
51
+ stateDir: `${sandbox.paths.homeDir}/.neckbeard/sessions/${sessionId}`,
52
+ workspaceDir: sandbox.paths.workDir,
53
+ pi: {
54
+ moduleSpecifier: DEFAULT_PI_SDK_MODULE,
55
+ expectedVersion: DEFAULT_PI_SDK_VERSION,
56
+ provider: "anthropic",
57
+ model: "claude-sonnet-4-5",
58
+ providerCredentialEnv: "ANTHROPIC_API_KEY",
59
+ thinking: "high",
60
+ },
61
+ });
62
+
63
+ const process = await deployDurableSessionArtifact(sandbox, artifact, {
64
+ envs: {
65
+ NECKBEARD_SUPERVISOR_CREDENTIAL: attemptCredential,
66
+ ANTHROPIC_API_KEY: modelCredential,
67
+ },
68
+ beforeRelease: async (prepared) => {
69
+ await persistSandboxProcess(prepared);
70
+ },
71
+ });
72
+
73
+ // During terminal reconciliation, use the identity persisted by beforeRelease.
74
+ try {
75
+ const persistedProcess = await loadSandboxProcess();
76
+ await sandbox.stopSession(persistedProcess);
77
+ await sandbox.disposeSessionArtifacts(persistedProcess);
78
+ } finally {
79
+ await sandbox.kill(); // Or apply an explicitly configured stop/delete policy.
80
+ }
81
+ ```
82
+
83
+ For callers that already own an `@daytona/sdk` sandbox, `createDaytonaSupervisorSandboxTarget(daytonaSandbox, { beforeMutation })` returns the same narrow deployment target without creating, stopping, or deleting the sandbox. `beforeMutation` may revalidate an external lifecycle claim before path discovery, staging, bootstrap, each prepare request, and every cleanup/adoption request for which no exact prepared identity was returned. It is deliberately not used for release or launch-decision cleanup of a captured exact identity: `beforeRelease` is that authorization boundary, while the single-winner decision must remain finishable after a claim changes. If any identity-less ownership check fails after a transport-uncertain request, the stale caller performs no later cancellation or adoption request because the deterministic launch may now belong to a successor; leaving its decision untouched preserves same-attempt retry by the current owner.
84
+
85
+ Terminal reconciliation is a separate destructive boundary. A raw Daytona SDK caller uses `stopDaytonaSupervisorSession(daytonaSandbox, persistedProcess, { beforeMutation })` and, after any application-owned final diagnostic capture, `disposeDaytonaSupervisorSessionArtifacts(...)`. Both helpers use only Daytona's command transport, without launch-only HOME or working-directory discovery, and revalidate `beforeMutation` immediately before every provider control request, including a retry after an uncertain response; a failed check performs no later provider I/O. Disposal accepts only the exact managed handle. An absent or nonmatching exact leader plus an absent safe `started` marker and an intact descriptor-bound empty quiescent leaf proves a PROCESS_V3 generation never launched its workload; once exact `started` exists, disposal instead requires its exact completion proof. It atomically renames the eligible generation to an identity-derived recovery path, fsyncs and removes that exact path, and unlinks the validated generation lock last while its descriptor remains held. A crash-left launch-key replacement-retirement directory is moved through that same exact recovery path only when its intact descriptor-bound identity and terminal proof match the handle; mismatch, partial deletion, malformed state, symlinks, or hard links fail closed and preserve possible successor state. Retrying completes partial identity-derived disposal in place or succeeds when all exact paths are absent. It never treats artifact absence as stop proof. After disposal the old handle has no retained logs or stop proof, and the same attempt launch ID can create a new generation. Do not race generic same-launch start with disposal. `validateDurableSessionDeploymentEnvironment(artifact, envs)` exposes the bounded, credential-safe environment preflight independently; deployment calls it before any sandbox I/O.
86
+
87
+ `stateDurabilityAnchor` is a pre-existing durable directory trusted by the deployer. The runtime validates or creates and parent-fsyncs every directory edge from that anchor through `stateDir`, rejects symlinks below it, and never traverses above it.
88
+
89
+ `installDir` must be immutable and attempt-scoped. Reusing it across attempts is rejected because the staged runtime, config, and exact dependency graph are bound to one bootstrap fingerprint.
90
+
91
+ `createDurableSessionArtifact()` returns:
92
+
93
+ - `files`: graph-addressed flat staging files for `neckbeard-supervisor.mjs`, `neckbeard-supervisor.json`, and exact dependency `package.json`, `package-lock.json`, and `npm-shrinkwrap.json` files;
94
+ - `bootstrap`: structured npm command, arguments, working directory, and timeout;
95
+ - `start`: the structured Node start command;
96
+ - protocol, runtime, and provider versions;
97
+ - `requiredEnvironmentVariables`;
98
+ - `requiredRuntimeModules`, including the exact Pi SDK package/version.
99
+
100
+ Every detached launch serializes caller variables into one bounded internal provider value rather than placing them in the lifecycle preparation environment. Before the provider SDK's outer command shell starts, each control request supplies fixed trusted `PATH`, `TMPDIR`, and `LANG` values, an inaccessible `HOME`, `/dev/null` Bash/sh startup files, and neutral shell-option/xtrace controls. This boundary applies to E2B's login Bash as well as prepare, release, cancellation, read, and stop requests. The launcher then enters an `env -i` shell with fixed `PATH`, `HOME`, `TMPDIR`, and `LANG`; preparation, the permanent Python 3 subreaper, and diagnostic pumps therefore cannot be redirected by caller `PATH`, `PYTHONPATH`, or similar variables. The generic reaper validates the caller-owned unlinked `0600` handoff descriptor, consumes and erases it before publishing `started`, and supplies the decoded variables only when it spawns the requested `/bin/sh` payload. Its payload environment defaults `HOME` to the provider's `sandbox.paths.homeDir`, preserving the provider runtime default, and an explicit caller `HOME` overrides it. Supervisor mode instead passes the same anonymous descriptor to runtime entry for strict validation, erasure, and hydration at that payload boundary. Current generic and supervisor detached launch paths both require Python 3 with Linux `prctl` and pidfd support.
101
+
102
+ No secret is embedded in any file, bootstrap command, or detached-process lifecycle marker. The clean path preflight and bootstrap report only their exit codes on failure, and provider exceptions while creating the workspace or uploading staged files collapse to one fixed artifact-staging diagnostic, so unknown ambient sandbox or npm credentials cannot be copied into host errors. `deployDurableSessionArtifact()` accepts a narrow sandbox interface, validates the attempt credential, securely establishes the runtime install path, creates the workspace directory, uploads all files, installs the exact dependency, and starts a detached provider process with `environmentMode: "supervisor-fd-v1"`. The provider encodes the complete launch environment into one bounded structured provider value. Its launcher opens an empty `0600` file through separate read and write descriptors, unlinks it before writing, closes the writer, removes the composite value, and starts the long-lived process with a clean initial environment plus a fixed descriptor indicator. The runtime strictly validates and reads the v1 payload, truncates the anonymous inode to zero, closes the descriptor, and only then hydrates `process.env` before runtime startup or Pi's dynamic import. Caller-supplied handoff values of at least eight characters are bulk-captured by the runtime redactor before config loading or runtime construction; shorter generic settings remain visible because replacing low-entropy substrings would corrupt ordinary diagnostics. The validated attempt credential and configured provider credential are captured explicitly, independent of length. Supervisor launcher-only `PATH`, `HOME`, `TMPDIR`, and `LANG` defaults remain outside the handoff set unless the caller explicitly supplies them; the separate generic runtime path serializes its provider-home `HOME` default as described above. Truncation also clears a duplicate descriptor retained by a shell that forks the final command. It uses `attemptId` as the stable launch identity. The provider hashes that ID for paths and binds adoption to a hash of command, working directory, environment mode, environment names, and a non-secret environment revision. Deployment derives that revision with a keyed HMAC over the canonical environment. The key is the attempt's independently generated 256-bit opaque credential; deployment and runtime both reject password-shaped or non-canonical credentials. No value or dictionary-checkable value hash therefore enters lifecycle state. Environment rotation fails the stable launch descriptor and requires a replacement attempt/launch ID, including after a dead generation is eligible for restart.
103
+
104
+ The provider first prepares a blocked, birth-fenced process. `beforeRelease(prepared)` must idempotently persist that exact provider identity before returning. Its failure is distinguishable from provider launch failure through the fixed, credential-safe `Supervisor prepared identity persistence failed.` message unless subsequent cleanup confirms that cancellation won. Release and cancellation then race through one atomic durable decision. When cancellation is confirmed, `deployDurableSessionArtifact()` throws `SupervisorLaunchCancelledError` with fixed message `Supervisor launch was cancelled before release.` and stable discriminant `code === "NECKBEARD_SUPERVISOR_LAUNCH_CANCELLED"`. This outcome proves the prepared generation cannot run; it is also used when a failed persistence callback is followed by confirmed cancellation. Cleanup response loss is not classified as cancellation and preserves safe same-attempt retry. If release already won, cleanup adopts that released identity instead. After release, the exact setsid leader becomes a permanent Python subreaper, enables `PR_SET_CHILD_SUBREAPER`, durably publishes `started`, and only then spawns the diagnostic pumps and original shell string. A lost prepare or release response adopts the same live record rather than starting a duplicate. If the exact leader dies before `started`, its absence proves that no logger or user payload could have launched, so a later locked prepare can reclaim that incomplete directory. Once `started` exists, retirement requires the exact descriptor-bound completion marker written and fsynced by that leader only after its payload, pumps, and adopted descendants reach `ECHILD`. A retry then safely retires the dead generation under the per-launch lock, prepares a replacement for the same attempt, and persists its new identity before release. An exited started PROCESS_V2 generation has no subreaper completion proof and fails closed instead of being replaced. Generic `startDetachedCommand()` launch IDs remain permanently idempotent after short commands exit and do not opt into this supervisor restart policy. A callback failure cancels and confirms the captured generation unless another retry already won release; in that case cleanup does not kill the shared process and reconciliation uses the persisted identity.
105
+
106
+ Replacement-capable RELEASE and adoption commands hold the generation lock and return a released handle only while the exact PROCESS_V3 leader is proven live. Exact descriptor-bound quiescence makes the current call fail closed but leaves the same attempt retryable so its next prepare can retire and replace that completed generation. If exact `started` exists while the leader is dead or ambiguous and no valid exact quiescent proof exists, `deployDurableSessionArtifact()` throws fixed-message `SupervisorReleasedGenerationUnavailableError` with stable discriminant `code === "NECKBEARD_SUPERVISOR_RELEASED_GENERATION_UNAVAILABLE"`. The generation may have run, so callers must not treat this as cancellation or generic transport uncertainty: fence and confirm termination of the whole sandbox, then use a new attempt or terminally interrupt the run. The public error's enumerable `name` and `code` survive `JSON.parse(JSON.stringify(error))`; its prototype and non-enumerable `message` are not part of that serialized shape.
107
+
108
+ Detached lifecycle state and diagnostic logs use a private, real, caller-owned `0700` root plus a `077` process umask; the root, launch directories, markers, locks, and log leaves reject symlinks or incompatible filesystem types before use. Each V2 stdout and stderr writer rotates between bounded private segments, retaining at most 8 MiB of newest output per stream. Captured output is best-effort diagnostics only. If capture, append, rotation, or marker publication fails, that stream disables storage but its pump keeps draining the FIFO until the target closes it; diagnostic failure therefore cannot remove the target's pipe reader, inject `EPIPE`, or become process-liveness state. The two streams are read independently rather than as one atomic pair, and neither Neckbeard's durable supervisor nor Mission Control uses them for transcript, lifecycle, ownership, completion, or acknowledgement correctness. Public `readSessionLogs()` preserves raw output because Neckbeard does not persist a historical secret dictionary; callers must treat it as sensitive diagnostic data and apply their own redaction before exposure or retention. The detached envelope rejects invalid UTF-8 before returning strings, so replacement characters cannot expand an accepted 8 MiB byte stream beyond the documented limit. The two built-in generic runtime-startup error paths separately redact every credential-named configured environment value plus configured values of at least eight characters, leave shorter generic settings visible, and ignore diagnostic read failures.
109
+
110
+ Each writer publishes an atomically replaced `ROTATING` marker before a chunk append or rotation and a `STABLE` marker afterward. A reader makes bounded optimistic attempts: it validates the marker before the read, opens the current and optional previous segments, matches each owner-only single-link regular-file path back to its open descriptor, reads through those descriptors, and accepts the payload only when the marker remains unchanged afterward. This closes the identified symlink and path-substitution read races without an inner per-stream log `flock`; the unchanged marker remains a best-effort race detector, not a guarantee of an atomic or perfectly coherent diagnostic snapshot. A successful sample may already be stale relative to bytes buffered in the pipe; sustained contention or any unsafe, malformed, or unstable state may make the whole provider read fail closed to empty diagnostics. A process or sandbox crash may also lose a final fragment that never reached a published segment.
111
+
112
+ Recovery from a V2 `ROTATING` marker or a current segment missing after an interrupted current-to-previous rename occurs only when a current PROCESS_V3 lifecycle record has its exact subreaper completion proof. An older started PROCESS_V2 generation has no such proof and may fail diagnostic recovery. An interrupted legacy copy/truncate rotation fails closed because its on-disk phases are ambiguous. Persisted V1 `STABLE` markers retain their compatible bounded marker-before/read/marker-after algorithm without requiring `flock`, with the same descriptor/path validation. Empty `.snapshot.lock` leaves are retained only as inert compatibility artifacts for older readers during a rolling upgrade from the former flock-based protocol; current log writers and readers do not synchronize on them.
113
+
114
+ Replacement-capable generations still require util-linux `flock` for the independent outer launch, decision, and replacement fence, and optional artifact disposal requires it for the destructive generation fence. The launcher validates the already-open caller-owned `0600` single-link lock, keeps its shared open-file description inherited by the blocked leader until exact identity publication and parent-directory fsync, and closes rather than explicitly unlocking it. A provider/control-shell crash before identity therefore cannot expose a reclaimable directory while the pre-publication leader is still alive. Retries and serialized launch decisions verify exact identity while holding that fence. Generic permanent launch, stop, and diagnostic log reads do not require `flock`; a generic launch needs it only if disposal is later requested. Stop remains exact-handle and PID-birth fenced without taking the 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. Reads also enforce the 8 MiB tail limit for legacy launch logs; legacy Daytona log leaves are opened once and matched back to caller-owned `0600` single-link regular-file paths before the bounded descriptor read. Deprecated native-provider log results are byte-tail bounded to the same limit before returning. Both E2B and Daytona current handles include Linux PID birth and session identity. Stop preserves the exact V3 subreaper leader, opens each captured-session candidate through Python 3's pidfd API before checking and signaling it, and continues revalidating the leader. It resolves after exact leader absence when `started` is safely absent, or after leader absence plus the exact completion marker once `started` exists; PID reuse, missing pidfd support, malformed proof, or an escaped-session descendant that outlives the deadline fails closed. Pre-V2 native stop remains a weaker documented compatibility path. Persist the complete prepared process handle for launch reconciliation, diagnostic log reads, and explicit termination; the deprecated string overloads exist only for older persisted handles and native provider sessions.
115
+
116
+ The older `createPiSupervisorArtifact()` and `deploySupervisorArtifact()` names remain as deprecated aliases for source compatibility.
117
+
118
+ The supervisor loads Pi in-process with `ModelRuntime`, `DefaultResourceLoader`, `SettingsManager`, `createAgentSession()`, and `SessionManager.open(sessionPath, sessionDir, workspaceDir)`. It consumes the configured provider credential into `ModelRuntime.setRuntimeApiKey(..., { allowNetwork: false })`, removes that secret from `process.env` before agent tools can run, and subscribes before the first prompt. The Pi session file and effective agent directory must be non-overlapping strict descendants of `stateDir`; neither may overlap the revision-pointer, attempt-data, or resource-snapshot namespaces owned by the supervisor. Their directory chain is opened from the durability anchor without following links. When configured, the agent-directory root itself must be process-owned and startup normalizes and revalidates its mode as `0700`; the mutable session and `auth.json` leaves must be process-owned, single-link private regular files. Immediately before Pi opens the session, the supervisor reopens its canonical leaf through the retained parent descriptor and requires it to identify the retained session inode, so a rename-and-replacement cannot silently move current writes away from the path used on restart. Pi receives the retained session descriptor and the validated private resource-snapshot descriptor. `ModelRuntime` receives persistent `auth.json` through the retained source-directory descriptor, so parent-path substitution cannot redirect reads or writes, Pi's adjacent `auth.json.lock` remains shared with other Pi processes, and OAuth refresh-token rotation survives supervisor restart. The workspace and state trees may not overlap. A restart reopens the same Pi JSONL session file only when it is at most 64 MiB and its first record is a current version-3 session header, preserving prior completed conversation history without allowing Pi's parser or legacy migration rewrite to escape that bound; an interrupted in-memory turn is never claimed to have resumed.
119
+
120
+ ## Gateway protocol
121
+
122
+ `SUPERVISOR_PROTOCOL_VERSION` and `SUPERVISOR_RUNTIME_VERSION` are independent explicit versions. The current wire protocol remains version 1 while the current runtime/storage revision is version 2. Every frame is fenced by `sessionId`, `runId`, and `attemptId`. Session and run identifiers are capped at 512 UTF-8 bytes at the runtime-config boundary; attempt identifiers retain the stricter safe-path-segment limit of 255 UTF-8 bytes. There is one event per frame.
123
+
124
+ The gateway accepts an unauthenticated WebSocket upgrade and requires the first frame, within its short handshake timeout, to be:
125
+
126
+ ```json
127
+ {
128
+ "type": "resume",
129
+ "protocolVersion": 1,
130
+ "runtimeVersion": 2,
131
+ "provider": "daytona",
132
+ "providerVersion": 1,
133
+ "sessionId": "session_...",
134
+ "runId": "run_...",
135
+ "attemptId": "attempt_...",
136
+ "credential": "attempt-scoped-secret",
137
+ "lastAcknowledgedEventSequence": 41,
138
+ "lastAppliedCommandSequence": 7
139
+ }
140
+ ```
141
+
142
+ The credential appears only in this first `resume` frame. The runtime retains it in private supervisor memory and deletes its environment variable before importing Pi, so Pi tools and subprocesses cannot inherit it. The separately configured provider credential is moved into the fork's in-memory `ModelRuntime` and its environment variable is also removed before tools run. Both values remain registered with an in-memory redactor after deletion; persisted errors, stderr, raw SDK event strings, stop/supersession reasons, socket close reasons, and process logs are scrubbed without writing the redaction set to disk. Because the Node process starts clean and receives secrets after `exec`, those values are absent from its initial Linux `/proc/<pid>/environ`; the handoff FD is closed before Pi loads, and post-initialization subprocesses inherit neither credential.
143
+
144
+ This boundary protects Pi, its tools, and subprocesses created after supervisor initialization. It is not isolation from a process that was already running as the same sandbox Unix user: such a process may inspect the short-lived provider launcher or its open descriptor before the runtime consumes it. That threat requires a separate Unix identity, a provider-managed secret primitive, or an equivalently isolated broker and hardened `/proc`; do not run untrusted same-UID workloads before supervisor initialization. The configured gateway URL cannot contain user info, a query, or a fragment, so credentials cannot be smuggled into the credential-free artifact through its URL. The gateway authenticates the attempt credential, derives the attempt principal, acquires its lease, and replies with `resume_ok`, authoritative cursors, and ordered pending commands. It may instead send `attempt_superseded`; frames carrying another attempt identity are rejected.
145
+
146
+ A fresh replacement journal may fast-forward its local command cursor to the authoritative nonzero `resume_ok.lastAppliedCommandSequence`. It never moves backward and rejects a baseline that would skip a locally recorded unfinished command. Each WebSocket generation processes normal inbound frames in arrival order, validates an entire `resume_ok.pendingCommands` batch before scheduling work, and rechecks connection ownership after durable cursor writes. `attempt_superseded` is the intentional urgent exception: it closes the shared execution gate immediately, aborting attachment downloads and preventing any later Pi side effect from the fenced attempt.
147
+
148
+ Raw gateway frames are rejected before decode or JSON parsing at 1,000,000 UTF-8 bytes. A missing command prefix may retain at most 256 commands, 8 MiB of serialized command data, and a 256-sequence lead over the durable applied cursor. The gateway must page a larger backlog in order, keep both the count and byte windows bounded, and deliver the next page as prior commands become terminal.
149
+
150
+ A normal live `event_ack` cannot exceed the highest event sequence actually sent on that connection. Only `resume_ok` may reconcile against the durable gateway cursor, and it may never roll the local durable acknowledgement backward. Invalid cursors close the connection without appending another sequenced event, so a claimed future sequence cannot make itself valid across reconnects.
151
+
152
+ Commands use a stable `commandId` and a positive monotonic `commandSequence`:
153
+
154
+ - `prompt` calls the Pi SDK's `session.prompt()`. The adapter returns after `preflightResult(true)` and retains the independent run Promise, so later `steer` and `stop` commands are not blocked and a gateway disconnect cannot cancel the turn.
155
+ - `steer` calls `session.steer()` while the Promise is active. Pi applies steering at its supported turn boundary.
156
+ - `stop` calls `session.abort()` without disposing the reusable Pi session. A successful user stop produces `turn_stopped`, not `turn_completed` or `turn_failed`.
157
+
158
+ The supervisor fsyncs a URL-free semantic command receipt before applying a command. Its SHA-256 fingerprint covers attempt identity, command identity/sequence/kind, message or stop reason, and ordered stable attachment metadata; a rotated signed URL does not change identity, while any other replay mutation fails closed. The corresponding `command_received` event is durable before Pi is called.
159
+
160
+ After a side effect, the supervisor fsyncs `command_applied` or `command_failed` before closing the command ledger record. Ledger recovery permits only receipt-to-terminal progress, accepts an idempotently repeated matching terminal outcome, and rejects terminal-first records, receipt regressions, or applied/failed conflicts. Atomic control-file writes use unpredictable temporary names so crash debris cannot wedge a restarted process through PID/counter reuse. A bounded recovery index retains the outcome even after the gateway acknowledges and compacts the event, so a crash in the event-to-ledger gap completes the same outcome without rerunning Pi or inventing its opposite. Persisted usage fields must be nonnegative integers, optional cost must be nonnegative and finite, and a persisted harness PID must be positive. Terminal turn lifecycle is gated until the originating prompt receipt is durable. Likewise, `turn_stopped` is released only after the winning stop command's `command_applied`; a durable accepted-stop marker is itself recovery evidence and cannot be overwritten by a later stop.
161
+
162
+ Pi reports prompt preflight before it appends the user entry, and `steer()` accepts into an in-memory turn queue. Therefore `command_applied` means the SDK side effect was accepted under the at-most-once command contract; it does not claim that a corresponding Pi JSONL entry already exists. The adapter securely creates and parent-fsyncs the private session file before opening Pi, fsyncs Pi's header after open, and fsyncs the regular non-symlink session file before any normalized `turn_completed`, `turn_failed`, or `turn_stopped` event. Completed/stopped transcript history therefore precedes the durable terminal event. A crash during an accepted but unfinished prompt or queued steer is recovered through the supervisor marker/ledger semantics rather than by replaying an assumed Pi entry.
163
+
164
+ Pi JSONL growth is finite per attempt. The hard ceiling is 64 MiB, aligned with the ordinary command-ledger and resource-snapshot budgets. New prompts and steers are rejected at or above 56 MiB, leaving 8 MiB of logical headroom for an already admitted turn; after asynchronous canonical validation, a final synchronous retained-descriptor size check sits immediately before each Pi side effect. Use a replacement attempt for more work. The pinned Pi 0.83 `SessionManager.open()` path initializes the explicit session file into `flushed === true`. The adapter requires that exact append-only state and retained-descriptor path before every `_persist`, serializes the pending JSONL line exactly once, rejects it before disk I/O if the resulting file would exceed 64 MiB, writes the same bytes positionally through the retained descriptor, and rechecks the state, path, hard bound, and exact size delta. It never estimates Pi's private `fileEntries`: an unexpected `flushed === false` full-rewrite state fails before writing. Empty-file initialization is the only supported full rewrite. Non-empty history must begin with a bounded UTF-8 Pi version-3 header, so legacy migration is refused before `SessionManager.open()` can rewrite the canonical file. Because Pi advances its in-memory tree before `_persist`, any serialization, capacity, write, or postcondition error latches `harness_failed`; even an extension that catches the immediate error cannot admit more work or publish normalized terminal success. The 8 MiB margin is budgeting headroom rather than a filesystem reservation or a guarantee that every pending record fits, while failure and restart facts remain governed by the outbox's separate recovery reserve.
165
+
166
+ Every durability sync reopens the canonical private leaf through the retained parent and compares it with the retained session descriptor both before and after the retained-file fsync plus descriptor-bound parent fsync. A leaf rename, replacement, privacy change, or hard-link change observed at either boundary fails the harness before normalized terminal lifecycle publication. Pi continues to read and write only through its retained descriptor path.
167
+
168
+ ## Attachments
169
+
170
+ Prompt and steer commands may include attempt-scoped descriptors:
171
+
172
+ ```json
173
+ {
174
+ "id": "attachment_...",
175
+ "url": "https://signed-object-url.example/...",
176
+ "path": "input.csv",
177
+ "mimeType": "text/csv",
178
+ "sha256": "64-lowercase-hex-characters...",
179
+ "sizeBytes": 1234
180
+ }
181
+ ```
182
+
183
+ Before invoking Pi, the supervisor:
184
+
185
+ 1. accepts only HTTPS downloads and rejects redirects;
186
+ 2. enforces safe single-component filenames plus configured per-file, per-command, and durable per-attempt file/byte limits;
187
+ 3. derives a flat command/content/name-scoped local target from SHA-256 digests without exposing the raw command ID in the path;
188
+ 4. streams to an attempt-owned temporary file with a timeout and aborts the response on every failed materialization path, including validation failures before a body reader is acquired;
189
+ 5. verifies the exact byte count and SHA-256 digest;
190
+ 6. fsyncs the file, publishes it with a no-clobber hard link, removes the temporary name, and fsyncs the descriptor-bound attachment directory before publication;
191
+ 7. retains the downloaded file descriptor through publication, reopens the canonical attempt path with a no-follow leaf check, and requires both descriptors to identify the same process-owned, single-link private regular file before appending that restart-stable path to the prompt or steer text.
192
+
193
+ The attachment directory itself is the durable quota ledger. Materializations are serialized, reserve the whole batch before fetching, and reconstruct current private regular-file counts and bytes after restart. A pending marker records only targets absent at admission; it is fsynced under a unique temporary name, published with a no-clobber hard link, reduced to one link, and directory-fsynced before any download begins. Restart first removes crash-left partial links, then removes the targets owned by an interrupted pending batch. A directory-fsynced committed marker preserves the completed batch across its short cleanup window. Attachment temporary names are likewise removed and directory-fsynced before accounting, including the two-link window between target publication and temporary-name removal. `maxFilesPerAttempt` defaults to 100, while `maxBytesPerAttempt` defaults to the configured `maxBytesPerCommand` (500 MiB by default), so a sequence of individually valid commands cannot grow attachment state without bound. If any attachment in one command fails, files newly owned by that batch are unlinked and the directory is fsynced before its pending marker is removed; cleanup failure retains the marker for recovery. A matching immutable file that existed before the batch is validated and retained.
194
+
195
+ The signed URL is held only in the inbound command object. It is never written to the command ledger, outbox, Pi prompt/session history, or error text. A later command cannot replace a path already handed to Pi, even when it reuses the same logical filename. Pi always receives the path manifest so non-image formats such as CSV, PDF, and XLSX remain tool-accessible.
196
+
197
+ ## Lifecycle, durability, and replay
198
+
199
+ The adapter forwards JSON-safe Pi SDK events as `harness_event` extensions and separately normalizes product lifecycle:
200
+
201
+ - `turn_started { adapter, commandId? }`
202
+ - `turn_completed { adapter, commandId?, stopReason?, usage? }`
203
+ - `turn_failed { adapter, commandId?, stopReason?, error, usage? }`
204
+ - `turn_stopped { adapter, commandId?, reason?, usage? }`
205
+
206
+ Pi's `turn_end`/`agent_end` data supplies the terminal reason and token/cost usage when available. `harness_exited` only describes supervisor/SDK disposal; it is never normal proof that a turn completed.
207
+
208
+ Every admitted durable or coalesced event receives `<attemptId>:<attemptSequence>` and an attempt-monotonic sequence. One non-healing store writer serializes event, acknowledgement, metadata, command-ledger, active-turn, and compaction mutations. Runtime 2 first durably publishes a permanent revision pointer at `stateDir/attempts/<attemptId>` and stores the actual attempt data beneath `stateDir/attempt-data-v2/<attemptId>`. That file pointer makes a pre-revision runtime fail before it can open or mutate the newer journal. The deployer supplies a pre-existing durable `stateDurabilityAnchor`; every directory edge beneath it through the state and attempt directories is opened without following links, validated, and parent-fsynced before journal use, without traversing platform paths above the anchor. The store records the attempt directory's device/inode identity and rebinds it through those descriptor-owned edges for each serialized mutation; replacement of any parent or the final attempt directory therefore fails closed instead of redirecting journal or control-file access. Existing pre-fence attempt directories are not upgraded in place; reconciliation must mint a replacement attempt.
209
+
210
+ The supervisor validates the complete serialized frame against the transport ceiling before it appends and fsyncs the versioned outbox. A present empty, malformed, schema-invalid, or wrong-attempt `active-turn.json` is corruption and fails startup without altering its bytes; only a missing marker means no active turn. The gateway must transactionally persist one event before returning a cumulative `event_ack`. On reconnect, the supervisor replays all events above the gateway cursor.
211
+
212
+ Raw Pi extension payloads are deeply redacted and JSON-normalized before that durable append and limited to 512 KiB, leaving substantial envelope headroom below the gateway's 1,000,000-byte frame ceiling. Serialization enforces byte, node, and depth budgets while traversing the original value, before allocating full serialized, parsed, or redacted copies. An oversized or non-serializable payload is replaced by redacted bounded scalar metadata (including event, tool, and message identifiers when present) plus `neckbeardTruncation: { truncated: true, reason, maxPayloadBytes, originalPayloadBytes? }`. This keeps the ordered outbox replayable while making data loss explicit; normalized lifecycle events such as `turn_completed` remain separate durable frames.
213
+
214
+ Pi text-delta events declared `coalesced` use bounded latest-wins buffering while persistence is backpressured. The first in-flight delta and latest pending delta on each contiguous delta run are retained; an intervening tool, lifecycle, or other durable event is an ordering boundary. Suppressed deltas never receive a sequence. This stream is intentionally lossy under pressure, while non-coalesced events and normalized terminal lifecycle remain ordered and durable.
215
+
216
+ Acknowledgement first persists the cumulative cursor, then prunes acknowledged frames from memory. Thresholded compaction rewrites a v2 checkpoint plus the contiguous unacknowledged suffix with file and directory fsyncs; the checkpoint preserves the next sequence and unresolved recovery facts. Restart accepts those facts only when they match the command ledger and durable cursors; a fact above the acknowledgement cursor must also match the exact retained event frame, while a compacted fact must be corroborated by the checkpoint recovery index. Durable metadata, active-turn, outbox, and command-ledger leaves are opened without following symlinks, never block on special files, and must be regular files before any read, repair, or append. The mutable outbox and command-ledger descriptors must additionally remain process-owned and single-link before an append or crash-partial repair, so a hard-linked peer is never modified. Every leaf has an explicit byte ceiling, including the small metadata, active-turn, and revision-pointer control files; reads stop after at most the ceiling plus one byte so a same-UID replacement cannot turn restart into an unbounded allocation. Within a valid runtime-2 revision fence, the record reader remains backward-compatible with genuine runtime-1 full-history frames under current shape and frame-size validation, atomically rewrites them as a v2 checkpoint plus current-version unacknowledged suffix, repairs only a crash-partial final line, and rejects malformed middle records or unacknowledged gaps. That record compatibility does not migrate a pre-fence `attempts/<attemptId>` directory, which remains replacement-only as described above. Socket delivery is bounded by frame size, per-flush bytes, configured event count, an 8 MiB unacknowledged byte window, and `bufferedAmount`; a send failure leaves the event replayable.
217
+
218
+ The exact-replay command ledger is append-only in runtime 2 and is therefore also finite: one attempt admits at most 65,536 distinct commands, 131,072 ordinary ledger records, and 64 MiB. A separate 512-record/8 MiB reserve is available only for terminalizing already admitted receipts. Command IDs are capped at 512 UTF-8 bytes. Crossing any applicable bound fails the supervisor closed; use a replacement attempt for additional work. Semantic checkpoint compaction may raise this lifetime ceiling in a future disk revision.
219
+
220
+ Heartbeats are ephemeral and report harness state, outbox depth, and both cursors. Reconnect uses capped jittered exponential backoff. During a gateway outage, accepted Pi work may continue only while the durable unacknowledged outbox remains below 8,192 events and 32 MiB. A separate 64-event/8 MiB reserve admits restart and terminal recovery facts. Crossing the applicable bound rejects the append, closes the execution gate, and fails the supervisor rather than risking unbounded resident memory or restart-time journal allocation. Acknowledgement and compaction free capacity; operators should still alert on sustained outbox growth before this fail-closed boundary.
221
+
222
+ ## Restart and ownership invariant
223
+
224
+ No agent execution may survive without an owner capable of observing and aborting it. The Pi SDK runs in the supervisor process rather than a detached child, so the operating system enforces that ownership: Pi cannot outlive a supervisor crash.
225
+
226
+ The runtime atomically records an active-turn marker before prompt preflight and removes it only after a durable normalized terminal event. On restart:
227
+
228
+ - `SessionManager.open()` reopens conversation history for later work;
229
+ - an active turn cannot be reattached because its Promise died with the process;
230
+ - the supervisor emits exactly one durable `turn_failed` with `stopReason: "supervisor_restarted_during_prompt"`;
231
+ - if an accepted stop marker was already durable, recovery emits exactly one `turn_stopped` instead;
232
+ - unfinished prompt command receipts are terminalized even if an older runtime crashed before writing an active-turn marker;
233
+ - unfinished steer/stop commands become `command_failed` without inventing a new turn.
234
+
235
+ Recovery checks the durable outcome/terminal index before emitting, then closes the command ledger record and finally clears the active marker. This ordering makes repeated restarts idempotent even when acknowledged events have already been compacted.
236
+
237
+ One monotonic execution gate coordinates the runtime, command processor, attachment materializer, and Pi adapter. The first shutdown, supersession, startup, runtime transport, harness, or persistence failure wins. New side effects recheck the gate immediately before Pi calls; once Pi accepts a call, a later gate closure cannot relabel that accepted side effect as safely rejected. Persistence/listener failure is sticky, closes the socket, aborts/disposes Pi, rejects pending receipt waiters, and makes the process exit nonzero. A synchronous WebSocket construction failure is fatal rather than an infinite reconnect loop. Successful non-superseding shutdown bounds Pi settlement/event drainage and command quiescence, then durably terminalizes any accepted active turn before exit; supersession or fatal shutdown leaves its marker for restart recovery.
238
+
239
+ ## Operational boundaries
240
+
241
+ - A Hatchet launch/reconcile task boots or verifies the supervisor and returns. It does not await Pi's run Promise.
242
+ - The Render gateway persists each event before acknowledgment and each command before delivery.
243
+ - Postgres is the product lifecycle source of truth. Sandbox files are an attempt-local replay journal, command ledger, Pi session history, and recovery marker.
244
+ - Daytona stop/archive policies must exceed the control plane's run limits.
245
+ - Stage repositories, environment files, skills, and setup hooks before booting the artifact; deployment bootstraps the exact Pi SDK package itself. The attached Pi adapter keeps project package/resource trust disabled. Every initial or extension-triggered Pi resource reload copies `agentDir` through descriptor-relative `O_NOFOLLOW` source and destination traversal into a complete private generation. It rejects symlinks, special files, structural changes during traversal, and mutation of each descriptor-bound file while that file is copied. After finalizing owner-only modes, it recursively reopens the complete destination namespace without following links and verifies every entry against the copied descriptor identity and exact expected-name manifest; it repeats that validation immediately before giving Pi the retained generation descriptor. Snapshots are bounded to 16 MiB per file, 64 MiB and 4,096 files per tree, 1,024 directories, and 32 directory levels. Up to eight successfully loaded generations remain allocated for resource paths Pi may reference later; a ninth reload fails closed, while failed candidate reloads are removed immediately and do not consume the limit. Each attempt has its own snapshot namespace; startup reclaims only that attempt's stale crash residue and leaves other attempts untouched, and stop removes the active attempt namespace. Stop rejects within `stopGraceMs` if an SDK-triggered reload remains stuck, but keeps its descriptors alive and completes namespace cleanup in the background once that reload settles. Snapshot directories and ordinary files are owner-only `0500` and `0400` respectively, while source executables remain owner-executable at `0500`. These modes and validation boundaries prevent accidental writes and reject observed construction-time namespace substitution, but they cannot make files immutable against a deliberately hostile process running continuously as the supervisor's Unix UID; that threat requires separate Unix-user or provider isolation. Pi still loads its ordinary project instruction context from the workspace and its ancestors; those instruction files are not executable project packages or skills.
246
+ - `attemptId` must be one safe POSIX path segment. Install, state, workspace, Pi session, and agent directories must be canonical absolute non-root POSIX paths; the artifact rejects aliases and traversal instead of normalizing them. The Pi session file and agent directory are strictly below state, while workspace and state must be disjoint.
247
+ - Daytona current detached-process stop is leader-PID-birth fenced, preserves the permanent subreaper, and resolves only after its exact fsynced completion proof or bounded TERM-to-KILL escalation fails. A descendant that creates an independent session is not signaled; while the subreaper still owns or waits for it, stop fails closed at the deadline rather than claiming quiescence.
248
+ - Do not log resume frames, signed URLs, authorization headers, environment values, or generated application configuration.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.17",
3
+ "version": "1.1.19",
4
4
  "description": "Deploy AI agents to E2B and Daytona sandboxes",
5
5
  "type": "module",
6
6
  "exports": {
@@ -13,6 +13,16 @@
13
13
  "types": "./dist/index.d.cts",
14
14
  "default": "./dist/index.cjs"
15
15
  }
16
+ },
17
+ "./supervisor": {
18
+ "import": {
19
+ "types": "./dist/supervisor.d.ts",
20
+ "default": "./dist/supervisor.js"
21
+ },
22
+ "require": {
23
+ "types": "./dist/supervisor.d.cts",
24
+ "default": "./dist/supervisor.cjs"
25
+ }
16
26
  }
17
27
  },
18
28
  "main": "./dist/index.cjs",
@@ -20,18 +30,21 @@
20
30
  "types": "./dist/index.d.cts",
21
31
  "sideEffects": false,
22
32
  "files": [
23
- "dist"
33
+ "dist",
34
+ "CHANGELOG.md",
35
+ "docs/SUPERVISOR.md"
24
36
  ],
25
37
  "engines": {
26
- "node": ">=20.0.0"
38
+ "node": ">=20.18.1 <21 || >=22"
27
39
  },
28
40
  "packageManager": "npm@10.9.4",
29
41
  "scripts": {
30
- "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && node scripts/generate-runtime-server-source.mjs && tsup",
42
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && node scripts/generate-runtime-server-source.mjs && node scripts/generate-supervisor-runtime-source.mjs && tsup",
31
43
  "check": "npm run typecheck && npm run lint && npm run format:check && npm test && npm run check:generated && npm run test:cjs && npm run pack:dry-run",
32
- "check:generated": "node scripts/verify-runtime-server-source.mjs",
44
+ "check:generated": "node scripts/verify-runtime-server-source.mjs && node scripts/verify-supervisor-runtime-source.mjs && node scripts/verify-supervisor-package-lock.mjs",
33
45
  "dev": "tsup --watch",
34
46
  "format:check": "node scripts/check-format.mjs",
47
+ "generate:supervisor-package-lock": "node scripts/generate-supervisor-package-lock.mjs",
35
48
  "lint": "node scripts/repo-lint.mjs",
36
49
  "pack:dry-run": "npm pack --dry-run",
37
50
  "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs",
@@ -45,9 +58,9 @@
45
58
  "prepare": "npm run build"
46
59
  },
47
60
  "dependencies": {
48
- "@daytona/sdk": "^0.192.0",
49
- "e2b": "^2.2.0",
50
- "esbuild": "^0.24.0"
61
+ "@daytona/sdk": "^0.204.1",
62
+ "e2b": "^2.39.0",
63
+ "esbuild": "^0.28.2"
51
64
  },
52
65
  "peerDependencies": {
53
66
  "zod": "^3.0.0 || ^4.0.0"