alineo 0.1.0 → 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/dist/index.d.mts CHANGED
@@ -1,418 +1,912 @@
1
- import { BashSession, CheckpointInfo, CommandError, DiagnosticEvent, DiagnosticLog, EnvironmentRecord, EnvironmentRecord as EnvironmentRecord$1, EnvironmentRecord as EnvironmentRecord$2, ExecCodeOptions, ExecConnectionError, ExecHandle, ExecOptions, ExecResult, FileInfo, IStorageAdapter, IStorageAdapter as IStorageAdapter$1, InteractiveExecHandle, LedgerEntry, LedgerEvent, ListSandboxOptions, ListSandboxOptions as ListSandboxOptions$1, Metrics, PendingInteractiveExec, Sandbox, Sandbox as Sandbox$1, SandboxDetails, SandboxDetails as SandboxDetails$1, SandboxError, SandboxHooks, SandboxStatus, StepTimeoutError } from "@alineo-labs/core";
2
- import { CodeLanguage } from "@alineo-labs/opensandbox";
1
+ import { z } from "zod";
2
+ import { IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
3
+ import { Memory, ResourceRef } from "@alineo-labs/memory";
3
4
 
4
- //#region src/types.d.ts
5
+ //#region src/schema.d.ts
5
6
  /**
6
- * Client-side SDK error carrying an HTTP-style status code, thrown for
7
- * invariant/state failures such as a sandbox missing from the local ledger
8
- * (404), a sandbox not in `Running` state (409), or a client-side timeout
9
- * (408). This does not wrap non-2xx OpenSandbox API responses — those throw
10
- * `OpenSandboxError` from `@alineo-labs/opensandbox`, which is never rethrown as a
11
- * `AlineoError`.
7
+ * Opt-in alternative to a plain `AgentSpec.env` string value — instead of interpolating
8
+ * straight into the container's environment, `credential` is registered with the sandbox's
9
+ * `CredentialBroker` via `sb.credentials.set()` and injected transparently into outbound
10
+ * requests to `host`. The sandbox process never sees the resolved value at all. Requires the
11
+ * agent's sandbox to be created with `credentialProxy: true` — `Alineo.load()`/`.resume()`/
12
+ * `.spawn()` set this automatically whenever `env` contains at least one binding like this.
12
13
  */
13
- declare class AlineoError extends Error {
14
- readonly status: number;
15
- constructor(message: string, status: number);
14
+ interface CredentialEnvBinding {
15
+ /** Host env var reference to resolve the real value from, e.g. `"${OPENAI_API_KEY}"`. */
16
+ credential: string;
17
+ /** FQDN or wildcard domain this credential is injected for. */
18
+ host: string;
19
+ /** Narrows the binding to requests whose path starts with this prefix. */
20
+ pathPrefix?: string;
21
+ /** How the credential reaches the request. */
22
+ injection: {
23
+ type: "header";
24
+ name: string;
25
+ } | {
26
+ type: "query";
27
+ param: string;
28
+ } | {
29
+ type: "path";
30
+ segment: string;
31
+ };
16
32
  }
17
- /** Options for constructing a {@link Alineo} client. */
18
- interface AlineoOptions {
19
- /** Base URL of your OpenSandbox server (e.g. `http://localhost:8080`). */
20
- baseUrl: string;
21
- /** OpenSandbox API key. Pass an empty string for local dev with no auth. */
22
- apiKey?: string;
23
- /**
24
- * Storage adapter for persisting sandbox events.
25
- *
26
- * Pass `new SQLiteAdapter("./alineo.db")` from `@alineo-labs/sqlite` for local use, or
27
- * `new PostgresAdapter(connectionString)` from `@alineo-labs/postgres` for production.
28
- */
29
- adapter: IStorageAdapter$1;
33
+ /**
34
+ * A single named setup step run inside the sandbox after Pi CLI install,
35
+ * before the snapshot is taken. The step is a bash shell command.
36
+ */
37
+ interface SetupStep {
38
+ /** Human-readable label shown in logs and included in the setup hash. */
39
+ name: string;
40
+ /** Shell command to run (bash). */
41
+ run: string;
42
+ /** If set, the command runs as `cd <cwd> && <run>`. */
43
+ cwd?: string;
44
+ }
45
+ /**
46
+ * JSON spec for an agent — typically loaded from an `agent.json` file on disk.
47
+ * Pass it to `Alineo.load(spec)` — read it from disk yourself first (e.g.
48
+ * `await Bun.file(path).json()`) if it's not already an in-memory object.
49
+ *
50
+ * Environment variable references in `env` values are interpolated from
51
+ * `process.env` at load time: `"${MY_API_KEY}"` → `process.env.MY_API_KEY`.
52
+ */
53
+ interface AgentSpec {
54
+ $schema?: string;
55
+ /** Unique identifier for this agent. Used as the sandbox session name. */
56
+ name: string;
57
+ /** Human-readable display name. */
58
+ title?: string;
59
+ description?: string;
60
+ author?: string;
61
+ categories?: string[];
62
+ /** CLI to run inside the sandbox. Currently only `"pi"` is supported. */
63
+ cli: "pi";
30
64
  /**
31
- * Maximum number of sandboxes that may be active simultaneously.
32
- * When at capacity, `sandbox()` awaits until a slot is free.
33
- * Omit for no limit.
65
+ * npm version specifier for the Pi CLI, e.g. `"1.2.3"`, `"^1.2.0"`, or a
66
+ * dist-tag like `"latest"`. Passed directly to
67
+ * `npm install -g @earendil-works/pi-coding-agent@<cliVersion>`. When
68
+ * omitted, `install()` runs the bare package name and npm resolves
69
+ * whatever it considers latest. Included in the setup-hash cache key, so
70
+ * changing it forces a fresh snapshot rebuild.
34
71
  */
35
- maxConcurrency?: number;
72
+ cliVersion?: string;
36
73
  /**
37
- * Route execd and proxy traffic through the OpenSandbox server instead of
38
- * connecting to sandbox containers directly. Required when the server runs
39
- * in Docker (e.g. started via `alineo init`). Defaults to `false`.
74
+ * AI provider passed to the CLI via `--provider`. For Pi with a direct Google
75
+ * API key, omit this (Pi defaults to the Google Generative AI endpoint).
40
76
  */
41
- useServerProxy?: boolean;
42
- }
43
- /** Options for `Alineo.resume()`. */
44
- interface ResumeOptions {
45
- /** Resume from the checkpoint with this tag. Defaults to the most recent checkpoint. */
46
- tag?: string;
47
- }
48
- /** Options for `Alineo.sandbox()`. */
49
- interface SandboxOptions {
50
- /**
51
- * Container image to run. Pass a string (`"node:22"`) or a full `ImageSpec`
52
- * with optional auth (`{ uri: "ghcr.io/org/image", auth: { username, password } }`).
53
- */
54
- image: string | {
55
- uri: string;
56
- auth?: {
57
- username: string;
58
- password: string;
59
- };
60
- };
61
- /** CPU/memory/GPU resource limits. Required by the OpenSandbox server. */
62
- resources: {
63
- cpu: string;
64
- memory: string;
65
- gpu?: string;
66
- };
67
- /** Environment variables set in the container at startup. */
68
- env?: Record<string, string>;
69
- /** Arbitrary key-value labels attached to the sandbox. Not ledger-queryable — see `runId`. */
70
- metadata?: Record<string, string>;
77
+ provider?: string;
71
78
  /**
72
- * User-provided name for this sandbox run. Used as the ledger key.
73
- * Defaults to `"sandbox-<first 8 chars of sandboxId>"` if omitted.
79
+ * Model ID passed to the CLI via `--model`.
80
+ * For Pi 0.80.x with a free Google AI Studio key, use `"gemini-flash-latest"`
81
+ * (Pi's alias for gemini-3.5-flash via the direct Google Generative AI API).
74
82
  */
75
- name?: string;
83
+ model?: string;
76
84
  /**
77
- * Identifies the logical run this sandbox belongs to — see `SandboxDetails.runId`.
78
- * Defaults to a fresh `crypto.randomUUID()` if omitted. A resumed, forked, or
79
- * restored-from-snapshot sandbox always inherits its origin's `runId` rather than getting
80
- * a new one, so pass this explicitly only when correlating independent top-level sandboxes
81
- * that don't share a fork/resume relationship (e.g. two agents started separately by the
82
- * same host script for one logical run).
85
+ * APT packages to install in the sandbox before starting the CLI.
86
+ * Example: `["python3", "git"]`. `nodejs_22` and `nodejs` are silently ignored
87
+ * since the base image is `node:22`.
83
88
  */
84
- runId?: string;
85
- /** Sandbox lifetime in seconds. Defaults to the OpenSandbox server default. */
86
- timeout?: number;
87
- /** Observability hooks (e.g. `otelHooks(tracer)` from `@alineo-labs/otel`). */
88
- hooks?: SandboxHooks;
89
+ packages?: string[];
89
90
  /**
90
- * Default shell for all `sb.exec()` calls on this sandbox.
91
- * Pass an absolute path to the shell binary (e.g. `"/bin/bash"`, `"/bin/zsh"`).
92
- * Defaults to `"/bin/sh"`.
91
+ * Environment variables available inside the sandbox.
92
+ * Values may reference host env vars: `{ GEMINI_API_KEY: "${GEMINI_API_KEY}" }`.
93
+ *
94
+ * A value can instead be a `CredentialEnvBinding` to opt that one key out of plain env-var
95
+ * interpolation entirely — the key never becomes a container env var; its value is injected
96
+ * transparently into matching outbound requests instead. See `CredentialEnvBinding`.
93
97
  */
94
- shell?: string;
98
+ env?: Record<string, string | CredentialEnvBinding>;
95
99
  /**
96
- * Override the container entrypoint. Defaults to `["tail", "-f", "/dev/null"]`
97
- * which keeps the container alive without a TTY.
98
- *
99
- * Set this when using images that need their own init process — for example,
100
- * `opensandbox/code-interpreter` requires `["/opt/code-interpreter/code-interpreter.sh"]`
101
- * to start the Jupyter kernel service that `execCode()` depends on.
100
+ * CPU/memory/GPU resource limits for the sandbox container.
101
+ * Falls back to defaults in `alineo.config.json` if omitted.
102
102
  */
103
- entrypoint?: string[];
104
- }
105
- //#endregion
106
- //#region src/environment.d.ts
107
- interface EnvironmentOptions {
108
- /**
109
- * Container image to boot. Same format as `SandboxOptions.image` —
110
- * a string URI or a full spec with optional auth.
111
- */
112
- image: string | {
113
- uri: string;
114
- auth?: {
115
- username: string;
116
- password: string;
117
- };
118
- };
119
- /** CPU/memory/GPU limits applied to both the build sandbox and each spawned sandbox. */
120
- resources: {
103
+ resources?: {
121
104
  cpu: string;
122
105
  memory: string;
123
106
  gpu?: string;
124
107
  };
108
+ /** Not read anywhere in `alineo`; has no effect on the sandbox. */
109
+ metadata?: Record<string, string>;
125
110
  /**
126
- * Setup function run once on a fresh sandbox during the first `env.sandbox()` call
127
- * (or after `env.rebuild()`). Install packages, copy files, write config — anything
128
- * that makes the environment ready. The result is snapshotted and reused from then on.
111
+ * Not read by `alineo` itself — used by `alineo add`, which fetches
112
+ * and saves each dependency spec first, depth-first.
129
113
  */
130
- setup: (sb: Sandbox$1) => Promise<void>;
114
+ registryDependencies?: string[];
131
115
  /**
132
- * Default shell for all `exec()` calls — both during setup and in sandboxes spawned
133
- * from this environment. Pass an absolute path (e.g. `"/bin/bash"`).
134
- * Defaults to `"/bin/sh"`.
116
+ * Setup steps run inside the sandbox after Pi CLI install, before the snapshot.
117
+ * Baked into the snapshot — any change to a step invalidates the cache automatically.
118
+ * Example: create directories, write seed files, install project dependencies.
135
119
  */
136
- shell?: string;
137
- }
138
- /** Extra options forwarded to each sandbox spawned from an environment. */
139
- interface EnvironmentSandboxOptions {
140
- /** Additional environment variables set at container startup. */
141
- env?: Record<string, string>;
142
- /** Observability hooks. */
143
- hooks?: SandboxHooks;
120
+ setup?: SetupStep[];
121
+ /**
122
+ * Remaining budget for `Alineo.spawn()` calls made from inside this agent's sandbox.
123
+ * Translated by `Alineo.load()`/`Alineo.resume()` into the `ALINEO_SPAWN_DEPTH` env var.
124
+ * `Alineo.spawn()` reads that value, refuses unless it's a positive integer, and
125
+ * force-injects `value - 1` into the spawned child — a tamper-resistant counter,
126
+ * not something a spec or the model can hand-propagate. Omit to disable spawning
127
+ * entirely (the default — most agents never need it).
128
+ */
129
+ spawnDepth?: number;
130
+ /**
131
+ * Remaining budget for total agents this lineage may spawn — a resource
132
+ * ceiling, distinct from `spawnDepth`'s nesting-depth limit. Translated by
133
+ * `Alineo.load()`/`Alineo.resume()` into the `ALINEO_MAX_AGENTS` env var and
134
+ * force-decremented into each spawned child, the same tamper-resistant
135
+ * pattern as `spawnDepth`. Unlike `spawnDepth`, omitting this means
136
+ * "uncapped" for this dimension, not "spawning disabled" — `spawnDepth`
137
+ * alone still gates whether spawning is allowed at all. Enforced
138
+ * per-lineage only: sibling branches spawned in parallel don't share or
139
+ * coordinate this budget with each other.
140
+ */
141
+ maxAgents?: number;
144
142
  /**
145
- * Override the shell for this spawned sandbox only.
146
- * Falls back to `EnvironmentOptions.shell`, then `"/bin/sh"`.
143
+ * Durable team identity for this agent's `.resourceRef` — see `@alineo-labs/memory`'s
144
+ * `ResourceRef.teamId`. Unset by default (unlike `resourceId`, which always gets
145
+ * `spec.name` as its own default) — most agents aren't tied to a team-scoped memory.
146
+ * `Alineo.load()`/`.resume()` also thread this into `SandboxOptions.teamId`/
147
+ * `RestoreSnapshotOptions.teamId` so it stays consistent with the ledger, not just
148
+ * `.resourceRef` — otherwise a team-scoped agent's own episodic history would be
149
+ * unreachable through its own `resourceRef`, since `episodicRecall()` enforces `teamId`
150
+ * strictly. `Alineo.spawn()` passes `SandboxHandle.fork()`'s `resourceId`/`teamId` override
151
+ * (see its own doc comment) so a spawned child's ledger record matches its
152
+ * `.resourceRef` too, rather than silently inheriting the parent's.
147
153
  */
148
- shell?: string;
154
+ teamId?: string;
155
+ /**
156
+ * Durable resource identity for this agent's `.resourceRef` — see `@alineo-labs/memory`'s
157
+ * `ResourceRef.resourceId`. Defaults to `spec.name` when unset, same as the implicit
158
+ * behavior before this field existed.
159
+ *
160
+ * Exists as its own field, separate from `name`, specifically for `Alineo.spawn()`: a
161
+ * spawned child's `.name` is overwritten to the forked sandbox's auto-generated ledger name
162
+ * (`fork-<parent>-<id>`, used for `alineo agents` display and future fork labeling) — not
163
+ * `childSpec.name`. Without a separate `resourceId` field, a spawned child's memory scope
164
+ * would silently become that auto-generated name instead of the identity the spec author
165
+ * actually declared. `Alineo.spawn()` freezes this to `childSpec.resourceId ?? childSpec.name`
166
+ * before the rename happens, so a spawned child's memory scope is stable and predictable
167
+ * regardless of what the ledger ends up calling the forked sandbox.
168
+ */
169
+ resourceId?: string;
149
170
  }
150
171
  /**
151
- * A named, reusable sandbox environment.
172
+ * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
173
+ * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
174
+ * `.issues` array) rather than a bare `Error` — see #185.
175
+ */
176
+ declare function validateAgentSpec(data: unknown): AgentSpec;
177
+ //#endregion
178
+ //#region src/types.d.ts
179
+ /**
180
+ * A single event emitted by an agent stream. Discriminated on `type`.
152
181
  *
153
- * Created via `client.environment(name, opts)`. The first call to `env.sandbox()`
154
- * runs the setup recipe, snapshots the result, and caches the snapshot ID in the
155
- * ledger. Subsequent calls restore from that snapshot — skipping setup entirely.
182
+ * - `text` — a chunk of Pi's text response (assistant prose)
183
+ * - `tool_start` — Pi started executing a tool (bash, file write, etc.)
184
+ * - `tool_update` — streaming progress from an in-flight tool execution
185
+ * - `tool_end` — a tool finished; `result` holds its output, `isError` whether it failed
186
+ * - `extension_ui` — a Pi extension requested UI interaction; dialog requests are
187
+ * auto-cancelled by the bridge so Pi never stalls, but the event is forwarded so
188
+ * callers can observe what was requested
189
+ * - `auto_retry_start` — Pi is about to retry after a transient error (429, 5xx)
190
+ * - `auto_retry_end` — Pi's retry sequence completed (success or exhausted)
191
+ * - `agent_start` — Pi began processing the prompt
192
+ * - `agent_end` — Pi finished the full agent run (all turns complete)
193
+ * - `turn_start` — a new LLM turn began
194
+ * - `turn_end` — a turn completed with its assistant message and tool results
195
+ * - `message_start` — a new assistant message began streaming
196
+ * - `message_update` — streaming delta from an in-flight message; `delta` is the raw
197
+ * Pi assistantMessageEvent (text_delta, thinking_delta, tool_call_delta, etc.)
198
+ * - `message_end` — an assistant message completed
199
+ * - `queue_update` — the steering/follow-up queue changed (e.g. after `followUp()`)
200
+ * - `compaction_start` — Pi began compacting context (manual or auto)
201
+ * - `compaction_end` — context compaction finished
202
+ * - `extension_error` — a Pi extension threw an error
203
+ */
204
+ type AgentEvent = {
205
+ type: "text";
206
+ text: string;
207
+ } | {
208
+ type: "tool_start";
209
+ toolCallId: string;
210
+ toolName: string;
211
+ args: unknown;
212
+ } | {
213
+ type: "tool_update";
214
+ toolCallId: string;
215
+ toolName: string;
216
+ partialResult: unknown;
217
+ } | {
218
+ type: "tool_end";
219
+ toolCallId: string;
220
+ toolName: string;
221
+ result: unknown;
222
+ isError: boolean;
223
+ } | {
224
+ type: "extension_ui";
225
+ method: string;
226
+ params: unknown;
227
+ isDialog: boolean;
228
+ requestId?: string;
229
+ } | {
230
+ type: "auto_retry_start";
231
+ attempt: number;
232
+ maxAttempts: number;
233
+ delayMs: number;
234
+ errorMessage: string;
235
+ } | {
236
+ type: "auto_retry_end";
237
+ success: boolean;
238
+ attempt: number;
239
+ finalError?: string;
240
+ } | {
241
+ type: "agent_start";
242
+ } | {
243
+ type: "agent_end";
244
+ messages: unknown[];
245
+ } | {
246
+ type: "turn_start";
247
+ turnIndex: number;
248
+ timestamp: number;
249
+ } | {
250
+ type: "turn_end";
251
+ turnIndex: number;
252
+ message: unknown;
253
+ toolResults: unknown[];
254
+ } | {
255
+ type: "message_start";
256
+ message: unknown;
257
+ } | {
258
+ type: "message_update";
259
+ message: unknown;
260
+ delta: unknown;
261
+ } | {
262
+ type: "message_end";
263
+ message: unknown;
264
+ } | {
265
+ type: "queue_update";
266
+ steering: string[];
267
+ followUp: string[];
268
+ } | {
269
+ type: "compaction_start";
270
+ reason: "manual" | "threshold" | "overflow";
271
+ } | {
272
+ type: "compaction_end";
273
+ reason: "manual" | "threshold" | "overflow";
274
+ result: {
275
+ summary: string;
276
+ firstKeptEntryId: string;
277
+ tokensBefore: number;
278
+ estimatedTokensAfter: number;
279
+ details: unknown;
280
+ } | null;
281
+ aborted: boolean;
282
+ willRetry: boolean;
283
+ } | {
284
+ type: "extension_error";
285
+ extensionPath: string;
286
+ event: string;
287
+ error: string;
288
+ };
289
+ /**
290
+ * Async iterable of structured agent events. Returned by `Alineo.prompt()` and `Alineo.bash()`.
291
+ *
292
+ * Use `textOnly()` to filter down to just the text chunks:
156
293
  *
157
- * @example
158
294
  * ```ts
159
- * const env = client.environment("python", {
160
- * image: "debian:bookworm-slim",
161
- * resources: { cpu: "500m", memory: "512Mi" },
162
- * setup: async (sb) => {
163
- * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
164
- * await sb.exec("pip install numpy pandas");
165
- * },
166
- * });
295
+ * for await (const chunk of textOnly(agent.prompt("Hello"))) {
296
+ * process.stdout.write(chunk);
297
+ * }
298
+ * ```
167
299
  *
168
- * const sb = await env.sandbox();
169
- * try {
170
- * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
171
- * } finally {
172
- * await sb.close();
300
+ * Or iterate the full stream to observe tool calls:
301
+ *
302
+ * ```ts
303
+ * for await (const ev of agent.prompt("Build a widget")) {
304
+ * if (ev.type === "text") process.stdout.write(ev.text);
305
+ * else if (ev.type === "tool_start") console.log("Pi is running:", ev.toolName, ev.args);
306
+ * else if (ev.type === "tool_end") console.log("Tool done, isError:", ev.isError);
173
307
  * }
174
308
  * ```
175
309
  */
176
- declare class Environment {
177
- /** The environment name, as passed to `client.environment()`. */
178
- readonly name: string;
179
- private readonly opts;
180
- private readonly client;
181
- constructor(/** The environment name, as passed to `client.environment()`. */
182
-
183
- name: string, opts: EnvironmentOptions, client: Alineo);
310
+ type AgentStream = AsyncIterable<AgentEvent>;
311
+ /** Filter an `AgentStream` down to just text chunks. */
312
+ declare function textOnly(stream: AgentStream): AsyncIterable<string>;
313
+ /**
314
+ * @deprecated Use `AgentStream`. `PromptStream` will be removed in a future minor.
315
+ */
316
+ type PromptStream = AsyncIterable<string>;
317
+ /**
318
+ * A Pi model as returned by `getAvailableModels`, `setModel`, and (nested in
319
+ * `{ model, thinkingLevel, isScoped } | null`) `cycleModel`.
320
+ */
321
+ interface PiModel {
322
+ id: string;
323
+ api: string;
324
+ [key: string]: unknown;
325
+ }
326
+ /** Thinking (reasoning) level supported by models that have extended thinking. */
327
+ type ThinkingLevel = "none" | "low" | "medium" | "high";
328
+ /** A single message in Pi's conversation history, as returned by `getMessages`. */
329
+ interface PiMessage {
330
+ role: "user" | "assistant";
331
+ [key: string]: unknown;
332
+ }
333
+ /** Result of a `compact` operation. */
334
+ interface CompactResult {
335
+ summary: string;
336
+ firstKeptEntryId: string;
337
+ tokensBefore: number;
338
+ estimatedTokensAfter: number;
339
+ }
340
+ /** Session statistics returned by `agent.getSessionStats()`. */
341
+ interface SessionStats {
342
+ sessionFile?: string;
343
+ sessionId: string;
344
+ userMessages: number;
345
+ assistantMessages: number;
346
+ toolCalls: number;
347
+ toolResults: number;
348
+ totalMessages: number;
349
+ tokens: {
350
+ input: number;
351
+ output: number;
352
+ cacheRead: number;
353
+ cacheWrite: number;
354
+ total: number;
355
+ };
356
+ cost: number;
357
+ contextUsage?: {
358
+ tokens: number;
359
+ contextWindow: number;
360
+ percent: number;
361
+ };
362
+ }
363
+ /** A Pi slash command as returned by `agent.getCommands()`. */
364
+ interface PiSlashCommand {
365
+ name: string;
366
+ description?: string;
367
+ source: "extension" | "prompt" | "skill";
368
+ sourceInfo: unknown;
369
+ }
370
+ /** Pi's current session state, as returned by `agent.getState()`. */
371
+ interface PiSessionState {
372
+ model?: PiModel;
373
+ thinkingLevel: ThinkingLevel;
374
+ isStreaming: boolean;
375
+ isCompacting: boolean;
376
+ steeringMode: "all" | "one-at-a-time";
377
+ followUpMode: "all" | "one-at-a-time";
378
+ sessionFile?: string;
379
+ sessionId: string;
380
+ sessionName?: string;
381
+ autoCompactionEnabled: boolean;
382
+ messageCount: number;
383
+ pendingMessageCount: number;
384
+ }
385
+ //#endregion
386
+ //#region src/adapters/pi.d.ts
387
+ declare class PiAdapter {
388
+ private _bridgeUrl;
184
389
  /**
185
- * Return a sandbox pre-configured with this environment.
390
+ * Controllers for prompt/bash streams `sseStream` deliberately left open (its early
391
+ * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
392
+ * documents — see that method's comment). `AbortController.abort()`, not
393
+ * `reader.cancel()`: Bun's `fetch()` tears down the underlying connection (and unrefs the
394
+ * poll keeping the event loop alive) reliably on an abort signal, but was observed to
395
+ * leave the socket referenced after `reader.cancel()` alone on this bridge's specific
396
+ * long-lived, heartbeat-pinged connections (unlike execd's exec/code streams, which
397
+ * self-resolve within execd's own bounded post-completion sleep either way — see
398
+ * disposeConnections() below).
186
399
  *
187
- * First call: runs the setup recipe (~30–60 s), snapshots the result.
188
- * Subsequent calls: restores from snapshot (~2–3 s), no setup re-run.
189
- * Concurrent first calls share a single build — setup runs exactly once.
400
+ * Known limitation: this reliably lets a process exit after exactly one prompt()/bash()
401
+ * call per agent lifetime (verified). A script making two or more such calls before
402
+ * close() can still hang even though every controller here does abort cleanly on the
403
+ * client side -- root cause traced to the same class of bug as
404
+ * opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination confusing the
405
+ * OpenSandbox control server's own proxy relay, which is what `bridgeUrl` is proxied
406
+ * through). Tracked in our own #189; not fixable from this file alone.
190
407
  */
191
- sandbox(extra?: EnvironmentSandboxOptions): Promise<Sandbox$1>;
408
+ private pendingStreams;
409
+ private get bridgeUrl();
192
410
  /**
193
- * Force a full rebuild of the environment, regardless of any cached snapshot.
194
- * Use this after changing the setup recipe.
411
+ * Force-close any prompt/bash streams `sseStream` deliberately left open (its early
412
+ * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
413
+ * documents — see that method's comment). Those connections sit ESTABLISHED, keeping
414
+ * Bun's event loop alive indefinitely, until something force-closes them -- unlike
415
+ * execd's exec/code streams (see `ExecClient.disposeConnections()`), the bridge's own
416
+ * `: ping` heartbeat (every 3s, see pi-bridge.js) means there's no bounded server-side
417
+ * timeout to eventually resolve a dangling one on its own. Call this once the agent is
418
+ * being torn down anyway (from `agent.close()`) instead of leaving the process to hang
419
+ * forever on whichever stream's `[DONE]` arrived last.
195
420
  */
196
- rebuild(): Promise<void>;
421
+ disposeConnections(): void;
422
+ /** Install Pi CLI and any spec packages. Slow — result is captured by checkpoint(). */
423
+ install(sb: SandboxHandle, spec: AgentSpec): Promise<void>;
197
424
  /**
198
- * Return the cached environment record, or `null` if the environment has not
199
- * been built yet.
425
+ * Write config files and the bridge script. Always runs on every start (fresh install
426
+ * and snapshot resume alike) so env values, model/provider, and bridge code stay current.
200
427
  */
201
- info(): Promise<EnvironmentRecord$2 | null>;
428
+ configure(sb: SandboxHandle, spec: AgentSpec, resolvedEnv: Record<string, string>, opts?: {
429
+ resume?: boolean;
430
+ }): Promise<void>;
431
+ /**
432
+ * Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the
433
+ * *same* exec command that starts `node` — required for `Alineo.spawn()`'s forked
434
+ * sandboxes, where the container's OS-level env still carries whatever the parent
435
+ * had baked into it at snapshot time (`env` passed to `createSandbox` at fork time
436
+ * has no effect on this — verified live, see `plans/alineo-rlm-substrate.md`). A
437
+ * plain `sb.exec("unset ...")` beforehand would not work: `unset` only clears the
438
+ * shell session it runs in, and each `exec()` call is its own session — it has to
439
+ * be part of the exact command that spawns the bridge process so the bridge (and
440
+ * everything it in turn spawns, including Pi itself) inherits the already-clean env.
441
+ */
442
+ startBridge(sb: SandboxHandle, unsetVars?: string[]): Promise<void>;
443
+ waitReady(timeoutMs?: number): Promise<void>;
444
+ prompt(message: string, opts?: {
445
+ streamingBehavior?: "steer" | "followUp";
446
+ inactivityTimeoutMs?: number;
447
+ }): AgentStream;
448
+ bash(command: string): AgentStream;
449
+ steer(message: string): Promise<void>;
450
+ abort(): Promise<void>;
451
+ followUp(message: string): Promise<void>;
452
+ newSession(): Promise<void>;
453
+ setThinkingLevel(level: ThinkingLevel): Promise<void>;
454
+ setAutoCompaction(enabled: boolean): Promise<void>;
455
+ setAutoRetry(enabled: boolean): Promise<void>;
456
+ abortRetry(): Promise<void>;
457
+ abortBash(): Promise<void>;
458
+ getSessionStats(): Promise<SessionStats>;
459
+ getLastAssistantText(): Promise<string | null>;
460
+ getForkMessages(): Promise<{
461
+ entryId: string;
462
+ text: string;
463
+ }[]>;
464
+ getCommands(): Promise<PiSlashCommand[]>;
465
+ setSessionName(name: string): Promise<void>;
466
+ setSteeringMode(mode: "all" | "one-at-a-time"): Promise<void>;
467
+ setFollowUpMode(mode: "all" | "one-at-a-time"): Promise<void>;
468
+ exportHtml(outputPath?: string): Promise<{
469
+ path: string;
470
+ }>;
471
+ fork(entryId: string): Promise<{
472
+ text: string;
473
+ cancelled: boolean;
474
+ }>;
475
+ clone(): Promise<{
476
+ cancelled: boolean;
477
+ }>;
478
+ switchSession(sessionPath: string): Promise<{
479
+ cancelled: boolean;
480
+ }>;
481
+ setModel(provider: string, modelId: string): Promise<PiModel>;
482
+ cycleModel(): Promise<{
483
+ model: PiModel;
484
+ thinkingLevel: ThinkingLevel;
485
+ isScoped: boolean;
486
+ } | null>;
487
+ cycleThinkingLevel(): Promise<{
488
+ level: ThinkingLevel;
489
+ } | null>;
490
+ compact(customInstructions?: string): Promise<CompactResult>;
491
+ getMessages(): Promise<PiMessage[]>;
492
+ getAvailableModels(): Promise<PiModel[]>;
493
+ getState(): Promise<PiSessionState>;
494
+ reloadEnv(env: Record<string, string>): Promise<void>;
495
+ getLogs(): Promise<string>;
496
+ }
497
+ //#endregion
498
+ //#region src/snapshots.d.ts
499
+ interface AgentSnapshotRecord {
500
+ specName: string;
501
+ setupHash: string;
502
+ /** OpenSandbox snapshot ID returned by `sb.checkpoint()`. Pass to `client.restoreSnapshot()`. */
503
+ snapshotId: string;
504
+ createdAt: number;
505
+ }
506
+ /**
507
+ * Hash of the fields that require re-installing the agent CLI or rerunning
508
+ * setup: cli, cliVersion, packages, and setup. Excludes env (hot-reloadable),
509
+ * model/provider (CLI flags only), and cosmetic fields.
510
+ */
511
+ declare function computeSetupHash(spec: AgentSpec): string;
512
+ /** Derive the agent-snapshots.json path from the ledger adapter path. */
513
+ declare function snapshotsPath(adapterPath: string): string;
514
+ /** File-backed store for agent snapshot records, keyed by specName + setupHash. */
515
+ declare class AgentSnapshotStore {
516
+ private readonly path;
517
+ constructor(path: string);
518
+ private _read;
519
+ private _write;
520
+ private _key;
521
+ get(specName: string, setupHash: string): Promise<AgentSnapshotRecord | null>;
522
+ save(record: AgentSnapshotRecord): Promise<void>;
523
+ /** Remove all snapshot records for the given spec name. */
524
+ delete(specName: string): Promise<void>;
525
+ list(): Promise<AgentSnapshotRecord[]>;
202
526
  }
203
527
  //#endregion
204
- //#region src/client.d.ts
528
+ //#region src/agent/agent.d.ts
205
529
  /**
206
- * Main entry point for alineo. Manages sandbox lifecycle and session history.
530
+ * A live AI coding agent running inside an OpenSandbox container.
531
+ *
532
+ * Wraps a Pi CLI process (`pi --mode rpc --approve`) in an HTTP bridge so the
533
+ * host can send prompts and receive streamed responses over a stable API,
534
+ * while Pi manages its own tool use, file writes, and code execution inside the
535
+ * sandbox.
536
+ *
537
+ * Create an agent with `Alineo.load(spec)`. Always call `close()` when done
538
+ * to release the underlying sandbox container.
207
539
  *
208
540
  * @example
209
541
  * ```ts
210
542
  * import { Alineo } from "alineo";
211
- * import { SQLiteAdapter } from "@alineo-labs/sqlite";
212
- *
213
- * const client = new Alineo({
214
- * baseUrl: "http://localhost:8080",
215
- * adapter: new SQLiteAdapter("./alineo.db"),
216
- * });
217
543
  *
218
- * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
219
- * await sb.exec("npm ci");
220
- * await sb.checkpoint();
221
- * await sb.exec("npm test").pipe(process.stdout);
222
- * await sb.close();
544
+ * const spec = await Bun.file("./agents/my-agent.json").json();
545
+ * const agent = await Alineo.load(spec, { adapter });
546
+ * try {
547
+ * for await (const chunk of agent.prompt("Explain this codebase")) {
548
+ * process.stdout.write(chunk);
549
+ * }
550
+ * } finally {
551
+ * await agent.close();
552
+ * }
223
553
  * ```
224
554
  */
225
555
  declare class Alineo {
226
- private readonly _control;
227
- private readonly _adapter;
228
- private readonly _maxConcurrency;
229
- private readonly _useServerProxy;
230
- private _activeCount;
231
- private readonly _waiters;
232
- private _connectPromise;
233
- private _adapterClosed;
234
- private readonly _envBuilds;
235
- constructor(options: AlineoOptions);
236
- /** Lazily initialises the adapter on first use. Concurrent callers share the same promise. */
237
- private _ensureConnected;
238
- /**
239
- * Create a new sandbox container and return a live `Sandbox` object.
556
+ /** OpenSandbox container ID for this agent's sandbox. */
557
+ readonly sandboxId: string;
558
+ readonly name: string;
559
+ /**
560
+ * Direct access to the underlying `SandboxHandle` — full alineo SandboxHandle API, bypasses Pi.
561
+ * Use this to read or write files, run shell commands, or inspect container state
562
+ * independently of the Pi conversation.
563
+ */
564
+ readonly sandbox: SandboxHandle;
565
+ /**
566
+ * `true` when this agent was loaded from a cached snapshot (fast path).
567
+ * `false` on the first load for a given spec, or after `{ rebuild: true }`.
568
+ */
569
+ readonly fromSnapshot: boolean;
570
+ readonly adapter: PiAdapter;
571
+ env: Record<string, string>;
572
+ /**
573
+ * Identifies the logical run this agent's sandbox belongs to — see
574
+ * `SandboxDetails.runId`. Always present; a fresh `crypto.randomUUID()` if not
575
+ * explicitly passed to `load()`/`resume()`. A child from `.spawn()` (and
576
+ * transitively, `alineo fork`) always inherits its parent's `runId`.
577
+ */
578
+ readonly runId: string;
579
+ /**
580
+ * Optional provider-agnostic memory (`@alineo-labs/memory`), wired in via `opts.memory` on
581
+ * `load()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
582
+ * constructs a `Memory` on your own behalf, matching this package's "own the pipeline,
583
+ * don't assume a backend" design. `spawn()` carries the parent's `memory` (if any) onto the
584
+ * child automatically, the same way it force-computes spawn-depth rather than reading it
585
+ * back off the child's own spec.
586
+ */
587
+ memory?: Memory;
588
+ /**
589
+ * Durable team identity for `.resourceRef` — see `AgentSpec.teamId`. `undefined` unless the
590
+ * spec this agent was loaded from set it.
591
+ */
592
+ readonly teamId: string | undefined;
593
+ /**
594
+ * Durable resource identity for `.resourceRef` — see `AgentSpec.resourceId`. Deliberately
595
+ * separate from `.name`: for a spawned child specifically, `.name` gets overwritten to the
596
+ * forked sandbox's auto-generated ledger name (`fork-<parent>-<id>`), which is NOT what
597
+ * memory should be scoped by — see `AgentSpec.resourceId`'s own doc comment for why.
598
+ */
599
+ readonly resourceId: string;
600
+ /**
601
+ * Convenience `ResourceRef` scoping `.memory` calls to this agent. `resourceId`/`teamId`
602
+ * come from `AgentSpec.resourceId`/`AgentSpec.teamId` (`resourceId` defaulting to this
603
+ * agent's `name` when unset) — `load()`/`resume()`/`spawn()` also thread both into the
604
+ * ledger (see each field's own doc comment) so this getter and the agent's own episodic
605
+ * history stay consistent, including across a spawned child whose `.name` differs from its
606
+ * memory identity.
240
607
  *
241
- * Waits until the container reaches `Running` state before returning.
242
- * Call `sb.close()` when done to release resources (use try/finally).
608
+ * Only meaningful once `.memory` is set; pass a different `ResourceRef` explicitly to
609
+ * `.memory` methods instead if this agent's resourceId/teamId aren't the identity you want.
610
+ */
611
+ get resourceRef(): ResourceRef;
612
+ private constructor();
613
+ /**
614
+ * Validate `spec` and return a fully initialised `Alineo`.
243
615
  *
244
- * @example
245
- * ```ts
246
- * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
247
- * try {
248
- * await sb.exec("npm ci");
249
- * await sb.exec("npm test").pipe(process.stdout);
250
- * } finally {
251
- * await sb.close();
252
- * }
253
- * ```
616
+ * `spec` is an already-parsed object, not a file path — `alineo` no longer does its own
617
+ * file I/O here (see #184). Read one from disk yourself first (`await
618
+ * Bun.file(path).json()`), fetch it over HTTP, pull it from a database, or build it
619
+ * programmatically — however you get it, pass the object. It's validated internally
620
+ * regardless (via `validateAgentSpec()`), so a raw `JSON.parse()`'d object works fine; you
621
+ * don't need to call `validateAgentSpec()` yourself first unless you want validation errors
622
+ * to surface before any sandbox/network work starts.
623
+ *
624
+ * On first load the Pi CLI is installed inside a `node:22` sandbox, then
625
+ * the sandbox is checkpointed. Subsequent `load()` calls for the same spec
626
+ * restore from that snapshot — skipping the install and starting in ~3s instead
627
+ * of ~90s.
628
+ *
629
+ * Pass `{ rebuild: true }` to force a full reinstall (e.g. after changing
630
+ * the spec's `packages` or `cliVersion`).
631
+ *
632
+ * Pass `{ spawnDepth }` to override the spec's own `spawnDepth` (e.g. a
633
+ * `--depth` CLI flag) — standard flag-beats-config precedence. Same for
634
+ * `{ maxAgents }` and `--max`.
635
+ *
636
+ * Logs timing for each phase to stdout via `[agent]` prefixed lines.
254
637
  */
255
- sandbox(opts: SandboxOptions): Promise<Sandbox$1>;
638
+ static load(spec: AgentSpec | Record<string, unknown>, opts: {
639
+ adapter: IStorageAdapter;
640
+ rebuild?: boolean;
641
+ spawnDepth?: number;
642
+ maxAgents?: number;
643
+ runId?: string; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
644
+ memory?: Memory;
645
+ }): Promise<Alineo>;
256
646
  /**
257
- * Resume a sandbox session from its last checkpoint.
647
+ * Reconnect to a previously-created agent whose host process has exited.
648
+ *
649
+ * The sandbox container must still be running. Pi and any installed packages
650
+ * are already present — only the bridge process needs to be restarted.
651
+ * Pi is started with `--continue` so it resumes the most recent session.
258
652
  *
259
- * Restores an OpenSandbox container from the snapshot captured by the most
260
- * recent `sb.checkpoint()` call. Execs that completed before the checkpoint
261
- * are returned from ledger cache without re-running; subsequent execs run
262
- * against the restored container.
653
+ * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
654
+ * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
655
+ * `load()`. Takes precedence over `opts.specPath` if both are set.
656
+ * @param opts.specPath Path to the agent spec JSON, read and validated internally. If
657
+ * neither `opts.spec` nor `opts.specPath` is set, the ledger is queried for the sandbox's
658
+ * name and the spec is read from `./agents/<name>.json` — this fallback is the one thing
659
+ * `resume()` can do that `load()` can't, since a resumed sandbox's original spec may not be
660
+ * in memory anywhere the caller can hand it over.
263
661
  *
264
662
  * @example
265
663
  * ```ts
266
- * // original session (crashed mid-test)
267
- * const sb = await client.sandbox({ image: "node:22", name: "ci", resources: { cpu: "500m", memory: "256Mi" } });
268
- * await sb.exec("npm ci");
269
- * await sb.checkpoint();
270
- * await sb.exec("npm test"); // container dies here
664
+ * // Original process:
665
+ * const spec = await Bun.file("./agents/hello-agent.json").json();
666
+ * const agent = await Alineo.load(spec, { adapter });
667
+ * console.log(agent.sandboxId); // save this
668
+ * // ... process exits ...
271
669
  *
272
- * // resume later
273
- * const sb2 = await client.resume(originalSessionId);
274
- * await sb2.exec("npm ci"); // instant — replayed from ledger
275
- * await sb2.exec("npm test"); // actually runs on restored container
276
- * await sb2.close();
670
+ * // New process:
671
+ * const agent = await Alineo.resume(savedSandboxId, { adapter });
672
+ * for await (const chunk of agent.prompt("What did we discuss earlier?")) {
673
+ * process.stdout.write(chunk);
674
+ * }
675
+ * await agent.close();
277
676
  * ```
278
677
  */
279
- resume(sandboxId: string, opts?: ResumeOptions): Promise<Sandbox$1>;
280
- private _resumeSession;
678
+ static resume(sandboxId: string, opts: {
679
+ adapter: IStorageAdapter;
680
+ spec?: AgentSpec | Record<string, unknown>;
681
+ specPath?: string;
682
+ runId?: string; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
683
+ memory?: Memory;
684
+ }): Promise<Alineo>;
281
685
  /**
282
- * Attach to an already-running sandbox container without creating or restoring anything.
686
+ * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
687
+ * `resume()`, which kills and restarts the bridge process. Use this when you only
688
+ * need `.spawn()`/`.sandbox`, not `.prompt()`/`.bash()`.
283
689
  *
284
- * Use this to reconnect to a sandbox whose host process has exited but whose container
285
- * is still running. Unlike `resume()`, no snapshot is involved — the container keeps
286
- * its current state. The execd endpoint is resolved lazily on first use.
690
+ * The main caller is `alineo fork`: it runs as a fresh CLI process started BY the
691
+ * very Pi bash-tool call it's attaching to (a master agent spawning a child from
692
+ * inside its own turn). Going through `resume()` there would `pkill` the bridge
693
+ * that's currently running the Pi process making the call — self-destructive.
287
694
  *
288
- * @throws `AlineoError` (409) if the sandbox is not in Running state.
695
+ * The returned `Alineo` has no bridge, so `.prompt()`/`.bash()`/etc. all throw.
696
+ * Its env is read back from `/etc/alineo-env` on the sandbox itself (the ground
697
+ * truth for what's actually running there) rather than re-derived from a spec
698
+ * file, which may not even exist inside this particular sandbox.
289
699
  *
290
- * @param opts.resources CPU/memory/GPU to use if `.fork()` is later called on the
291
- * returned `Sandbox`. The control API doesn't echo back a running sandbox's own
292
- * resource limits, so there's no way to discover them automatically here — omit
293
- * this and `.fork()` will throw. Pass it (e.g. from `alineo.config.json`'s
294
- * defaults) when the caller needs fork support on a merely-connected sandbox.
295
- * @param opts.runId Default run-correlation ID for any later `.fork()` call on the
296
- * returned `Sandbox`. `connect()` has no way to discover the sandbox's original
297
- * `runId` (no ledger lookup is attempted — the caller may be using a completely
298
- * different adapter than whatever originally created it, as `alineo fork` does when
299
- * self-attaching). Omit this and pass `runId` explicitly to `.fork()` itself instead.
700
+ * When `sandboxId` matches `ALINEO_SANDBOX_ID` in this process's own env (true
701
+ * self-attach, e.g. `alineo fork` running from inside its own container),
702
+ * `/etc/alineo-env` is read straight off the local filesystem instead of via
703
+ * `sb.readFile()`. A self-referential exec call would need this sandbox to
704
+ * reach itself through its own externally-facing bridge IP, which Docker's
705
+ * default bridge network generally can't hairpin back to the originating
706
+ * container — sibling-to-sibling traffic works fine, only this exact
707
+ * self-connect case doesn't, and the caller already has the file locally.
300
708
  *
301
- * @example
302
- * ```ts
303
- * // In a new process, reconnect to a sandbox started earlier:
304
- * const sb = await client.connect(savedSandboxId, "my-sandbox");
305
- * const { stdout } = await sb.exec("cat /results.txt");
306
- * await sb.close();
307
- * ```
709
+ * `opts.resources` sizes a subsequent `.spawn()`'s forked container — the
710
+ * control API doesn't echo back a running sandbox's own resource limits, so
711
+ * there's no way to discover this agent's *actual* footprint here. Defaults to
712
+ * `alineo.config.json`'s `defaults.resources`, same fallback `Alineo.load()` uses
713
+ * for a spec that doesn't set its own.
308
714
  */
309
- connect(sandboxId: string, name: string, opts?: {
715
+ static attach(sandboxId: string, opts: {
716
+ adapter: IStorageAdapter;
717
+ name: string;
310
718
  resources?: {
311
719
  cpu: string;
312
720
  memory: string;
313
721
  gpu?: string;
314
- };
315
- runId?: string;
316
- }): Promise<Sandbox$1>;
722
+ }; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
723
+ memory?: Memory;
724
+ }): Promise<Alineo>;
317
725
  /**
318
- * Create a fresh sandbox from a snapshot ID without exec replay.
726
+ * Fork this agent's live sandbox — filesystem, installed packages, checked-out
727
+ * state, everything currently on disk — into a brand-new independent sandbox
728
+ * running its own Pi bridge, per `childSpecPath`. Unlike `Alineo.load()` (always
729
+ * starts from a spec's own snapshot) or `fork()`/`clone()` below (Pi's own
730
+ * conversation-branching — same container, same bridge, new session branch),
731
+ * this is sandbox-level forking: the child sees exactly what this agent's
732
+ * sandbox sees right now, including any uncommitted work.
319
733
  *
320
- * Unlike `resume()`, this does not replay prior exec results — the new sandbox
321
- * starts with a clean exec history. Use this when you want to restore a
322
- * checkpointed environment and run new commands from scratch.
734
+ * The child's environment is resolved fresh from its OWN spec — nothing is
735
+ * inherited from this agent except the spawn-depth counter, which is
736
+ * force-computed (`current - 1`) regardless of what the child's spec or
737
+ * `opts.spawnDepth` says. Every name this agent's own env declares is also
738
+ * explicitly `unset` in the shell command that starts the child's bridge, since
739
+ * the forked container's OS-level env still carries whatever was baked in at
740
+ * snapshot time independent of what gets written to `/etc/alineo-env`.
323
741
  *
324
- * @param snapshotId The snapshot ID returned by `sb.checkpoint()`.
325
- * @param name A name for the new sandbox session in the ledger.
326
- * @param resources CPU and memory for the restored container.
327
- * @param runId Run-correlation ID for the restored sandbox — see `SandboxDetails.runId`.
328
- * Defaults to a fresh `crypto.randomUUID()` if omitted.
742
+ * Refuses immediately unless this agent's own spawn-depth budget
743
+ * (`ALINEO_SPAWN_DEPTH`, or `opts.spawnDepth` to override it) is a positive
744
+ * integer — `0` means no budget left, `undefined` means spawning was never
745
+ * enabled for this agent.
329
746
  *
330
- * @example
331
- * ```ts
332
- * const snapshotId = await sb.checkpoint();
333
- * await sb.close();
747
+ * If `ALINEO_MAX_AGENTS` (or `opts.maxAgents`) is set, also refuses once it
748
+ * hits `0` — a separate, optional ceiling on total descendants for this
749
+ * lineage, independent of nesting depth. Unset means uncapped for this
750
+ * dimension; only `spawnDepth` gates whether spawning is allowed at all.
751
+ * Not coordinated across sibling branches spawned in parallel.
334
752
  *
335
- * // Later — restore and run fresh commands:
336
- * const sb2 = await client.restoreSnapshot(snapshotId, "my-sandbox", { cpu: "500m", memory: "256Mi" });
337
- * await sb2.exec("npm test");
338
- * await sb2.close();
339
- * ```
753
+ * No install/setup steps run — the child inherits Pi (and anything else)
754
+ * already installed on this agent's sandbox. If the child needs packages this
755
+ * agent's own sandbox doesn't have, add them to a setup step on the spec THIS
756
+ * agent was loaded from, not on the child's spec.
340
757
  */
341
- restoreSnapshot(snapshotId: string, name: string, resources: {
342
- cpu: string;
343
- memory: string;
344
- gpu?: string;
345
- }, runId?: string): Promise<Sandbox$1>;
758
+ spawn(childSpecPath: string, opts?: {
759
+ spawnDepth?: number;
760
+ maxAgents?: number;
761
+ }): Promise<Alineo>;
762
+ /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
763
+ prompt(message: string, opts?: {
764
+ streamingBehavior?: "steer" | "followUp";
765
+ inactivityTimeoutMs?: number;
766
+ }): AgentStream;
346
767
  /**
347
- * Sandbox history management. List, inspect, and delete past sandbox records.
348
- *
349
- * @example
350
- * ```ts
351
- * const all = await client.sandboxes.list();
352
- * const details = await client.sandboxes.get("ci", sandboxId);
353
- * await client.sandboxes.delete("ci", sandboxId);
354
- * ```
768
+ * Run a shell command inside Pi's working context. Not incrementally
769
+ * streamed — Pi returns bash output synchronously, so the full output
770
+ * arrives as a single `text` event once the command completes.
355
771
  */
356
- readonly sandboxes: {
357
- /** List all sandbox records across all names, newest first. */list: (opts?: ListSandboxOptions$1) => Promise<SandboxDetails$1[]>; /** List sandbox records for a specific name, newest first. */
358
- listByName: (name: string, opts?: ListSandboxOptions$1) => Promise<SandboxDetails$1[]>; /** Return details for a single sandbox record. Returns `null` if not found. */
359
- get: (name: string, sandboxId: string) => Promise<SandboxDetails$1 | null>; /** Delete all ledger events for a sandbox. */
360
- delete: (name: string, sandboxId: string) => Promise<void>;
361
- };
772
+ bash(command: string): AgentStream;
773
+ /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
774
+ steer(message: string): Promise<void>;
775
+ /** Abort Pi's current operation. */
776
+ abort(): Promise<void>;
777
+ /** Queue a message to be sent to Pi after it finishes its current task. */
778
+ followUp(message: string): Promise<void>;
779
+ /** Start a fresh Pi session, clearing all prior context. */
780
+ newSession(): Promise<void>;
781
+ /** Set Pi's reasoning level (for models that support extended thinking). */
782
+ setThinkingLevel(level: ThinkingLevel): Promise<void>;
783
+ /** Enable or disable Pi's automatic context compaction. */
784
+ setAutoCompaction(enabled: boolean): Promise<void>;
362
785
  /**
363
- * Define a named, reusable sandbox environment.
364
- *
365
- * Returns an `Environment` object — no I/O happens here. The first call to
366
- * `env.sandbox()` builds the environment (runs setup + snapshots), then caches
367
- * the snapshot ID in the ledger. Subsequent calls restore from that snapshot.
368
- *
369
- * @example
370
- * ```ts
371
- * const env = client.environment("python", {
372
- * image: "debian:bookworm-slim",
373
- * resources: { cpu: "500m", memory: "512Mi" },
374
- * setup: async (sb) => {
375
- * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
376
- * await sb.exec("pip install numpy pandas");
377
- * },
378
- * });
379
- *
380
- * const sb = await env.sandbox();
381
- * try {
382
- * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
383
- * } finally {
384
- * await sb.close();
385
- * }
386
- * ```
786
+ * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
787
+ * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
788
+ * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
789
+ * events in the stream.
387
790
  */
388
- environment(name: string, opts: EnvironmentOptions): Environment;
791
+ setAutoRetry(enabled: boolean): Promise<void>;
389
792
  /**
390
- * Environment management. List and delete cached environment records.
391
- *
392
- * @example
393
- * ```ts
394
- * const envs = await client.environments.list();
395
- * await client.environments.delete("python");
396
- * ```
793
+ * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
794
+ * operation, emitting `auto_retry_end` with `success: false`.
397
795
  */
398
- readonly environments: {
399
- /** Return all environment records, newest first. */list: () => Promise<EnvironmentRecord$1[]>; /** Remove the ledger record for a named environment. Does not delete the server-side snapshot. */
400
- delete: (name: string) => Promise<void>;
401
- };
402
- _envInfo(name: string): Promise<EnvironmentRecord$1 | null>;
403
- _envRebuild(name: string, opts: EnvironmentOptions): Promise<void>;
404
- _envSandbox(name: string, opts: EnvironmentOptions, extra?: EnvironmentSandboxOptions): Promise<Sandbox$1>;
405
- _getOrBuildEnvironment(name: string, opts: EnvironmentOptions): Promise<string>;
406
- _buildEnvironment(name: string, opts: EnvironmentOptions): Promise<string>;
407
- _createFromSnapshot(snapshotId: string, resources: {
408
- cpu: string;
409
- memory: string;
410
- gpu?: string;
411
- }, envName: string, envShell?: string, extra?: EnvironmentSandboxOptions): Promise<Sandbox$1>;
412
- private _forkFromSnapshot;
413
- private _waitForRunning;
414
- private _acquireSlot;
415
- private _releaseSlot;
796
+ abortRetry(): Promise<void>;
797
+ /** Abort a currently-executing bash command without cancelling the whole prompt. */
798
+ abortBash(): Promise<void>;
799
+ /** Retrieve token usage, cost, and message counts for the current session. */
800
+ getSessionStats(): Promise<SessionStats>;
801
+ /** Retrieve the text of Pi's most recent assistant response. Returns `null` if none yet. */
802
+ getLastAssistantText(): Promise<string | null>;
803
+ /**
804
+ * List the fork entry points available in the current session.
805
+ * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
806
+ */
807
+ getForkMessages(): Promise<{
808
+ entryId: string;
809
+ text: string;
810
+ }[]>;
811
+ /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
812
+ getCommands(): Promise<PiSlashCommand[]>;
813
+ /** Set a display name for the current Pi session. */
814
+ setSessionName(name: string): Promise<void>;
815
+ /**
816
+ * Control how Pi processes queued steering messages.
817
+ * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
818
+ */
819
+ setSteeringMode(mode: "all" | "one-at-a-time"): Promise<void>;
820
+ /**
821
+ * Control how Pi processes queued follow-up messages.
822
+ * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
823
+ */
824
+ setFollowUpMode(mode: "all" | "one-at-a-time"): Promise<void>;
825
+ /**
826
+ * Export a static HTML transcript of the current session to the sandbox filesystem.
827
+ * Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
828
+ * to retrieve it.
829
+ */
830
+ exportHtml(outputPath?: string): Promise<{
831
+ path: string;
832
+ }>;
833
+ /**
834
+ * Fork Pi's session at the given entry ID, creating a new branch.
835
+ * Returns the text of the forked message and whether the fork was cancelled.
836
+ */
837
+ fork(entryId: string): Promise<{
838
+ text: string;
839
+ cancelled: boolean;
840
+ }>;
841
+ /** Clone the current Pi session into a new branch at the current position. */
842
+ clone(): Promise<{
843
+ cancelled: boolean;
844
+ }>;
845
+ /** Switch Pi to a different session file on disk. */
846
+ switchSession(sessionPath: string): Promise<{
847
+ cancelled: boolean;
848
+ }>;
849
+ /** Switch Pi to a specific model. Returns the activated model. */
850
+ setModel(provider: string, modelId: string): Promise<PiModel>;
851
+ /** Cycle Pi to the next available model. Returns null if only one model is configured. */
852
+ cycleModel(): Promise<{
853
+ model: PiModel;
854
+ thinkingLevel: ThinkingLevel;
855
+ isScoped: boolean;
856
+ } | null>;
857
+ /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
858
+ cycleThinkingLevel(): Promise<{
859
+ level: ThinkingLevel;
860
+ } | null>;
861
+ /** Manually trigger Pi's context compaction. */
862
+ compact(customInstructions?: string): Promise<CompactResult>;
863
+ /** Retrieve Pi's full conversation history for the current session. */
864
+ getMessages(): Promise<PiMessage[]>;
865
+ /** List all models available to Pi under the current provider configuration. */
866
+ getAvailableModels(): Promise<PiModel[]>;
867
+ /**
868
+ * Retrieve Pi's current session state: active model, thinking level, streaming/compaction
869
+ * status, queue modes, and session identity. The only piece of Pi's RPC surface with no
870
+ * other way to observe the *current* model or thinking level (as opposed to the full list).
871
+ */
872
+ getState(): Promise<PiSessionState>;
873
+ /**
874
+ * Set or update env vars in the running container. Writes to /etc/alineo-env and restarts
875
+ * the Pi subprocess so it picks up the new env. Waits until Pi is ready before returning.
876
+ */
877
+ setEnv(vars: Record<string, string>): Promise<void>;
878
+ /** Retrieve recent bridge logs (ring-buffered, last 200 entries). */
879
+ getLogs(): Promise<string>;
880
+ /** Delete the sandbox container and release all resources. Always call in a `finally` block. */
881
+ close(): Promise<void>;
882
+ }
883
+ //#endregion
884
+ //#region src/errors.d.ts
885
+ /**
886
+ * Thrown when a prompt/bash SSE stream from a sandbox's Pi bridge goes quiet for longer than
887
+ * the configured inactivity window -- no real `AgentEvent` (only the bridge's own `: ping`
888
+ * keep-alives, which exist purely to defeat OpenSandbox's proxy idle-timeout and say nothing
889
+ * about whether Pi itself is making progress) for that long. Previously this surfaced as an
890
+ * indefinite hang with zero visibility: `sseStream()` had no timeout at all, so a genuinely
891
+ * stuck Pi process (e.g. blocked in a credential refresh, or any other silent stall) blocked
892
+ * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo fork --prompt` --
893
+ * forever, with no error and no partial output.
894
+ */
895
+ declare class PromptTimeoutError extends WorkflowError {
896
+ readonly timeoutMs: number;
897
+ readonly bridgeUrl: string;
898
+ constructor(timeoutMs: number, bridgeUrl: string);
899
+ }
900
+ /**
901
+ * Thrown by `validateAgentSpec()` when a spec object fails schema validation. Carries every
902
+ * failing field in one pass (`.issues`, mirroring `z.ZodIssue[]` shape) rather than surfacing
903
+ * only the first problem found -- see #185. `.message` is a pre-formatted, human-readable
904
+ * multi-line summary (via `z.prettifyError()`) suitable for printing as-is; `.issues` is for
905
+ * callers that want to handle failures programmatically (e.g. highlight specific fields in a UI).
906
+ */
907
+ declare class AgentSpecValidationError extends WorkflowError {
908
+ readonly issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[];
909
+ constructor(message: string, issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[]);
416
910
  }
417
911
  //#endregion
418
- export { Alineo, AlineoError, type AlineoOptions, BashSession, type CheckpointInfo, CodeLanguage, CommandError, type DiagnosticEvent, type DiagnosticLog, Environment, type EnvironmentOptions, type EnvironmentRecord, type EnvironmentSandboxOptions, type ExecCodeOptions, ExecConnectionError, type ExecHandle, type ExecOptions, type ExecResult, type FileInfo, type IStorageAdapter, type InteractiveExecHandle, type LedgerEntry, LedgerEvent, type ListSandboxOptions, type Metrics, type PendingInteractiveExec, type ResumeOptions, Sandbox, type SandboxDetails, SandboxError, type SandboxOptions, SandboxStatus, StepTimeoutError };
912
+ export { type AgentEvent, type AgentSnapshotRecord, AgentSnapshotStore, type AgentSpec, AgentSpecValidationError, type AgentStream, Alineo, type CompactResult, type PiMessage, type PiModel, type PiSessionState, type PiSlashCommand, type PromptStream, PromptTimeoutError, type SessionStats, type SetupStep, type ThinkingLevel, computeSetupHash, snapshotsPath, textOnly, validateAgentSpec };