@evelandhq/sandbox-bwrap 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -71,20 +71,25 @@ which requires that nothing be left running afterwards, and `stop()`, which auth
71
71
  triggers mid-run through `ctx.getSandbox().stop()`. Backends with provider-side compute
72
72
  distinguish the two — a container to pause, a VM to snapshot; bwrap has no such resource,
73
73
  because the processes are the compute. Neither method touches the session's workspace
74
- directory — it is durable state, and remains available when the session reattaches or the
75
- next callback reopens it.
74
+ directory — it is durable state. Cleanup closes that compute generation to new commands;
75
+ the next backend `create()` opens a fresh generation over the same workspace. Repeated
76
+ `create()` calls through one backend instance share the live generation, so one handle
77
+ cannot race a new spawn past another handle's cleanup barrier.
76
78
 
77
79
  ### Options
78
80
 
79
- | Option | Default | Meaning |
80
- | ------------------ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
81
- | `env` | `{}` | Environment variables set for every sandboxed command. |
82
- | `networkPolicy` | `"allow-all"` | `"allow-all"` shares the host network; `"deny-all"` runs each command with no network (`--unshare-net`). `setNetworkPolicy` can switch between the two at run time; granular domain policies are rejected (use the Vercel backend for those). |
83
- | `hidePaths` | `[]` | Extra host paths hidden from the sandbox (each covered by an empty tmpfs). |
84
- | `bwrapPath` | `"bwrap"` | bwrap executable to invoke. |
85
- | `cacheDir` | `<appRoot>/.eve/sandbox-cache/bwrap` | Absolute directory holding templates and durable session workspaces. Pin this outside the release directory so a redeploy does not discard durable session state: since eve 0.22.0, eve keys session sandboxes per durable session, not per deployment, so an `appRoot`-derived default would silently destroy every session's `/workspace` on the next redeploy. The generated eveland module always sets this from `EVELAND_SANDBOX_CACHE_DIR`. |
86
- | `templateRevision` | `null` | Optional immutable release identity included in the template cache key but not the session path. Change it when seed files change so new Sessions use a fresh template without overwriting durable workspaces. Eveland sets it from its internal `EVELAND_SANDBOX_TEMPLATE_REVISION`. |
87
- | `runTimeoutMs` | `600000` | Hard wall-clock limit for one `run()` command. Timeout aborts the command and kills its complete bwrap process group. Set `null` to disable it. The limit deliberately does not apply to `spawn()`, which is the API for long-running processes. |
81
+ | Option | Default | Meaning |
82
+ | ------------------------ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
83
+ | `env` | `{}` | Environment variables set for every sandboxed command. |
84
+ | `networkPolicy` | `"allow-all"` | `"allow-all"` shares the host network; `"deny-all"` runs each command with no network (`--unshare-net`). `setNetworkPolicy` can switch between the two at run time; granular domain policies are rejected (use the Vercel backend for those). |
85
+ | `hidePaths` | `[]` | Extra host paths hidden from the sandbox (each covered by an empty tmpfs). |
86
+ | `bwrapPath` | `"bwrap"` | bwrap executable to invoke. |
87
+ | `cacheDir` | `<appRoot>/.eve/sandbox-cache/bwrap` | Absolute directory holding templates and durable session workspaces. Pin this outside the release directory so a redeploy does not discard durable session state: since eve 0.22.0, eve keys session sandboxes per durable session, not per deployment, so an `appRoot`-derived default would silently destroy every session's `/workspace` on the next redeploy. The generated eveland module always sets this from `EVELAND_SANDBOX_CACHE_DIR`. |
88
+ | `templateRevision` | `null` | Optional immutable release identity included in the template cache key but not the session path. Change it when seed files change so new Sessions use a fresh template without overwriting durable workspaces. Eveland sets it from its internal `EVELAND_SANDBOX_TEMPLATE_REVISION`. |
89
+ | `runTimeoutMs` | `600000` | Hard wall-clock limit for one `run()` command. Timeout aborts the command and kills its complete bwrap process group. Set `null` to disable it. The limit deliberately does not apply to `spawn()`, which is the API for long-running processes. |
90
+ | `maxConcurrentProcesses` | `64` | Maximum live `run()`/`spawn()` commands admitted in one compute generation. A live `spawn()` counts until it actually exits, even when its caller never waits. Set `null` to disable. |
91
+ | `maxOutputBytes` | `16777216` | Maximum combined stdout and stderr retained by one `run()` call. Exceeding it aborts and reaps the complete process group. Set `null` to disable. Streaming `spawn()` output is not retained by this backend. |
92
+ | `onEvent` | `undefined` | Best-effort structured lifecycle sink for generation, command, and cleanup events. Sink failures are ignored so telemetry cannot change command behavior. |
88
93
 
89
94
  Both lifecycle callbacks may call `use({ networkPolicy: "allow-all" | "deny-all" })`. The
90
95
  policy is applied before `use()` returns the template or live Session, so subsequent commands in
@@ -100,34 +105,72 @@ backend's configured policy.
100
105
  `<cacheDir>/templates/<hash>` (`<cacheDir>` defaults to
101
106
  `<appRoot>/.eve/sandbox-cache/bwrap` when the `cacheDir` option is not set). Idempotent
102
107
  per template key + options hash; `templateRevision` participates in that hash.
103
- - **create** (runtime): clones the template into `<cacheDir>/sessions/<hash>` on first
104
- use. The directory IS the durable session state: it persists across reconnects and
105
- process restarts.
108
+ - **create** (runtime): atomically clones the template into
109
+ `<cacheDir>/sessions/<hash>` on first use. It first requests a filesystem reflink
110
+ (copy-on-write); filesystems without reflink support fall back to a normal recursive
111
+ copy. The selected strategy is recorded in cache metadata. The directory IS the durable
112
+ session state: it persists across reconnects and process restarts.
106
113
  - **run/spawn**: every command is one transient bwrap invocation —
107
114
  read-only host rootfs, the session directory bound read-write at `/workspace`,
108
115
  tmpfs `/tmp`, PID/IPC/UTS namespaces unshared, `--die-with-parent`.
109
- `run()` also applies `runTimeoutMs` and kills the entire detached process group
110
- when the deadline or caller AbortSignal fires; `spawn()` remains unbounded until
111
- its holder calls `kill()`, the Session is stopped, or the backend shuts down.
116
+ `run()` also applies `runTimeoutMs` and `maxOutputBytes`, and kills the entire
117
+ detached process group when a boundary or caller AbortSignal fires. Both APIs count
118
+ against `maxConcurrentProcesses`; `spawn()` remains long-running until its holder
119
+ calls `kill()`, the compute generation is stopped, or the backend shuts down.
112
120
  - **File I/O** (`readTextFile`, `writeFile`, …): host-side operations on the session
113
121
  directory; no subprocess. Writes outside `/workspace` are refused.
114
122
 
115
123
  ## Disk usage and cache management
116
124
 
117
- Session and template directories persist indefinitely under
118
- `<cacheDir>/{sessions,templates}` across process restarts and reconnects, enabling fast
119
- reattach when a session resumes. Each session key gets a directory that is reused for
120
- the lifetime of the session; each template is cached per (template key, options hash), with
121
- an optional release revision in the options hash,
122
- and reused across sessions. This backend intentionally does not prune either — its
123
- `stop()` and `shutdown()` methods only kill the session's live processes and leave the
124
- workspace on disk, so reattach is instant and stateless from the agent's perspective. On a long-lived
125
- host, this means the cache will grow with the number of durable sessions and unique
126
- templates, consuming disk space indefinitely. On eveland deployments this cache lives at
127
- `EVELAND_SANDBOX_CACHE_DIR` (one subdirectory per project), outside every release
128
- directory, precisely so that redeploying a project does not touch it.
129
-
130
- Reclaiming space today requires manual intervention: identify which sessions are known dead and delete their corresponding directories under the cache root. Automatic cache pruning (e.g., based on age or LRU) is a known gap and a planned follow-up.
125
+ Session and template directories persist under `<cacheDir>/{sessions,templates}` across
126
+ process restarts and reconnects, enabling fast reattach. `stop()` and `shutdown()` never
127
+ delete durable state, and this package never schedules automatic deletion. On Eveland,
128
+ the cache lives at `EVELAND_SANDBOX_CACHE_DIR` outside every release directory, so a
129
+ redeploy does not touch it.
130
+
131
+ Operator metadata lives separately under `<cacheDir>/metadata`; sandboxed code cannot
132
+ rewrite its own retention timestamps, tags, clone strategy, or active-generation leases.
133
+ Use the explicit APIs to inspect and reclaim storage:
134
+
135
+ ```ts
136
+ import { listBwrapCache, pruneBwrapCache } from "@evelandhq/sandbox-bwrap";
137
+
138
+ const location = { appRoot: "/srv/my-agent", cacheDir: "/var/lib/eveland/sandbox/project" };
139
+ const entries = await listBwrapCache(location);
140
+
141
+ // Dry-run is the default. Age and LRU policies may be combined independently
142
+ // for durable sessions and templates.
143
+ const preview = await pruneBwrapCache({
144
+ ...location,
145
+ sessions: { maxAgeMs: 30 * 24 * 60 * 60 * 1000 },
146
+ templates: { maxEntries: 10 },
147
+ });
148
+
149
+ // Apply only after inspecting preview.candidates and preview.skippedActive.
150
+ const applied = await pruneBwrapCache({
151
+ ...location,
152
+ sessions: { maxAgeMs: 30 * 24 * 60 * 60 * 1000 },
153
+ templates: { maxEntries: 10 },
154
+ dryRun: false,
155
+ });
156
+ ```
157
+
158
+ Active compute generations are skipped and rechecked immediately before deletion. The
159
+ backend uses both process-local reference counts and lease files outside the writable
160
+ workspace, so a separate pruning process can see active sessions. A process crash can
161
+ leave a conservative stale lease; inspect `listBwrapCacheLeases(location)` and confirm
162
+ the owning deployment is stopped before removing such a lease. Leases are not expired
163
+ automatically because deleting a live durable workspace is worse than retaining a false
164
+ positive.
165
+
166
+ ## Lifecycle observability
167
+
168
+ `onEvent` receives discriminated `generation.started`, `command.started`,
169
+ `command.finished`, `cleanup.started`, `cleanup.completed`, and `cleanup.failed` events.
170
+ They include session/generation/command identities, tags, PID/process-group identity when
171
+ available, duration, output byte counts, live-process counts, finish reason, and cleanup
172
+ errors. Events deliberately omit command text and output. Do not put secrets in `tags`;
173
+ the sink is operator-controlled telemetry, not part of the sandbox boundary.
131
174
 
132
175
  ## Security boundary
133
176
 
@@ -158,8 +201,9 @@ Reclaiming space today requires manual intervention: identify which sessions are
158
201
  container's filesystem, not the Docker host; no host root or Docker socket is mounted.
159
202
  - CPU, memory, and PID limits are inherited from whatever cgroup the agent runs in
160
203
  (on eveland, the deployment's Docker container or systemd unit covers sandbox
161
- children too). The backend adds only the `run()` wall-clock deadline; it does not
162
- create a per-command cgroup or impose resource quotas on `spawn()`.
204
+ children too). `maxConcurrentProcesses` is an admission bound, not a kernel PID or
205
+ thread quota; `runTimeoutMs` and `maxOutputBytes` bound one `run()`. The backend does
206
+ not create a per-command cgroup or impose CPU/memory quotas on `spawn()`.
163
207
  - Host-side write/remove calls (`writeFile`, `writeTextFile`, `writeBinaryFile`,
164
208
  `removePath`) verify containment with a realpath-aware check
165
209
  (`isWithinWorkspaceReal`): they resolve symlinks along the path and re-check that
@@ -184,8 +228,11 @@ Reclaiming space today requires manual intervention: identify which sessions are
184
228
  Eveland's generated local Docker image installs `bubblewrap` and `bash`, creates
185
229
  `/workspace`, and starts the outer Agent container with its default capability set
186
230
  dropped, `SYS_ADMIN` and `NET_ADMIN` added for bwrap namespaces, `no-new-privileges`,
187
- and `seccomp=unconfined`. This is a local-development boundary; the supported Linux
188
- production topology uses the unprivileged systemd path below.
231
+ `seccomp=unconfined`, and Docker `--init`. The init process is required to reap orphaned
232
+ bwrap descendants; without it they can accumulate as zombies until the container PID
233
+ limit is exhausted. Containers created before enabling it must be recreated. This is a
234
+ local-development boundary; the supported Linux production topology uses the
235
+ unprivileged systemd path below, where host PID 1 already reaps orphans.
189
236
 
190
237
  - Linux with unprivileged user namespaces available to the calling process. Ubuntu's
191
238
  packaged bubblewrap (0.9.0-1ubuntu0.1 on 24.04) ships **no** AppArmor profile. Since
@@ -225,7 +272,9 @@ production topology uses the unprivileged systemd path below.
225
272
  - Works under systemd hardening (`NoNewPrivileges=yes`, `ProtectSystem=strict`):
226
273
  apt's `bwrap` is not setuid, so it needs no privilege escalation to run — but it
227
274
  still needs the AppArmor profile above to create a user namespace as an
228
- unprivileged user.
275
+ unprivileged user. There is no Docker-style `--init` setting to add to a systemd
276
+ Deployment; systemd already provides the host init/subreaper and `TasksMax` cgroup
277
+ boundary.
229
278
 
230
279
  ## Testing
231
280
 
@@ -236,7 +285,8 @@ production topology uses the unprivileged systemd path below.
236
285
  It provisions a Lima VM (`brew install lima`), streams this worktree in, and runs the
237
286
  test as an unprivileged user under the systemd hardening a deployed eve agent actually
238
287
  gets — `NoNewPrivileges=yes`, `ProtectSystem=strict`, `PrivateTmp=yes`. Prints
239
- `BWRAP SMOKE OK`. Run this before pushing anything that touches `src/args.ts` or
288
+ `BWRAP SMOKE OK`. The test also churns 500 short bwrap commands and checks that the
289
+ zombie count returns to baseline. Run this before pushing anything that touches `src/args.ts` or
240
290
  `src/process.ts`: CI's smoke job covers the unprivileged-user case but not the systemd
241
291
  constraints, and argv that looks right is not the same as a kernel that accepts it.
242
292
  - `pnpm tsx src/integration/bwrap-backend-smoke.ts` — the same test, run directly. Needs
package/dist/backend.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { SandboxBackend } from "eve/sandbox";
2
2
  import type { BwrapSandboxCreateOptions, BwrapSandboxUseOptions } from "./options.js";
3
3
  import type { ProcessRunner } from "./process.js";
4
+ import { type BwrapDirectoryCopier } from "./cache.js";
4
5
  /**
5
6
  * Stable backend name. Participates in eve's template/session cache-key
6
7
  * derivation and persisted reconnect state — never change it.
@@ -10,5 +11,7 @@ export interface CreateBwrapSandboxBackendInput {
10
11
  readonly createOptions?: BwrapSandboxCreateOptions;
11
12
  /** Injectable process launcher so backend logic is testable without bwrap. */
12
13
  readonly runner?: ProcessRunner;
14
+ /** Injectable clone primitive for filesystem-capability tests. */
15
+ readonly copyDirectory?: BwrapDirectoryCopier;
13
16
  }
14
17
  export declare function createBwrapSandboxBackend(input?: CreateBwrapSandboxBackendInput): SandboxBackend<BwrapSandboxUseOptions, BwrapSandboxUseOptions>;
package/dist/backend.js CHANGED
@@ -1,37 +1,24 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { existsSync } from "node:fs";
3
- import { cp, mkdir, rename, rm } from "node:fs/promises";
4
- import { dirname } from "node:path";
3
+ import { mkdir, rename, rm } from "node:fs/promises";
4
+ import { basename } from "node:path";
5
5
  import { SandboxTemplateNotProvisionedError } from "eve/sandbox";
6
6
  import { createBwrapOptionsHash, resolveBwrapSandboxOptions } from "./options.js";
7
- import { resolveSessionPath, resolveTemplatePath, WORKSPACE_ROOT } from "./paths.js";
7
+ import { resolveBwrapCacheRoot, resolveSessionPath, resolveTemplatePath, WORKSPACE_ROOT, } from "./paths.js";
8
8
  import { createNodeProcessRunner, describeMissingPrereqs, isBwrapAvailable } from "./process.js";
9
9
  import { createBwrapSession } from "./session.js";
10
+ import { cloneDirectoryAtomically, createBwrapCacheLease, registerActiveCachePath, removeCacheMetadata, touchCacheMetadata, } from "./cache.js";
10
11
  const EVE_MODEL_SKILL_ROOT = "$HOME/.agents/skills";
11
12
  /**
12
13
  * Stable backend name. Participates in eve's template/session cache-key
13
14
  * derivation and persisted reconnect state — never change it.
14
15
  */
15
16
  export const BWRAP_BACKEND_NAME = "bwrap";
16
- async function copyDirectoryAtomically(sourcePath, targetPath) {
17
- const tmpPath = `${targetPath}.${randomUUID()}.tmp`;
18
- await mkdir(dirname(targetPath), { recursive: true });
19
- try {
20
- await cp(sourcePath, tmpPath, { recursive: true });
21
- await rename(tmpPath, targetPath);
22
- }
23
- catch (error) {
24
- await rm(tmpPath, { force: true, recursive: true }).catch(() => { });
25
- // A concurrent writer winning the rename race is success, not failure.
26
- if (existsSync(targetPath))
27
- return;
28
- throw error;
29
- }
30
- }
31
17
  export function createBwrapSandboxBackend(input = {}) {
32
18
  const options = resolveBwrapSandboxOptions(input.createOptions);
33
19
  const optionsHash = createBwrapOptionsHash(options);
34
20
  const runner = input.runner ?? createNodeProcessRunner();
21
+ const generations = new Map();
35
22
  // Probe only when running against the real bwrap; injected runners skip it.
36
23
  const shouldProbe = input.runner === undefined;
37
24
  let probed = false;
@@ -47,8 +34,42 @@ export function createBwrapSandboxBackend(input = {}) {
47
34
  throw new Error(missing);
48
35
  probed = true;
49
36
  }
50
- function openSession(id, workspaceDir, appRoot) {
51
- return createBwrapSession({ id, workspaceDir, appRoot, runner, options });
37
+ function openSession(id, workspaceDir, appRoot, tags, generationId, onStopped) {
38
+ return createBwrapSession({
39
+ id,
40
+ workspaceDir,
41
+ appRoot,
42
+ runner,
43
+ options,
44
+ tags,
45
+ generationId,
46
+ onStopped,
47
+ });
48
+ }
49
+ async function openRuntimeSession(id, workspaceDir, appRoot, tags) {
50
+ const current = generations.get(workspaceDir);
51
+ if (current && current.lifecycleState() !== "stopped")
52
+ return current;
53
+ const releaseActive = registerActiveCachePath(workspaceDir);
54
+ const cacheRoot = resolveBwrapCacheRoot(appRoot, options.cacheDir);
55
+ const activeLease = await createBwrapCacheLease({
56
+ cacheRoot,
57
+ sessionId: basename(workspaceDir),
58
+ });
59
+ let session;
60
+ try {
61
+ session = openSession(id, workspaceDir, appRoot, tags, activeLease.lease.generationId, async () => {
62
+ releaseActive();
63
+ await activeLease.release();
64
+ });
65
+ }
66
+ catch (error) {
67
+ releaseActive();
68
+ await activeLease.release();
69
+ throw error;
70
+ }
71
+ generations.set(workspaceDir, session);
72
+ return session;
52
73
  }
53
74
  function resolveSeedPath(seedPath) {
54
75
  if (seedPath === EVE_MODEL_SKILL_ROOT || seedPath.startsWith(`${EVE_MODEL_SKILL_ROOT}/`)) {
@@ -78,8 +99,16 @@ export function createBwrapSandboxBackend(input = {}) {
78
99
  async prewarm({ templateKey, bootstrap, seedFiles, log, runtimeContext }) {
79
100
  assertBwrapAvailable();
80
101
  const templatePath = resolveTemplatePath(runtimeContext.appRoot, templateKey, optionsHash, options.cacheDir);
81
- if (existsSync(templatePath))
102
+ const touchTemplate = async () => await touchCacheMetadata({
103
+ cacheRoot: resolveBwrapCacheRoot(runtimeContext.appRoot, options.cacheDir),
104
+ kind: "template",
105
+ id: basename(templatePath),
106
+ templateRevision: options.templateRevision,
107
+ });
108
+ if (existsSync(templatePath)) {
109
+ await touchTemplate();
82
110
  return { reused: true };
111
+ }
83
112
  log?.(`bwrap: capturing template for ${templateKey}`);
84
113
  const stagingPath = `${templatePath}.staging-${randomUUID()}`;
85
114
  await mkdir(stagingPath, { recursive: true });
@@ -94,18 +123,23 @@ export function createBwrapSandboxBackend(input = {}) {
94
123
  catch (error) {
95
124
  await rm(stagingPath, { force: true, recursive: true }).catch(() => { });
96
125
  // A concurrent prewarm winning the race is reuse, not failure.
97
- if (existsSync(templatePath))
126
+ if (existsSync(templatePath)) {
127
+ await touchTemplate();
98
128
  return { reused: true };
129
+ }
99
130
  throw error;
100
131
  }
132
+ await touchTemplate();
101
133
  return { reused: false };
102
134
  },
103
- async create({ templateKey, sessionKey, runtimeContext }) {
135
+ async create({ templateKey, sessionKey, runtimeContext, tags }) {
104
136
  assertBwrapAvailable();
105
137
  const sessionPath = resolveSessionPath(runtimeContext.appRoot, sessionKey, options.cacheDir);
138
+ let cloneStrategy = "existing";
106
139
  if (!existsSync(sessionPath)) {
107
140
  if (templateKey === null) {
108
141
  await mkdir(sessionPath, { recursive: true });
142
+ cloneStrategy = "empty";
109
143
  }
110
144
  else {
111
145
  const templatePath = resolveTemplatePath(runtimeContext.appRoot, templateKey, optionsHash, options.cacheDir);
@@ -115,10 +149,21 @@ export function createBwrapSandboxBackend(input = {}) {
115
149
  templateKey,
116
150
  });
117
151
  }
118
- await copyDirectoryAtomically(templatePath, sessionPath);
152
+ cloneStrategy = await cloneDirectoryAtomically({
153
+ sourcePath: templatePath,
154
+ targetPath: sessionPath,
155
+ copyDirectory: input.copyDirectory,
156
+ });
119
157
  }
120
158
  }
121
- const session = openSession(sessionKey, sessionPath, runtimeContext.appRoot);
159
+ await touchCacheMetadata({
160
+ cacheRoot: resolveBwrapCacheRoot(runtimeContext.appRoot, options.cacheDir),
161
+ kind: "session",
162
+ id: basename(sessionPath),
163
+ tags,
164
+ cloneStrategy,
165
+ });
166
+ const session = await openRuntimeSession(sessionKey, sessionPath, runtimeContext.appRoot, tags);
122
167
  return {
123
168
  session,
124
169
  useSessionFn: async (useOptions) => await useSession(session, useOptions),
@@ -141,6 +186,23 @@ export function createBwrapSandboxBackend(input = {}) {
141
186
  async shutdown() {
142
187
  await session.killAll();
143
188
  },
189
+ // eve (>=0.47) calls this when authored code runs
190
+ // `ctx.getSandbox().delete()`: the sandbox and its disposable state are
191
+ // gone for good, and the next access reprovisions from the template.
192
+ // For bwrap the disposable state is the session workspace directory and
193
+ // its metadata sidecar; the template it was cloned from is shared and
194
+ // must survive.
195
+ async delete(deleteOptions) {
196
+ deleteOptions?.abortSignal?.throwIfAborted();
197
+ await session.killAll();
198
+ generations.delete(sessionPath);
199
+ await rm(sessionPath, { force: true, recursive: true });
200
+ await removeCacheMetadata({
201
+ cacheRoot: resolveBwrapCacheRoot(runtimeContext.appRoot, options.cacheDir),
202
+ kind: "session",
203
+ id: basename(sessionPath),
204
+ });
205
+ },
144
206
  };
145
207
  },
146
208
  };
@@ -0,0 +1,85 @@
1
+ export type BwrapCacheEntryKind = "session" | "template";
2
+ export type BwrapCloneStrategy = "empty" | "reflink" | "copy" | "existing";
3
+ export interface BwrapCacheMetadata {
4
+ readonly schemaVersion: 1;
5
+ readonly kind: BwrapCacheEntryKind;
6
+ readonly id: string;
7
+ readonly createdAt: string;
8
+ readonly lastUsedAt: string;
9
+ readonly tags?: Readonly<Record<string, string>>;
10
+ readonly cloneStrategy?: BwrapCloneStrategy;
11
+ readonly templateRevision?: string;
12
+ }
13
+ export interface BwrapCacheEntry extends BwrapCacheMetadata {
14
+ readonly path: string;
15
+ readonly sizeBytes: number;
16
+ readonly active: boolean;
17
+ readonly metadataPresent: boolean;
18
+ }
19
+ export interface BwrapCacheLocation {
20
+ readonly appRoot: string;
21
+ readonly cacheDir?: string | null;
22
+ }
23
+ export interface BwrapCachePrunePolicy {
24
+ readonly maxAgeMs?: number;
25
+ readonly maxEntries?: number;
26
+ }
27
+ export interface BwrapCachePruneInput extends BwrapCacheLocation {
28
+ readonly dryRun?: boolean;
29
+ readonly sessions?: BwrapCachePrunePolicy;
30
+ readonly templates?: BwrapCachePrunePolicy;
31
+ readonly now?: Date;
32
+ }
33
+ export interface BwrapCachePruneResult {
34
+ readonly dryRun: boolean;
35
+ readonly candidates: readonly BwrapCacheEntry[];
36
+ readonly removed: readonly BwrapCacheEntry[];
37
+ readonly skippedActive: readonly BwrapCacheEntry[];
38
+ readonly retained: readonly BwrapCacheEntry[];
39
+ }
40
+ export interface BwrapCacheLease {
41
+ readonly sessionId: string;
42
+ readonly generationId: string;
43
+ readonly pid: number;
44
+ readonly createdAt: string;
45
+ readonly path: string;
46
+ }
47
+ export declare function registerActiveCachePath(path: string): () => void;
48
+ export declare function createBwrapCacheLease(input: {
49
+ cacheRoot: string;
50
+ sessionId: string;
51
+ }): Promise<{
52
+ lease: BwrapCacheLease;
53
+ release(): Promise<void>;
54
+ }>;
55
+ export declare function listBwrapCacheLeases(input: BwrapCacheLocation): Promise<BwrapCacheLease[]>;
56
+ export declare function listBwrapCache(input: BwrapCacheLocation): Promise<BwrapCacheEntry[]>;
57
+ export declare function pruneBwrapCache(input: BwrapCachePruneInput): Promise<BwrapCachePruneResult>;
58
+ export type BwrapDirectoryCopier = (source: string, target: string, options: {
59
+ recursive: true;
60
+ mode?: number;
61
+ }) => Promise<void>;
62
+ export declare function cloneDirectoryAtomically(input: {
63
+ sourcePath: string;
64
+ targetPath: string;
65
+ copyDirectory?: BwrapDirectoryCopier;
66
+ }): Promise<BwrapCloneStrategy>;
67
+ export declare function touchCacheMetadata(input: {
68
+ cacheRoot: string;
69
+ kind: BwrapCacheEntryKind;
70
+ id: string;
71
+ tags?: Readonly<Record<string, string>>;
72
+ cloneStrategy?: BwrapCloneStrategy;
73
+ templateRevision?: string | null;
74
+ now?: Date;
75
+ }): Promise<BwrapCacheMetadata>;
76
+ /**
77
+ * Removes one cache entry's metadata sidecar. Deleting a session removes its
78
+ * workspace directory too, and a metadata file without a directory would read
79
+ * as an orphan to `pruneBwrapCache` — remove both together.
80
+ */
81
+ export declare function removeCacheMetadata(input: {
82
+ cacheRoot: string;
83
+ kind: BwrapCacheEntryKind;
84
+ id: string;
85
+ }): Promise<void>;