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