alineo 0.6.0 → 0.7.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/dist/index.d.mts CHANGED
@@ -1,277 +1,15 @@
1
+ import { AgentSpec, AgentSpec as AgentSpec$1, PermissionAction, PermissionMode, PermissionPolicy, PermissionRule, ProjectConfig, SetupStep } from "@alineo-labs/schema";
1
2
  import { CredentialBinding, CredentialSource, ExecOptions, ExecResult, IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
2
3
  import { z } from "zod";
3
4
  import { Memory, ResourceRef } from "@alineo-labs/memory";
4
5
  //#endregion
5
- //#region src/permissions.d.ts
6
- /**
7
- * Human-in-the-loop tool-call policy — the host-side half.
8
- *
9
- * `AgentSpec.permissions` (a mode string or a full policy) is normalized here into a
10
- * `NormalizedPermissionPolicy`, written into the sandbox at `/etc/alineo-pi.json`, and read
11
- * by the bundled Pi gate extension (`adapters/pi-permission-gate.js`), which re-implements
12
- * the tiny matcher below inline (same duplication tradeoff `pi-bridge.js` already makes —
13
- * the gate can't import from a published package it runs beside via jiti). Keep the two
14
- * matchers in sync; `test/permissions.test.ts` covers this one.
15
- */
16
- /**
17
- * Shorthand for the common cases:
18
- * - `"auto"` — never ask (the default; identical to not setting `permissions` at all)
19
- * - `"ask"` — ask before every tool call
20
- * - `"readonly"` — auto-allow the read-only tools (`read`/`grep`/`find`/`ls`), ask before
21
- * `write`/`edit`/`bash`/`powershell`. Pi has no network tool — an agent reaches the
22
- * network through `bash`, so `"readonly"` gates that by gating `bash`, not as a category.
23
- */
24
- type PermissionMode = "auto" | "ask" | "readonly";
25
- /**
26
- * What happens when a rule (or the policy default) matches a tool call:
27
- * - `allow` — run it, no prompt
28
- * - `ask` — pause, surface a `permission_request`, wait for a human decision
29
- * - `deny` — refuse, with a reason the model reads and can adjust to
30
- * - `rate_limit` — allow up to `limit.count` matching calls per `limit.windowMs`, then deny
31
- * - `classify` — best-effort read-vs-write triage of the call (today: `bash`/`powershell`
32
- * only, splitting on `&&`/`||`/`;`/`|`/newline and checking each sub-command against a
33
- * built-in safe-reader list). All sub-commands look read-only → `allow`; anything
34
- * unrecognised or a redirect/`sudo`/`rm` → falls through to `ask`. For any other tool,
35
- * `classify` is treated as `ask`.
36
- */
37
- type PermissionAction = "allow" | "ask" | "deny" | "rate_limit" | "classify";
38
- interface PermissionRule {
39
- /** Tool name or glob (`*` = any run of chars, `?` = one), e.g. `"bash"`, `"write"`, `"*"`. */
40
- tool: string;
41
- /**
42
- * Glob matched against a tool-specific target string, extracted from Pi's typed
43
- * `event.input` — the command for `bash`, the path for `read`/`write`/`edit`, the query
44
- * for `grep`. Anchored: `"git *"` matches `"git status"` but not `"x && git status"` —
45
- * use `"*git*"` for a substring match. Omit to match any call to `tool`.
46
- */
47
- pattern?: string;
48
- action: PermissionAction;
49
- /** `rate_limit` only: the ceiling and rolling window. */
50
- limit?: {
51
- count: number;
52
- windowMs: number;
53
- };
54
- }
55
- interface PermissionPolicy {
56
- /** Action when no rule matches. Default `"ask"`. */
57
- default?: PermissionAction;
58
- /** Evaluated in order; the **last** matching rule wins (opencode semantics). */
59
- rules?: PermissionRule[];
60
- /**
61
- * Tools the agent may never call. The gate strips these from the model's tool list at
62
- * session start (via Pi's `setActiveTools`) so the model never attempts them, and also
63
- * keeps an unconditional `deny` as a backstop for any tool registered after startup
64
- * (SDK / MCP tools).
65
- */
66
- disabledTools?: string[];
67
- /**
68
- * If set, the ONLY tools the model may see — the gate calls Pi's `setActiveTools` with
69
- * this list at session start. `"readonly"` mode expands to this (the read-only tools).
70
- * Distinct from `disabledTools` (a denylist); this is an allowlist for the toolset.
71
- */
72
- restrictToTools?: string[];
73
- }
74
- /**
75
- * Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
76
- * recognised pure reader with no output redirection; `false` = something needs a human.
77
- * Mirrored verbatim in `adapters/pi-permission-gate.js`.
78
- */
79
- export declare function isReadOnlyBashCommand(command: string): boolean;
80
- //#endregion
81
6
  //#region src/schema.d.ts
82
- /**
83
- * Opt-in alternative to a plain `AgentSpec.env` string value — instead of interpolating
84
- * straight into the container's environment, `credential` is registered with the sandbox's
85
- * `CredentialBroker` via `sb.credentials.set()` and injected transparently into outbound
86
- * requests to `host`. The sandbox process never sees the resolved value at all. Requires the
87
- * agent's sandbox to be created with `credentialProxy: true` — `Alineo.load()`/`.resume()`/
88
- * `.spawn()` set this automatically whenever `env` contains at least one binding like this.
89
- */
90
- interface CredentialEnvBinding {
91
- /** Host env var reference to resolve the real value from, e.g. `"${OPENAI_API_KEY}"`. */
92
- credential: string;
93
- /** FQDN or wildcard domain this credential is injected for. */
94
- host: string;
95
- /** Narrows the binding to requests whose path starts with this prefix. */
96
- pathPrefix?: string;
97
- /**
98
- * How the credential reaches the request. `header` adds `name: <value>`. `substitution`
99
- * replaces every literal `placeholder` in the listed request surfaces with the value — the
100
- * request must already contain `placeholder` verbatim (put it in a base URL, say). Mirrors
101
- * `@alineo-labs/core`'s `CredentialInjection`; `packages/agent/test/schema.test.ts` is the
102
- * drift check.
103
- */
104
- injection: {
105
- type: "header";
106
- name: string;
107
- } | {
108
- type: "substitution";
109
- placeholder: string;
110
- in: Array<"path" | "query" | "header" | "body">;
111
- };
112
- /**
113
- * `"hold"` gates outbound egress to `host` behind a human decision: the agent's sandbox
114
- * starts with `host` denied at the egress sidecar, the first request to it pauses and
115
- * raises an approval request, and the host is allowed only once someone approves. Requires
116
- * an `onEgressRequest` handler on `Alineo.load()`. Omit for the default (the host is
117
- * reachable as soon as the credential is bound).
118
- */
119
- approval?: "hold";
120
- }
121
- /**
122
- * A single named setup step run inside the sandbox after Pi CLI install,
123
- * before the snapshot is taken. The step is a bash shell command.
124
- */
125
- interface SetupStep {
126
- /** Human-readable label shown in logs and included in the setup hash. */
127
- name: string;
128
- /** Shell command to run (bash). */
129
- run: string;
130
- /** If set, the command runs as `cd <cwd> && <run>`. */
131
- cwd?: string;
132
- }
133
- /**
134
- * JSON spec for an agent — typically loaded from an `agent.json` file on disk.
135
- * Pass it to `Alineo.load(spec)` — read it from disk yourself first (e.g.
136
- * `await Bun.file(path).json()`) if it's not already an in-memory object.
137
- *
138
- * Environment variable references in `env` values are interpolated from
139
- * `process.env` at load time: `"${MY_API_KEY}"` → `process.env.MY_API_KEY`.
140
- */
141
- interface AgentSpec {
142
- $schema?: string;
143
- /** Unique identifier for this agent. Used as the sandbox session name. */
144
- name: string;
145
- /** Human-readable display name. */
146
- title?: string;
147
- description?: string;
148
- author?: string;
149
- categories?: string[];
150
- /** CLI to run inside the sandbox. Currently only `"pi"` is supported. */
151
- cli: "pi";
152
- /**
153
- * npm version specifier for the Pi CLI, e.g. `"1.2.3"`, `"^1.2.0"`, or a
154
- * dist-tag like `"latest"`. Passed directly to
155
- * `npm install -g @earendil-works/pi-coding-agent@<cliVersion>`. When
156
- * omitted, `install()` runs the bare package name and npm resolves
157
- * whatever it considers latest. Included in the setup-hash cache key, so
158
- * changing it forces a fresh snapshot rebuild.
159
- */
160
- cliVersion?: string;
161
- /**
162
- * AI provider passed to the CLI via `--provider`. For Pi with a direct Google
163
- * API key, omit this (Pi defaults to the Google Generative AI endpoint).
164
- */
165
- provider?: string;
166
- /**
167
- * Model ID passed to the CLI via `--model`.
168
- * For Pi 0.80.x with a free Google AI Studio key, use `"gemini-flash-latest"`
169
- * (Pi's alias for gemini-3.5-flash via the direct Google Generative AI API).
170
- */
171
- model?: string;
172
- /**
173
- * APT packages to install in the sandbox before starting the CLI.
174
- * Example: `["python3", "git"]`. `nodejs_22` and `nodejs` are silently ignored
175
- * since the base image is `node:22`.
176
- */
177
- packages?: string[];
178
- /**
179
- * Environment variables available inside the sandbox.
180
- * Values may reference host env vars: `{ GEMINI_API_KEY: "${GEMINI_API_KEY}" }`.
181
- *
182
- * A value can instead be a `CredentialEnvBinding` to opt that one key out of plain env-var
183
- * interpolation entirely — the key never becomes a container env var; its value is injected
184
- * transparently into matching outbound requests instead. See `CredentialEnvBinding`.
185
- */
186
- env?: Record<string, string | CredentialEnvBinding>;
187
- /**
188
- * CPU/memory/GPU resource limits for the sandbox container.
189
- * Falls back to defaults in `alineo.config.json` if omitted.
190
- */
191
- resources?: {
192
- cpu: string;
193
- memory: string;
194
- gpu?: string;
195
- };
196
- /** Not read anywhere in `alineo`; has no effect on the sandbox. */
197
- metadata?: Record<string, string>;
198
- /**
199
- * Not read by `alineo` itself — used by `alineo add`, which fetches
200
- * and saves each dependency spec first, depth-first.
201
- */
202
- registryDependencies?: string[];
203
- /**
204
- * Setup steps run inside the sandbox after Pi CLI install, before the snapshot.
205
- * Baked into the snapshot — any change to a step invalidates the cache automatically.
206
- * Example: create directories, write seed files, install project dependencies.
207
- */
208
- setup?: SetupStep[];
209
- /**
210
- * Remaining budget for `Alineo.spawn()` calls made from inside this agent's sandbox.
211
- * Translated by `Alineo.load()`/`Alineo.resume()` into the `ALINEO_SPAWN_DEPTH` env var.
212
- * `Alineo.spawn()` reads that value, refuses unless it's a positive integer, and
213
- * force-injects `value - 1` into the spawned child — a tamper-resistant counter,
214
- * not something a spec or the model can hand-propagate. Omit to disable spawning
215
- * entirely (the default — most agents never need it).
216
- */
217
- spawnDepth?: number;
218
- /**
219
- * Remaining budget for total agents this lineage may spawn — a resource
220
- * ceiling, distinct from `spawnDepth`'s nesting-depth limit. Translated by
221
- * `Alineo.load()`/`Alineo.resume()` into the `ALINEO_MAX_AGENTS` env var and
222
- * force-decremented into each spawned child, the same tamper-resistant
223
- * pattern as `spawnDepth`. Unlike `spawnDepth`, omitting this means
224
- * "uncapped" for this dimension, not "spawning disabled" — `spawnDepth`
225
- * alone still gates whether spawning is allowed at all. Enforced
226
- * per-lineage only: sibling branches spawned in parallel don't share or
227
- * coordinate this budget with each other.
228
- */
229
- maxAgents?: number;
230
- /**
231
- * Durable team identity for this agent's `.resourceRef` — see `@alineo-labs/memory`'s
232
- * `ResourceRef.teamId`. Unset by default (unlike `resourceId`, which always gets
233
- * `spec.name` as its own default) — most agents aren't tied to a team-scoped memory.
234
- * `Alineo.load()`/`.resume()` also thread this into `SandboxOptions.teamId`/
235
- * `RestoreSnapshotOptions.teamId` so it stays consistent with the ledger, not just
236
- * `.resourceRef` — otherwise a team-scoped agent's own episodic history would be
237
- * unreachable through its own `resourceRef`, since `episodicRecall()` enforces `teamId`
238
- * strictly. `Alineo.spawn()` passes `SandboxHandle.fork()`'s `resourceId`/`teamId` override
239
- * (see its own doc comment) so a spawned child's ledger record matches its
240
- * `.resourceRef` too, rather than silently inheriting the parent's.
241
- */
242
- teamId?: string;
243
- /**
244
- * Durable resource identity for this agent's `.resourceRef` — see `@alineo-labs/memory`'s
245
- * `ResourceRef.resourceId`. Defaults to `spec.name` when unset, same as the implicit
246
- * behavior before this field existed.
247
- *
248
- * Exists as its own field, separate from `name`, specifically for `Alineo.spawn()`: a
249
- * spawned child's `.name` is overwritten to the forked sandbox's auto-generated ledger name
250
- * (`fork-<parent>-<id>`, used for `alineo agents` display and future fork labeling) — not
251
- * `childSpec.name`. Without a separate `resourceId` field, a spawned child's memory scope
252
- * would silently become that auto-generated name instead of the identity the spec author
253
- * actually declared. `Alineo.spawn()` freezes this to `childSpec.resourceId ?? childSpec.name`
254
- * before the rename happens, so a spawned child's memory scope is stable and predictable
255
- * regardless of what the ledger ends up calling the forked sandbox.
256
- */
257
- resourceId?: string;
258
- /**
259
- * Human-in-the-loop tool-call policy, enforced by a bundled Pi extension that runs on
260
- * every tool call before it executes. Either a mode shorthand (`"auto"` — the default,
261
- * never ask; `"ask"` — ask before every call; `"readonly"` — auto-allow reads, ask before
262
- * writes/exec) or a full `PermissionPolicy` with ordered per-tool / per-pattern rules
263
- * (last match wins). When set to anything other than `"auto"`, a `permission_request`
264
- * event is emitted on the agent stream for each gated call; resolve it with
265
- * `agent.resolvePermission(requestId, decision)`.
266
- */
267
- permissions?: PermissionMode | PermissionPolicy;
268
- }
269
7
  /**
270
8
  * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
271
9
  * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
272
10
  * `.issues` array) rather than a bare `Error` — see #185.
273
11
  */
274
- export declare function validateAgentSpec(data: unknown): AgentSpec;
12
+ export declare function validateAgentSpec(data: unknown): AgentSpec$1;
275
13
  //#endregion
276
14
  //#region src/types.d.ts
277
15
  /**
@@ -666,35 +404,16 @@ declare class PiAdapter {
666
404
  getLogs(): Promise<string>;
667
405
  }
668
406
  //#endregion
669
- //#region src/snapshots.d.ts
670
- interface AgentSnapshotRecord {
671
- specName: string;
672
- setupHash: string;
673
- /** OpenSandbox snapshot ID returned by `sb.checkpoint()`. Pass to `client.restoreSnapshot()`. */
674
- snapshotId: string;
675
- createdAt: number;
676
- }
407
+ //#region src/config.d.ts
677
408
  /**
678
- * Hash of the fields that require re-installing the agent CLI or rerunning
679
- * setup: cli, cliVersion, packages, and setup. Excludes env (hot-reloadable),
680
- * model/provider (CLI flags only), and cosmetic fields.
409
+ * Shape of `alineo.config.json`, merged with built-in defaults.
410
+ *
411
+ * The schema and the merge live in `@alineo-labs/config-shared` because three consumers read
412
+ * this same file (this package, `@alineo-labs/cli-shared`, and alineod through its Docker
413
+ * entrypoint). That package is private and bundled at build time, so nothing new is resolved at
414
+ * runtime for anyone installing `alineo`.
681
415
  */
682
- export declare function computeSetupHash(spec: AgentSpec): string;
683
- /** Derive the agent-snapshots.json path from the ledger adapter path. */
684
- export declare function snapshotsPath(adapterPath: string): string;
685
- /** File-backed store for agent snapshot records, keyed by specName + setupHash. */
686
- export declare class AgentSnapshotStore {
687
- private readonly path;
688
- constructor(path: string);
689
- private _read;
690
- private _write;
691
- private _key;
692
- get(specName: string, setupHash: string): Promise<AgentSnapshotRecord | null>;
693
- save(record: AgentSnapshotRecord): Promise<void>;
694
- /** Remove all snapshot records for the given spec name. */
695
- delete(specName: string): Promise<void>;
696
- list(): Promise<AgentSnapshotRecord[]>;
697
- }
416
+ type AlineoAgentConfig = ProjectConfig;
698
417
  //#endregion
699
418
  //#region src/agent/egress-approval.d.ts
700
419
  /** The subset of `SandboxHandle` the gate calls. */
@@ -875,7 +594,7 @@ declare function setSessionName(a: AgentInternal, name: string): Promise<void>;
875
594
  * while Pi manages its own tool use, file writes, and code execution inside the
876
595
  * sandbox.
877
596
  *
878
- * Create an agent with `Alineo.load(spec)`. Always call `close()` when done
597
+ * Create an agent with `Alineo.start(spec)`. Always call `close()` when done
879
598
  * to release the underlying sandbox container.
880
599
  *
881
600
  * @example
@@ -883,7 +602,7 @@ declare function setSessionName(a: AgentInternal, name: string): Promise<void>;
883
602
  * import { Alineo } from "alineo";
884
603
  *
885
604
  * const spec = await Bun.file("./agents/my-agent.json").json();
886
- * const agent = await Alineo.load(spec, { adapter });
605
+ * const agent = await Alineo.start(spec, { adapter });
887
606
  * try {
888
607
  * for await (const chunk of agent.prompt("Explain this codebase")) {
889
608
  * process.stdout.write(chunk);
@@ -913,13 +632,13 @@ export declare class Alineo {
913
632
  /**
914
633
  * Identifies the logical run this agent's sandbox belongs to — see
915
634
  * `SandboxDetails.runId`. Always present; a fresh `crypto.randomUUID()` if not
916
- * explicitly passed to `load()`/`resume()`. A child from `.spawn()` (and
917
- * transitively, `alineo fork`) always inherits its parent's `runId`.
635
+ * explicitly passed to `start()`/`resume()`. A child from `.spawn()` (and
636
+ * transitively, `alineo spawn`) always inherits its parent's `runId`.
918
637
  */
919
638
  readonly runId: string;
920
639
  /**
921
640
  * Optional provider-agnostic memory (`@alineo-labs/memory`), wired in via `opts.memory` on
922
- * `load()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
641
+ * `start()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
923
642
  * constructs a `Memory` on your own behalf, matching this package's "own the pipeline,
924
643
  * don't assume a backend" design. `spawn()` carries the parent's `memory` (if any) onto the
925
644
  * child automatically, the same way it force-computes spawn-depth rather than reading it
@@ -941,7 +660,7 @@ export declare class Alineo {
941
660
  /**
942
661
  * Convenience `ResourceRef` scoping `.memory` calls to this agent. `resourceId`/`teamId`
943
662
  * come from `AgentSpec.resourceId`/`AgentSpec.teamId` (`resourceId` defaulting to this
944
- * agent's `name` when unset) — `load()`/`resume()`/`spawn()` also thread both into the
663
+ * agent's `name` when unset) — `start()`/`resume()`/`spawn()` also thread both into the
945
664
  * ledger (see each field's own doc comment) so this getter and the agent's own episodic
946
665
  * history stay consistent, including across a spawned child whose `.name` differs from its
947
666
  * memory identity.
@@ -970,13 +689,13 @@ export declare class Alineo {
970
689
  * don't need to call `validateAgentSpec()` yourself first unless you want validation errors
971
690
  * to surface before any sandbox/network work starts.
972
691
  *
973
- * On first load the Pi CLI is installed inside a `node:22` sandbox, then
974
- * the sandbox is checkpointed. Subsequent `load()` calls for the same spec
692
+ * On first start the Pi CLI is installed inside a `node:22` sandbox, then
693
+ * the sandbox is checkpointed. Subsequent `start()` calls for the same spec
975
694
  * restore from that snapshot — skipping the install and starting in ~3s instead
976
695
  * of ~90s.
977
696
  *
978
697
  * Pass `{ rebuild: true }` to force a full reinstall (e.g. after changing
979
- * the spec's `packages` or `cliVersion`).
698
+ * the spec's `packages` or `harnessVersion`).
980
699
  *
981
700
  * Pass `{ spawnDepth }` to override the spec's own `spawnDepth` (e.g. a
982
701
  * `--depth` CLI flag) — standard flag-beats-config precedence. Same for
@@ -985,7 +704,7 @@ export declare class Alineo {
985
704
  * Reports timing for each phase through `@alineo-labs/logger` (component `agent`, tagged with
986
705
  * the spec `name`). Silent by default — set `ALINEO_LOG_LEVEL=info` to see it.
987
706
  */
988
- static load(spec: AgentSpec | Record<string, unknown>, opts: {
707
+ static start(spec: AgentSpec | Record<string, unknown>, opts: {
989
708
  adapter: IStorageAdapter;
990
709
  rebuild?: boolean;
991
710
  spawnDepth?: number;
@@ -993,6 +712,11 @@ export declare class Alineo {
993
712
  runId?: string;
994
713
  /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
995
714
  memory?: Memory;
715
+ /**
716
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
717
+ * tests that must not depend on the working directory.
718
+ */
719
+ config?: AlineoAgentConfig;
996
720
  /**
997
721
  * Required when the spec has `approval: "hold"` credential bindings — decides each
998
722
  * first outbound request to a held host: return `"allow-once"` (reverts at turn end),
@@ -1014,20 +738,20 @@ export declare class Alineo {
1014
738
  * first and fall back to this only if it fails (e.g. the whole sandbox — not just this
1015
739
  * process — actually restarted).
1016
740
  *
1017
- * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
741
+ * @param sandboxId The sandbox ID returned by the original `Alineo.start()`.
1018
742
  * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
1019
- * `load()`. Takes precedence over `opts.specPath` if both are set.
743
+ * `start()`. Takes precedence over `opts.specPath` if both are set.
1020
744
  * @param opts.specPath Path to the agent spec JSON, read and validated internally. If
1021
745
  * neither `opts.spec` nor `opts.specPath` is set, the ledger is queried for the sandbox's
1022
746
  * name and the spec is read from `./agents/<name>.json` — this fallback is the one thing
1023
- * `resume()` can do that `load()` can't, since a resumed sandbox's original spec may not be
747
+ * `resume()` can do that `start()` can't, since a resumed sandbox's original spec may not be
1024
748
  * in memory anywhere the caller can hand it over.
1025
749
  *
1026
750
  * @example
1027
751
  * ```ts
1028
752
  * // Original process:
1029
753
  * const spec = await Bun.file("./agents/hello-agent.json").json();
1030
- * const agent = await Alineo.load(spec, { adapter });
754
+ * const agent = await Alineo.start(spec, { adapter });
1031
755
  * console.log(agent.sandboxId); // save this
1032
756
  * // ... process exits ...
1033
757
  *
@@ -1046,6 +770,11 @@ export declare class Alineo {
1046
770
  runId?: string;
1047
771
  /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
1048
772
  memory?: Memory;
773
+ /**
774
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
775
+ * tests that must not depend on the working directory.
776
+ */
777
+ config?: AlineoAgentConfig;
1049
778
  }): Promise<Alineo>;
1050
779
  /**
1051
780
  * Reconnect to a previously-created agent WITHOUT restarting its bridge — the crash-only
@@ -1063,7 +792,7 @@ export declare class Alineo {
1063
792
  * the bridge process inside it has independently died, and this can't distinguish that from
1064
793
  * a slow-to-respond-but-fine bridge on its own. On failure, fall back to `Alineo.resume()`.
1065
794
  *
1066
- * @param sandboxId The sandbox ID returned by the original `Alineo.load()`/`.spawn()`.
795
+ * @param sandboxId The sandbox ID returned by the original `Alineo.start()`/`.spawn()`.
1067
796
  * @param opts.spec / opts.specPath Same three-way fallback as `resume()` — see its docs.
1068
797
  *
1069
798
  * @example
@@ -1083,6 +812,11 @@ export declare class Alineo {
1083
812
  runId?: string;
1084
813
  /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
1085
814
  memory?: Memory;
815
+ /**
816
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
817
+ * tests that must not depend on the working directory.
818
+ */
819
+ config?: AlineoAgentConfig;
1086
820
  /**
1087
821
  * Don't probe the bridge before returning, and accept a Paused sandbox. For a paused
1088
822
  * sandbox, whose frozen bridge can't answer until `agent.sandbox.resume()` — check it
@@ -1096,7 +830,7 @@ export declare class Alineo {
1096
830
  * `resume()`, which kills and restarts the bridge process. Use this when you only
1097
831
  * need `.spawn()`/`.sandbox`, not `.prompt()`/`.bash()`.
1098
832
  *
1099
- * The main caller is `alineo fork`: it runs as a fresh CLI process started BY the
833
+ * The main caller is `alineo spawn`: it runs as a fresh CLI process started BY the
1100
834
  * very Pi bash-tool call it's attaching to (a master agent spawning a child from
1101
835
  * inside its own turn). Going through `resume()` there would `pkill` the bridge
1102
836
  * that's currently running the Pi process making the call — self-destructive.
@@ -1107,7 +841,7 @@ export declare class Alineo {
1107
841
  * file, which may not even exist inside this particular sandbox.
1108
842
  *
1109
843
  * When `sandboxId` matches `ALINEO_SANDBOX_ID` in this process's own env (true
1110
- * self-attach, e.g. `alineo fork` running from inside its own container),
844
+ * self-attach, e.g. `alineo spawn` running from inside its own container),
1111
845
  * `/etc/alineo-env` is read straight off the local filesystem instead of via
1112
846
  * `sb.readFile()`. A self-referential exec call would need this sandbox to
1113
847
  * reach itself through its own externally-facing bridge IP, which Docker's
@@ -1118,7 +852,7 @@ export declare class Alineo {
1118
852
  * `opts.resources` sizes a subsequent `.spawn()`'s forked container — the
1119
853
  * control API doesn't echo back a running sandbox's own resource limits, so
1120
854
  * there's no way to discover this agent's *actual* footprint here. Defaults to
1121
- * `alineo.config.json`'s `defaults.resources`, same fallback `Alineo.load()` uses
855
+ * `alineo.config.json`'s `defaults.resources`, same fallback `Alineo.start()` uses
1122
856
  * for a spec that doesn't set its own.
1123
857
  */
1124
858
  static attach(sandboxId: string, opts: {
@@ -1131,11 +865,16 @@ export declare class Alineo {
1131
865
  };
1132
866
  /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
1133
867
  memory?: Memory;
868
+ /**
869
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
870
+ * tests that must not depend on the working directory.
871
+ */
872
+ config?: AlineoAgentConfig;
1134
873
  }): Promise<Alineo>;
1135
874
  /**
1136
875
  * Fork this agent's live sandbox — filesystem, installed packages, checked-out
1137
876
  * state, everything currently on disk — into a brand-new independent sandbox
1138
- * running its own Pi bridge, per `childSpecPath`. Unlike `Alineo.load()` (always
877
+ * running its own Pi bridge, per `childSpecPath`. Unlike `Alineo.start()` (always
1139
878
  * starts from a spec's own snapshot) or `fork()`/`clone()` below (Pi's own
1140
879
  * conversation-branching — same container, same bridge, new session branch),
1141
880
  * this is sandbox-level forking: the child sees exactly what this agent's
@@ -1240,7 +979,7 @@ export declare class Alineo {
1240
979
  * List the fork entry points available in the current session.
1241
980
  * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
1242
981
  */
1243
- getForkMessages(): Promise<{
982
+ getBranchPoints(): Promise<{
1244
983
  entryId: string;
1245
984
  text: string;
1246
985
  }[]>;
@@ -1267,15 +1006,21 @@ export declare class Alineo {
1267
1006
  path: string;
1268
1007
  }>;
1269
1008
  /**
1270
- * Fork Pi's session at the given entry ID, creating a new branch.
1271
- * Returns the text of the forked message and whether the fork was cancelled.
1009
+ * Branch the harness conversation at the given entry ID.
1010
+ *
1011
+ * Named for what it touches. This never leaves the container: it is the harness's own
1012
+ * session that branches, not the sandbox — `agent.sandbox.fork()` is the one that copies a
1013
+ * filesystem. Unqualified `fork` meant both for a while, which is the confusion this name
1014
+ * exists to end.
1015
+ *
1016
+ * Returns the text of the branched message and whether the branch was cancelled.
1272
1017
  */
1273
- fork(entryId: string): Promise<{
1018
+ branchSession(entryId: string): Promise<{
1274
1019
  text: string;
1275
1020
  cancelled: boolean;
1276
1021
  }>;
1277
- /** Clone the current Pi session into a new branch at the current position. */
1278
- clone(): Promise<{
1022
+ /** Branch the harness conversation at its current position. Same container, same bridge. */
1023
+ duplicateSession(): Promise<{
1279
1024
  cancelled: boolean;
1280
1025
  }>;
1281
1026
  /** Switch Pi to a different session file on disk. */
@@ -1317,6 +1062,50 @@ export declare class Alineo {
1317
1062
  close(): Promise<void>;
1318
1063
  }
1319
1064
  //#endregion
1065
+ //#region src/permissions.d.ts
1066
+ /**
1067
+ * Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
1068
+ * recognised pure reader with no output redirection; `false` = something needs a human.
1069
+ * Mirrored verbatim in `adapters/pi-permission-gate.js`.
1070
+ */
1071
+ export declare function isReadOnlyBashCommand(command: string): boolean;
1072
+ //#endregion
1073
+ //#region src/snapshots.d.ts
1074
+ interface AgentSnapshotRecord {
1075
+ specName: string;
1076
+ setupHash: string;
1077
+ /** OpenSandbox snapshot ID returned by `sb.checkpoint()`. Pass to `client.restoreSnapshot()`. */
1078
+ snapshotId: string;
1079
+ createdAt: number;
1080
+ }
1081
+ /**
1082
+ * Hash of the fields that require re-installing the harness or rerunning
1083
+ * setup: harness, harnessVersion, packages, and setup. Excludes env (hot-reloadable),
1084
+ * model/provider (harness flags only), and cosmetic fields.
1085
+ *
1086
+ * The hashed object deliberately keeps the **old** key names. This is a cache key, not a
1087
+ * vocabulary surface — nobody reads it — and changing the keys would change every existing
1088
+ * snapshot's hash, so the `harness` rename would silently cost every user a ~90s rebuild of
1089
+ * every agent instead of a ~3s snapshot restore. The values are what identify the install;
1090
+ * the key spelling is incidental.
1091
+ */
1092
+ export declare function computeSetupHash(spec: AgentSpec): string;
1093
+ /** Derive the agent-snapshots.json path from the ledger adapter path. */
1094
+ export declare function snapshotsPath(adapterPath: string): string;
1095
+ /** File-backed store for agent snapshot records, keyed by specName + setupHash. */
1096
+ export declare class AgentSnapshotStore {
1097
+ private readonly path;
1098
+ constructor(path: string);
1099
+ private _read;
1100
+ private _write;
1101
+ private _key;
1102
+ get(specName: string, setupHash: string): Promise<AgentSnapshotRecord | null>;
1103
+ save(record: AgentSnapshotRecord): Promise<void>;
1104
+ /** Remove all snapshot records for the given spec name. */
1105
+ delete(specName: string): Promise<void>;
1106
+ list(): Promise<AgentSnapshotRecord[]>;
1107
+ }
1108
+ //#endregion
1320
1109
  //#region src/errors.d.ts
1321
1110
  /**
1322
1111
  * Thrown when a prompt/bash SSE stream from a sandbox's Pi bridge goes quiet for longer than
@@ -1325,7 +1114,7 @@ export declare class Alineo {
1325
1114
  * about whether Pi itself is making progress) for that long. Previously this surfaced as an
1326
1115
  * indefinite hang with zero visibility: `sseStream()` had no timeout at all, so a genuinely
1327
1116
  * stuck Pi process (e.g. blocked in a credential refresh, or any other silent stall) blocked
1328
- * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo fork --prompt` --
1117
+ * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo spawn --prompt` --
1329
1118
  * forever, with no error and no partial output.
1330
1119
  */
1331
1120
  export declare class PromptTimeoutError extends WorkflowError {
@@ -1333,6 +1122,20 @@ export declare class PromptTimeoutError extends WorkflowError {
1333
1122
  readonly bridgeUrl: string;
1334
1123
  constructor(timeoutMs: number, bridgeUrl: string);
1335
1124
  }
1125
+ /**
1126
+ * Thrown when a prompt/bash SSE stream's underlying connection closes (`reader.read()` reports
1127
+ * `done: true`) without the bridge ever having sent its own `[DONE]` sentinel first -- the
1128
+ * signal that the bridge process died mid-stream (e.g. a crash, an OOM kill), not that Pi
1129
+ * actually finished the turn. Previously `sseStream()` treated this exactly like a clean finish
1130
+ * (durability-roadmap M2.1, verified live on `my-vps` 2026-10-03: `kill -9`ing the bridge process
1131
+ * mid-tool-call settled the turn as a false `success` with no text, in under 20s, instead of
1132
+ * ever reaching the inactivity-timeout/catch-up path at all) -- a TCP-level EOF and an
1133
+ * application-level `[DONE]` are indistinguishable to a bare `for await` without this.
1134
+ */
1135
+ export declare class BridgeDisconnectedError extends WorkflowError {
1136
+ readonly bridgeUrl: string;
1137
+ constructor(bridgeUrl: string);
1138
+ }
1336
1139
  /**
1337
1140
  * Thrown by `validateAgentSpec()` when a spec object fails schema validation. Carries every
1338
1141
  * failing field in one pass (`.issues`, mirroring `z.ZodIssue[]` shape) rather than surfacing
@@ -1345,4 +1148,125 @@ export declare class AgentSpecValidationError extends WorkflowError {
1345
1148
  constructor(message: string, issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[]);
1346
1149
  }
1347
1150
  //#endregion
1348
- export type { AgentEvent, AgentSnapshotRecord, AgentSpec, AgentStream, CompactResult, EgressApprovalGateOptions, EgressDecision, EgressRequest, EgressRequestHandler, HeldCredential, PendingPermission, PermissionAction, PermissionDecision, PermissionHandler, PermissionMode, PermissionPolicy, PermissionRequest, PermissionRule, PiMessage, PiModel, PiSessionState, PiSlashCommand, PromptStream, SessionStats, SetupStep, ThinkingLevel };
1151
+ //#region src/checkpoint.d.ts
1152
+ /**
1153
+ * Turn-level checkpointing (durability-roadmap.md M3, 3.2) — deliberately NOT
1154
+ * `sb.checkpoint()`. That method calls OpenSandbox's own snapshot primitive, which on the
1155
+ * Docker runtime is literally `docker commit` (confirmed against OpenSandbox's own source,
1156
+ * M3's 3.1 research) — measured at 44.3s for a 236MB container, re-exporting the whole
1157
+ * filesystem every time regardless of how much actually changed. Calling that every turn would
1158
+ * silently reintroduce the exact cost 3.1 ruled out. This module tars a few directories via
1159
+ * `sb.exec()` instead — measured at well under 2s even unfiltered.
1160
+ *
1161
+ * This is a different mechanism from the agent SDK's other "snapshot" concept, the setup
1162
+ * snapshot (`./snapshots.ts`'s `AgentSnapshotStore`) — that one is taken once per unique
1163
+ * `(specName, setupHash)` to skip reinstalling Pi/packages on every `Alineo.start()`. This one
1164
+ * is taken after every completed turn, captures that specific conversation's state (not a
1165
+ * shared install), and is what `Alineo.resume()` restores from when the container itself is
1166
+ * gone (3.3) — the setup snapshot only gets a fresh, *empty* container, not this agent's actual
1167
+ * conversation.
1168
+ */
1169
+ /** Directories/globs left out of every checkpoint tarball by default — universally-safe
1170
+ * package/toolchain caches, nothing else (3.1's decision: err toward inclusion, since the
1171
+ * measured unfiltered cost is already cheap — losing real workspace state by over-excluding is
1172
+ * a worse mistake than a few extra seconds). Paths are relative to `CHECKPOINT_ROOT`. */
1173
+ export declare const DEFAULT_CHECKPOINT_EXCLUDES: string[];
1174
+ /**
1175
+ * The directory tarred into every checkpoint — Pi's home directory, where its session file
1176
+ * (`.pi/agent/sessions/...`) and whatever the agent wrote both live. Every sandbox measured for
1177
+ * 3.1 ran Pi as root; a spec that runs as a different user is a known simplification this
1178
+ * chunk doesn't yet handle (no portable way to ask a sandbox its $HOME without an extra exec
1179
+ * round trip on every checkpoint, and nothing in the current fleet needs it).
1180
+ */
1181
+ export declare const CHECKPOINT_ROOT = "root";
1182
+ /**
1183
+ * durability-roadmap M3, 3.5: restore (3.3) only ever reads the *latest* checkpoint — an older
1184
+ * one is slack for debugging/manual rollback, not a live requirement. 3 was decided without
1185
+ * real usage data to justify more (measured sizes are sub-30MB, typically far less once the
1186
+ * exclusion list applies), and is cheap to revisit if real retention pressure ever shows up.
1187
+ */
1188
+ export declare const DEFAULT_CHECKPOINT_RETENTION = 3;
1189
+ interface CheckpointRecord {
1190
+ /** Monotonic within this `Alineo` instance's lifetime — an ordinal for humans reading
1191
+ * `alineo logs`, not the mechanism restore uses to find the latest one (that's ledger
1192
+ * append order, via `AgentCheckpointed` events). Resets to 0 across a resume/reattach — a
1193
+ * fresh process starting its own count at 0 again causes no restore-correctness issue. */
1194
+ turn: number;
1195
+ /** A path on the host filesystem today (single-node M3 scope). M4 moves this off-box. */
1196
+ snapshotRef: string;
1197
+ createdAt: number;
1198
+ }
1199
+ /** Derive the checkpoints directory from the ledger adapter's own path, same convention as
1200
+ * `./snapshots.ts`'s `snapshotsPath()`. */
1201
+ export declare function checkpointsPath(adapterPath: string): string;
1202
+ /**
1203
+ * Tar `CHECKPOINT_ROOT` (minus the default excludes) inside the sandbox, pull the bytes out
1204
+ * byte-safe (`sb.readFileBytes()`, never `readFile()`'s UTF-8 path — a gzip tarball is not
1205
+ * valid UTF-8), write them to `checkpointsDir`, and record `AgentCheckpointed` on the sandbox's
1206
+ * own ledger — in that order, snapshot-then-event, so a checkpoint event is never written
1207
+ * pointing at a tarball that doesn't actually exist on disk.
1208
+ *
1209
+ * Throws on any step's failure (tar inside the sandbox, the byte-safe download, or the host
1210
+ * write) — the caller decides whether a failed checkpoint should interrupt the turn it was
1211
+ * taken after (3.2's own call site treats it as best-effort and logs rather than throws
1212
+ * further, since a checkpoint failing is not the same failure as the turn itself failing).
1213
+ * Retention (3.5) runs only after a successful write+event, pruning this sandbox's own
1214
+ * directory down to `opts.retain` (default `DEFAULT_CHECKPOINT_RETENTION`). A pruning failure
1215
+ * is swallowed, not thrown — the checkpoint this call was actually for already succeeded, and
1216
+ * a cleanup failure must never retroactively turn that into an error.
1217
+ */
1218
+ export declare function takeCheckpoint(sb: SandboxHandle, checkpointsDir: string, opts: {
1219
+ turn: number;
1220
+ excludeGlobs?: string[];
1221
+ retain?: number;
1222
+ }): Promise<CheckpointRecord>;
1223
+ //#endregion
1224
+ //#region src/sandbox-gone.d.ts
1225
+ /**
1226
+ * Classifies an error from `client.connect()` (or any other sandbox-control call) as "no live
1227
+ * container to reattach or resume into" — as opposed to a transient failure that might clear on
1228
+ * retry. Shared between `resumeAgent()`/`reattachAgent()` (M3, 3.3 — falls through to
1229
+ * restore-from-checkpoint on this) and `apps/alineod/src/engine/rehydrate.ts`'s restore ladder
1230
+ * (M3, 3.4 — same question, same answer), which previously had its own private copy covering
1231
+ * only the first case below.
1232
+ *
1233
+ * Two distinct ways a sandbox can be "gone," both confirmed against OpenSandbox's actual
1234
+ * behavior (DeepWiki, not just its higher-level docs — same discipline M1.4/M2's research used):
1235
+ *
1236
+ * 1. Truly deleted/unknown (`docker rm -f`, expired and reaped): a 404, surfaced as
1237
+ * `<RUNTIME>::SANDBOX_NOT_FOUND` on the error's `code` or in its message.
1238
+ * 2. `Exited` after a host reboot or Docker daemon restart (durability-roadmap's former M2
1239
+ * 2.3, moved here): **not** a 404 — a `200 OK` with `state: "Terminated"`/`"Failed"`.
1240
+ * `@alineo-labs/sandbox`'s `client.connect()` (`packages/sdks/typescript/src/client.ts`)
1241
+ * already surfaces this as a `SandboxClientError` with `status: 409` and a message of the
1242
+ * shape `"SandboxHandle <id> is <state> — can only connect to Running sandboxes"` — this
1243
+ * classifier matches that message shape rather than re-deriving the state check itself, so
1244
+ * it stays correct if `connect()`'s own wording ever changes without this file knowing.
1245
+ */
1246
+ export declare function isSandboxGone(err: unknown): boolean;
1247
+ //#endregion
1248
+ //#region src/restore.d.ts
1249
+ /**
1250
+ * durability-roadmap M3, 3.3 — the other half of `./checkpoint.ts`. Finds the latest
1251
+ * `AgentCheckpointed` record for a sandbox from its own ledger (the same `IStorageAdapter` the
1252
+ * sandbox already writes to via `sb.emit()` — this works whether that sandbox still exists or
1253
+ * not, since the ledger is exactly what's supposed to survive it) and extracts the tarball
1254
+ * into a *different*, already-running container — the one a fresh snapshot restore just
1255
+ * provisioned, per `resumeAgent()`'s fallback in `./agent/factory.ts`.
1256
+ */
1257
+ interface LatestCheckpoint {
1258
+ turn: number;
1259
+ snapshotRef: string;
1260
+ }
1261
+ /** `undefined` if this sandbox was never checkpointed — not an error; the caller falls back
1262
+ * to whatever state a bare snapshot restore already produced. */
1263
+ export declare function findLatestCheckpoint(adapter: IStorageAdapter, name: string, sandboxId: string): Promise<LatestCheckpoint | undefined>;
1264
+ /**
1265
+ * Extract a checkpoint tarball (from the host path `takeCheckpoint()` stored it at) into `sb`,
1266
+ * overwriting whatever a fresh container's own setup left in place at the same paths. Byte-safe
1267
+ * on both ends (`writeFileBytes`/raw `tar xzf`) — the same corruption risk `takeCheckpoint()`'s
1268
+ * doc comment already covers on the capture side applies symmetrically here on restore.
1269
+ */
1270
+ export declare function restoreCheckpoint(sb: SandboxHandle, snapshotRef: string): Promise<void>;
1271
+ //#endregion
1272
+ export type { AgentEvent, AgentSnapshotRecord, AgentSpec, AgentStream, CheckpointRecord, CompactResult, EgressApprovalGateOptions, EgressDecision, EgressRequest, EgressRequestHandler, HeldCredential, LatestCheckpoint, PendingPermission, PermissionAction, PermissionDecision, PermissionHandler, PermissionMode, PermissionPolicy, PermissionRequest, PermissionRule, PiMessage, PiModel, PiSessionState, PiSlashCommand, PromptStream, SessionStats, SetupStep, ThinkingLevel };