agent-neckbeard 1.1.28 → 1.1.30

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +28 -30
  3. package/dist/archil.d.ts +73 -0
  4. package/dist/archil.js +673 -0
  5. package/dist/build.cjs +129 -5160
  6. package/dist/build.d.cts +9 -5
  7. package/dist/build.d.ts +9 -5
  8. package/dist/build.js +4 -6
  9. package/dist/{chunk-JF5YPOBY.js → chunk-FHNQ5DNA.js} +3235 -511
  10. package/dist/{chunk-M7XNBKG4.js → chunk-I5GIWADK.js} +29 -7
  11. package/dist/chunk-I5NULOJP.js +129 -0
  12. package/dist/chunk-PKUGXECR.js +13 -0
  13. package/dist/chunk-QA4L7ZI2.js +72 -0
  14. package/dist/{chunk-KG6SJM74.js → chunk-VHBDBB3N.js} +8 -5
  15. package/dist/cli.cjs +124 -5154
  16. package/dist/cli.js +7 -8
  17. package/dist/define-gdmBe9RA.d.ts +227 -0
  18. package/dist/durable.d.ts +53 -0
  19. package/dist/durable.js +92 -0
  20. package/dist/index.cjs +720 -833
  21. package/dist/index.d.cts +139 -78
  22. package/dist/index.d.ts +139 -78
  23. package/dist/index.js +12 -11
  24. package/dist/inside.d.ts +15 -0
  25. package/dist/inside.js +530 -0
  26. package/dist/{invoke-client-P2CPBYTF.js → invoke-client-QB2NTZ3L.js} +1 -2
  27. package/dist/pi-watch-legacy.d.ts +4503 -0
  28. package/dist/serve.cjs +9 -309
  29. package/dist/serve.d.cts +14 -1
  30. package/dist/serve.d.ts +14 -1
  31. package/dist/serve.js +3 -5
  32. package/docs/AGENT.md +95 -59
  33. package/docs/DAYTONA.md +2 -0
  34. package/docs/DOCKER.md +0 -1
  35. package/docs/E2B.md +1 -1
  36. package/docs/LEGACY.md +1 -8
  37. package/docs/MODAL.md +1 -1
  38. package/package.json +57 -23
  39. package/types/pi-watch.d.cts +68 -0
  40. package/dist/chunk-33IXN6MM.js +0 -21
  41. package/dist/chunk-6P5I7ZCH.js +0 -2552
  42. package/dist/chunk-M3FISP7J.js +0 -377
  43. package/dist/sandbox-capabilities-CFjnZ_kB.d.cts +0 -77
  44. package/dist/sandbox-capabilities-CFjnZ_kB.d.ts +0 -77
  45. package/dist/serve-Dan1HQKN.d.cts +0 -89
  46. package/dist/serve-Dan1HQKN.d.ts +0 -89
  47. package/dist/supervisor.cjs +0 -5731
  48. package/dist/supervisor.d.cts +0 -482
  49. package/dist/supervisor.d.ts +0 -482
  50. package/dist/supervisor.js +0 -3187
  51. package/docs/SUPERVISOR.md +0 -258
package/docs/AGENT.md CHANGED
@@ -1,58 +1,61 @@
1
- # Agents from Prebuilt Images
1
+ # Pi Durable agent placements
2
2
 
3
- An agent runs a Pi session from a container image you build ahead of time, usually in CI. The image holds everything the agent needs: OS packages, Python and npm dependencies, skills, and the agent itself. Starting a sandbox installs and uploads nothing, so a cold start is the provider's sandbox start plus the agent process start.
3
+ Set `mode` on the definition to choose where the harness runs. Both examples acquire a conversation with `start`.
4
4
 
5
- This replaces `LegacyBundledAgent`, which bundles the agent's code on the host and uploads it, its dependencies, and its local directories at every deploy. That class still works and is deprecated.
5
+ - **Sandbox** packages Pi and the tools in the provider image. The worker attaches over HTTP. [Sandbox example](#defining-an-agent)
6
+ - **Host** runs Pi in the worker and uses an Archil tools image for commands. The worker can commit native Pi transactions. [Host example](#host-side-pi-durable-harness)
7
+
8
+ The prebuilt sandbox image replaces `LegacyBundledAgent`, which bundles the agent's code on the host and uploads it, its dependencies, and its local directories at every deploy. That class still works and is deprecated.
6
9
 
7
10
  ## Defining an agent
8
11
 
9
12
  `defineAgent()` describes an agent once, in one module: its image, its sandbox, and its Pi session. Your process imports it to start sandboxes and run turns; `neckbeard build` bundles the same module as the image's entry point, which serves the session.
10
13
 
11
14
  ```ts
12
- // src/agent.ts
15
+ // agent.ts
13
16
  import { defineAgent } from "agent-neckbeard";
14
- import type { JsonAgentSessionEvent } from "@earendil-works/pi-coding-agent";
15
17
 
16
- export const myAgent = defineAgent<JsonAgentSessionEvent>({
18
+ export const myAgent = defineAgent({
19
+ mode: 'harness-inside-sandbox',
17
20
  name: "my-agent", // the image is ghcr.io/acme/my-agent:<tag>
18
21
  registry: "ghcr.io/acme",
19
22
  sandbox: { provider: "modal", cpu: 2, memoryMiB: 4096, regions: ["us-east"], registrySecret: "ghcr" },
20
- envs: () => ({ OPENAI_API_KEY: process.env.OPENAI_API_KEY }),
21
- maxTurnDurationMs: 2 * 60 * 60 * 1000, // optional: ends a turn that runs longer as failed
23
+ env: () => ({ OPENAI_API_KEY: process.env.OPENAI_API_KEY }),
24
+ maxTurnDurationMs: 2 * 60 * 60 * 1000, // optional: aborts a submission that exceeds this duration
22
25
  pi: {
23
26
  model: "openai/gpt-6.1-sol",
24
27
  thinkingLevel: "high",
25
- tools: ["read", "bash", "grep", "ls"],
28
+ tools: ["read", "bash"],
26
29
  systemPrompt: "You are ...",
27
30
  cwd: "workspace",
28
31
  },
29
32
  });
30
33
  ```
31
34
 
32
- `sandbox` and `envs` may be functions, read the first time the host needs them, so the image, which never calls them, needs none of the host's configuration. Pass Pi's `JsonAgentSessionEvent` to type the events; neckbeard's own declarations don't reference Pi's, so a package that only runs turns needn't install Pi.
35
+ `sandbox` and `env` may be functions, read the first time the host needs them, so the image, which never calls them, needs none of the host's configuration. `defineAgent()` infers `PiWatchEvent`, the native callback argument from Pi Durable’s `conversation.watch()`.
33
36
 
34
37
  `pi` creates the session in the sandbox, which needs Pi's Node.js 22.19 or later (`PiSessionConfig` in [`src/define.ts`](../src/define.ts)):
35
38
 
36
- - `model` as `provider/model`, with `thinkingLevel` and the built-in `tools` to enable. The model's credential comes from the sandbox's environment, such as `OPENAI_API_KEY`.
39
+ - `model` as `provider/model`, with `thinkingLevel` and an optional subset of the built-in tools `read`, `write`, `edit`, and `bash`. The model's credential comes from the sandbox's environment, such as `OPENAI_API_KEY`.
37
40
  - `systemPrompt` replaces Pi's. Pi's agent directory is `~/agent/.pi`, and its skills are the image's `/app/.agents/skills` (`SKILLS_DIR`) only: no extensions, prompt templates, or context files are loaded from the sandbox.
38
41
  - `cwd`, relative to the sandbox user's home unless absolute (default `workspace`), is created before the session and exported as `NECKBEARD_CWD`, so the agent's scripts can find it.
39
- - `persist` keeps the conversation in `~/agent/.pi/sessions/<sessionId>.jsonl`, for the `sessionId` passed to `start()`, so a restarted runtime, or a sandbox restored from a copy of that file, continues it. `sessionFilePath(homeDir, sessionId)` gives the path for copying it out and back. Otherwise the conversation lives in memory as long as the sandbox.
42
+ - `persist` keeps the conversation in `~/agent/.pi/sessions/<sessionId>.sqlite`, for the `sessionId` passed to `start()`, so a restarted runtime, or a sandbox restored from a copy of that file, continues it. `sessionFilePath(homeDir, sessionId)` gives the path for copying it out and back. Reopening applies the current definition and skill index to the restored root conversation before the next turn. Copy SQLite snapshots after `waitForIdle()`. Existing JSONL snapshots require a consumer migration. Otherwise the conversation lives in memory as long as the sandbox.
40
43
 
41
- For a session that config can't express, pass `createSession` instead of `pi`, returning anything with Pi's `subscribe`, `prompt`, and `abort`, and optionally `afterTurn()`, which runs once each turn's outcome is known, before its `end` record and outside its deadline, as to send traces; an abort that arrives meanwhile changes nothing. Keep it bounded, since it delays the `end` record. A definition needs exactly one of them.
44
+ A custom image can supply `createSession` returning the resources produced by `openInsideConversation()` from `agent-neckbeard/inside`. A definition takes exactly one of `pi` and `createSession`. For a custom factory, set the deadline where the runtime is constructed, for example `createSession: () => openInsideConversation(pi, models, 120_000)`. A definition-level `maxTurnDurationMs` requires the built-in `pi` factory.
42
45
 
43
46
  ### Tracing
44
47
 
45
- A `pi` agent traces its turns in [Braintrust](https://www.braintrust.dev) when its sandbox has `BRAINTRUST_API_KEY` and `BRAINTRUST_PROJECT_NAME`. Pass them in `envs`, and add `braintrust` `>=3.44.0 <4.0.0`, an optional peer dependency, to the agent's package's `dependencies` (not `devDependencies`), so `neckbeard build` installs it in the image, shared with any imports of it in the agent's own code; the build fails on a version outside that range, which can't trace Pi 1.x:
48
+ A `pi` agent traces its turns in [Braintrust](https://www.braintrust.dev) when its sandbox has `BRAINTRUST_API_KEY` and `BRAINTRUST_PROJECT_NAME`. Pass them in `env`, and add `braintrust` `>=3.44.0 <4.0.0`, an optional peer dependency, to the agent's package's `dependencies` (not `devDependencies`), so `neckbeard build` installs it in the image, shared with any imports of it in the agent's own code; the build fails on a version outside that range, which can't trace Pi 1.x:
46
49
 
47
50
  ```ts
48
- envs: () => ({
51
+ env: () => ({
49
52
  OPENAI_API_KEY: process.env.OPENAI_API_KEY,
50
53
  BRAINTRUST_API_KEY: process.env.BRAINTRUST_API_KEY,
51
54
  BRAINTRUST_PROJECT_NAME: "my-agent",
52
55
  }),
53
56
  ```
54
57
 
55
- Each turn is a trace of Pi's prompt, its model calls, and its tool calls, sent once its outcome is known: before its `end` record, so a sandbox deleted right after a turn loses nothing, and outside `maxTurnDurationMs`, so sending it can't fail the turn. Tracing never fails a turn: a trace that can't be sent within 10 seconds, or a Braintrust that can't start, is reported with `console.warn` and the agent runs on. The key turns tracing on: without it, tracing is off, so an agent can name its project and run untraced wherever no key is configured, as in local development. A key without a project name is a mistake: the first `start()` warns on the host, the sandbox warns in its own log, and the agent runs untraced.
58
+ Each admitted submission is traced as `Pi Durable turn`. Wait for idle before snapshotting or deleting a sandbox so its trace can flush.
56
59
 
57
60
  A sandbox with a network allowlist must allow `www.braintrust.dev`, where Braintrust logs in, and the organization's API host, by default `api.braintrust.dev`.
58
61
 
@@ -65,7 +68,7 @@ A host runs `<registry>/<name>:<tag>`, where the tag is the first of these set:
65
68
  From the agent's package, after logging in to the registry:
66
69
 
67
70
  ```sh
68
- npx neckbeard push src/agent.ts [--export <name>] [--tag <tag>]... [--cache] [--dry-run]
71
+ npx neckbeard push agent.ts [--export <name>] [--tag <tag>]... [--cache] [--dry-run]
69
72
  ```
70
73
 
71
74
  `push` writes the image's build context, as `neckbeard build` does, to a temporary directory it removes afterwards, so the package needn't ignore it, and builds it for `linux/amd64`, which every provider runs, with the package's `sandbox/Dockerfile` (`build.dockerfile`) and `docker build`, tagged `<registry>/<name>:<tag>` for each `--tag` (default: `resolveImageTag()`, so `GITHUB_SHA` in a GitHub workflow). It then pushes each tag, and readies each for its provider: on Daytona it builds the tag's snapshot, on E2B its template, again even when one exists, since a tag such as `master` may now name new contents, and deletes older ones, keeping three in all and never one this push built (`prepare({ refresh: true })` and `gc({ keep: 3, alsoKeep })`), so no sandbox start waits on a build. Modal pulls the image itself, and [keeps a tag's contents once pulled](https://modal.com/docs/guide/sandboxes#separating-image-builds-from-sandbox-creation), so a reused tag such as `master` can't be refreshed there: a Modal host should run an immutable tag, as a deployed host running its commit does, and `push` says so for each later tag of a Modal agent. That needs the provider's credentials, such as `DAYTONA_API_KEY`, and whatever the definition's `sandbox` function reads. `--cache` builds with `docker buildx`, reusing and updating layers cached in the registry under the image's `buildcache` tag. `--dry-run` builds without pushing or preparing, as for a pull request. `--export` picks the agent when the module exports several; by default it is the default export or the module's only agent. `pushAgent()` from `agent-neckbeard/build` does the same. A workflow:
@@ -74,12 +77,12 @@ npx neckbeard push src/agent.ts [--export <name>] [--tag <tag>]... [--cache] [--
74
77
  - uses: docker/setup-buildx-action@v3
75
78
  - uses: docker/login-action@v3
76
79
  with: { registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}" }
77
- - run: npx neckbeard push src/agent.ts --tag ${{ github.sha }} --tag latest --cache ${{ github.event_name == 'pull_request' && '--dry-run' || '' }}
80
+ - run: npx neckbeard push agent.ts --tag ${{ github.sha }} --tag latest --cache ${{ github.event_name == 'pull_request' && '--dry-run' || '' }}
78
81
  working-directory: packages/my-agent
79
82
  env: { DAYTONA_API_KEY: "${{ secrets.DAYTONA_API_KEY }}" }
80
83
  ```
81
84
 
82
- `neckbeard build src/agent.ts [--export <name>] [--out dist-sandbox]` writes only the build context, for inspecting it. It replaces `dist-sandbox/`, or `--out`, with three things. It refuses an output directory that holds the package or its module, or that is not empty and was not written by an earlier build.
85
+ `neckbeard build agent.ts [--export <name>] [--out dist-sandbox]` writes only the build context, for inspecting it. It replaces `dist-sandbox/`, or `--out`, with three things. It refuses an output directory that holds the package or its module, or that is not empty and was not written by an earlier build.
83
86
 
84
87
  - `agent.mjs`: the module, bundled with an entry point that calls the agent's `serve()`. Pi's packages (`@earendil-works/*`), Braintrust for a `pi` agent whose package depends on it, the host-only provider SDKs, and each package in the definition's `build.external` stay out of the bundle, for ones that load native modules or wasm or otherwise must be installed. The build loads the module on the host to read its definition, so its top level must not need the image.
85
88
  - `package.json`: those packages, each pinned to the version its importer resolves, as Node will in the image. The build fails when the bundle imports one package at two versions.
@@ -104,46 +107,43 @@ COPY .agents /app/.agents
104
107
  CMD ["node", "/app/agent.mjs"]
105
108
  ```
106
109
 
107
- The runtime listens on `NECKBEARD_PORT`, which the host sets, or 8080, and sends Pi's events in the JSON form Pi's JSON and RPC modes write: a `message_update` carries only its delta, not the cumulative message. The image needs Bash for file and command access through `SandboxClient`. Never bake secrets into it: pass them as `envs`, or as turn `env`.
110
+ The runtime listens on `NECKBEARD_PORT`, which the host sets, or 8080, and streams each native watch callback argument over SSE. For a value callback, `event.value` holds the conversation view and `event.ops` holds its operations. The image needs Bash for file and command access through `SandboxClient`. Pass secrets at sandbox startup with `Agent.start({ env })`.
108
111
 
109
112
  ## The host
110
113
 
111
114
  ```ts
112
- import { getPiTurnResult } from "agent-neckbeard";
113
- import { myAgent } from "./agent";
114
-
115
- const sandboxId = await myAgent.start({ sessionId });
116
- for await (const record of myAgent.prompt(sandboxId, {
117
- turnId: runId,
118
- message: "Summarize the data room.",
119
- env: { API_TOKEN: shortLivedToken },
120
- })) {
121
- if (record.type === "event") store(record.seq, record.event);
122
- else console.log(record.outcome, record.error);
115
+ import { BACKGROUND_CONTEXT as ctx } from '@earendil-works/chord/context';
116
+ import { answerFromEntry } from 'agent-neckbeard/durable';
117
+ import { myAgent } from './agent';
118
+
119
+ const { sandboxId, conversation } = await myAgent.start({ env: { API_TOKEN: shortLivedToken } });
120
+ try {
121
+ const submission = await conversation.submit({
122
+ type: 'input', content: 'Summarize the data room.', requestId: runId, whenBusy: 'reject',
123
+ }, ctx);
124
+ const record = await submission.wait(ctx);
125
+ if (record.type === 'input' && record.status === 'done') {
126
+ const result = answerFromEntry(await conversation.entry(record.answer, ctx));
127
+ console.log(result);
128
+ }
129
+ await conversation.waitForIdle(ctx);
130
+ } finally {
131
+ await myAgent.kill(sandboxId);
123
132
  }
124
- await myAgent.kill(sandboxId);
125
133
  ```
126
134
 
127
- Every method takes the sandbox ID, so a host process that restarts, or another one, can drive a sandbox the first one started.
135
+ `Agent` and `DefinedAgent` own sandbox lifecycle: `start`, `attach`, `prepare`, `sandbox`, `health`, `waitForIdle`, `kill` and `gc`. Two calls return the same `{ sandboxId, conversation }`:
136
+
137
+ - `agent.start({ env?, sessionId?, signal? })` always launches a sandbox. A `pi` agent with `persist` requires a `sessionId` of letters, digits, underscores and dashes. One without `persist` rejects a `sessionId`. Both throw `ConfigurationError` before anything is launched.
138
+ - `agent.attach(sandboxId, { signal? })` reconnects to that exact provider sandbox, including while it is busy. It makes one health request, checks the runtime protocol and admits no input. It never creates, starts or kills a sandbox.
128
139
 
129
- | Method | Does |
130
- |---|---|
131
- | `start({ envs, sessionId, signal })` | Prepares the image for the provider if needed, creates a sandbox whose main process is the image's runtime, waits until it answers, returns the sandbox ID. `sessionId` is the sandbox's `NECKBEARD_SESSION_ID`, which names a persisted session's file. A start that fails or is cancelled deletes its sandbox; if that fails too, it throws `DeploymentError` with the `sandboxId` to `kill()` |
132
- | `prompt(sandboxId, { turnId, message, env }, { after, signal })` | Starts a turn and yields its records until its `end` record. A `turnId` the runtime already has resumes that turn instead of running it again |
133
- | `run(sandboxId, turn, { onRecord, signal })` | Runs a turn to its end, passing each record to `onRecord`, and returns the last assistant message's text; throws `ExecutionError` when the turn doesn't complete. Calling it again with the same `turnId` resumes the turn and replays its records from the start, so store them keyed by `seq` |
134
- | `events(sandboxId, turnId, { after, signal })` | Resumes a turn's records after `after`. Throws `TurnLostError` when the runtime no longer has the turn |
135
- | `abort(sandboxId, turnId)` | Stops the turn; its stream ends with an `aborted` record |
136
- | `health`, `waitForIdle` | Whether a turn is running |
137
- | `sandbox(sandboxId)` | A `SandboxClient` for files and commands, for staging inputs or reading results |
138
- | `kill(sandboxId)` | Deletes the sandbox without starting it. One that is gone counts as deleted; any other failure throws, so cleanup can be retried, since a Daytona sandbox without `autoDeleteInterval` never expires |
139
- | `prepare({ refresh })` | Creates the Daytona snapshot or E2B template if missing, or replaces one an earlier attempt left failed, or with `refresh` builds it again, within `prepareTimeoutMs` (30 minutes) and the caller's `signal`; does nothing on Modal |
140
- | `gc({ keep, alsoKeep })` | Deletes this agent's older Daytona snapshots or E2B templates (exactly `nb-<name>-<hash>`, so not another agent's whose name starts with this one's), keeping the newest `keep`, and never the current one or those named in `alsoKeep` |
140
+ `attach()` throws `SandboxGoneError`, a `DeploymentError`, when the provider reports the sandbox absent or not running: Modal reports it finished or unknown, Daytona reports it missing or in any state other than `started`, or E2B returns 404 or reports it paused. For E2B, `attach()` reads the state before connecting, and a sandbox that pauses between the two calls can still be resumed by the E2B SDK. Every other failure, such as a provider outage or an unreachable runtime, surfaces as itself, so retry those and replace the sandbox only on `SandboxGoneError`. Neither `attach()` nor any later request on its conversation, `health()` or `waitForIdle()` starts a stopped Daytona sandbox or resumes a paused E2B one. A restarted Daytona runtime would return with an empty in-memory conversation and a repeated `requestId` would run the turn again, and resuming an E2B sandbox restarts its billing. When a request fails to connect, or returns a failure status that is not one of the runtime’s own coded rejections, Neckbeard asks the provider once whether the sandbox still runs and throws `SandboxGoneError` if it does not. That check never sends the request again; the only resend is the single retry after a 401 or 403, where the proxy rejected the endpoint credential before the request reached the runtime. If the sandbox still runs, or the provider cannot say, the caller gets the original failure. In a live run on 2026-11-23, Daytona’s proxy answered a stopped sandbox with 400 and `code: "SANDBOX_NOT_RUNNING"`. Only `agent.sandbox(sandboxId)` starts or resumes one, for file access. Call `agent.kill(sandboxId)` to terminate a sandbox. To restore a snapshot into a replacement, start a new sandbox with the logical session ID and restore its SQLite file before the first conversation operation.
141
141
 
142
- The first call builds the agent's `Agent` for the image `imageRef()` names; `forImage(image)` returns one for another image. `new Agent({ name, image, sandbox, envs })` takes the same options for an image built some other way, and `serve({ createSession })` from `agent-neckbeard/serve` serves a session from an entry point you write yourself.
142
+ A worker that dies after the provider creates a sandbox and before the caller saves its ID leaks that sandbox until its provider lifetime ends. Set a lifetime that bounds this: Modal and E2B `timeoutMs`, and Daytona `autoDeleteInterval`, because Daytona stops an idle sandbox but never deletes it by default.
143
143
 
144
- `getPiTurnResult(records)` reads how a turn ended: completed with its last assistant message's text when the records include the `end` record, the turn ended normally, and the model stopped on its own; otherwise an error, including for records that stop before the `end` record.
144
+ CRM setup records the ID from `const { sandboxId } = await crmAgent.start({ env: connection.env })`. The next Hatchet task acquires `const { conversation } = await crmAgent.attach(sandboxId)` and kills the sandbox in its cleanup. This ephemeral session needs no logical session ID or snapshot store.
145
145
 
146
- `signal` stops reading a stream, never the turn: a host that stops or restarts leaves the turn running, and the next `prompt` or `events` call resumes it. Use `abort()` to stop a turn. A stream that drops reconnects on its own from the last record, and fails after `reconnectTimeoutMs` (two minutes) without a healthy connection. A connection is healthy while bytes arrive: records, the comment the runtime sends as a stream opens, or its heartbeat every 15 seconds. A connection that sends nothing for that long is abandoned, including one the server accepts and never answers, so keep `reconnectTimeoutMs` above 15 seconds. An `Agent` prepares once and reuses the result, until a start fails to create its sandbox, as when a newer release's `gc()` deleted its snapshot; the next start then prepares again. `start()` and `waitForIdle()` bound each health check by their own deadlines, and a malformed `/health` body is an error, never an idle runtime. A whole record that is invalid fails the stream with `ExecutionError` rather than being retried, while a record cut off by a dropped connection is read again after reconnecting.
146
+ Marketplace launches with `marketplaceAgent.start({ sessionId: appSessionId, env: sandboxEnv })` and copies any saved SQLite snapshot before the first Pi operation. A warm worker reconnects with `marketplaceAgent.attach(row.providerSandboxId)`, including while busy. After an ambiguous submit it looks up the stable request ID on the original conversation. A missing instance throws `SandboxGoneError`. The app decides whether replacement is safe because the S3 snapshot can predate the last admission.
147
147
 
148
148
  ## Providers
149
149
 
@@ -155,19 +155,55 @@ The first call builds the agent's `Agent` for the image `imageRef()` names; `for
155
155
 
156
156
  The hash covers the image reference, the command (Daytona), and the resources, so equal inputs share a snapshot or template and `prepare()` is a lookup. `neckbeard push` runs `prepare()` after pushing the image so no sandbox waits on a build; in our live tests a first build took 20 to 45 seconds, and a sandbox start after it about 2.5 seconds. It then runs `gc()` to delete older ones. Docker is not supported by `Agent` yet.
157
157
 
158
- ## Turn protocol
158
+ ## Conversation operations
159
+
160
+ `submit(draft, ctx)` accepts a text input with a stable `requestId` and Pi’s `whenBusy` and `whenIdle` policies. Pi checks the request ID before its busy or idle policy. Retrying a known ID returns the original input even if the text differs. `submissionByRequest(requestId, ctx)` is a read-only lookup and returns undefined for a missing ID. A transport failure can leave admission uncertain. Look up the original request before any retry. A settled `unanswered` record carries Pi’s reason and detail. A `RemoteAdmissionRejected` error certifies rejection of that submit request. A `RemoteSubmissionNotFound` error identifies a missing handle. Other HTTP errors leave admission uncertain. Wait and idle operations repeat ten-second polls. Cancellation calls have a thirty-second request deadline and may have reached the runtime if the response is lost.
161
+
162
+ `submission.status(ctx)`, `submission.wait(ctx)` and `submission.abort(ctx)` use the Pi result types. Withdrawal returns `aborted`, `already_placed` or `settled`. To stop the active task containing a particular input use `conversation.stopSubmission(submission.id, ctx)`. To abort the whole conversation use `conversation.abort(ctx, { background }?)`. A targeted stop atomically withdraws queued inputs with Pi's default withdraw policy and captures the active task. Set `onAbort: 'keep'` on a follow-up to preserve it. A kept input stays queued until a later submission starts another run. Stop rechecks the input after each tool-round handover. A stale target cannot cancel the successor. A runtime deadline targets the submission. On SQLite restore the new runtime starts its deadline timers for pending inputs when a caller requests progress. Lookup and status leave the conversation paused. `entry(settled.answer, ctx)` reads the native assistant entry for that input. A steer that leads a later run has its own submission and answer. [Pi Durable submissions and abort](https://www.npmjs.com/package/@earendil-works/pi-durable/v/1.6.0#abort)
163
+
164
+ Use `await conversation.watch(ctx, { min: 1, max: 4 })` before submitting. Inspect `watch.value` at acquisition and install the listener with `watch.start(async (call, context) => { ... })`. Callbacks run locally, in sequence. `submission.wait()` can resolve while a listener is still saving a write. After the native submission settles, await `conversation.waitForIdle(ctx)` when snapshotting, then await `watch.stop()` and inspect its `WatchEnd`. A successful stop drains frames emitted through the server stop boundary and waits for their callbacks. Aborting the watch context ends the watch stream immediately with `{ kind: 'aborted' }`. A callback already in progress remains caller-owned. A source failure or missing terminal frame closes the stream even while a callback is running. A listener error or a backlog exceeding 256 pending callbacks also fails the drain. The `watch.closed` promise also reports interruption without needing another entry or a visible ID gap.
165
+
166
+ A disconnect ends the watch stream. Open a new one with `conversation.watch()`, optionally supplying Pi’s `from` entry and window. `watch()` is the stream of conversation changes. `agent.attach()` reconnects to the sandbox and opens no stream. Its snapshot describes current state. Native folding, a reset or an interval without a watcher can hide transient changes. A caller deciding whether to repeat side effects needs positive evidence of non-admission or a complete, authoritative read-only interval. An uncertain admission, interrupted watch stream or incomplete terminal boundary supplies neither. [Pi Durable watches](https://www.npmjs.com/package/@earendil-works/pi-durable/v/1.6.0#watching-a-conversation)
167
+
168
+ Bash inherits the sandbox process environment. Pass launch credentials through `agent.start({ env })`. Every active and queued submission in that sandbox uses the same environment. To replace credentials, launch a replacement sandbox with fresh `env`. A restored SQLite conversation resumes with that sandbox’s environment. Neckbeard does not copy launch credentials into Pi drafts, watch frames or session storage.
169
+
170
+ ## Host-side Pi Durable harness
171
+
172
+ On Node 22.19 or later, install the matching optional peers `@earendil-works/pi-durable@1.6.0`, `@earendil-works/pi-ai@1.6.0` and `@earendil-works/chord@1.6.0` alongside neckbeard. Archil also needs `disk@1.13.0`. Both placements open the same harness. In-sandbox definitions use NodeExecutionEnv and in-memory or SQLite storage. For a host-side conversation, call the defined agent’s `.start({ sessionId, storage, execution }, context)`. Its registry includes Pi Durable's native read, write, edit and bash tools. The applied skill index comes from the tools image. [Pi tools](https://www.npmjs.com/package/@earendil-works/pi-durable#tools)
173
+
174
+ ```ts
175
+ import { archilStorage, archilExecution } from 'agent-neckbeard/archil';
176
+
177
+ const { disk, executionConfig } = await getSessionDisk(sessionId);
178
+ const storage = await archilStorage(disk, context);
179
+ const execution = archilExecution({ disk, ...executionConfig });
180
+ const session = await sbaFinancingAgent.start({ sessionId, storage, execution }, context);
181
+ try {
182
+ const submission = await session.conversation.submit({ type: 'input', content: message, requestId }, context);
183
+ await submission.wait(context);
184
+ } finally {
185
+ await session.close();
186
+ }
187
+ ```
188
+
189
+ Set `mode: "harness-outside-sandbox"` on the definition. The same `start()` call opens a session for the first time and reopens it every time after. Pass any Pi Storage and either a Pi ExecutionEnv or a Neckbeard execution factory. Start stamps the agent name and logical session ID atomically when it creates the root. For an existing root it verifies the stamp before acquiring the execution environment, and throws `SessionIdentityMismatch`, exported from `agent-neckbeard/durable`, when the storage holds another agent’s or another session’s conversation. The returned `session.storage` is the supplied Pi Storage.
190
+
191
+ `archilStorage(disk, context, options?)` takes the context second, as Pi’s `openNodeJsonlStorage(directory, context, options)` does. With `create` omitted it opens the disk’s session log or starts one, as every Pi storage does, so the same call serves the first start and every retry and reopen. That matters because the log first exists when `start()` commits the root, after it has written to the workspace. A first start that fails in between leaves a disk with no log, and the next `start()` initialises it. A log that exists without a root is initialised and stamped the same way. Pass `create: true` to require a disk with no log, which throws `ArchilSessionAlreadyExists` otherwise. Pass `create: false` to require a log with a root, which throws `ArchilSessionNotFound` otherwise. Both errors, `ArchilStorage`, `createArchilExecutionEnv` and `getArchilToolsImageId` are exported from `agent-neckbeard/archil`. `agent-neckbeard/durable` needs only the Pi peers. Call `archilStorage` immediately before `start()`, which takes ownership of the returned storage. The execution factory opens lazily. Aborting the context given to `archilStorage()` or `start()` ends their pending Archil reads and the wait for the execution factory; an environment a factory returns after that is cleaned up. A storage commit and `close()` always wait for a pending append, because its outcome must be known. Start assumes ownership of the supplied storage and environment, including cleanup on failure. The caller owns the disk.
192
+
193
+ One process writes a storage at a time, and the consumer must guarantee that. Neckbeard takes no lock, so two workers that open the same disk can each append commits the other never replays. Serialize a session’s runs with the worker’s own concurrency control, such as a Hatchet concurrency key on the session ID.
194
+
195
+ Both modes use Pi’s built-in provider registry with the definition’s `pi.model`. The session exposes the native conversation and harness for Pi transactions, along with its storage and `executionEnv`. Its idempotent `close()` shuts down the harness and storage and cleans up temporary files. Startup failures release the same resources. The session disk remains available for reopening. Host-side workers own deadlines for native submissions, including those admitted inside a transaction. An Archil start rejects a definition with the inside-runtime option `maxTurnDurationMs` before opening the harness. Commits append to `session-storage/commits.jsonl`. Opening the tape replays it through Pi's storage validation. Commits larger than the 1 MiB append limit are stored by SHA-256 before the tape atomically references them. Replay verifies the digest. Reopen after an append failure to discover its outcome. [History on the tenant's disk](https://archil.com/guides/building-agents/many-agents-one-machine#history-on-the-tenants-disk)
196
+
197
+ Build the separate tools image with `neckbeard push agent.ts --archil-dockerfile sandbox/Tools.Dockerfile --tag "$GITHUB_SHA"`. The Dockerfile installs the consumer's system dependencies, including bash and GNU coreutils and findutils, and copies `.agents` to `/app/.agents`. The context contains the agent's own and locked skills and their index. CI authenticates Docker and pushes the commit tag. The worker prepares the Archil image on first use. Set `ARCHIL_API_KEY` and `ARCHIL_REGION` on the worker. For private GHCR packages the worker also needs `REGISTRY_USERNAME` and a pull-scoped `REGISTRY_TOKEN`. The resolver exchanges those credentials for a pull token, resolves the tag to its manifest digest, and asks Archil for that exact image. [Archil private images](https://docs.archil.com/compute/sandboxes/images#private-images)
198
+
199
+ Each bash call runs in a fresh microVM with only the disk's `workspace/` mounted at `/mnt/archil/workspace`. Ordinary file contents use the object API. The environment reads image skills through exec and rejects writes outside the workspace. A binary reader streams the object into a private temporary file on the worker. Pi reads ranges and scans lines from that open file, which keeps its contents available if a later command renames the original. Serverless exec returns buffered stdout and stderr. Bash saves full output to the workspace when it exceeds Pi’s spill thresholds, before Archil caps either response stream. [Archil execution limits](https://docs.archil.com/compute/serverless-execution#limits)
159
200
 
160
- `serve()` speaks protocol version 2 over HTTP, behind each provider's endpoint auth (`TURN_PROTOCOL_VERSION`; types in `src/turn-protocol.ts`).
201
+ Stopping the targeted Pi turn ends the host's wait and discards the command's late output. It also ends the wait for a pending file request, and the rest of that file operation is not sent; a write already sent may still land. A dispatched command may finish and write to the workspace after the turn stops, including its `.pi-output-*.log` spill file, which the session does not remove. A timeout has the same command-side limitation. [Serverless execution](https://docs.archil.com/compute/serverless-execution#composing-multiple-disks-into-a-single-command)
161
202
 
162
- - `GET /health` returns `{ ok, protocolVersion, busy, turnId }`. `busy` stays true until the turn's prompt has returned and its `env` is restored, which can be after its `end` record, as when an event fails to convert and the prompt is still stopping. `start()` rejects a runtime with another protocol version.
163
- - `POST /turns` with `{ turnId, message, env? }` starts a turn and returns 202. A known `turnId`, the current or previous turn, returns 200 without starting anything; another turn while one is busy returns 409. `env` is set in `process.env` for the turn and restored after it.
164
- - `GET /turns/:turnId/events?after=<seq>` opens with an SSE comment, streams the turn's records after `seq`, then live records with a heartbeat comment every 15 seconds, and closes after the `end` record. A reader already past the end of an ended turn gets the `end` record again, so it can tell the turn ended from a dropped stream. Unknown turns return 404.
165
- - `POST /turns/:turnId/abort` returns 202 and aborts the session's prompt. Pi waits for a running tool before its prompt returns, so a turn that is aborted, or exceeds `maxTurnDurationMs` (which counts from the turn's start, creating the session included), and hasn't stopped within `serve()`'s `abortGraceMs` (10 seconds) gets its end record anyway. `busy` stays true until the prompt does return.
203
+ The worker can cache the prepared image ID for its registry, release and Archil account, and retry preparation on failure. The resolver defaults to the deployed commit from `resolveImageTag()`, then the current Git HEAD. Pass `tag` explicitly for other build environments. Set `mode: "harness-outside-sandbox"` on the host-side definition.
166
204
 
167
- A record is `{ seq, type: "event", event }` or `{ seq, type: "end", outcome: "completed" | "aborted" | "failed", error? }`. `seq` starts at 0 for each turn and increases by one, and the runtime serializes each record when it is written, so a replay of a `seq` sends exactly what streamed live, and a host can store records keyed by `seq` and ignore repeats. The runtime keeps the current and previous turns in memory. A runtime that restarts, or a replaced sandbox, loses them, and a resume then fails with `TurnLostError`.
205
+ Both placements use `turnRequestId(turnId)` and `steerRequestId(turnId, steerId)` to keep request identities distinct. A retry with different text returns the first submission and does not edit the input. Use a new ID for a new input. For native worker admission use `root.submit(tx, { type: 'input', requestId: turnRequestId(runId), content })` inside the worker’s cursor transaction. `durableTurnResult(storage, settled, context)` reads the final placed input for that turn and distinguishes completed, aborted and failed outcomes. Use `parseDurableRequestId(requestId)` to attribute a native submission to its turn and optional steer ID.
168
206
 
169
- ## Limits
207
+ Set `execution.network` for baseline egress on every Archil VM, including skill reads and cleanup. When a Bash call needs run authorization, supply one optional `execution.dispatch(identity, ctx)` callback. At Pi environment resolution the SDK captures the active leader’s submission ID and optional request ID. Each subsequent Bash command invokes the callback with that identity, the logical session ID and the workspace `cwd`, even if another run has since started. Return time-sensitive credentials through Archil’s network header transform. Bash starts with Pi’s command variables. Values in `execution.env` override those, and values returned in `dispatch.env` override both. The SDK sets `NECKBEARD_CWD` to the workspace last. A returned network policy replaces the baseline for that command, so include every required baseline restriction. Stopping a turn interrupts the wait for authorization. A command’s timeout covers its authorization, the command and its spill lookup, so a timeout or stop reported during the spill lookup can follow a command that already ran. A callback that finishes later cannot launch a VM. Non-Bash operations use the baseline. The caller can reuse the image and client across sessions and keep any session-bound token source in its session closure. [Pi Durable environment](https://github.com/earendil-works/pi/blob/v1.6.0/packages/durable/README.md#environment) · [Archil egress](https://docs.archil.com/compute/serverless-execution#restricting-network-access)
170
208
 
171
- - The session runs in the runtime process: if the agent crashes the process, the turn is lost and the provider's sandbox usually ends with it.
172
- - One turn runs at a time per sandbox.
173
- - `Agent` supports Pi-style sessions only. Other runtimes would get their own class.
209
+ Use `root.watch(context, durableWatchWindow)` to match the inside runtime’s one-to-four-entry window. Every callback still carries its full native value and operations. [Watching a conversation](https://www.npmjs.com/package/@earendil-works/pi-durable/v/1.6.0#watching-a-conversation)
package/docs/DAYTONA.md CHANGED
@@ -26,6 +26,8 @@ Modal sandboxes accept the same three options in the same shape. Modal's domain
26
26
 
27
27
  `autoStopInterval` and `autoDeleteInterval` set the sandbox's Daytona lifecycle, in whole minutes, when the sandbox is created; reconnecting to an existing sandbox does not change them. Daytona stops a sandbox after `autoStopInterval` minutes without activity (`0` disables auto-stop; omitting it keeps Daytona's default, 15 minutes for standard sandbox classes) and deletes it `autoDeleteInterval` minutes after it stops (`0` deletes it immediately; `-1`, the default, never auto-deletes it). `new Agent()` rejects values that are not whole minutes.
28
28
 
29
+ Starting a stopped sandbox runs the image entrypoint again as a new PID 1 on the same filesystem; a live run on 2026-11-23 kept `/tmp` and the boot ID and changed only PID 1's start time. A runtime that keeps its conversation in memory therefore comes back empty, which is why `Agent.attach()` and every runtime request report a stopped sandbox as `SandboxGoneError` instead of starting it. `Agent.sandbox()` and `SandboxClient.connect()` still start it.
30
+
29
31
  ## SandboxClient
30
32
 
31
33
  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:
package/docs/DOCKER.md CHANGED
@@ -82,7 +82,6 @@ Sandbox-level `envs` are written to `/root/.neckbeard-env` inside the container
82
82
  - Containers are started with `--rm` and a fixed lifetime, so a host that crashes before cleanup leaks a container for at most `timeoutMs`. `destroy()` tolerates an already-removed container.
83
83
  - `setTimeout()` is unsupported: choose the lifetime at creation.
84
84
  - Unknown options are rejected rather than dropped, including `apiKey`, published ports, volumes, privileged mode, and Daytona network policies.
85
- - The durable Pi supervisor target remains Daytona-specific.
86
85
 
87
86
  ## Tests
88
87
 
package/docs/E2B.md CHANGED
@@ -8,4 +8,4 @@ E2B starts sandboxes from templates. `Agent.prepare()` builds a template named `
8
8
 
9
9
  ## Lifetime, paths, and HTTP
10
10
 
11
- `SandboxClient.create()` accepts `timeoutMs`, and E2B is the provider that supports `setTimeout()` to extend a running sandbox's lifetime; other providers throw `ConfigurationError`. The home directory is `/home/user`. Neckbeard sends E2B's traffic token as the `e2b-traffic-access-token` header; callers only store the sandbox ID.
11
+ `SandboxClient.create()` accepts `timeoutMs`, and E2B is the provider that supports `setTimeout()` to extend a running sandbox's lifetime; other providers throw `ConfigurationError`. The home directory is `/home/user`. `Agent.attach()` and runtime requests read the sandbox state first and report a paused sandbox as `SandboxGoneError`, because the SDK's `Sandbox.connect()` resumes one. Only that call returns the traffic token, so a sandbox that pauses between the state read and the connection is still resumed; SDK 2.39 offers no connection that cannot resume. `Agent.sandbox()` and `SandboxClient.connect()` still resume it. Neckbeard sends E2B's traffic token as the `e2b-traffic-access-token` header; callers only store the sandbox ID.
package/docs/LEGACY.md CHANGED
@@ -1,12 +1,11 @@
1
1
  # Legacy API (deprecated)
2
2
 
3
- > **Deprecated.** Everything on this page is deprecated: `LegacyBundledAgent`, its structured tasks and attached sessions, `dependencies`, `files`, `localDirectories`, `claudeDir`, the `mode` property, the Next.js helpers, and the durable-session supervisor. It will be deleted once Tupelo's `cim-agent`, `valuation-agent`, and `deal-qualification-agent` have moved to the image-based `Agent` (see the [README](../README.md) and [AGENT.md](AGENT.md)). It still works, and it receives fixes but no new features.
3
+ > **Deprecated.** Everything on this page is deprecated: `LegacyBundledAgent`, its structured tasks and attached sessions, `dependencies`, `files`, `localDirectories`, `claudeDir`, the `mode` property, and the Next.js helpers. It will be deleted once Tupelo's `cim-agent`, `valuation-agent`, and `deal-qualification-agent` have moved to the image-based `Agent` (see the [README](../README.md) and [AGENT.md](AGENT.md)). It still works, and it receives fixes but no new features.
4
4
 
5
5
  `LegacyBundledAgent` bundles your agent's code on the host and, at every deploy, uploads it with the embedded runtime server, installs its dependencies, and copies its local directories into the sandbox. Its usage patterns:
6
6
 
7
7
  - Structured tasks: an agent runs once per background task and returns one validated output (Structured Tasks below).
8
8
  - Attached sessions: a caller-owned session emits typed progress frames while work runs (Attached Sessions below).
9
- - Durable sessions: an opt-in generated supervisor owns Pi inside Daytona and reconnects outward to a long-lived gateway (Durable Sessions below).
10
9
 
11
10
  `SandboxClient`, which these also use, is not deprecated; see the README.
12
11
 
@@ -327,9 +326,3 @@ A successfully deployed sandbox remains caller-owned and runs until you kill it
327
326
  All errors extend `NeckbeardError`. `ConfigurationError` covers invalid agent config, missing provider API keys, and provider features a sandbox does not support. `DeploymentError` covers sandbox creation, dependency install, and runtime server startup failures. After a runtime-server health-check failure, the two built-in startup paths include bounded best-effort captured logs when available, redact credential-named configured environment values and configured values of at least eight characters (including a possible tail-boundary fragment), and preserve the original health error if the diagnostic read fails or exceeds its local deadline. `ValidationError` wraps input/output schema failures with the parser error as `cause`. `ExecutionError` represents agent handler failures.
328
327
 
329
328
  `run()` never throws; it returns `{ ok: false, error }`. Attached `session.prompt()` throws. The deprecated `invoke()` wrapper preserves that throwing behavior.
330
-
331
- ## Durable Sessions
332
-
333
- > **Deprecated.** The durable-session supervisor is no longer maintained and will be removed in a future major release. Attached sessions (`LegacyBundledAgent.createSession()`) remain supported, but they are not durable: a turn stops when its caller disconnects, and nothing is replayed.
334
-
335
- `agent-neckbeard/supervisor` runs a persistent sandbox process that owns Pi while a separate gateway and lifecycle worker may restart independently. `createDurableSessionArtifact()` builds it and `deployDurableSessionArtifact()` boots it in a Daytona sandbox. [SUPERVISOR.md](SUPERVISOR.md) documents it completely: the launch contract and an example, the attempt credential, `beforeRelease`, cancellation and unavailable-generation errors, the Daytona target and terminal helpers, the 64 MiB session history ceiling, the gateway protocol, and the deprecated `createPiSupervisorArtifact()` and `deploySupervisorArtifact()` aliases.
package/docs/MODAL.md CHANGED
@@ -145,7 +145,7 @@ Modal config uses a strict allowlist. Unknown options are rejected rather than s
145
145
 
146
146
  `setTimeout()` is unsupported: choose the lifetime at creation. Foreground command options support only `cwd`, `envs`, `timeoutMs`, `onStdout`, and `onStderr`; do not pass a provider-native `background` option. Use `startDetachedCommand()` instead.
147
147
 
148
- The separate public durable Pi supervisor target remains Daytona-specific. This provider adds generic managed detached commands and HTTP/SSE agents; it does not add a Modal supervisor target or promise memory persistence after termination/snapshot restore.
148
+ This provider adds generic managed detached commands and HTTP/SSE agents; it does not promise memory persistence after termination/snapshot restore.
149
149
 
150
150
  ## Next.js and Live Tests
151
151
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-neckbeard",
3
- "version": "1.1.28",
3
+ "version": "1.1.30",
4
4
  "description": "Deploy AI agents to E2B, Daytona, and Modal sandboxes, or local Docker containers",
5
5
  "type": "module",
6
6
  "exports": {
@@ -14,16 +14,6 @@
14
14
  "default": "./dist/index.cjs"
15
15
  }
16
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
- }
26
- },
27
17
  "./serve": {
28
18
  "import": {
29
19
  "types": "./dist/serve.d.ts",
@@ -43,6 +33,27 @@
43
33
  "types": "./dist/build.d.cts",
44
34
  "default": "./dist/build.cjs"
45
35
  }
36
+ },
37
+ "./archil": {
38
+ "import": {
39
+ "types": "./dist/archil.d.ts",
40
+ "default": "./dist/archil.js"
41
+ }
42
+ },
43
+ "./durable": {
44
+ "import": {
45
+ "types": "./dist/durable.d.ts",
46
+ "default": "./dist/durable.js"
47
+ }
48
+ },
49
+ "./inside": {
50
+ "import": {
51
+ "types": "./dist/inside.d.ts",
52
+ "default": "./dist/inside.js"
53
+ }
54
+ },
55
+ "./pi-watch": {
56
+ "types": "./types/pi-watch.d.cts"
46
57
  }
47
58
  },
48
59
  "bin": {
@@ -55,25 +66,24 @@
55
66
  "files": [
56
67
  "dist",
57
68
  "CHANGELOG.md",
58
- "docs/SUPERVISOR.md",
59
69
  "docs/MODAL.md",
60
70
  "docs/DOCKER.md",
61
71
  "docs/AGENT.md",
62
72
  "docs/DAYTONA.md",
63
73
  "docs/E2B.md",
64
- "docs/LEGACY.md"
74
+ "docs/LEGACY.md",
75
+ "types/pi-watch.d.cts"
65
76
  ],
66
77
  "engines": {
67
78
  "node": ">=20.18.1 <21 || >=22"
68
79
  },
69
80
  "packageManager": "npm@10.9.4",
70
81
  "scripts": {
71
- "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",
82
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && node scripts/generate-runtime-server-source.mjs && tsup && node scripts/build-watch-type.mjs",
72
83
  "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",
73
- "check:generated": "node scripts/verify-runtime-server-source.mjs && node scripts/verify-supervisor-runtime-source.mjs && node scripts/verify-supervisor-package-lock.mjs",
84
+ "check:generated": "node scripts/verify-runtime-server-source.mjs",
74
85
  "dev": "tsup --watch",
75
86
  "format:check": "node scripts/check-format.mjs",
76
- "generate:supervisor-package-lock": "node scripts/generate-supervisor-package-lock.mjs",
77
87
  "lint": "node scripts/repo-lint.mjs",
78
88
  "pack:dry-run": "npm pack --dry-run",
79
89
  "test": "node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.config.mjs",
@@ -84,7 +94,7 @@
84
94
  "test:e2e:modal": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand --testNamePattern=\"live Modal smoke tests\"",
85
95
  "test:e2e:docker": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.e2e.config.mjs --runInBand --testNamePattern=\"live Docker smoke tests\"",
86
96
  "test:compat:next": "npm run build && node scripts/run-next-compat-test.mjs",
87
- "test:cjs": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.build.config.mjs",
97
+ "test:cjs": "npm run build && node --experimental-vm-modules ./node_modules/jest/bin/jest.js --config jest.build.config.mjs && tsc --strict --module Node16 --target ES2022 --types node --noEmit tests/fixtures/node16-consumer.cts && node scripts/test-commonjs-types.mjs",
88
98
  "typecheck": "tsc --noEmit -p tsconfig.test.json",
89
99
  "prepare": "npm run build"
90
100
  },
@@ -98,29 +108,46 @@
98
108
  "skills": "1.8.1"
99
109
  },
100
110
  "peerDependencies": {
101
- "zod": "^3.0.0 || ^4.0.0",
102
- "@earendil-works/pi-coding-agent": ">=1.3.0 <2.0.0",
103
- "braintrust": ">=3.44.0 <4.0.0"
111
+ "@earendil-works/chord": "1.6.0",
112
+ "@earendil-works/pi-ai": "1.6.0",
113
+ "@earendil-works/pi-durable": "1.6.0",
114
+ "braintrust": ">=3.44.0 <4.0.0",
115
+ "disk": "1.13.0",
116
+ "zod": "^3.0.0 || ^4.0.0"
104
117
  },
105
118
  "peerDependenciesMeta": {
106
- "zod": {
119
+ "@earendil-works/chord": {
107
120
  "optional": true
108
121
  },
109
- "@earendil-works/pi-coding-agent": {
122
+ "@earendil-works/pi-ai": {
123
+ "optional": true
124
+ },
125
+ "@earendil-works/pi-durable": {
110
126
  "optional": true
111
127
  },
112
128
  "braintrust": {
113
129
  "optional": true
130
+ },
131
+ "disk": {
132
+ "optional": true
133
+ },
134
+ "zod": {
135
+ "optional": true
114
136
  }
115
137
  },
116
138
  "devDependencies": {
117
- "@earendil-works/pi-coding-agent": "1.5.2",
139
+ "@earendil-works/chord": "1.6.0",
140
+ "@earendil-works/pi-ai": "1.6.0",
141
+ "@earendil-works/pi-durable": "1.6.0",
118
142
  "@grpc/grpc-js": "^1.14.4",
119
143
  "@types/jest": "^30.0.0",
120
144
  "@types/node": "^22.0.0",
121
145
  "braintrust": "3.44.0",
146
+ "disk": "1.13.0",
122
147
  "dotenv": "^17.3.1",
123
148
  "jest": "^30.3.0",
149
+ "rollup": "4.55.3",
150
+ "rollup-plugin-dts": "^6.5.1",
124
151
  "ts-jest": "^29.4.6",
125
152
  "tsup": "^8.3.0",
126
153
  "typescript": "^5.6.0"
@@ -146,5 +173,12 @@
146
173
  },
147
174
  "publishConfig": {
148
175
  "access": "public"
176
+ },
177
+ "typesVersions": {
178
+ "*": {
179
+ "pi-watch": [
180
+ "dist/pi-watch-legacy.d.ts"
181
+ ]
182
+ }
149
183
  }
150
184
  }
@@ -0,0 +1,68 @@
1
+ // @ts-ignore Standalone host installations omit the optional Pi Durable peer.
2
+ import type { ConversationView, WatchCall } from '@earendil-works/pi-durable' with { 'resolution-mode': 'import' };
3
+
4
+ export type PiWatchEvent = WatchCall<ConversationView>;
5
+
6
+ // @ts-ignore Standalone host installations omit the optional Pi Durable peer.
7
+ import type { ConversationAbortOptions, ConversationWindow, ConversationWatch, EntryId, EntryRecord, Submission, SubmissionId } from '@earendil-works/pi-durable' with { 'resolution-mode': 'import' };
8
+ // @ts-ignore Standalone host installations omit the optional Chord peer.
9
+ import type { Context } from '@earendil-works/chord/context' with { 'resolution-mode': 'import' };
10
+
11
+ // @ts-ignore Standalone host installations omit the optional Pi Durable peer.
12
+ import type { Conversation, Harness, HarnessOptions, Storage } from '@earendil-works/pi-durable' with { 'resolution-mode': 'import' };
13
+ // @ts-ignore Standalone host installations omit the optional Pi Durable peer.
14
+ import type { ExecutionEnv } from '@earendil-works/pi-durable/env' with { 'resolution-mode': 'import' };
15
+
16
+ export type { Context };
17
+
18
+ export type RemoteInput = {
19
+ type: 'input';
20
+ content: string;
21
+ requestId: string;
22
+ whenBusy?: 'reject' | 'steer' | 'followUp';
23
+ whenIdle?: 'reject';
24
+ onAbort?: 'withdraw' | 'keep';
25
+ };
26
+ export interface RemoteConversation {
27
+ watch(context: Context, window?: ConversationWindow): Promise<ConversationWatch>;
28
+ waitForIdle(context: Context): Promise<void>;
29
+ abort(context: Context, options?: ConversationAbortOptions): Promise<void>;
30
+ submit(draft: RemoteInput, context: Context): Promise<Submission>;
31
+ submissionByRequest(requestId: string, context: Context): Promise<Submission | undefined>;
32
+ stopSubmission(id: SubmissionId, context: Context): Promise<void>;
33
+ entry(id: EntryId, context: Context): Promise<EntryRecord | undefined>;
34
+ }
35
+
36
+ /** Resources owned by a Pi Durable runtime inside its sandbox. */
37
+ export interface ServedConversation {
38
+ submit(draft: RemoteInput, context: Context): Promise<SubmissionId>;
39
+ watch(context: Context, window?: ConversationWindow): Promise<ConversationWatch>;
40
+ abort(context: Context, options?: ConversationAbortOptions): Promise<void>;
41
+ waitForIdle(context: Context): Promise<void>;
42
+ entry(id: EntryId, context: Context): Promise<EntryRecord | undefined>;
43
+ submissionByRequest(requestId: string, context: Context): Promise<SubmissionId | undefined>;
44
+ submission(id: SubmissionId, context: Context): Promise<Submission | undefined>;
45
+ busy(context: Context): Promise<boolean>;
46
+ stopSubmission(id: SubmissionId, context: Context): Promise<void>;
47
+ close(): Promise<void>;
48
+ }
49
+
50
+ export interface HostSession {
51
+ sessionId: string;
52
+ conversation: Conversation;
53
+ harness: Harness;
54
+ executionEnv: ExecutionEnv;
55
+ storage: Storage;
56
+ close(): Promise<void>;
57
+ }
58
+
59
+ export type HostExecutionFactory = (session: { sessionId: string; storage: Storage }, context: Context) => Promise<{
60
+ executionEnv: ExecutionEnv;
61
+ resolve?: NonNullable<HarnessOptions['env']>;
62
+ }>;
63
+
64
+ export interface HostStartOptions {
65
+ sessionId: string;
66
+ storage: Storage;
67
+ execution: ExecutionEnv | HostExecutionFactory;
68
+ }
@@ -1,21 +0,0 @@
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
- };