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.mjs CHANGED
@@ -1,657 +1,1307 @@
1
- import { BashSession, CommandError, ExecConnectionError, LedgerEvent, LedgerEvent as LedgerEvent$1, Sandbox, Sandbox as Sandbox$1, SandboxError, SandboxStatus, StepTimeoutError } from "@alineo-labs/core";
2
- import { CodeLanguage, ControlClient, SandboxState, SnapshotState } from "@alineo-labs/opensandbox";
3
- //#region src/types.ts
1
+ import { Sandbox } from "@alineo-labs/sandbox";
2
+ import { readFileSync } from "node:fs";
3
+ import { existsSync } from "fs";
4
+ import * as z$1 from "zod";
5
+ import { WorkflowError } from "@alineo-labs/core";
6
+ import { fileURLToPath } from "node:url";
7
+ import { createHash } from "node:crypto";
8
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
9
+ import { dirname } from "node:path";
10
+ //#region src/config.ts
11
+ const CONFIG_FILE = "alineo.config.json";
12
+ const DEFAULT_CONFIG = {
13
+ serverUrl: "http://127.0.0.1:8080",
14
+ apiKey: "",
15
+ adapterPath: "./.alineo/ledger.db",
16
+ useServerProxy: true,
17
+ agentsDir: "./agents",
18
+ defaults: { resources: {
19
+ cpu: "1000m",
20
+ memory: "1Gi"
21
+ } }
22
+ };
23
+ /**
24
+ * Read `alineo.config.json` from the current working directory and merge it with
25
+ * built-in defaults. Missing fields fall back to the defaults — the config file
26
+ * is fully optional.
27
+ */
28
+ async function readProjectConfig() {
29
+ if (!existsSync(CONFIG_FILE)) return DEFAULT_CONFIG;
30
+ const data = await Bun.file(CONFIG_FILE).json();
31
+ return {
32
+ ...DEFAULT_CONFIG,
33
+ ...data,
34
+ defaults: {
35
+ ...DEFAULT_CONFIG.defaults,
36
+ ...data.defaults ?? {},
37
+ resources: {
38
+ ...DEFAULT_CONFIG.defaults.resources,
39
+ ...data.defaults?.resources ?? {}
40
+ }
41
+ }
42
+ };
43
+ }
44
+ //#endregion
45
+ //#region src/errors.ts
46
+ /**
47
+ * Thrown when a prompt/bash SSE stream from a sandbox's Pi bridge goes quiet for longer than
48
+ * the configured inactivity window -- no real `AgentEvent` (only the bridge's own `: ping`
49
+ * keep-alives, which exist purely to defeat OpenSandbox's proxy idle-timeout and say nothing
50
+ * about whether Pi itself is making progress) for that long. Previously this surfaced as an
51
+ * indefinite hang with zero visibility: `sseStream()` had no timeout at all, so a genuinely
52
+ * stuck Pi process (e.g. blocked in a credential refresh, or any other silent stall) blocked
53
+ * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo fork --prompt` --
54
+ * forever, with no error and no partial output.
55
+ */
56
+ var PromptTimeoutError = class extends WorkflowError {
57
+ timeoutMs;
58
+ bridgeUrl;
59
+ constructor(timeoutMs, bridgeUrl) {
60
+ super(`Prompt produced no activity for ${timeoutMs / 1e3}s (bridge ${bridgeUrl}) -- the underlying agent process may be stuck`);
61
+ this.timeoutMs = timeoutMs;
62
+ this.bridgeUrl = bridgeUrl;
63
+ this.name = "PromptTimeoutError";
64
+ }
65
+ };
4
66
  /**
5
- * Client-side SDK error carrying an HTTP-style status code, thrown for
6
- * invariant/state failures such as a sandbox missing from the local ledger
7
- * (404), a sandbox not in `Running` state (409), or a client-side timeout
8
- * (408). This does not wrap non-2xx OpenSandbox API responses — those throw
9
- * `OpenSandboxError` from `@alineo-labs/opensandbox`, which is never rethrown as a
10
- * `AlineoError`.
67
+ * Thrown by `validateAgentSpec()` when a spec object fails schema validation. Carries every
68
+ * failing field in one pass (`.issues`, mirroring `z.ZodIssue[]` shape) rather than surfacing
69
+ * only the first problem found -- see #185. `.message` is a pre-formatted, human-readable
70
+ * multi-line summary (via `z.prettifyError()`) suitable for printing as-is; `.issues` is for
71
+ * callers that want to handle failures programmatically (e.g. highlight specific fields in a UI).
11
72
  */
12
- var AlineoError = class extends Error {
13
- status;
14
- constructor(message, status) {
73
+ var AgentSpecValidationError = class extends WorkflowError {
74
+ issues;
75
+ constructor(message, issues) {
15
76
  super(message);
16
- this.status = status;
17
- this.name = "AlineoError";
77
+ this.issues = issues;
78
+ this.name = "AgentSpecValidationError";
18
79
  }
19
80
  };
20
81
  //#endregion
21
- //#region src/environment.ts
82
+ //#region src/schema.ts
22
83
  /**
23
- * A named, reusable sandbox environment.
24
- *
25
- * Created via `client.environment(name, opts)`. The first call to `env.sandbox()`
26
- * runs the setup recipe, snapshots the result, and caches the snapshot ID in the
27
- * ledger. Subsequent calls restore from that snapshot — skipping setup entirely.
28
- *
29
- * @example
30
- * ```ts
31
- * const env = client.environment("python", {
32
- * image: "debian:bookworm-slim",
33
- * resources: { cpu: "500m", memory: "512Mi" },
34
- * setup: async (sb) => {
35
- * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
36
- * await sb.exec("pip install numpy pandas");
37
- * },
38
- * });
39
- *
40
- * const sb = await env.sandbox();
41
- * try {
42
- * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
43
- * } finally {
44
- * await sb.close();
45
- * }
46
- * ```
84
+ * Runtime schema for `SetupStep`/`AgentSpec` above. Kept as a separate Zod schema rather than
85
+ * generating the interfaces from it (`z.infer<>`) so the hand-written interfaces above can carry
86
+ * full field-level JSDoc — TypeScript doesn't propagate comments through generic type inference,
87
+ * and that documentation is load-bearing (it's what IDE hover/autocomplete shows spec authors).
88
+ * If you add/change/remove a field on `AgentSpec`/`SetupStep`, update the matching schema field
89
+ * here too — `packages/agent/test/schema.test.ts` is the drift check.
47
90
  */
48
- var Environment = class {
49
- name;
50
- opts;
51
- client;
52
- constructor(name, opts, client) {
53
- this.name = name;
54
- this.opts = opts;
55
- this.client = client;
56
- }
91
+ const SetupStepSchema = z$1.object({
92
+ name: z$1.string({ error: "Each setup step must have a 'name' string" }),
93
+ run: z$1.string({ error: "Each setup step must have a 'run' string" }),
94
+ cwd: z$1.string().optional()
95
+ }).loose();
96
+ const nonNegativeIntSpecField = (fieldName) => z$1.number({ error: `Agent spec '${fieldName}' must be a non-negative integer if set` }).int(`Agent spec '${fieldName}' must be a non-negative integer if set`).nonnegative(`Agent spec '${fieldName}' must be a non-negative integer if set`).optional();
97
+ const AgentSpecSchema = z$1.object({
98
+ $schema: z$1.string().optional(),
99
+ name: z$1.string({ error: (issue) => issue.input === void 0 ? "Agent spec must have a 'name' string" : "Agent spec 'name' must be a string" }).min(1, "Agent spec must have a 'name' string"),
100
+ title: z$1.string().optional(),
101
+ description: z$1.string().optional(),
102
+ author: z$1.string().optional(),
103
+ categories: z$1.array(z$1.string()).optional(),
104
+ cli: z$1.literal("pi", { error: (issue) => issue.input === void 0 ? "Agent spec must have a 'cli' field. Supported values: pi" : `Unsupported CLI: '${String(issue.input)}'. Supported values: pi` }),
105
+ cliVersion: z$1.string().optional(),
106
+ provider: z$1.string().optional(),
107
+ model: z$1.string().optional(),
108
+ packages: z$1.array(z$1.string()).optional(),
109
+ env: z$1.record(z$1.string(), z$1.string()).optional(),
110
+ resources: z$1.object({
111
+ cpu: z$1.string(),
112
+ memory: z$1.string(),
113
+ gpu: z$1.string().optional()
114
+ }).optional(),
115
+ metadata: z$1.record(z$1.string(), z$1.string()).optional(),
116
+ registryDependencies: z$1.array(z$1.string()).optional(),
117
+ setup: z$1.array(SetupStepSchema).optional(),
118
+ spawnDepth: nonNegativeIntSpecField("spawnDepth"),
119
+ maxAgents: nonNegativeIntSpecField("maxAgents")
120
+ }).loose();
121
+ /**
122
+ * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
123
+ * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
124
+ * `.issues` array) rather than a bare `Error` — see #185.
125
+ */
126
+ function validateAgentSpec(data) {
127
+ const result = AgentSpecSchema.safeParse(data);
128
+ if (!result.success) throw new AgentSpecValidationError(`Invalid agent spec:\n${z$1.prettifyError(result.error)}`, result.error.issues.map((issue) => ({
129
+ path: issue.path,
130
+ message: issue.message,
131
+ code: issue.code
132
+ })));
133
+ return result.data;
134
+ }
135
+ //#endregion
136
+ //#region src/adapters/pi.ts
137
+ const BRIDGE_SCRIPT = readFileSync(fileURLToPath(new URL("./pi-bridge.js", import.meta.url)), "utf8");
138
+ function toShellExports(env) {
139
+ return Object.entries(env).map(([k, v]) => `export ${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join("\n") + "\n";
140
+ }
141
+ function resolveEnv(env) {
142
+ const result = {};
143
+ for (const [key, value] of Object.entries(env)) result[key] = value.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? "");
144
+ return result;
145
+ }
146
+ /** Inverse of `toShellExports` — parses `/etc/alineo-env`'s content back into a plain object. */
147
+ function parseShellExports(content) {
148
+ const result = {};
149
+ const re = /^export ([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"$/gm;
150
+ let m;
151
+ while (m = re.exec(content)) result[m[1]] = m[2].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
152
+ return result;
153
+ }
154
+ var PiAdapter = class {
155
+ _bridgeUrl = null;
57
156
  /**
58
- * Return a sandbox pre-configured with this environment.
157
+ * Controllers for prompt/bash streams `sseStream` deliberately left open (its early
158
+ * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
159
+ * documents — see that method's comment). `AbortController.abort()`, not
160
+ * `reader.cancel()`: Bun's `fetch()` tears down the underlying connection (and unrefs the
161
+ * poll keeping the event loop alive) reliably on an abort signal, but was observed to
162
+ * leave the socket referenced after `reader.cancel()` alone on this bridge's specific
163
+ * long-lived, heartbeat-pinged connections (unlike execd's exec/code streams, which
164
+ * self-resolve within execd's own bounded post-completion sleep either way — see
165
+ * disposeConnections() below).
59
166
  *
60
- * First call: runs the setup recipe (~30–60 s), snapshots the result.
61
- * Subsequent calls: restores from snapshot (~2–3 s), no setup re-run.
62
- * Concurrent first calls share a single build — setup runs exactly once.
167
+ * Known limitation: this reliably lets a process exit after exactly one prompt()/bash()
168
+ * call per agent lifetime (verified). A script making two or more such calls before
169
+ * close() can still hang even though every controller here does abort cleanly on the
170
+ * client side -- root cause traced to the same class of bug as
171
+ * opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination confusing the
172
+ * OpenSandbox control server's own proxy relay, which is what `bridgeUrl` is proxied
173
+ * through). Tracked in our own #189; not fixable from this file alone.
174
+ */
175
+ pendingStreams = /* @__PURE__ */ new Set();
176
+ get bridgeUrl() {
177
+ if (!this._bridgeUrl) throw new Error("PiAdapter: bridge not started");
178
+ return this._bridgeUrl;
179
+ }
180
+ /**
181
+ * Force-close any prompt/bash streams `sseStream` deliberately left open (its early
182
+ * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
183
+ * documents — see that method's comment). Those connections sit ESTABLISHED, keeping
184
+ * Bun's event loop alive indefinitely, until something force-closes them -- unlike
185
+ * execd's exec/code streams (see `ExecClient.disposeConnections()`), the bridge's own
186
+ * `: ping` heartbeat (every 3s, see pi-bridge.js) means there's no bounded server-side
187
+ * timeout to eventually resolve a dangling one on its own. Call this once the agent is
188
+ * being torn down anyway (from `agent.close()`) instead of leaving the process to hang
189
+ * forever on whichever stream's `[DONE]` arrived last.
63
190
  */
64
- sandbox(extra) {
65
- return this.client._envSandbox(this.name, this.opts, extra);
191
+ disposeConnections() {
192
+ for (const controller of this.pendingStreams) controller.abort();
193
+ this.pendingStreams.clear();
194
+ }
195
+ /** Install Pi CLI and any spec packages. Slow — result is captured by checkpoint(). */
196
+ async install(sb, spec) {
197
+ const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
198
+ if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
199
+ const versionSpecifier = spec.cliVersion?.trim();
200
+ const pkg = versionSpecifier ? `@earendil-works/pi-coding-agent@${versionSpecifier}` : "@earendil-works/pi-coding-agent";
201
+ await sb.exec(`npm install -g --ignore-scripts ${pkg}`);
66
202
  }
67
203
  /**
68
- * Force a full rebuild of the environment, regardless of any cached snapshot.
69
- * Use this after changing the setup recipe.
204
+ * Write config files and the bridge script. Always runs on every start (fresh install
205
+ * and snapshot resume alike) so env values, model/provider, and bridge code stay current.
70
206
  */
71
- rebuild() {
72
- return this.client._envRebuild(this.name, this.opts);
207
+ async configure(sb, spec, resolvedEnv, opts) {
208
+ const piConfig = {};
209
+ if (spec.provider) piConfig.provider = spec.provider;
210
+ if (spec.model) piConfig.model = spec.model;
211
+ if (opts?.resume) piConfig.resume = true;
212
+ await sb.writeFile("/etc/alineo-pi.json", JSON.stringify(piConfig));
213
+ await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
214
+ await sb.writeFile("/alineo-bridge.js", BRIDGE_SCRIPT);
73
215
  }
74
216
  /**
75
- * Return the cached environment record, or `null` if the environment has not
76
- * been built yet.
217
+ * Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the
218
+ * *same* exec command that starts `node` — required for `Alineo.spawn()`'s forked
219
+ * sandboxes, where the container's OS-level env still carries whatever the parent
220
+ * had baked into it at snapshot time (`env` passed to `createSandbox` at fork time
221
+ * has no effect on this — verified live, see `plans/alineo-rlm-substrate.md`). A
222
+ * plain `sb.exec("unset ...")` beforehand would not work: `unset` only clears the
223
+ * shell session it runs in, and each `exec()` call is its own session — it has to
224
+ * be part of the exact command that spawns the bridge process so the bridge (and
225
+ * everything it in turn spawns, including Pi itself) inherits the already-clean env.
77
226
  */
78
- info() {
79
- return this.client._envInfo(this.name);
227
+ async startBridge(sb, unsetVars) {
228
+ const prefix = unsetVars && unsetVars.length > 0 ? `unset ${unsetVars.join(" ")}; ` : "";
229
+ await sb.exec(`${prefix}node /alineo-bridge.js &`);
230
+ const { url } = await sb.proxy(3001);
231
+ this._bridgeUrl = url;
232
+ }
233
+ async waitReady(timeoutMs = 3e4) {
234
+ const deadline = Date.now() + timeoutMs;
235
+ while (Date.now() < deadline) {
236
+ try {
237
+ const res = await fetch(`${this.bridgeUrl}/health`);
238
+ if (res.ok) {
239
+ if ((await res.json()).ok) return;
240
+ }
241
+ } catch {}
242
+ await new Promise((r) => setTimeout(r, 500));
243
+ }
244
+ throw new Error(`alineo-bridge did not become ready within ${timeoutMs / 1e3}s`);
245
+ }
246
+ prompt(message, opts) {
247
+ return sseStream(this.bridgeUrl, "/prompt", {
248
+ message,
249
+ streamingBehavior: opts?.streamingBehavior
250
+ }, this.pendingStreams, opts?.inactivityTimeoutMs);
251
+ }
252
+ bash(command) {
253
+ return sseStream(this.bridgeUrl, "/bash", { command }, this.pendingStreams);
254
+ }
255
+ async steer(message) {
256
+ const res = await fetch(`${this.bridgeUrl}/steer`, {
257
+ method: "POST",
258
+ headers: { "Content-Type": "application/json" },
259
+ body: JSON.stringify({ message })
260
+ });
261
+ if (!res.ok) {
262
+ const body = await res.json().catch(() => ({}));
263
+ throw new Error(`steer failed: ${body.error ?? res.status}`);
264
+ }
265
+ }
266
+ async abort() {
267
+ await rpcPost(this.bridgeUrl, "/abort");
268
+ }
269
+ async followUp(message) {
270
+ await rpcPost(this.bridgeUrl, "/follow-up", { message });
271
+ }
272
+ async newSession() {
273
+ await rpcPost(this.bridgeUrl, "/new-session");
274
+ }
275
+ async setThinkingLevel(level) {
276
+ await rpcPost(this.bridgeUrl, "/set-thinking-level", { level });
277
+ }
278
+ async setAutoCompaction(enabled) {
279
+ await rpcPost(this.bridgeUrl, "/set-auto-compaction", { enabled });
280
+ }
281
+ async setAutoRetry(enabled) {
282
+ await rpcPost(this.bridgeUrl, "/set-auto-retry", { enabled });
283
+ }
284
+ async abortRetry() {
285
+ await rpcPost(this.bridgeUrl, "/abort-retry");
286
+ }
287
+ async abortBash() {
288
+ await rpcPost(this.bridgeUrl, "/abort-bash");
289
+ }
290
+ async getSessionStats() {
291
+ return rpcPost(this.bridgeUrl, "/get-session-stats");
292
+ }
293
+ async getLastAssistantText() {
294
+ return (await rpcPost(this.bridgeUrl, "/get-last-assistant-text")).text;
295
+ }
296
+ async getForkMessages() {
297
+ return (await rpcPost(this.bridgeUrl, "/get-fork-messages")).messages;
298
+ }
299
+ async getCommands() {
300
+ return (await rpcPost(this.bridgeUrl, "/get-commands")).commands;
301
+ }
302
+ async setSessionName(name) {
303
+ await rpcPost(this.bridgeUrl, "/set-session-name", { name });
304
+ }
305
+ async setSteeringMode(mode) {
306
+ await rpcPost(this.bridgeUrl, "/set-steering-mode", { mode });
307
+ }
308
+ async setFollowUpMode(mode) {
309
+ await rpcPost(this.bridgeUrl, "/set-follow-up-mode", { mode });
310
+ }
311
+ async exportHtml(outputPath) {
312
+ return rpcPost(this.bridgeUrl, "/export-html", outputPath !== void 0 ? { outputPath } : {});
313
+ }
314
+ async fork(entryId) {
315
+ return rpcPost(this.bridgeUrl, "/fork", { entryId });
316
+ }
317
+ async clone() {
318
+ return rpcPost(this.bridgeUrl, "/clone");
319
+ }
320
+ async switchSession(sessionPath) {
321
+ return rpcPost(this.bridgeUrl, "/switch-session", { sessionPath });
322
+ }
323
+ async setModel(provider, modelId) {
324
+ return rpcPost(this.bridgeUrl, "/set-model", {
325
+ provider,
326
+ modelId
327
+ });
328
+ }
329
+ async cycleModel() {
330
+ return rpcPost(this.bridgeUrl, "/cycle-model");
331
+ }
332
+ async cycleThinkingLevel() {
333
+ return rpcPost(this.bridgeUrl, "/cycle-thinking-level");
334
+ }
335
+ async compact(customInstructions) {
336
+ return rpcPost(this.bridgeUrl, "/compact", { customInstructions });
337
+ }
338
+ async getMessages() {
339
+ return (await rpcGet(this.bridgeUrl, "/messages")).messages;
340
+ }
341
+ async getAvailableModels() {
342
+ return (await rpcGet(this.bridgeUrl, "/available-models")).models;
343
+ }
344
+ async getState() {
345
+ return rpcGet(this.bridgeUrl, "/state");
346
+ }
347
+ async reloadEnv(env) {
348
+ await rpcPost(this.bridgeUrl, "/reload-env", { env });
349
+ await this.waitReady();
350
+ }
351
+ async getLogs() {
352
+ return (await fetch(`${this.bridgeUrl}/logs`)).text();
353
+ }
354
+ };
355
+ async function rpcPost(bridgeUrl, path, body = {}) {
356
+ const res = await fetch(`${bridgeUrl}${path}`, {
357
+ method: "POST",
358
+ headers: { "Content-Type": "application/json" },
359
+ body: JSON.stringify(body)
360
+ });
361
+ if (!res.ok) {
362
+ const err = await res.json().catch(() => ({}));
363
+ throw new Error(`${path} failed: ${err.error ?? res.status}`);
364
+ }
365
+ return (await res.json()).data;
366
+ }
367
+ async function rpcGet(bridgeUrl, path) {
368
+ const res = await fetch(`${bridgeUrl}${path}`);
369
+ if (!res.ok) throw new Error(`${path} failed: ${res.status}`);
370
+ return (await res.json()).data;
371
+ }
372
+ /**
373
+ * How long to tolerate zero real `AgentEvent`s before treating the stream as stuck. The
374
+ * bridge's own `: ping` keep-alive (every 3s, see pi-bridge.js's `startHeartbeat`) exists only
375
+ * to defeat OpenSandbox's proxy idle-timeout -- it keeps `reader.read()` resolving regardless
376
+ * of whether Pi itself is making progress, so this can't just be "no read() in N seconds". The
377
+ * timer below is instead reset only when a real event is parsed and yielded (or `[DONE]`
378
+ * arrives), so a connection that's alive-but-silent for this long still times out.
379
+ *
380
+ * 60s (the original default) was too tight for a common, legitimate pattern: Pi's own `bash`
381
+ * tool is not incrementally streamed (see the `bash()` doc comment in session-control.ts), so
382
+ * a single tool call that spins up a whole child sandbox -- e.g. a master session running
383
+ * `alineo fork` on itself, as in examples/rlm-repo-fanout -- produces zero AgentEvents for as
384
+ * long as that tool call takes, which regularly exceeded 60s (child sandbox provisioning +
385
+ * Pi CLI install alone routinely took 30-150s+ in practice) and tripped this timeout mid-run
386
+ * even though the session was making real progress. Raised to 3 minutes as a still-bounded
387
+ * but realistic ceiling for that pattern; pass `inactivityTimeoutMs` explicitly to `prompt()`
388
+ * for sessions that need something tighter or looser.
389
+ */
390
+ const DEFAULT_INACTIVITY_TIMEOUT_MS = 18e4;
391
+ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeoutMs = DEFAULT_INACTIVITY_TIMEOUT_MS) {
392
+ const controller = new AbortController();
393
+ const res = await fetch(`${bridgeUrl}${path}`, {
394
+ method: "POST",
395
+ headers: { "Content-Type": "application/json" },
396
+ body: JSON.stringify(body),
397
+ signal: controller.signal,
398
+ keepalive: false
399
+ });
400
+ if (!res.ok || !res.body) throw new Error(`Bridge ${path} error: ${res.status}`);
401
+ pendingStreams.add(controller);
402
+ const reader = res.body.getReader();
403
+ const decoder = new TextDecoder();
404
+ let buf = "";
405
+ let lastEventAt = Date.now();
406
+ let reachedNaturalEnd = false;
407
+ try {
408
+ while (true) {
409
+ const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
410
+ if (remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
411
+ const result = await Promise.race([reader.read(), new Promise((resolve) => setTimeout(() => resolve("timeout"), remainingMs))]);
412
+ if (result === "timeout") throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
413
+ const { done, value } = result;
414
+ if (done) {
415
+ reachedNaturalEnd = true;
416
+ break;
417
+ }
418
+ buf += decoder.decode(value, { stream: true });
419
+ const lines = buf.split("\n");
420
+ buf = lines.pop();
421
+ for (const line of lines) {
422
+ if (!line.startsWith("data: ")) continue;
423
+ const payload = line.slice(6).trim();
424
+ if (payload === "[DONE]") return;
425
+ const raw = JSON.parse(payload);
426
+ if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
427
+ lastEventAt = Date.now();
428
+ yield raw;
429
+ }
430
+ }
431
+ } finally {
432
+ if (reachedNaturalEnd) {
433
+ pendingStreams.delete(controller);
434
+ reader.releaseLock();
435
+ }
436
+ }
437
+ }
438
+ //#endregion
439
+ //#region src/snapshots.ts
440
+ /**
441
+ * Hash of the fields that require re-installing the agent CLI or rerunning
442
+ * setup: cli, cliVersion, packages, and setup. Excludes env (hot-reloadable),
443
+ * model/provider (CLI flags only), and cosmetic fields.
444
+ */
445
+ function computeSetupHash(spec) {
446
+ return createHash("sha256").update(JSON.stringify({
447
+ cli: spec.cli,
448
+ cliVersion: spec.cliVersion ?? "latest",
449
+ packages: [...spec.packages ?? []].sort(),
450
+ setup: spec.setup ?? []
451
+ })).digest("hex").slice(0, 12);
452
+ }
453
+ /** Derive the agent-snapshots.json path from the ledger adapter path. */
454
+ function snapshotsPath(adapterPath) {
455
+ return `${dirname(adapterPath)}/agent-snapshots.json`;
456
+ }
457
+ /** File-backed store for agent snapshot records, keyed by specName + setupHash. */
458
+ var AgentSnapshotStore = class {
459
+ path;
460
+ constructor(path) {
461
+ this.path = path;
462
+ }
463
+ async _read() {
464
+ try {
465
+ return JSON.parse(await readFile(this.path, "utf-8"));
466
+ } catch {
467
+ return {};
468
+ }
469
+ }
470
+ async _write(data) {
471
+ await mkdir(dirname(this.path), { recursive: true });
472
+ await writeFile(this.path, JSON.stringify(data, null, 2));
473
+ }
474
+ _key(specName, setupHash) {
475
+ return `${specName}:${setupHash}`;
476
+ }
477
+ async get(specName, setupHash) {
478
+ return (await this._read())[this._key(specName, setupHash)] ?? null;
479
+ }
480
+ async save(record) {
481
+ const data = await this._read();
482
+ for (const k of Object.keys(data)) if (data[k].specName === record.specName) delete data[k];
483
+ data[this._key(record.specName, record.setupHash)] = record;
484
+ await this._write(data);
485
+ }
486
+ /** Remove all snapshot records for the given spec name. */
487
+ async delete(specName) {
488
+ const data = await this._read();
489
+ for (const k of Object.keys(data)) if (data[k].specName === specName) delete data[k];
490
+ await this._write(data);
491
+ }
492
+ async list() {
493
+ return Object.values(await this._read());
80
494
  }
81
495
  };
82
496
  //#endregion
83
- //#region src/client.ts
497
+ //#region src/agent/validation.ts
498
+ function assertValidSpawnDepth(value, context) {
499
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${context}: spawnDepth must be a non-negative integer (got ${value})`);
500
+ }
501
+ function assertValidMaxAgents(value, context) {
502
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${context}: maxAgents must be a non-negative integer (got ${value})`);
503
+ }
504
+ /**
505
+ * Resolves and validates the spawn-depth budget available to `Alineo.spawn()` —
506
+ * `override` (a `--depth` CLI flag) wins if given, else whatever value was
507
+ * materialised into `ALINEO_SPAWN_DEPTH` by `Alineo.load()`/`Alineo.resume()`. Throws
508
+ * unless the result is a positive integer: `0` means "no budget left", not "spawn
509
+ * one more time" — spawning stops one level before the counter would go negative.
510
+ */
511
+ function resolveParentSpawnDepth(envValue, override) {
512
+ const raw = override ?? (envValue !== void 0 ? Number(envValue) : void 0);
513
+ if (raw === void 0 || !Number.isInteger(raw) || raw <= 0) throw new Error(`Alineo.spawn() refused: spawn depth must be a positive integer (got ${envValue ?? "unset"}). Set "spawnDepth" in this agent's spec, or pass { spawnDepth } explicitly.`);
514
+ return raw;
515
+ }
516
+ /**
517
+ * Resolves the max-agents budget for `Alineo.spawn()` — same tamper-resistant
518
+ * env-counter shape as `resolveParentSpawnDepth`, but optional: `undefined`
519
+ * means "no cap enforced for this dimension," not "spawning refused."
520
+ * `spawnDepth` alone still gates whether spawning is allowed at all; this is
521
+ * an independent, additive ceiling on total descendants for THIS lineage —
522
+ * sibling branches spawned in parallel don't share this budget.
523
+ */
524
+ function resolveParentMaxAgents(envValue, override) {
525
+ const raw = override ?? (envValue !== void 0 ? Number(envValue) : void 0);
526
+ if (raw === void 0) return void 0;
527
+ if (!Number.isInteger(raw) || raw < 0) throw new Error(`Alineo.spawn() refused: maxAgents must be a non-negative integer (got ${raw}).`);
528
+ return raw;
529
+ }
530
+ //#endregion
531
+ //#region src/agent/factory.ts
532
+ function elapsed(t) {
533
+ return `${Date.now() - t}ms`;
534
+ }
535
+ /**
536
+ * Validate `specInput` and return everything needed to construct a fully initialised `Alineo`.
537
+ * See `Alineo.load()` for the public-facing docs.
538
+ */
539
+ async function loadAgent(specInput, opts) {
540
+ const t0 = Date.now();
541
+ const spec = validateAgentSpec(specInput);
542
+ const config = await readProjectConfig();
543
+ const resolvedEnv = resolveEnv(spec.env ?? {});
544
+ const effectiveSpawnDepth = opts.spawnDepth ?? spec.spawnDepth;
545
+ if (effectiveSpawnDepth !== void 0) {
546
+ assertValidSpawnDepth(effectiveSpawnDepth, "Alineo.load()");
547
+ resolvedEnv.ALINEO_SPAWN_DEPTH = String(effectiveSpawnDepth);
548
+ }
549
+ const effectiveMaxAgents = opts.maxAgents ?? spec.maxAgents;
550
+ if (effectiveMaxAgents !== void 0) {
551
+ assertValidMaxAgents(effectiveMaxAgents, "Alineo.load()");
552
+ resolvedEnv.ALINEO_MAX_AGENTS = String(effectiveMaxAgents);
553
+ }
554
+ const runId = opts.runId ?? crypto.randomUUID();
555
+ resolvedEnv.ALINEO_RUN_ID = runId;
556
+ const resources = {
557
+ ...config.defaults.resources,
558
+ ...spec.resources ?? {}
559
+ };
560
+ const client = new Sandbox({
561
+ baseUrl: config.serverUrl,
562
+ apiKey: config.apiKey,
563
+ adapter: opts.adapter,
564
+ useServerProxy: config.useServerProxy
565
+ });
566
+ const store = new AgentSnapshotStore(snapshotsPath(config.adapterPath));
567
+ const setupHash = computeSetupHash(spec);
568
+ const adapter = new PiAdapter();
569
+ let sb;
570
+ let fromSnapshot = false;
571
+ if (!opts.rebuild) {
572
+ const record = await store.get(spec.name, setupHash);
573
+ if (record) try {
574
+ console.log(`[agent] restoring from snapshot...`);
575
+ const t1 = Date.now();
576
+ sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId);
577
+ console.log(`[agent] snapshot ready ${elapsed(t1)} (${sb.sandboxId})`);
578
+ fromSnapshot = true;
579
+ } catch (err) {
580
+ const reason = err instanceof Error ? err.message : String(err);
581
+ console.log(`[agent] snapshot restore failed (${reason}), rebuilding...`);
582
+ await store.delete(spec.name);
583
+ }
584
+ }
585
+ if (!fromSnapshot) {
586
+ console.log(`[agent] starting sandbox (${spec.name})...`);
587
+ const t1 = Date.now();
588
+ sb = await client.sandbox({
589
+ image: "node:22",
590
+ resources,
591
+ name: spec.name,
592
+ env: resolvedEnv,
593
+ runId
594
+ });
595
+ console.log(`[agent] sandbox ready ${elapsed(t1)} (${sb.sandboxId})`);
596
+ console.log(`[agent] installing Pi CLI...`);
597
+ const t2 = Date.now();
598
+ await adapter.install(sb, spec);
599
+ console.log(`[agent] Pi CLI ready ${elapsed(t2)}`);
600
+ for (const step of spec.setup ?? []) {
601
+ console.log(`[agent] setup: ${step.name}...`);
602
+ const ts = Date.now();
603
+ const cmd = step.cwd ? `cd ${step.cwd} && ${step.run}` : step.run;
604
+ await sb.exec(cmd);
605
+ console.log(`[agent] setup done ${elapsed(ts)} (${step.name})`);
606
+ }
607
+ console.log(`[agent] checkpointing...`);
608
+ const t3 = Date.now();
609
+ const snapshotId = await sb.checkpoint();
610
+ await store.save({
611
+ specName: spec.name,
612
+ setupHash,
613
+ snapshotId,
614
+ createdAt: Date.now()
615
+ });
616
+ console.log(`[agent] checkpoint done ${elapsed(t3)}`);
617
+ }
618
+ resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
619
+ await adapter.configure(sb, spec, resolvedEnv);
620
+ console.log(`[agent] starting bridge...`);
621
+ const t4 = Date.now();
622
+ await adapter.startBridge(sb);
623
+ await adapter.waitReady();
624
+ console.log(`[agent] bridge ready ${elapsed(t4)}`);
625
+ console.log(`[agent] total ${elapsed(t0)}${fromSnapshot ? " (from snapshot)" : ""}`);
626
+ return {
627
+ sandbox: sb,
628
+ spec,
629
+ env: resolvedEnv,
630
+ adapter,
631
+ fromSnapshot,
632
+ runId
633
+ };
634
+ }
635
+ /**
636
+ * Reconnect to a previously-created agent whose host process has exited. See
637
+ * `Alineo.resume()` for the public-facing docs.
638
+ */
639
+ async function resumeAgent(sandboxId, opts) {
640
+ const t0 = Date.now();
641
+ const config = await readProjectConfig();
642
+ const client = new Sandbox({
643
+ baseUrl: config.serverUrl,
644
+ apiKey: config.apiKey,
645
+ adapter: opts.adapter,
646
+ useServerProxy: config.useServerProxy
647
+ });
648
+ let spec;
649
+ if (opts.spec) spec = validateAgentSpec(opts.spec);
650
+ else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
651
+ else {
652
+ const session = (await client.sandboxes.list()).find((s) => s.sandboxId === sandboxId);
653
+ if (!session) throw new Error(`No ledger record for sandbox ${sandboxId} — pass opts.spec or opts.specPath explicitly`);
654
+ spec = validateAgentSpec(await Bun.file(`./agents/${session.name}.json`).json());
655
+ }
656
+ const resolvedEnv = resolveEnv(spec.env ?? {});
657
+ if (spec.maxAgents !== void 0) {
658
+ assertValidMaxAgents(spec.maxAgents, "Alineo.resume()");
659
+ resolvedEnv.ALINEO_MAX_AGENTS = String(spec.maxAgents);
660
+ }
661
+ if (spec.spawnDepth !== void 0) {
662
+ assertValidSpawnDepth(spec.spawnDepth, "Alineo.resume()");
663
+ resolvedEnv.ALINEO_SPAWN_DEPTH = String(spec.spawnDepth);
664
+ }
665
+ const runId = opts.runId ?? crypto.randomUUID();
666
+ resolvedEnv.ALINEO_RUN_ID = runId;
667
+ console.log(`[agent] reconnecting to ${sandboxId}...`);
668
+ const t1 = Date.now();
669
+ const sb = await client.connect(sandboxId, spec.name, { runId });
670
+ console.log(`[agent] connected ${elapsed(t1)}`);
671
+ await sb.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
672
+ const adapter = new PiAdapter();
673
+ resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
674
+ await adapter.configure(sb, spec, resolvedEnv, { resume: true });
675
+ console.log(`[agent] starting bridge...`);
676
+ const t2 = Date.now();
677
+ await adapter.startBridge(sb);
678
+ await adapter.waitReady();
679
+ console.log(`[agent] bridge ready ${elapsed(t2)}`);
680
+ console.log(`[agent] total ${elapsed(t0)}`);
681
+ return {
682
+ sandbox: sb,
683
+ spec,
684
+ env: resolvedEnv,
685
+ adapter,
686
+ fromSnapshot: false,
687
+ runId
688
+ };
689
+ }
690
+ /**
691
+ * Connect to an already-running sandbox WITHOUT touching its Pi bridge. See
692
+ * `Alineo.attach()` for the public-facing docs.
693
+ */
694
+ async function attachAgent(sandboxId, opts) {
695
+ const config = await readProjectConfig();
696
+ const client = new Sandbox({
697
+ baseUrl: config.serverUrl,
698
+ apiKey: config.apiKey,
699
+ adapter: opts.adapter,
700
+ useServerProxy: config.useServerProxy
701
+ });
702
+ const resources = opts.resources ?? config.defaults.resources;
703
+ const sb = await client.connect(sandboxId, opts.name, { resources });
704
+ let envFile;
705
+ try {
706
+ envFile = sandboxId === process.env.ALINEO_SANDBOX_ID ? readFileSync("/etc/alineo-env", "utf8") : await sb.readFile("/etc/alineo-env");
707
+ } catch {
708
+ envFile = "";
709
+ }
710
+ const env = parseShellExports(envFile);
711
+ const runId = env.ALINEO_RUN_ID ?? crypto.randomUUID();
712
+ return {
713
+ sandbox: sb,
714
+ spec: {
715
+ name: opts.name,
716
+ cli: "pi"
717
+ },
718
+ env,
719
+ adapter: new PiAdapter(),
720
+ fromSnapshot: false,
721
+ runId
722
+ };
723
+ }
724
+ /**
725
+ * Fork `self`'s live sandbox into a brand-new independent sandbox running its
726
+ * own Pi bridge, per `childSpecPath`. See `Alineo.spawn()` for the public-facing docs.
727
+ */
728
+ async function spawnChild(self, childSpecPath, opts = {}) {
729
+ const parentDepth = resolveParentSpawnDepth(process.env.ALINEO_SPAWN_DEPTH, opts.spawnDepth);
730
+ const parentMax = resolveParentMaxAgents(process.env.ALINEO_MAX_AGENTS, opts.maxAgents);
731
+ if (parentMax !== void 0 && parentMax <= 0) throw new Error(`Alineo.spawn() refused: max-agents budget exhausted (0 remaining).`);
732
+ const childSpec = validateAgentSpec(await Bun.file(childSpecPath).json());
733
+ const childEnv = resolveEnv(childSpec.env ?? {});
734
+ childEnv.ALINEO_SPAWN_DEPTH = String(parentDepth - 1);
735
+ if (parentMax !== void 0) childEnv.ALINEO_MAX_AGENTS = String(parentMax - 1);
736
+ const runId = process.env.ALINEO_RUN_ID ?? crypto.randomUUID();
737
+ childEnv.ALINEO_RUN_ID = runId;
738
+ console.log(`[agent] forking sandbox for spawn (${childSpec.name})...`);
739
+ const t0 = Date.now();
740
+ const forkedSb = await self.sandbox.fork(childSpec.name, runId);
741
+ console.log(`[agent] fork ready ${elapsed(t0)} (${forkedSb.sandboxId})`);
742
+ const adapter = new PiAdapter();
743
+ childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
744
+ await adapter.configure(forkedSb, childSpec, childEnv);
745
+ console.log(`[agent] starting bridge...`);
746
+ const t1 = Date.now();
747
+ await adapter.startBridge(forkedSb, Object.keys(self.env));
748
+ await adapter.waitReady();
749
+ console.log(`[agent] bridge ready ${elapsed(t1)}`);
750
+ return {
751
+ sandbox: forkedSb,
752
+ spec: {
753
+ ...childSpec,
754
+ name: forkedSb.name
755
+ },
756
+ env: childEnv,
757
+ adapter,
758
+ fromSnapshot: false,
759
+ runId
760
+ };
761
+ }
762
+ //#endregion
763
+ //#region src/agent/session-control.ts
764
+ /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
765
+ function prompt(a, message, opts) {
766
+ return a.adapter.prompt(message, opts);
767
+ }
768
+ /**
769
+ * Run a shell command inside Pi's working context. Not incrementally
770
+ * streamed — Pi returns bash output synchronously, so the full output
771
+ * arrives as a single `text` event once the command completes.
772
+ */
773
+ function bash(a, command) {
774
+ return a.adapter.bash(command);
775
+ }
776
+ /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
777
+ async function steer(a, message) {
778
+ return a.adapter.steer(message);
779
+ }
780
+ /** Abort Pi's current operation. */
781
+ async function abort(a) {
782
+ return a.adapter.abort();
783
+ }
784
+ /** Queue a message to be sent to Pi after it finishes its current task. */
785
+ async function followUp(a, message) {
786
+ return a.adapter.followUp(message);
787
+ }
788
+ /** Start a fresh Pi session, clearing all prior context. */
789
+ async function newSession(a) {
790
+ return a.adapter.newSession();
791
+ }
792
+ /** Enable or disable Pi's automatic context compaction. */
793
+ async function setAutoCompaction(a, enabled) {
794
+ return a.adapter.setAutoCompaction(enabled);
795
+ }
796
+ /**
797
+ * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
798
+ * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
799
+ * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
800
+ * events in the stream.
801
+ */
802
+ async function setAutoRetry(a, enabled) {
803
+ return a.adapter.setAutoRetry(enabled);
804
+ }
805
+ /**
806
+ * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
807
+ * operation, emitting `auto_retry_end` with `success: false`.
808
+ */
809
+ async function abortRetry(a) {
810
+ return a.adapter.abortRetry();
811
+ }
812
+ /** Abort a currently-executing bash command without cancelling the whole prompt. */
813
+ async function abortBash(a) {
814
+ return a.adapter.abortBash();
815
+ }
816
+ /**
817
+ * Control how Pi processes queued steering messages.
818
+ * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
819
+ */
820
+ async function setSteeringMode(a, mode) {
821
+ return a.adapter.setSteeringMode(mode);
822
+ }
823
+ /**
824
+ * Control how Pi processes queued follow-up messages.
825
+ * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
826
+ */
827
+ async function setFollowUpMode(a, mode) {
828
+ return a.adapter.setFollowUpMode(mode);
829
+ }
830
+ /** Set a display name for the current Pi session. */
831
+ async function setSessionName(a, name) {
832
+ return a.adapter.setSessionName(name);
833
+ }
834
+ //#endregion
835
+ //#region src/agent/model.ts
836
+ /** Set Pi's reasoning level (for models that support extended thinking). */
837
+ async function setThinkingLevel(a, level) {
838
+ return a.adapter.setThinkingLevel(level);
839
+ }
840
+ /** Switch Pi to a specific model. Returns the activated model. */
841
+ async function setModel(a, provider, modelId) {
842
+ return a.adapter.setModel(provider, modelId);
843
+ }
844
+ /** Cycle Pi to the next available model. Returns null if only one model is configured. */
845
+ async function cycleModel(a) {
846
+ return a.adapter.cycleModel();
847
+ }
848
+ /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
849
+ async function cycleThinkingLevel(a) {
850
+ return a.adapter.cycleThinkingLevel();
851
+ }
852
+ /** List all models available to Pi under the current provider configuration. */
853
+ async function getAvailableModels(a) {
854
+ return a.adapter.getAvailableModels();
855
+ }
856
+ //#endregion
857
+ //#region src/agent/introspection.ts
858
+ /** Retrieve token usage, cost, and message counts for the current session. */
859
+ async function getSessionStats(a) {
860
+ return a.adapter.getSessionStats();
861
+ }
862
+ /** Retrieve the text of Pi's most recent assistant response. Returns `null` if none yet. */
863
+ async function getLastAssistantText(a) {
864
+ return a.adapter.getLastAssistantText();
865
+ }
866
+ /**
867
+ * List the fork entry points available in the current session.
868
+ * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
869
+ */
870
+ async function getForkMessages(a) {
871
+ return a.adapter.getForkMessages();
872
+ }
873
+ /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
874
+ async function getCommands(a) {
875
+ return a.adapter.getCommands();
876
+ }
877
+ /** Retrieve Pi's full conversation history for the current session. */
878
+ async function getMessages(a) {
879
+ return a.adapter.getMessages();
880
+ }
881
+ /**
882
+ * Retrieve Pi's current session state: active model, thinking level, streaming/compaction
883
+ * status, queue modes, and session identity. The only piece of Pi's RPC surface with no
884
+ * other way to observe the *current* model or thinking level (as opposed to the full list).
885
+ */
886
+ async function getState(a) {
887
+ return a.adapter.getState();
888
+ }
889
+ /** Retrieve recent bridge logs (ring-buffered, last 200 entries). */
890
+ async function getLogs(a) {
891
+ return a.adapter.getLogs();
892
+ }
893
+ //#endregion
894
+ //#region src/agent/lifecycle.ts
895
+ /**
896
+ * Fork Pi's session at the given entry ID, creating a new branch.
897
+ * Returns the text of the forked message and whether the fork was cancelled.
898
+ */
899
+ async function fork(a, entryId) {
900
+ return a.adapter.fork(entryId);
901
+ }
902
+ /** Clone the current Pi session into a new branch at the current position. */
903
+ async function clone(a) {
904
+ return a.adapter.clone();
905
+ }
906
+ /** Switch Pi to a different session file on disk. */
907
+ async function switchSession(a, sessionPath) {
908
+ return a.adapter.switchSession(sessionPath);
909
+ }
910
+ /**
911
+ * Export a static HTML transcript of the current session to the sandbox filesystem.
912
+ * Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
913
+ * to retrieve it.
914
+ */
915
+ async function exportHtml(a, outputPath) {
916
+ return a.adapter.exportHtml(outputPath);
917
+ }
918
+ /** Manually trigger Pi's context compaction. */
919
+ async function compact(a, customInstructions) {
920
+ return a.adapter.compact(customInstructions);
921
+ }
922
+ /**
923
+ * Set or update env vars in the running container. Writes to /etc/alineo-env and restarts
924
+ * the Pi subprocess so it picks up the new env. Waits until Pi is ready before returning.
925
+ */
926
+ async function setEnv(a, vars) {
927
+ a.env = {
928
+ ...a.env,
929
+ ...vars
930
+ };
931
+ await a.sandbox.writeFile("/etc/alineo-env", toShellExports(a.env));
932
+ await a.adapter.reloadEnv(a.env);
933
+ }
934
+ /** Delete the sandbox container and release all resources. Always call in a `finally` block. */
935
+ async function close(a) {
936
+ a.adapter.disposeConnections();
937
+ await a.sandbox.close();
938
+ }
939
+ //#endregion
940
+ //#region src/agent/agent.ts
84
941
  /**
85
- * Main entry point for alineo. Manages sandbox lifecycle and session history.
942
+ * A live AI coding agent running inside an OpenSandbox container.
943
+ *
944
+ * Wraps a Pi CLI process (`pi --mode rpc --approve`) in an HTTP bridge so the
945
+ * host can send prompts and receive streamed responses over a stable API,
946
+ * while Pi manages its own tool use, file writes, and code execution inside the
947
+ * sandbox.
948
+ *
949
+ * Create an agent with `Alineo.load(spec)`. Always call `close()` when done
950
+ * to release the underlying sandbox container.
86
951
  *
87
952
  * @example
88
953
  * ```ts
89
954
  * import { Alineo } from "alineo";
90
- * import { SQLiteAdapter } from "@alineo-labs/sqlite";
91
955
  *
92
- * const client = new Alineo({
93
- * baseUrl: "http://localhost:8080",
94
- * adapter: new SQLiteAdapter("./alineo.db"),
95
- * });
96
- *
97
- * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
98
- * await sb.exec("npm ci");
99
- * await sb.checkpoint();
100
- * await sb.exec("npm test").pipe(process.stdout);
101
- * await sb.close();
956
+ * const spec = await Bun.file("./agents/my-agent.json").json();
957
+ * const agent = await Alineo.load(spec, { adapter });
958
+ * try {
959
+ * for await (const chunk of agent.prompt("Explain this codebase")) {
960
+ * process.stdout.write(chunk);
961
+ * }
962
+ * } finally {
963
+ * await agent.close();
964
+ * }
102
965
  * ```
103
966
  */
104
- var Alineo = class {
105
- _control;
106
- _adapter;
107
- _maxConcurrency;
108
- _useServerProxy;
109
- _activeCount = 0;
110
- _waiters = [];
111
- _connectPromise = null;
112
- _adapterClosed = false;
113
- _envBuilds = /* @__PURE__ */ new Map();
114
- constructor(options) {
115
- this._control = new ControlClient({
116
- baseUrl: options.baseUrl,
117
- apiKey: options.apiKey ?? ""
118
- });
119
- this._adapter = options.adapter;
120
- this._maxConcurrency = options.maxConcurrency;
121
- this._useServerProxy = options.useServerProxy ?? false;
122
- process.setMaxListeners(process.getMaxListeners() + 1);
123
- process.on("beforeExit", () => {
124
- if (!this._adapterClosed) {
125
- this._adapterClosed = true;
126
- this._adapter.close?.();
127
- }
128
- });
129
- }
130
- /** Lazily initialises the adapter on first use. Concurrent callers share the same promise. */
131
- _ensureConnected() {
132
- this._connectPromise ??= this._adapter.connect?.() ?? Promise.resolve();
133
- return this._connectPromise;
967
+ var Alineo = class Alineo {
968
+ /** OpenSandbox container ID for this agent's sandbox. */
969
+ sandboxId;
970
+ name;
971
+ /**
972
+ * Direct access to the underlying `SandboxHandle` — full alineo SandboxHandle API, bypasses Pi.
973
+ * Use this to read or write files, run shell commands, or inspect container state
974
+ * independently of the Pi conversation.
975
+ */
976
+ sandbox;
977
+ /**
978
+ * `true` when this agent was loaded from a cached snapshot (fast path).
979
+ * `false` on the first load for a given spec, or after `{ rebuild: true }`.
980
+ */
981
+ fromSnapshot;
982
+ adapter;
983
+ env;
984
+ /**
985
+ * Identifies the logical run this agent's sandbox belongs to — see
986
+ * `SandboxDetails.runId`. Always present; a fresh `crypto.randomUUID()` if not
987
+ * explicitly passed to `load()`/`resume()`. A child from `.spawn()` (and
988
+ * transitively, `alineo fork`) always inherits its parent's `runId`.
989
+ */
990
+ runId;
991
+ constructor(sandbox, spec, env, adapter, fromSnapshot, runId) {
992
+ this.sandbox = sandbox;
993
+ this.sandboxId = sandbox.sandboxId;
994
+ this.name = spec.name;
995
+ this.adapter = adapter;
996
+ this.env = env;
997
+ this.fromSnapshot = fromSnapshot;
998
+ this.runId = runId;
134
999
  }
135
1000
  /**
136
- * Create a new sandbox container and return a live `Sandbox` object.
1001
+ * Validate `spec` and return a fully initialised `Alineo`.
137
1002
  *
138
- * Waits until the container reaches `Running` state before returning.
139
- * Call `sb.close()` when done to release resources (use try/finally).
1003
+ * `spec` is an already-parsed object, not a file path — `alineo` no longer does its own
1004
+ * file I/O here (see #184). Read one from disk yourself first (`await
1005
+ * Bun.file(path).json()`), fetch it over HTTP, pull it from a database, or build it
1006
+ * programmatically — however you get it, pass the object. It's validated internally
1007
+ * regardless (via `validateAgentSpec()`), so a raw `JSON.parse()`'d object works fine; you
1008
+ * don't need to call `validateAgentSpec()` yourself first unless you want validation errors
1009
+ * to surface before any sandbox/network work starts.
140
1010
  *
141
- * @example
142
- * ```ts
143
- * const sb = await client.sandbox({ image: "node:22", resources: { cpu: "500m", memory: "256Mi" } });
144
- * try {
145
- * await sb.exec("npm ci");
146
- * await sb.exec("npm test").pipe(process.stdout);
147
- * } finally {
148
- * await sb.close();
149
- * }
150
- * ```
1011
+ * On first load the Pi CLI is installed inside a `node:22` sandbox, then
1012
+ * the sandbox is checkpointed. Subsequent `load()` calls for the same spec
1013
+ * restore from that snapshot — skipping the install and starting in ~3s instead
1014
+ * of ~90s.
1015
+ *
1016
+ * Pass `{ rebuild: true }` to force a full reinstall (e.g. after changing
1017
+ * the spec's `packages` or `cliVersion`).
1018
+ *
1019
+ * Pass `{ spawnDepth }` to override the spec's own `spawnDepth` (e.g. a
1020
+ * `--depth` CLI flag) — standard flag-beats-config precedence. Same for
1021
+ * `{ maxAgents }` and `--max`.
1022
+ *
1023
+ * Logs timing for each phase to stdout via `[agent]` prefixed lines.
151
1024
  */
152
- async sandbox(opts) {
153
- await this._ensureConnected();
154
- await this._acquireSlot();
155
- const image = typeof opts.image === "string" ? { uri: opts.image } : opts.image;
156
- const runId = opts.runId ?? crypto.randomUUID();
157
- let sandboxId;
158
- try {
159
- sandboxId = (await this._control.createSandbox({
160
- image,
161
- env: opts.env,
162
- metadata: {
163
- ...opts.metadata,
164
- runId
165
- },
166
- entrypoint: opts.entrypoint ?? [
167
- "tail",
168
- "-f",
169
- "/dev/null"
170
- ],
171
- resourceLimits: opts.resources,
172
- timeout: opts.timeout
173
- })).id;
174
- await this._waitForRunning(sandboxId);
175
- const name = opts.name ?? `sandbox-${sandboxId.slice(0, 8)}`;
176
- await this._adapter.append({
177
- ts: Date.now(),
178
- name,
179
- sandboxId,
180
- stepIndex: -1,
181
- event: LedgerEvent$1.SandboxCreated,
182
- payload: {
183
- sandboxId,
184
- resources: opts.resources,
185
- runId
186
- }
187
- });
188
- const sb = new Sandbox$1(sandboxId, name, {
189
- control: this._control,
190
- adapter: this._adapter,
191
- hooks: opts.hooks,
192
- onClose: () => this._releaseSlot(),
193
- shell: opts.shell,
194
- fork: (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, opts.resources, opts.shell, overrideRunId ?? runId),
195
- useServerProxy: this._useServerProxy
196
- });
197
- opts.hooks?.onSandboxCreated?.(sandboxId, name);
198
- return sb;
199
- } catch (err) {
200
- this._releaseSlot();
201
- throw err;
202
- }
1025
+ static async load(spec, opts) {
1026
+ const r = await loadAgent(spec, opts);
1027
+ return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
203
1028
  }
204
1029
  /**
205
- * Resume a sandbox session from its last checkpoint.
1030
+ * Reconnect to a previously-created agent whose host process has exited.
1031
+ *
1032
+ * The sandbox container must still be running. Pi and any installed packages
1033
+ * are already present — only the bridge process needs to be restarted.
1034
+ * Pi is started with `--continue` so it resumes the most recent session.
206
1035
  *
207
- * Restores an OpenSandbox container from the snapshot captured by the most
208
- * recent `sb.checkpoint()` call. Execs that completed before the checkpoint
209
- * are returned from ledger cache without re-running; subsequent execs run
210
- * against the restored container.
1036
+ * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
1037
+ * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
1038
+ * `load()`. Takes precedence over `opts.specPath` if both are set.
1039
+ * @param opts.specPath Path to the agent spec JSON, read and validated internally. If
1040
+ * neither `opts.spec` nor `opts.specPath` is set, the ledger is queried for the sandbox's
1041
+ * name and the spec is read from `./agents/<name>.json` — this fallback is the one thing
1042
+ * `resume()` can do that `load()` can't, since a resumed sandbox's original spec may not be
1043
+ * in memory anywhere the caller can hand it over.
211
1044
  *
212
1045
  * @example
213
1046
  * ```ts
214
- * // original session (crashed mid-test)
215
- * const sb = await client.sandbox({ image: "node:22", name: "ci", resources: { cpu: "500m", memory: "256Mi" } });
216
- * await sb.exec("npm ci");
217
- * await sb.checkpoint();
218
- * await sb.exec("npm test"); // container dies here
1047
+ * // Original process:
1048
+ * const spec = await Bun.file("./agents/hello-agent.json").json();
1049
+ * const agent = await Alineo.load(spec, { adapter });
1050
+ * console.log(agent.sandboxId); // save this
1051
+ * // ... process exits ...
219
1052
  *
220
- * // resume later
221
- * const sb2 = await client.resume(originalSessionId);
222
- * await sb2.exec("npm ci"); // instant — replayed from ledger
223
- * await sb2.exec("npm test"); // actually runs on restored container
224
- * await sb2.close();
1053
+ * // New process:
1054
+ * const agent = await Alineo.resume(savedSandboxId, { adapter });
1055
+ * for await (const chunk of agent.prompt("What did we discuss earlier?")) {
1056
+ * process.stdout.write(chunk);
1057
+ * }
1058
+ * await agent.close();
225
1059
  * ```
226
1060
  */
227
- async resume(sandboxId, opts) {
228
- await this._ensureConnected();
229
- const session = (await this._adapter.listAllSandboxDetails()).find((s) => s.sandboxId === sandboxId);
230
- if (!session) throw new AlineoError(`Session ${sandboxId} not found`, 404);
231
- return this._resumeSession(session.name, sandboxId, opts?.tag);
232
- }
233
- async _resumeSession(name, sandboxId, tag) {
234
- const entries = await this._adapter.readAll(name, sandboxId);
235
- let checkpointIdx;
236
- if (tag) {
237
- checkpointIdx = entries.findIndex((e) => e.event === LedgerEvent$1.CheckpointCreated && e.payload?.name === tag);
238
- if (checkpointIdx === -1) throw new AlineoError(`No checkpoint with tag '${tag}' found for session ${sandboxId}`, 404);
239
- } else {
240
- checkpointIdx = entries.map((e) => e.event).lastIndexOf(LedgerEvent$1.CheckpointCreated);
241
- if (checkpointIdx === -1) throw new AlineoError(`No checkpoint found for session ${sandboxId}`, 404);
242
- }
243
- const { snapshotId } = entries[checkpointIdx].payload;
244
- const createdEntry = entries.find((e) => e.event === LedgerEvent$1.SandboxCreated);
245
- const resources = (createdEntry?.payload)?.resources;
246
- const runId = (createdEntry?.payload)?.runId ?? crypto.randomUUID();
247
- const replayCache = /* @__PURE__ */ new Map();
248
- const pendingStdout = /* @__PURE__ */ new Map();
249
- const pendingStderr = /* @__PURE__ */ new Map();
250
- const pendingStdin = /* @__PURE__ */ new Map();
251
- const interactiveMeta = /* @__PURE__ */ new Map();
252
- for (const entry of entries.slice(0, checkpointIdx)) if (entry.event === LedgerEvent$1.ExecStart) {
253
- const { seq, cmd, interactive, cwd, env } = entry.payload;
254
- pendingStdout.set(seq, []);
255
- pendingStderr.set(seq, []);
256
- if (interactive) {
257
- pendingStdin.set(seq, []);
258
- interactiveMeta.set(seq, {
259
- cmd,
260
- cwd,
261
- env
262
- });
263
- }
264
- } else if (entry.event === LedgerEvent$1.ExecEvent) {
265
- const { seq, type, text } = entry.payload;
266
- if (text) {
267
- if (type === "stdout") pendingStdout.get(seq)?.push(text);
268
- else if (type === "stderr") pendingStderr.get(seq)?.push(text);
269
- else if (type === "stdin") pendingStdin.get(seq)?.push(text);
270
- }
271
- } else if (entry.event === LedgerEvent$1.ExecComplete) {
272
- const { seq, exitCode } = entry.payload;
273
- replayCache.set(seq, {
274
- stdout: (pendingStdout.get(seq) ?? []).join(""),
275
- stderr: (pendingStderr.get(seq) ?? []).join(""),
276
- exitCode
277
- });
278
- }
279
- const pendingInteractive = /* @__PURE__ */ new Map();
280
- for (const [seq, meta] of interactiveMeta) {
281
- if (replayCache.has(seq)) continue;
282
- pendingInteractive.set(seq, {
283
- ...meta,
284
- stdin: pendingStdin.get(seq) ?? [],
285
- stdout: (pendingStdout.get(seq) ?? []).join("")
286
- });
287
- }
288
- await this._acquireSlot();
289
- try {
290
- const newSessionId = (await this._control.createSandbox({
291
- snapshotId,
292
- resourceLimits: resources,
293
- metadata: { runId }
294
- })).id;
295
- await this._waitForRunning(newSessionId);
296
- await this._adapter.append({
297
- ts: Date.now(),
298
- name,
299
- sandboxId: newSessionId,
300
- stepIndex: -1,
301
- event: LedgerEvent$1.SandboxCreated,
302
- payload: {
303
- sandboxId: newSessionId,
304
- resumedFrom: sandboxId,
305
- snapshotId,
306
- runId
307
- }
308
- });
309
- return new Sandbox$1(newSessionId, name, {
310
- control: this._control,
311
- adapter: this._adapter,
312
- onClose: () => this._releaseSlot(),
313
- fork: resources?.cpu && resources?.memory ? (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? runId) : void 0,
314
- useServerProxy: this._useServerProxy
315
- }, replayCache, pendingInteractive);
316
- } catch (err) {
317
- this._releaseSlot();
318
- throw err;
319
- }
1061
+ static async resume(sandboxId, opts) {
1062
+ const r = await resumeAgent(sandboxId, opts);
1063
+ return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
320
1064
  }
321
1065
  /**
322
- * Attach to an already-running sandbox container without creating or restoring anything.
1066
+ * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
1067
+ * `resume()`, which kills and restarts the bridge process. Use this when you only
1068
+ * need `.spawn()`/`.sandbox`, not `.prompt()`/`.bash()`.
323
1069
  *
324
- * Use this to reconnect to a sandbox whose host process has exited but whose container
325
- * is still running. Unlike `resume()`, no snapshot is involved — the container keeps
326
- * its current state. The execd endpoint is resolved lazily on first use.
1070
+ * The main caller is `alineo fork`: it runs as a fresh CLI process started BY the
1071
+ * very Pi bash-tool call it's attaching to (a master agent spawning a child from
1072
+ * inside its own turn). Going through `resume()` there would `pkill` the bridge
1073
+ * that's currently running the Pi process making the call — self-destructive.
327
1074
  *
328
- * @throws `AlineoError` (409) if the sandbox is not in Running state.
1075
+ * The returned `Alineo` has no bridge, so `.prompt()`/`.bash()`/etc. all throw.
1076
+ * Its env is read back from `/etc/alineo-env` on the sandbox itself (the ground
1077
+ * truth for what's actually running there) rather than re-derived from a spec
1078
+ * file, which may not even exist inside this particular sandbox.
329
1079
  *
330
- * @param opts.resources CPU/memory/GPU to use if `.fork()` is later called on the
331
- * returned `Sandbox`. The control API doesn't echo back a running sandbox's own
332
- * resource limits, so there's no way to discover them automatically here — omit
333
- * this and `.fork()` will throw. Pass it (e.g. from `alineo.config.json`'s
334
- * defaults) when the caller needs fork support on a merely-connected sandbox.
335
- * @param opts.runId Default run-correlation ID for any later `.fork()` call on the
336
- * returned `Sandbox`. `connect()` has no way to discover the sandbox's original
337
- * `runId` (no ledger lookup is attempted — the caller may be using a completely
338
- * different adapter than whatever originally created it, as `alineo fork` does when
339
- * self-attaching). Omit this and pass `runId` explicitly to `.fork()` itself instead.
1080
+ * When `sandboxId` matches `ALINEO_SANDBOX_ID` in this process's own env (true
1081
+ * self-attach, e.g. `alineo fork` running from inside its own container),
1082
+ * `/etc/alineo-env` is read straight off the local filesystem instead of via
1083
+ * `sb.readFile()`. A self-referential exec call would need this sandbox to
1084
+ * reach itself through its own externally-facing bridge IP, which Docker's
1085
+ * default bridge network generally can't hairpin back to the originating
1086
+ * container — sibling-to-sibling traffic works fine, only this exact
1087
+ * self-connect case doesn't, and the caller already has the file locally.
340
1088
  *
341
- * @example
342
- * ```ts
343
- * // In a new process, reconnect to a sandbox started earlier:
344
- * const sb = await client.connect(savedSandboxId, "my-sandbox");
345
- * const { stdout } = await sb.exec("cat /results.txt");
346
- * await sb.close();
347
- * ```
1089
+ * `opts.resources` sizes a subsequent `.spawn()`'s forked container — the
1090
+ * control API doesn't echo back a running sandbox's own resource limits, so
1091
+ * there's no way to discover this agent's *actual* footprint here. Defaults to
1092
+ * `alineo.config.json`'s `defaults.resources`, same fallback `Alineo.load()` uses
1093
+ * for a spec that doesn't set its own.
348
1094
  */
349
- async connect(sandboxId, name, opts) {
350
- await this._ensureConnected();
351
- const info = await this._control.getSandbox(sandboxId);
352
- if (info.status.state !== SandboxState.Running) throw new AlineoError(`Sandbox ${sandboxId} is ${info.status.state} — can only connect to Running sandboxes`, 409);
353
- await this._acquireSlot();
354
- const resources = opts?.resources;
355
- return new Sandbox$1(sandboxId, name, {
356
- control: this._control,
357
- adapter: this._adapter,
358
- onClose: () => this._releaseSlot(),
359
- fork: resources ? (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? opts?.runId) : void 0,
360
- useServerProxy: this._useServerProxy
361
- });
1095
+ static async attach(sandboxId, opts) {
1096
+ const r = await attachAgent(sandboxId, opts);
1097
+ return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
362
1098
  }
363
1099
  /**
364
- * Create a fresh sandbox from a snapshot ID without exec replay.
1100
+ * Fork this agent's live sandbox — filesystem, installed packages, checked-out
1101
+ * state, everything currently on disk — into a brand-new independent sandbox
1102
+ * running its own Pi bridge, per `childSpecPath`. Unlike `Alineo.load()` (always
1103
+ * starts from a spec's own snapshot) or `fork()`/`clone()` below (Pi's own
1104
+ * conversation-branching — same container, same bridge, new session branch),
1105
+ * this is sandbox-level forking: the child sees exactly what this agent's
1106
+ * sandbox sees right now, including any uncommitted work.
365
1107
  *
366
- * Unlike `resume()`, this does not replay prior exec results — the new sandbox
367
- * starts with a clean exec history. Use this when you want to restore a
368
- * checkpointed environment and run new commands from scratch.
1108
+ * The child's environment is resolved fresh from its OWN spec — nothing is
1109
+ * inherited from this agent except the spawn-depth counter, which is
1110
+ * force-computed (`current - 1`) regardless of what the child's spec or
1111
+ * `opts.spawnDepth` says. Every name this agent's own env declares is also
1112
+ * explicitly `unset` in the shell command that starts the child's bridge, since
1113
+ * the forked container's OS-level env still carries whatever was baked in at
1114
+ * snapshot time independent of what gets written to `/etc/alineo-env`.
369
1115
  *
370
- * @param snapshotId The snapshot ID returned by `sb.checkpoint()`.
371
- * @param name A name for the new sandbox session in the ledger.
372
- * @param resources CPU and memory for the restored container.
373
- * @param runId Run-correlation ID for the restored sandbox — see `SandboxDetails.runId`.
374
- * Defaults to a fresh `crypto.randomUUID()` if omitted.
1116
+ * Refuses immediately unless this agent's own spawn-depth budget
1117
+ * (`ALINEO_SPAWN_DEPTH`, or `opts.spawnDepth` to override it) is a positive
1118
+ * integer — `0` means no budget left, `undefined` means spawning was never
1119
+ * enabled for this agent.
375
1120
  *
376
- * @example
377
- * ```ts
378
- * const snapshotId = await sb.checkpoint();
379
- * await sb.close();
1121
+ * If `ALINEO_MAX_AGENTS` (or `opts.maxAgents`) is set, also refuses once it
1122
+ * hits `0` — a separate, optional ceiling on total descendants for this
1123
+ * lineage, independent of nesting depth. Unset means uncapped for this
1124
+ * dimension; only `spawnDepth` gates whether spawning is allowed at all.
1125
+ * Not coordinated across sibling branches spawned in parallel.
380
1126
  *
381
- * // Later — restore and run fresh commands:
382
- * const sb2 = await client.restoreSnapshot(snapshotId, "my-sandbox", { cpu: "500m", memory: "256Mi" });
383
- * await sb2.exec("npm test");
384
- * await sb2.close();
385
- * ```
1127
+ * No install/setup steps run — the child inherits Pi (and anything else)
1128
+ * already installed on this agent's sandbox. If the child needs packages this
1129
+ * agent's own sandbox doesn't have, add them to a setup step on the spec THIS
1130
+ * agent was loaded from, not on the child's spec.
386
1131
  */
387
- async restoreSnapshot(snapshotId, name, resources, runId) {
388
- await this._ensureConnected();
389
- await this._acquireSlot();
390
- try {
391
- const finalRunId = runId ?? crypto.randomUUID();
392
- const newId = (await this._control.createSandbox({
393
- snapshotId,
394
- resourceLimits: resources,
395
- metadata: { runId: finalRunId }
396
- })).id;
397
- await this._waitForRunning(newId);
398
- await this._adapter.append({
399
- ts: Date.now(),
400
- name,
401
- sandboxId: newId,
402
- stepIndex: -1,
403
- event: LedgerEvent$1.SandboxCreated,
404
- payload: {
405
- sandboxId: newId,
406
- fromSnapshot: snapshotId,
407
- runId: finalRunId
408
- }
409
- });
410
- return new Sandbox$1(newId, name, {
411
- control: this._control,
412
- adapter: this._adapter,
413
- onClose: () => this._releaseSlot(),
414
- fork: (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, name, resources, void 0, overrideRunId ?? finalRunId),
415
- useServerProxy: this._useServerProxy
416
- });
417
- } catch (err) {
418
- this._releaseSlot();
419
- throw err;
420
- }
1132
+ async spawn(childSpecPath, opts = {}) {
1133
+ const r = await spawnChild(this, childSpecPath, opts);
1134
+ return new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1135
+ }
1136
+ /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
1137
+ prompt(message, opts) {
1138
+ return prompt(this, message, opts);
421
1139
  }
422
1140
  /**
423
- * Sandbox history management. List, inspect, and delete past sandbox records.
424
- *
425
- * @example
426
- * ```ts
427
- * const all = await client.sandboxes.list();
428
- * const details = await client.sandboxes.get("ci", sandboxId);
429
- * await client.sandboxes.delete("ci", sandboxId);
430
- * ```
1141
+ * Run a shell command inside Pi's working context. Not incrementally
1142
+ * streamed — Pi returns bash output synchronously, so the full output
1143
+ * arrives as a single `text` event once the command completes.
431
1144
  */
432
- sandboxes = {
433
- /** List all sandbox records across all names, newest first. */
434
- list: async (opts) => {
435
- await this._ensureConnected();
436
- return this._adapter.listAllSandboxDetails(opts);
437
- },
438
- /** List sandbox records for a specific name, newest first. */
439
- listByName: async (name, opts) => {
440
- await this._ensureConnected();
441
- return this._adapter.listSandboxDetails(name, opts);
442
- },
443
- /** Return details for a single sandbox record. Returns `null` if not found. */
444
- get: async (name, sandboxId) => {
445
- await this._ensureConnected();
446
- return this._adapter.getSandboxDetails(name, sandboxId);
447
- },
448
- /** Delete all ledger events for a sandbox. */
449
- delete: async (name, sandboxId) => {
450
- await this._ensureConnected();
451
- return this._adapter.deleteSandbox(name, sandboxId);
452
- }
453
- };
1145
+ bash(command) {
1146
+ return bash(this, command);
1147
+ }
1148
+ /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
1149
+ async steer(message) {
1150
+ return steer(this, message);
1151
+ }
1152
+ /** Abort Pi's current operation. */
1153
+ async abort() {
1154
+ return abort(this);
1155
+ }
1156
+ /** Queue a message to be sent to Pi after it finishes its current task. */
1157
+ async followUp(message) {
1158
+ return followUp(this, message);
1159
+ }
1160
+ /** Start a fresh Pi session, clearing all prior context. */
1161
+ async newSession() {
1162
+ return newSession(this);
1163
+ }
1164
+ /** Set Pi's reasoning level (for models that support extended thinking). */
1165
+ async setThinkingLevel(level) {
1166
+ return setThinkingLevel(this, level);
1167
+ }
1168
+ /** Enable or disable Pi's automatic context compaction. */
1169
+ async setAutoCompaction(enabled) {
1170
+ return setAutoCompaction(this, enabled);
1171
+ }
454
1172
  /**
455
- * Define a named, reusable sandbox environment.
456
- *
457
- * Returns an `Environment` object — no I/O happens here. The first call to
458
- * `env.sandbox()` builds the environment (runs setup + snapshots), then caches
459
- * the snapshot ID in the ledger. Subsequent calls restore from that snapshot.
460
- *
461
- * @example
462
- * ```ts
463
- * const env = client.environment("python", {
464
- * image: "debian:bookworm-slim",
465
- * resources: { cpu: "500m", memory: "512Mi" },
466
- * setup: async (sb) => {
467
- * await sb.exec("apt-get update -qq && apt-get install -y python3-pip");
468
- * await sb.exec("pip install numpy pandas");
469
- * },
470
- * });
471
- *
472
- * const sb = await env.sandbox();
473
- * try {
474
- * await sb.exec("python3 -c 'import pandas; print(pandas.__version__)'").pipe(process.stdout);
475
- * } finally {
476
- * await sb.close();
477
- * }
478
- * ```
1173
+ * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
1174
+ * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
1175
+ * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
1176
+ * events in the stream.
479
1177
  */
480
- environment(name, opts) {
481
- return new Environment(name, opts, this);
1178
+ async setAutoRetry(enabled) {
1179
+ return setAutoRetry(this, enabled);
482
1180
  }
483
1181
  /**
484
- * Environment management. List and delete cached environment records.
485
- *
486
- * @example
487
- * ```ts
488
- * const envs = await client.environments.list();
489
- * await client.environments.delete("python");
490
- * ```
1182
+ * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
1183
+ * operation, emitting `auto_retry_end` with `success: false`.
491
1184
  */
492
- environments = {
493
- /** Return all environment records, newest first. */
494
- list: async () => {
495
- await this._ensureConnected();
496
- return this._adapter.listEnvironments();
497
- },
498
- /** Remove the ledger record for a named environment. Does not delete the server-side snapshot. */
499
- delete: async (name) => {
500
- await this._ensureConnected();
501
- return this._adapter.deleteEnvironment(name);
502
- }
503
- };
504
- async _envInfo(name) {
505
- await this._ensureConnected();
506
- return this._adapter.getEnvironment(name);
507
- }
508
- async _envRebuild(name, opts) {
509
- await this._ensureConnected();
510
- await this._buildEnvironment(name, opts);
511
- }
512
- async _envSandbox(name, opts, extra) {
513
- await this._ensureConnected();
514
- const record = await this._adapter.getEnvironment(name);
515
- if (record) {
516
- if ((await this._control.getSnapshot(record.snapshotId).catch(() => null))?.state === SnapshotState.Ready) return this._createFromSnapshot(record.snapshotId, opts.resources, name, opts.shell, extra);
517
- }
518
- const snapshotId = await this._getOrBuildEnvironment(name, opts);
519
- return this._createFromSnapshot(snapshotId, opts.resources, name, opts.shell, extra);
520
- }
521
- _getOrBuildEnvironment(name, opts) {
522
- const inflight = this._envBuilds.get(name);
523
- if (inflight) return inflight;
524
- const build = this._buildEnvironment(name, opts).finally(() => this._envBuilds.delete(name));
525
- this._envBuilds.set(name, build);
526
- return build;
527
- }
528
- async _buildEnvironment(name, opts) {
529
- const image = typeof opts.image === "string" ? opts.image : opts.image.uri;
530
- const buildName = `env-${name}-build`;
531
- const sb = await this.sandbox({
532
- image: opts.image,
533
- resources: opts.resources,
534
- name: buildName,
535
- shell: opts.shell
536
- });
537
- try {
538
- await opts.setup(sb);
539
- await sb.checkpoint(`env:${name}`);
540
- } finally {
541
- await sb.close();
542
- }
543
- const checkpoint = await this._adapter.lastCheckpoint(buildName, sb.sandboxId);
544
- if (!checkpoint) throw new AlineoError(`Environment build for '${name}' produced no checkpoint`, 500);
545
- const { snapshotId } = checkpoint.payload;
546
- await this._adapter.saveEnvironment({
547
- name,
548
- snapshotId,
549
- image,
550
- builtAt: Date.now()
551
- });
552
- return snapshotId;
1185
+ async abortRetry() {
1186
+ return abortRetry(this);
553
1187
  }
554
- async _createFromSnapshot(snapshotId, resources, envName, envShell, extra) {
555
- await this._acquireSlot();
556
- try {
557
- const runId = crypto.randomUUID();
558
- const newId = (await this._control.createSandbox({
559
- snapshotId,
560
- resourceLimits: resources,
561
- env: extra?.env,
562
- metadata: { runId }
563
- })).id;
564
- await this._waitForRunning(newId);
565
- const sessionName = `env-${envName}-${newId.slice(0, 8)}`;
566
- await this._adapter.append({
567
- ts: Date.now(),
568
- name: sessionName,
569
- sandboxId: newId,
570
- stepIndex: -1,
571
- event: LedgerEvent$1.SandboxCreated,
572
- payload: {
573
- sandboxId: newId,
574
- fromEnvironment: envName,
575
- snapshotId,
576
- runId
577
- }
578
- });
579
- const sb = new Sandbox$1(newId, sessionName, {
580
- control: this._control,
581
- adapter: this._adapter,
582
- hooks: extra?.hooks,
583
- onClose: () => this._releaseSlot(),
584
- shell: extra?.shell ?? envShell,
585
- fork: (snapshotId, tag, overrideRunId) => this._forkFromSnapshot(snapshotId, sessionName, resources, extra?.shell ?? envShell, overrideRunId ?? runId),
586
- useServerProxy: this._useServerProxy
587
- });
588
- extra?.hooks?.onSandboxCreated?.(newId, sessionName);
589
- return sb;
590
- } catch (err) {
591
- this._releaseSlot();
592
- throw err;
593
- }
1188
+ /** Abort a currently-executing bash command without cancelling the whole prompt. */
1189
+ async abortBash() {
1190
+ return abortBash(this);
594
1191
  }
595
- async _forkFromSnapshot(snapshotId, parentName, resources, shell, runId) {
596
- await this._acquireSlot();
597
- try {
598
- const finalRunId = runId ?? crypto.randomUUID();
599
- const newId = (await this._control.createSandbox({
600
- snapshotId,
601
- resourceLimits: resources,
602
- metadata: { runId: finalRunId }
603
- })).id;
604
- await this._waitForRunning(newId);
605
- const sessionName = `fork-${parentName}-${newId.slice(0, 8)}`;
606
- await this._adapter.append({
607
- ts: Date.now(),
608
- name: sessionName,
609
- sandboxId: newId,
610
- stepIndex: -1,
611
- event: LedgerEvent$1.SandboxCreated,
612
- payload: {
613
- sandboxId: newId,
614
- forkedFrom: snapshotId,
615
- runId: finalRunId
616
- }
617
- });
618
- return new Sandbox$1(newId, sessionName, {
619
- control: this._control,
620
- adapter: this._adapter,
621
- onClose: () => this._releaseSlot(),
622
- shell,
623
- fork: (sid, tag, overrideRunId) => this._forkFromSnapshot(sid, sessionName, resources, shell, overrideRunId ?? finalRunId),
624
- useServerProxy: this._useServerProxy
625
- });
626
- } catch (err) {
627
- this._releaseSlot();
628
- throw err;
629
- }
1192
+ /** Retrieve token usage, cost, and message counts for the current session. */
1193
+ async getSessionStats() {
1194
+ return getSessionStats(this);
630
1195
  }
631
- async _waitForRunning(sandboxId, timeoutMs = 12e4) {
632
- const deadline = Date.now() + timeoutMs;
633
- let delay = 100;
634
- while (Date.now() < deadline) {
635
- const s = await this._control.getSandbox(sandboxId);
636
- if (s.status.state === SandboxState.Running) return;
637
- if (s.status.state === SandboxState.Failed || s.status.state === SandboxState.Terminated) throw new AlineoError(`Sandbox ${sandboxId} entered state ${s.status.state}: ${s.status.message ?? ""}`, 500);
638
- await new Promise((r) => setTimeout(r, delay));
639
- delay = Math.min(delay * 1.5, 1e3);
640
- }
641
- throw new AlineoError(`Sandbox ${sandboxId} did not reach Running within ${timeoutMs}ms`, 408);
1196
+ /** Retrieve the text of Pi's most recent assistant response. Returns `null` if none yet. */
1197
+ async getLastAssistantText() {
1198
+ return getLastAssistantText(this);
642
1199
  }
643
- async _acquireSlot() {
644
- if (!this._maxConcurrency || this._activeCount < this._maxConcurrency) {
645
- this._activeCount++;
646
- return;
647
- }
648
- await new Promise((resolve) => this._waiters.push(resolve));
649
- this._activeCount++;
1200
+ /**
1201
+ * List the fork entry points available in the current session.
1202
+ * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
1203
+ */
1204
+ async getForkMessages() {
1205
+ return getForkMessages(this);
1206
+ }
1207
+ /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
1208
+ async getCommands() {
1209
+ return getCommands(this);
1210
+ }
1211
+ /** Set a display name for the current Pi session. */
1212
+ async setSessionName(name) {
1213
+ return setSessionName(this, name);
1214
+ }
1215
+ /**
1216
+ * Control how Pi processes queued steering messages.
1217
+ * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
1218
+ */
1219
+ async setSteeringMode(mode) {
1220
+ return setSteeringMode(this, mode);
1221
+ }
1222
+ /**
1223
+ * Control how Pi processes queued follow-up messages.
1224
+ * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
1225
+ */
1226
+ async setFollowUpMode(mode) {
1227
+ return setFollowUpMode(this, mode);
1228
+ }
1229
+ /**
1230
+ * Export a static HTML transcript of the current session to the sandbox filesystem.
1231
+ * Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
1232
+ * to retrieve it.
1233
+ */
1234
+ async exportHtml(outputPath) {
1235
+ return exportHtml(this, outputPath);
1236
+ }
1237
+ /**
1238
+ * Fork Pi's session at the given entry ID, creating a new branch.
1239
+ * Returns the text of the forked message and whether the fork was cancelled.
1240
+ */
1241
+ async fork(entryId) {
1242
+ return fork(this, entryId);
650
1243
  }
651
- _releaseSlot() {
652
- this._activeCount--;
653
- this._waiters.shift()?.();
1244
+ /** Clone the current Pi session into a new branch at the current position. */
1245
+ async clone() {
1246
+ return clone(this);
1247
+ }
1248
+ /** Switch Pi to a different session file on disk. */
1249
+ async switchSession(sessionPath) {
1250
+ return switchSession(this, sessionPath);
1251
+ }
1252
+ /** Switch Pi to a specific model. Returns the activated model. */
1253
+ async setModel(provider, modelId) {
1254
+ return setModel(this, provider, modelId);
1255
+ }
1256
+ /** Cycle Pi to the next available model. Returns null if only one model is configured. */
1257
+ async cycleModel() {
1258
+ return cycleModel(this);
1259
+ }
1260
+ /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
1261
+ async cycleThinkingLevel() {
1262
+ return cycleThinkingLevel(this);
1263
+ }
1264
+ /** Manually trigger Pi's context compaction. */
1265
+ async compact(customInstructions) {
1266
+ return compact(this, customInstructions);
1267
+ }
1268
+ /** Retrieve Pi's full conversation history for the current session. */
1269
+ async getMessages() {
1270
+ return getMessages(this);
1271
+ }
1272
+ /** List all models available to Pi under the current provider configuration. */
1273
+ async getAvailableModels() {
1274
+ return getAvailableModels(this);
1275
+ }
1276
+ /**
1277
+ * Retrieve Pi's current session state: active model, thinking level, streaming/compaction
1278
+ * status, queue modes, and session identity. The only piece of Pi's RPC surface with no
1279
+ * other way to observe the *current* model or thinking level (as opposed to the full list).
1280
+ */
1281
+ async getState() {
1282
+ return getState(this);
1283
+ }
1284
+ /**
1285
+ * Set or update env vars in the running container. Writes to /etc/alineo-env and restarts
1286
+ * the Pi subprocess so it picks up the new env. Waits until Pi is ready before returning.
1287
+ */
1288
+ async setEnv(vars) {
1289
+ return setEnv(this, vars);
1290
+ }
1291
+ /** Retrieve recent bridge logs (ring-buffered, last 200 entries). */
1292
+ async getLogs() {
1293
+ return getLogs(this);
1294
+ }
1295
+ /** Delete the sandbox container and release all resources. Always call in a `finally` block. */
1296
+ async close() {
1297
+ return close(this);
654
1298
  }
655
1299
  };
656
1300
  //#endregion
657
- export { Alineo, AlineoError, BashSession, CodeLanguage, CommandError, Environment, ExecConnectionError, LedgerEvent, Sandbox, SandboxError, SandboxStatus, StepTimeoutError };
1301
+ //#region src/types.ts
1302
+ /** Filter an `AgentStream` down to just text chunks. */
1303
+ async function* textOnly(stream) {
1304
+ for await (const ev of stream) if (ev.type === "text") yield ev.text;
1305
+ }
1306
+ //#endregion
1307
+ export { AgentSnapshotStore, AgentSpecValidationError, Alineo, PromptTimeoutError, computeSetupHash, snapshotsPath, textOnly, validateAgentSpec };