alineo 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,657 +1,1499 @@
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
83
+ /** Renders an arbitrary invalid field value for an error message without risking "[object Object]". */
84
+ function describeValue(value) {
85
+ if (typeof value === "string") return value;
86
+ try {
87
+ const json = JSON.stringify(value);
88
+ if (json !== void 0) return json;
89
+ } catch {}
90
+ return typeof value === "object" && value !== null ? Object.prototype.toString.call(value) : String(value);
91
+ }
22
92
  /**
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
- * });
93
+ * Runtime schema for `SetupStep`/`AgentSpec` above. Kept as a separate Zod schema rather than
94
+ * generating the interfaces from it (`z.infer<>`) so the hand-written interfaces above can carry
95
+ * full field-level JSDoc — TypeScript doesn't propagate comments through generic type inference,
96
+ * and that documentation is load-bearing (it's what IDE hover/autocomplete shows spec authors).
97
+ * If you add/change/remove a field on `AgentSpec`/`SetupStep`, update the matching schema field
98
+ * here too — `packages/agent/test/schema.test.ts` is the drift check.
99
+ */
100
+ const CredentialEnvBindingSchema = z$1.object({
101
+ credential: z$1.string({ error: "Each credential env binding must have a 'credential' string" }),
102
+ host: z$1.string({ error: "Each credential env binding must have a 'host' string" }),
103
+ pathPrefix: z$1.string().optional(),
104
+ injection: z$1.union([
105
+ z$1.object({
106
+ type: z$1.literal("header"),
107
+ name: z$1.string()
108
+ }),
109
+ z$1.object({
110
+ type: z$1.literal("query"),
111
+ param: z$1.string()
112
+ }),
113
+ z$1.object({
114
+ type: z$1.literal("path"),
115
+ segment: z$1.string()
116
+ })
117
+ ])
118
+ }).loose();
119
+ const SetupStepSchema = z$1.object({
120
+ name: z$1.string({ error: "Each setup step must have a 'name' string" }),
121
+ run: z$1.string({ error: "Each setup step must have a 'run' string" }),
122
+ cwd: z$1.string().optional()
123
+ }).loose();
124
+ 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();
125
+ const AgentSpecSchema = z$1.object({
126
+ $schema: z$1.string().optional(),
127
+ 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"),
128
+ title: z$1.string().optional(),
129
+ description: z$1.string().optional(),
130
+ author: z$1.string().optional(),
131
+ categories: z$1.array(z$1.string()).optional(),
132
+ cli: z$1.literal("pi", { error: (issue) => issue.input === void 0 ? "Agent spec must have a 'cli' field. Supported values: pi" : `Unsupported CLI: '${describeValue(issue.input)}'. Supported values: pi` }),
133
+ cliVersion: z$1.string().optional(),
134
+ provider: z$1.string().optional(),
135
+ model: z$1.string().optional(),
136
+ packages: z$1.array(z$1.string()).optional(),
137
+ env: z$1.record(z$1.string(), z$1.union([z$1.string(), CredentialEnvBindingSchema])).optional(),
138
+ resources: z$1.object({
139
+ cpu: z$1.string(),
140
+ memory: z$1.string(),
141
+ gpu: z$1.string().optional()
142
+ }).optional(),
143
+ metadata: z$1.record(z$1.string(), z$1.string()).optional(),
144
+ registryDependencies: z$1.array(z$1.string()).optional(),
145
+ setup: z$1.array(SetupStepSchema).optional(),
146
+ spawnDepth: nonNegativeIntSpecField("spawnDepth"),
147
+ maxAgents: nonNegativeIntSpecField("maxAgents"),
148
+ teamId: z$1.string().optional(),
149
+ resourceId: z$1.string().optional()
150
+ }).loose();
151
+ /**
152
+ * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
153
+ * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
154
+ * `.issues` array) rather than a bare `Error` — see #185.
155
+ */
156
+ function validateAgentSpec(data) {
157
+ const result = AgentSpecSchema.safeParse(data);
158
+ if (!result.success) throw new AgentSpecValidationError(`Invalid agent spec:\n${z$1.prettifyError(result.error)}`, result.error.issues.map((issue) => ({
159
+ path: issue.path,
160
+ message: issue.message,
161
+ code: issue.code
162
+ })));
163
+ return result.data;
164
+ }
165
+ //#endregion
166
+ //#region src/adapters/pi.ts
167
+ const BRIDGE_SCRIPT = readFileSync(fileURLToPath(new URL("./pi-bridge.js", import.meta.url)), "utf8");
168
+ function toShellExports(env) {
169
+ return Object.entries(env).map(([k, v]) => `export ${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join("\n") + "\n";
170
+ }
171
+ /**
172
+ * Resolves plain string entries of `AgentSpec.env`, interpolating `${VAR}` from `process.env`.
173
+ * Credential-bound entries (`{ credential, host, injection }`) are deliberately skipped here —
174
+ * see `extractCredentialBindings()` — they never become a container env var at all.
175
+ */
176
+ function resolveEnv(env) {
177
+ const result = {};
178
+ for (const [key, value] of Object.entries(env)) {
179
+ if (typeof value !== "string") continue;
180
+ result[key] = value.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? "");
181
+ }
182
+ return result;
183
+ }
184
+ /** Matches a `credential` value that is *only* a single `${VAR}` reference, nothing else. */
185
+ const SOLE_ENV_REF = /^\$\{([^}]+)\}$/;
186
+ /**
187
+ * Pulls the credential-bound entries out of `AgentSpec.env` — the opt-in alternative to plain
188
+ * env-var interpolation (see `AgentSpec.env`'s docs). Each entry's `credential` value is
189
+ * interpolated the same way `resolveEnv()` interpolates plain strings; the resolved value is
190
+ * only ever handed to `sb.credentials.set()`, never written into the container's environment.
39
191
  *
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
- * ```
192
+ * Also derives a `CredentialSource` for each: `credential: "${VAR}"` (the whole value, nothing
193
+ * else around it) becomes `{ type: "env", varName: "VAR" }`, letting `fork()`/`resume()`
194
+ * re-resolve it automatically later without needing a callback. Anything else — a literal
195
+ * value, or `${VAR}` embedded in a larger string — becomes `{ type: "external" }`, since it
196
+ * isn't reliably re-derivable the same way twice.
47
197
  */
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;
198
+ function extractCredentialBindings(env) {
199
+ const out = [];
200
+ for (const [key, value] of Object.entries(env)) {
201
+ if (typeof value === "string") continue;
202
+ const soleRef = value.credential.match(SOLE_ENV_REF);
203
+ out.push({
204
+ name: key,
205
+ value: value.credential.replace(/\$\{([^}]+)\}/g, (_, name) => process.env[name] ?? ""),
206
+ binding: {
207
+ host: value.host,
208
+ pathPrefix: value.pathPrefix,
209
+ injection: value.injection
210
+ },
211
+ source: soleRef ? {
212
+ type: "env",
213
+ varName: soleRef[1]
214
+ } : { type: "external" }
215
+ });
56
216
  }
217
+ return out;
218
+ }
219
+ /** Inverse of `toShellExports` — parses `/etc/alineo-env`'s content back into a plain object. */
220
+ function parseShellExports(content) {
221
+ const result = {};
222
+ const re = /^export ([A-Za-z_][A-Za-z0-9_]*)="((?:[^"\\]|\\.)*)"$/gm;
223
+ let m;
224
+ while (m = re.exec(content)) result[m[1]] = m[2].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
225
+ return result;
226
+ }
227
+ var PiAdapter = class {
228
+ _bridgeUrl = null;
57
229
  /**
58
- * Return a sandbox pre-configured with this environment.
230
+ * Controllers for prompt/bash streams `sseStream` deliberately left open (its early
231
+ * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
232
+ * documents — see that method's comment). `AbortController.abort()`, not
233
+ * `reader.cancel()`: Bun's `fetch()` tears down the underlying connection (and unrefs the
234
+ * poll keeping the event loop alive) reliably on an abort signal, but was observed to
235
+ * leave the socket referenced after `reader.cancel()` alone on this bridge's specific
236
+ * long-lived, heartbeat-pinged connections (unlike execd's exec/code streams, which
237
+ * self-resolve within execd's own bounded post-completion sleep either way — see
238
+ * disposeConnections() below).
59
239
  *
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.
240
+ * Known limitation: this reliably lets a process exit after exactly one prompt()/bash()
241
+ * call per agent lifetime (verified). A script making two or more such calls before
242
+ * close() can still hang even though every controller here does abort cleanly on the
243
+ * client side -- root cause traced to the same class of bug as
244
+ * opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination confusing the
245
+ * OpenSandbox control server's own proxy relay, which is what `bridgeUrl` is proxied
246
+ * through). Tracked in our own #189; not fixable from this file alone.
63
247
  */
64
- sandbox(extra) {
65
- return this.client._envSandbox(this.name, this.opts, extra);
248
+ pendingStreams = /* @__PURE__ */ new Set();
249
+ get bridgeUrl() {
250
+ if (!this._bridgeUrl) throw new Error("PiAdapter: bridge not started");
251
+ return this._bridgeUrl;
66
252
  }
67
253
  /**
68
- * Force a full rebuild of the environment, regardless of any cached snapshot.
69
- * Use this after changing the setup recipe.
254
+ * Force-close any prompt/bash streams `sseStream` deliberately left open (its early
255
+ * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
256
+ * documents — see that method's comment). Those connections sit ESTABLISHED, keeping
257
+ * Bun's event loop alive indefinitely, until something force-closes them -- unlike
258
+ * execd's exec/code streams (see `ExecClient.disposeConnections()`), the bridge's own
259
+ * `: ping` heartbeat (every 3s, see pi-bridge.js) means there's no bounded server-side
260
+ * timeout to eventually resolve a dangling one on its own. Call this once the agent is
261
+ * being torn down anyway (from `agent.close()`) instead of leaving the process to hang
262
+ * forever on whichever stream's `[DONE]` arrived last.
70
263
  */
71
- rebuild() {
72
- return this.client._envRebuild(this.name, this.opts);
264
+ disposeConnections() {
265
+ for (const controller of this.pendingStreams) controller.abort();
266
+ this.pendingStreams.clear();
267
+ }
268
+ /** Install Pi CLI and any spec packages. Slow — result is captured by checkpoint(). */
269
+ async install(sb, spec) {
270
+ const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
271
+ if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
272
+ const versionSpecifier = spec.cliVersion?.trim();
273
+ const pkg = versionSpecifier ? `@earendil-works/pi-coding-agent@${versionSpecifier}` : "@earendil-works/pi-coding-agent";
274
+ await sb.exec(`npm install -g --ignore-scripts ${pkg}`);
73
275
  }
74
276
  /**
75
- * Return the cached environment record, or `null` if the environment has not
76
- * been built yet.
277
+ * Write config files and the bridge script. Always runs on every start (fresh install
278
+ * and snapshot resume alike) so env values, model/provider, and bridge code stay current.
77
279
  */
78
- info() {
79
- return this.client._envInfo(this.name);
280
+ async configure(sb, spec, resolvedEnv, opts) {
281
+ const piConfig = {};
282
+ if (spec.provider) piConfig.provider = spec.provider;
283
+ if (spec.model) piConfig.model = spec.model;
284
+ if (opts?.resume) piConfig.resume = true;
285
+ await sb.writeFile("/etc/alineo-pi.json", JSON.stringify(piConfig));
286
+ await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
287
+ await sb.writeFile("/alineo-bridge.js", BRIDGE_SCRIPT);
288
+ }
289
+ /**
290
+ * Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the
291
+ * *same* exec command that starts `node` — required for `Alineo.spawn()`'s forked
292
+ * sandboxes, where the container's OS-level env still carries whatever the parent
293
+ * had baked into it at snapshot time (`env` passed to `createSandbox` at fork time
294
+ * has no effect on this — verified live, see `plans/alineo-rlm-substrate.md`). A
295
+ * plain `sb.exec("unset ...")` beforehand would not work: `unset` only clears the
296
+ * shell session it runs in, and each `exec()` call is its own session — it has to
297
+ * be part of the exact command that spawns the bridge process so the bridge (and
298
+ * everything it in turn spawns, including Pi itself) inherits the already-clean env.
299
+ */
300
+ async startBridge(sb, unsetVars) {
301
+ const prefix = unsetVars && unsetVars.length > 0 ? `unset ${unsetVars.join(" ")}; ` : "";
302
+ await sb.exec(`${prefix}node /alineo-bridge.js &`);
303
+ const { url } = await sb.proxy(3001);
304
+ this._bridgeUrl = url;
305
+ }
306
+ async waitReady(timeoutMs = 3e4) {
307
+ const deadline = Date.now() + timeoutMs;
308
+ while (Date.now() < deadline) {
309
+ try {
310
+ const res = await fetch(`${this.bridgeUrl}/health`);
311
+ if (res.ok) {
312
+ if ((await res.json()).ok) return;
313
+ }
314
+ } catch {}
315
+ await new Promise((r) => setTimeout(r, 500));
316
+ }
317
+ throw new Error(`alineo-bridge did not become ready within ${timeoutMs / 1e3}s`);
318
+ }
319
+ prompt(message, opts) {
320
+ return sseStream(this.bridgeUrl, "/prompt", {
321
+ message,
322
+ streamingBehavior: opts?.streamingBehavior
323
+ }, this.pendingStreams, opts?.inactivityTimeoutMs);
324
+ }
325
+ bash(command) {
326
+ return sseStream(this.bridgeUrl, "/bash", { command }, this.pendingStreams);
327
+ }
328
+ async steer(message) {
329
+ const res = await fetch(`${this.bridgeUrl}/steer`, {
330
+ method: "POST",
331
+ headers: { "Content-Type": "application/json" },
332
+ body: JSON.stringify({ message })
333
+ });
334
+ if (!res.ok) {
335
+ const body = await res.json().catch(() => ({}));
336
+ throw new Error(`steer failed: ${body.error ?? res.status}`);
337
+ }
338
+ }
339
+ async abort() {
340
+ await rpcPost(this.bridgeUrl, "/abort");
341
+ }
342
+ async followUp(message) {
343
+ await rpcPost(this.bridgeUrl, "/follow-up", { message });
344
+ }
345
+ async newSession() {
346
+ await rpcPost(this.bridgeUrl, "/new-session");
347
+ }
348
+ async setThinkingLevel(level) {
349
+ await rpcPost(this.bridgeUrl, "/set-thinking-level", { level });
350
+ }
351
+ async setAutoCompaction(enabled) {
352
+ await rpcPost(this.bridgeUrl, "/set-auto-compaction", { enabled });
353
+ }
354
+ async setAutoRetry(enabled) {
355
+ await rpcPost(this.bridgeUrl, "/set-auto-retry", { enabled });
356
+ }
357
+ async abortRetry() {
358
+ await rpcPost(this.bridgeUrl, "/abort-retry");
359
+ }
360
+ async abortBash() {
361
+ await rpcPost(this.bridgeUrl, "/abort-bash");
362
+ }
363
+ async getSessionStats() {
364
+ return rpcPost(this.bridgeUrl, "/get-session-stats");
365
+ }
366
+ async getLastAssistantText() {
367
+ return (await rpcPost(this.bridgeUrl, "/get-last-assistant-text")).text;
368
+ }
369
+ async getForkMessages() {
370
+ return (await rpcPost(this.bridgeUrl, "/get-fork-messages")).messages;
371
+ }
372
+ async getCommands() {
373
+ return (await rpcPost(this.bridgeUrl, "/get-commands")).commands;
374
+ }
375
+ async setSessionName(name) {
376
+ await rpcPost(this.bridgeUrl, "/set-session-name", { name });
377
+ }
378
+ async setSteeringMode(mode) {
379
+ await rpcPost(this.bridgeUrl, "/set-steering-mode", { mode });
380
+ }
381
+ async setFollowUpMode(mode) {
382
+ await rpcPost(this.bridgeUrl, "/set-follow-up-mode", { mode });
383
+ }
384
+ async exportHtml(outputPath) {
385
+ return rpcPost(this.bridgeUrl, "/export-html", outputPath !== void 0 ? { outputPath } : {});
386
+ }
387
+ async fork(entryId) {
388
+ return rpcPost(this.bridgeUrl, "/fork", { entryId });
389
+ }
390
+ async clone() {
391
+ return rpcPost(this.bridgeUrl, "/clone");
392
+ }
393
+ async switchSession(sessionPath) {
394
+ return rpcPost(this.bridgeUrl, "/switch-session", { sessionPath });
395
+ }
396
+ async setModel(provider, modelId) {
397
+ return rpcPost(this.bridgeUrl, "/set-model", {
398
+ provider,
399
+ modelId
400
+ });
401
+ }
402
+ async cycleModel() {
403
+ return rpcPost(this.bridgeUrl, "/cycle-model");
404
+ }
405
+ async cycleThinkingLevel() {
406
+ return rpcPost(this.bridgeUrl, "/cycle-thinking-level");
407
+ }
408
+ async compact(customInstructions) {
409
+ return rpcPost(this.bridgeUrl, "/compact", { customInstructions });
410
+ }
411
+ async getMessages() {
412
+ return (await rpcGet(this.bridgeUrl, "/messages")).messages;
413
+ }
414
+ async getAvailableModels() {
415
+ return (await rpcGet(this.bridgeUrl, "/available-models")).models;
416
+ }
417
+ async getState() {
418
+ return rpcGet(this.bridgeUrl, "/state");
419
+ }
420
+ async reloadEnv(env) {
421
+ await rpcPost(this.bridgeUrl, "/reload-env", { env });
422
+ await this.waitReady();
423
+ }
424
+ async getLogs() {
425
+ return (await fetch(`${this.bridgeUrl}/logs`)).text();
426
+ }
427
+ };
428
+ async function rpcPost(bridgeUrl, path, body = {}) {
429
+ const res = await fetch(`${bridgeUrl}${path}`, {
430
+ method: "POST",
431
+ headers: { "Content-Type": "application/json" },
432
+ body: JSON.stringify(body)
433
+ });
434
+ if (!res.ok) {
435
+ const err = await res.json().catch(() => ({}));
436
+ throw new Error(`${path} failed: ${err.error ?? res.status}`);
437
+ }
438
+ return (await res.json()).data;
439
+ }
440
+ async function rpcGet(bridgeUrl, path) {
441
+ const res = await fetch(`${bridgeUrl}${path}`);
442
+ if (!res.ok) throw new Error(`${path} failed: ${res.status}`);
443
+ return (await res.json()).data;
444
+ }
445
+ /**
446
+ * How long to tolerate zero real `AgentEvent`s before treating the stream as stuck. The
447
+ * bridge's own `: ping` keep-alive (every 3s, see pi-bridge.js's `startHeartbeat`) exists only
448
+ * to defeat OpenSandbox's proxy idle-timeout -- it keeps `reader.read()` resolving regardless
449
+ * of whether Pi itself is making progress, so this can't just be "no read() in N seconds". The
450
+ * timer below is instead reset only when a real event is parsed and yielded (or `[DONE]`
451
+ * arrives), so a connection that's alive-but-silent for this long still times out.
452
+ *
453
+ * 60s (the original default) was too tight for a common, legitimate pattern: Pi's own `bash`
454
+ * tool is not incrementally streamed (see the `bash()` doc comment in session-control.ts), so
455
+ * a single tool call that spins up a whole child sandbox -- e.g. a master session running
456
+ * `alineo fork` on itself, as in examples/rlm-repo-fanout -- produces zero AgentEvents for as
457
+ * long as that tool call takes, which regularly exceeded 60s (child sandbox provisioning +
458
+ * Pi CLI install alone routinely took 30-150s+ in practice) and tripped this timeout mid-run
459
+ * even though the session was making real progress. Raised to 3 minutes as a still-bounded
460
+ * but realistic ceiling for that pattern; pass `inactivityTimeoutMs` explicitly to `prompt()`
461
+ * for sessions that need something tighter or looser.
462
+ */
463
+ const DEFAULT_INACTIVITY_TIMEOUT_MS = 18e4;
464
+ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeoutMs = DEFAULT_INACTIVITY_TIMEOUT_MS) {
465
+ const controller = new AbortController();
466
+ const res = await fetch(`${bridgeUrl}${path}`, {
467
+ method: "POST",
468
+ headers: { "Content-Type": "application/json" },
469
+ body: JSON.stringify(body),
470
+ signal: controller.signal,
471
+ keepalive: false
472
+ });
473
+ if (!res.ok || !res.body) throw new Error(`Bridge ${path} error: ${res.status}`);
474
+ pendingStreams.add(controller);
475
+ const reader = res.body.getReader();
476
+ const decoder = new TextDecoder();
477
+ let buf = "";
478
+ let lastEventAt = Date.now();
479
+ let reachedNaturalEnd = false;
480
+ try {
481
+ while (true) {
482
+ const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
483
+ if (remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
484
+ const result = await Promise.race([reader.read(), new Promise((resolve) => {
485
+ setTimeout(() => {
486
+ resolve("timeout");
487
+ }, remainingMs);
488
+ })]);
489
+ if (result === "timeout") throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
490
+ const { done, value } = result;
491
+ if (done) {
492
+ reachedNaturalEnd = true;
493
+ break;
494
+ }
495
+ buf += decoder.decode(value, { stream: true });
496
+ const lines = buf.split("\n");
497
+ buf = lines.pop() ?? "";
498
+ for (const line of lines) {
499
+ if (!line.startsWith("data: ")) continue;
500
+ const payload = line.slice(6).trim();
501
+ if (payload === "[DONE]") return;
502
+ const raw = JSON.parse(payload);
503
+ if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
504
+ lastEventAt = Date.now();
505
+ yield raw;
506
+ }
507
+ }
508
+ } finally {
509
+ if (reachedNaturalEnd) {
510
+ pendingStreams.delete(controller);
511
+ reader.releaseLock();
512
+ }
513
+ }
514
+ }
515
+ //#endregion
516
+ //#region src/snapshots.ts
517
+ /**
518
+ * Hash of the fields that require re-installing the agent CLI or rerunning
519
+ * setup: cli, cliVersion, packages, and setup. Excludes env (hot-reloadable),
520
+ * model/provider (CLI flags only), and cosmetic fields.
521
+ */
522
+ function computeSetupHash(spec) {
523
+ return createHash("sha256").update(JSON.stringify({
524
+ cli: spec.cli,
525
+ cliVersion: spec.cliVersion ?? "latest",
526
+ packages: [...spec.packages ?? []].sort(),
527
+ setup: spec.setup ?? []
528
+ })).digest("hex").slice(0, 12);
529
+ }
530
+ /** Derive the agent-snapshots.json path from the ledger adapter path. */
531
+ function snapshotsPath(adapterPath) {
532
+ return `${dirname(adapterPath)}/agent-snapshots.json`;
533
+ }
534
+ /** File-backed store for agent snapshot records, keyed by specName + setupHash. */
535
+ var AgentSnapshotStore = class {
536
+ path;
537
+ constructor(path) {
538
+ this.path = path;
539
+ }
540
+ async _read() {
541
+ try {
542
+ return JSON.parse(await readFile(this.path, "utf-8"));
543
+ } catch {
544
+ return {};
545
+ }
546
+ }
547
+ async _write(data) {
548
+ await mkdir(dirname(this.path), { recursive: true });
549
+ await writeFile(this.path, JSON.stringify(data, null, 2));
550
+ }
551
+ _key(specName, setupHash) {
552
+ return `${specName}:${setupHash}`;
553
+ }
554
+ async get(specName, setupHash) {
555
+ return (await this._read())[this._key(specName, setupHash)] ?? null;
556
+ }
557
+ async save(record) {
558
+ const data = await this._read();
559
+ for (const k of Object.keys(data)) if (data[k].specName === record.specName) delete data[k];
560
+ data[this._key(record.specName, record.setupHash)] = record;
561
+ await this._write(data);
562
+ }
563
+ /** Remove all snapshot records for the given spec name. */
564
+ async delete(specName) {
565
+ const data = await this._read();
566
+ for (const k of Object.keys(data)) if (data[k].specName === specName) delete data[k];
567
+ await this._write(data);
568
+ }
569
+ async list() {
570
+ return Object.values(await this._read());
80
571
  }
81
572
  };
82
573
  //#endregion
83
- //#region src/client.ts
574
+ //#region src/agent/validation.ts
575
+ /**
576
+ * The durable resource identity for a spawned child, frozen from the child spec BEFORE
577
+ * `Alineo.spawn()` overwrites its `.name` to the forked sandbox's auto-generated ledger name
578
+ * (`fork-<parent>-<id>`) — see `AgentSpec.resourceId`'s own doc comment for why `child.name`
579
+ * can't be read for this after the fork completes. Extracted as its own function (mirroring
580
+ * `resolveParentSpawnDepth`/`resolveParentMaxAgents` below) so this one line of resolution
581
+ * logic — easy to get backwards, hard to notice if so, since both `spawnChild()`'s
582
+ * `self.sandbox.fork()` call and its returned `AgentConstructorArgs.spec.resourceId` must
583
+ * agree on the exact same value — is independently unit-testable.
584
+ */
585
+ function resolveChildResourceId(childSpec) {
586
+ return childSpec.resourceId ?? childSpec.name;
587
+ }
588
+ function assertValidSpawnDepth(value, context) {
589
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${context}: spawnDepth must be a non-negative integer (got ${value})`);
590
+ }
591
+ function assertValidMaxAgents(value, context) {
592
+ if (!Number.isInteger(value) || value < 0) throw new Error(`${context}: maxAgents must be a non-negative integer (got ${value})`);
593
+ }
594
+ /**
595
+ * Resolves and validates the spawn-depth budget available to `Alineo.spawn()` —
596
+ * `override` (a `--depth` CLI flag) wins if given, else whatever value was
597
+ * materialised into `ALINEO_SPAWN_DEPTH` by `Alineo.load()`/`Alineo.resume()`. Throws
598
+ * unless the result is a positive integer: `0` means "no budget left", not "spawn
599
+ * one more time" — spawning stops one level before the counter would go negative.
600
+ */
601
+ function resolveParentSpawnDepth(envValue, override) {
602
+ const raw = override ?? (envValue !== void 0 ? Number(envValue) : void 0);
603
+ 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.`);
604
+ return raw;
605
+ }
606
+ /**
607
+ * Resolves the max-agents budget for `Alineo.spawn()` — same tamper-resistant
608
+ * env-counter shape as `resolveParentSpawnDepth`, but optional: `undefined`
609
+ * means "no cap enforced for this dimension," not "spawning refused."
610
+ * `spawnDepth` alone still gates whether spawning is allowed at all; this is
611
+ * an independent, additive ceiling on total descendants for THIS lineage —
612
+ * sibling branches spawned in parallel don't share this budget.
613
+ */
614
+ function resolveParentMaxAgents(envValue, override) {
615
+ const raw = override ?? (envValue !== void 0 ? Number(envValue) : void 0);
616
+ if (raw === void 0) return void 0;
617
+ if (!Number.isInteger(raw) || raw < 0) throw new Error(`Alineo.spawn() refused: maxAgents must be a non-negative integer (got ${raw}).`);
618
+ return raw;
619
+ }
620
+ //#endregion
621
+ //#region src/agent/factory.ts
622
+ function elapsed(t) {
623
+ return `${Date.now() - t}ms`;
624
+ }
625
+ /**
626
+ * Validate `specInput` and return everything needed to construct a fully initialised `Alineo`.
627
+ * See `Alineo.load()` for the public-facing docs.
628
+ */
629
+ async function loadAgent(specInput, opts) {
630
+ const t0 = Date.now();
631
+ const spec = validateAgentSpec(specInput);
632
+ const config = await readProjectConfig();
633
+ const resolvedEnv = resolveEnv(spec.env ?? {});
634
+ const effectiveSpawnDepth = opts.spawnDepth ?? spec.spawnDepth;
635
+ if (effectiveSpawnDepth !== void 0) {
636
+ assertValidSpawnDepth(effectiveSpawnDepth, "Alineo.load()");
637
+ resolvedEnv.ALINEO_SPAWN_DEPTH = String(effectiveSpawnDepth);
638
+ }
639
+ const effectiveMaxAgents = opts.maxAgents ?? spec.maxAgents;
640
+ if (effectiveMaxAgents !== void 0) {
641
+ assertValidMaxAgents(effectiveMaxAgents, "Alineo.load()");
642
+ resolvedEnv.ALINEO_MAX_AGENTS = String(effectiveMaxAgents);
643
+ }
644
+ const runId = opts.runId ?? crypto.randomUUID();
645
+ resolvedEnv.ALINEO_RUN_ID = runId;
646
+ const resources = {
647
+ ...config.defaults.resources,
648
+ ...spec.resources ?? {}
649
+ };
650
+ const credentialBindings = extractCredentialBindings(spec.env ?? {});
651
+ const needsCredentialProxy = credentialBindings.length > 0;
652
+ const networkPolicy = needsCredentialProxy ? {
653
+ defaultAction: "allow",
654
+ egress: []
655
+ } : void 0;
656
+ const client = new Sandbox({
657
+ baseUrl: config.serverUrl,
658
+ apiKey: config.apiKey,
659
+ adapter: opts.adapter,
660
+ useServerProxy: config.useServerProxy
661
+ });
662
+ const store = new AgentSnapshotStore(snapshotsPath(config.adapterPath));
663
+ const setupHash = computeSetupHash(spec);
664
+ const adapter = new PiAdapter();
665
+ let sb;
666
+ let fromSnapshot = false;
667
+ if (!opts.rebuild) {
668
+ const record = await store.get(spec.name, setupHash);
669
+ if (record) try {
670
+ console.log(`[agent] restoring from snapshot...`);
671
+ const t1 = Date.now();
672
+ sb = await client.restoreSnapshot(record.snapshotId, spec.name, resources, runId, {
673
+ networkPolicy,
674
+ credentialProxy: needsCredentialProxy,
675
+ resourceId: spec.resourceId ?? spec.name,
676
+ teamId: spec.teamId
677
+ });
678
+ console.log(`[agent] snapshot ready ${elapsed(t1)} (${sb.sandboxId})`);
679
+ fromSnapshot = true;
680
+ } catch (err) {
681
+ const reason = err instanceof Error ? err.message : String(err);
682
+ console.log(`[agent] snapshot restore failed (${reason}), rebuilding...`);
683
+ await store.delete(spec.name);
684
+ }
685
+ }
686
+ if (!fromSnapshot) {
687
+ console.log(`[agent] starting sandbox (${spec.name})...`);
688
+ const t1 = Date.now();
689
+ sb = await client.sandbox({
690
+ image: "node:22",
691
+ resources,
692
+ name: spec.name,
693
+ env: resolvedEnv,
694
+ runId,
695
+ networkPolicy,
696
+ credentialProxy: needsCredentialProxy,
697
+ resourceId: spec.resourceId ?? spec.name,
698
+ teamId: spec.teamId
699
+ });
700
+ console.log(`[agent] sandbox ready ${elapsed(t1)} (${sb.sandboxId})`);
701
+ console.log(`[agent] installing Pi CLI...`);
702
+ const t2 = Date.now();
703
+ await adapter.install(sb, spec);
704
+ console.log(`[agent] Pi CLI ready ${elapsed(t2)}`);
705
+ for (const step of spec.setup ?? []) {
706
+ console.log(`[agent] setup: ${step.name}...`);
707
+ const ts = Date.now();
708
+ const cmd = step.cwd ? `cd ${step.cwd} && ${step.run}` : step.run;
709
+ await sb.exec(cmd);
710
+ console.log(`[agent] setup done ${elapsed(ts)} (${step.name})`);
711
+ }
712
+ console.log(`[agent] checkpointing...`);
713
+ const t3 = Date.now();
714
+ const snapshotId = await sb.checkpoint();
715
+ await store.save({
716
+ specName: spec.name,
717
+ setupHash,
718
+ snapshotId,
719
+ createdAt: Date.now()
720
+ });
721
+ console.log(`[agent] checkpoint done ${elapsed(t3)}`);
722
+ }
723
+ if (!sb) throw new Error("internal error: sandbox was neither restored nor created");
724
+ for (const { name, value, binding, source } of credentialBindings) await sb.credentials.set(name, value, binding, source);
725
+ resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
726
+ await adapter.configure(sb, spec, resolvedEnv);
727
+ console.log(`[agent] starting bridge...`);
728
+ const t4 = Date.now();
729
+ await adapter.startBridge(sb);
730
+ await adapter.waitReady();
731
+ console.log(`[agent] bridge ready ${elapsed(t4)}`);
732
+ console.log(`[agent] total ${elapsed(t0)}${fromSnapshot ? " (from snapshot)" : ""}`);
733
+ return {
734
+ sandbox: sb,
735
+ spec,
736
+ env: resolvedEnv,
737
+ adapter,
738
+ fromSnapshot,
739
+ runId
740
+ };
741
+ }
84
742
  /**
85
- * Main entry point for alineo. Manages sandbox lifecycle and session history.
743
+ * Reconnect to a previously-created agent whose host process has exited. See
744
+ * `Alineo.resume()` for the public-facing docs.
745
+ */
746
+ async function resumeAgent(sandboxId, opts) {
747
+ const t0 = Date.now();
748
+ const config = await readProjectConfig();
749
+ const client = new Sandbox({
750
+ baseUrl: config.serverUrl,
751
+ apiKey: config.apiKey,
752
+ adapter: opts.adapter,
753
+ useServerProxy: config.useServerProxy
754
+ });
755
+ let spec;
756
+ if (opts.spec) spec = validateAgentSpec(opts.spec);
757
+ else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
758
+ else {
759
+ const session = (await client.sandboxes.list()).find((s) => s.sandboxId === sandboxId);
760
+ if (!session) throw new Error(`No ledger record for sandbox ${sandboxId} — pass opts.spec or opts.specPath explicitly`);
761
+ spec = validateAgentSpec(await Bun.file(`./agents/${session.name}.json`).json());
762
+ }
763
+ const resolvedEnv = resolveEnv(spec.env ?? {});
764
+ if (spec.maxAgents !== void 0) {
765
+ assertValidMaxAgents(spec.maxAgents, "Alineo.resume()");
766
+ resolvedEnv.ALINEO_MAX_AGENTS = String(spec.maxAgents);
767
+ }
768
+ if (spec.spawnDepth !== void 0) {
769
+ assertValidSpawnDepth(spec.spawnDepth, "Alineo.resume()");
770
+ resolvedEnv.ALINEO_SPAWN_DEPTH = String(spec.spawnDepth);
771
+ }
772
+ const runId = opts.runId ?? crypto.randomUUID();
773
+ resolvedEnv.ALINEO_RUN_ID = runId;
774
+ console.log(`[agent] reconnecting to ${sandboxId}...`);
775
+ const t1 = Date.now();
776
+ const sb = await client.connect(sandboxId, spec.name, {
777
+ runId,
778
+ resourceId: spec.resourceId ?? spec.name,
779
+ teamId: spec.teamId
780
+ });
781
+ console.log(`[agent] connected ${elapsed(t1)}`);
782
+ await sb.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
783
+ const adapter = new PiAdapter();
784
+ resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
785
+ await adapter.configure(sb, spec, resolvedEnv, { resume: true });
786
+ console.log(`[agent] starting bridge...`);
787
+ const t2 = Date.now();
788
+ await adapter.startBridge(sb);
789
+ await adapter.waitReady();
790
+ console.log(`[agent] bridge ready ${elapsed(t2)}`);
791
+ console.log(`[agent] total ${elapsed(t0)}`);
792
+ return {
793
+ sandbox: sb,
794
+ spec,
795
+ env: resolvedEnv,
796
+ adapter,
797
+ fromSnapshot: false,
798
+ runId
799
+ };
800
+ }
801
+ /**
802
+ * Connect to an already-running sandbox WITHOUT touching its Pi bridge. See
803
+ * `Alineo.attach()` for the public-facing docs.
804
+ */
805
+ async function attachAgent(sandboxId, opts) {
806
+ const config = await readProjectConfig();
807
+ const client = new Sandbox({
808
+ baseUrl: config.serverUrl,
809
+ apiKey: config.apiKey,
810
+ adapter: opts.adapter,
811
+ useServerProxy: config.useServerProxy
812
+ });
813
+ const resources = opts.resources ?? config.defaults.resources;
814
+ const sb = await client.connect(sandboxId, opts.name, { resources });
815
+ let envFile;
816
+ try {
817
+ envFile = sandboxId === process.env.ALINEO_SANDBOX_ID ? readFileSync("/etc/alineo-env", "utf8") : await sb.readFile("/etc/alineo-env");
818
+ } catch {
819
+ envFile = "";
820
+ }
821
+ const env = parseShellExports(envFile);
822
+ const runId = env.ALINEO_RUN_ID ?? crypto.randomUUID();
823
+ return {
824
+ sandbox: sb,
825
+ spec: {
826
+ name: opts.name,
827
+ cli: "pi"
828
+ },
829
+ env,
830
+ adapter: new PiAdapter(),
831
+ fromSnapshot: false,
832
+ runId
833
+ };
834
+ }
835
+ /**
836
+ * Fork `self`'s live sandbox into a brand-new independent sandbox running its
837
+ * own Pi bridge, per `childSpecPath`. See `Alineo.spawn()` for the public-facing docs.
838
+ */
839
+ async function spawnChild(self, childSpecPath, opts = {}) {
840
+ const parentDepth = resolveParentSpawnDepth(process.env.ALINEO_SPAWN_DEPTH, opts.spawnDepth);
841
+ const parentMax = resolveParentMaxAgents(process.env.ALINEO_MAX_AGENTS, opts.maxAgents);
842
+ if (parentMax !== void 0 && parentMax <= 0) throw new Error(`Alineo.spawn() refused: max-agents budget exhausted (0 remaining).`);
843
+ const childSpec = validateAgentSpec(await Bun.file(childSpecPath).json());
844
+ const childEnv = resolveEnv(childSpec.env ?? {});
845
+ childEnv.ALINEO_SPAWN_DEPTH = String(parentDepth - 1);
846
+ if (parentMax !== void 0) childEnv.ALINEO_MAX_AGENTS = String(parentMax - 1);
847
+ const runId = process.env.ALINEO_RUN_ID ?? crypto.randomUUID();
848
+ childEnv.ALINEO_RUN_ID = runId;
849
+ const childCredentialBindings = extractCredentialBindings(childSpec.env ?? {});
850
+ const childResourceId = resolveChildResourceId(childSpec);
851
+ console.log(`[agent] forking sandbox for spawn (${childSpec.name})...`);
852
+ const t0 = Date.now();
853
+ const forkedSb = await self.sandbox.fork(childSpec.name, runId, {
854
+ credentialProxy: childCredentialBindings.length > 0,
855
+ resourceId: childResourceId,
856
+ teamId: childSpec.teamId
857
+ });
858
+ console.log(`[agent] fork ready ${elapsed(t0)} (${forkedSb.sandboxId})`);
859
+ for (const { name, value, binding, source } of childCredentialBindings) await forkedSb.credentials.set(name, value, binding, source);
860
+ const adapter = new PiAdapter();
861
+ childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
862
+ await adapter.configure(forkedSb, childSpec, childEnv);
863
+ console.log(`[agent] starting bridge...`);
864
+ const t1 = Date.now();
865
+ await adapter.startBridge(forkedSb, Object.keys(self.env));
866
+ await adapter.waitReady();
867
+ console.log(`[agent] bridge ready ${elapsed(t1)}`);
868
+ return {
869
+ sandbox: forkedSb,
870
+ spec: {
871
+ ...childSpec,
872
+ name: forkedSb.name,
873
+ resourceId: childResourceId
874
+ },
875
+ env: childEnv,
876
+ adapter,
877
+ fromSnapshot: false,
878
+ runId
879
+ };
880
+ }
881
+ /**
882
+ * Seed a just-constructed spawn child's memory from its parent — the memory-layer
883
+ * counterpart to `spawnChild()`'s sandbox-level fork above. Called from `Alineo.spawn()`
884
+ * after the child is constructed (not from `spawnChild()` itself, which runs before the
885
+ * child exists and so has no `child.resourceRef` to fork into yet).
886
+ *
887
+ * A no-op when `parentMemory` is `undefined` — most agents don't have `.memory` configured.
888
+ * Otherwise forks an independent snapshot copy the child can mutate on its own, not a live
889
+ * share of the parent's scope (`child.resourceRef` already names a different resource — the
890
+ * child spec's own name — so this seeds that scope rather than overwriting the parent's).
891
+ *
892
+ * The sandbox fork has already succeeded by the time this runs (`child.sandbox` is live) —
893
+ * if the memory-layer fork throws, close the child sandbox before rethrowing rather than
894
+ * leaving it orphaned with nothing left to close it.
895
+ */
896
+ async function forkChildMemory(parentMemory, parentRef, child) {
897
+ if (!parentMemory) return;
898
+ try {
899
+ await parentMemory.fork(parentRef, child.resourceRef.resourceId);
900
+ } catch (err) {
901
+ await child.close().catch(() => {});
902
+ throw err;
903
+ }
904
+ }
905
+ //#endregion
906
+ //#region src/agent/session-control.ts
907
+ /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
908
+ function prompt(a, message, opts) {
909
+ return a.adapter.prompt(message, opts);
910
+ }
911
+ /**
912
+ * Run a shell command inside Pi's working context. Not incrementally
913
+ * streamed — Pi returns bash output synchronously, so the full output
914
+ * arrives as a single `text` event once the command completes.
915
+ */
916
+ function bash(a, command) {
917
+ return a.adapter.bash(command);
918
+ }
919
+ /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
920
+ async function steer(a, message) {
921
+ return a.adapter.steer(message);
922
+ }
923
+ /** Abort Pi's current operation. */
924
+ async function abort(a) {
925
+ return a.adapter.abort();
926
+ }
927
+ /** Queue a message to be sent to Pi after it finishes its current task. */
928
+ async function followUp(a, message) {
929
+ return a.adapter.followUp(message);
930
+ }
931
+ /** Start a fresh Pi session, clearing all prior context. */
932
+ async function newSession(a) {
933
+ return a.adapter.newSession();
934
+ }
935
+ /** Enable or disable Pi's automatic context compaction. */
936
+ async function setAutoCompaction(a, enabled) {
937
+ return a.adapter.setAutoCompaction(enabled);
938
+ }
939
+ /**
940
+ * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
941
+ * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
942
+ * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
943
+ * events in the stream.
944
+ */
945
+ async function setAutoRetry(a, enabled) {
946
+ return a.adapter.setAutoRetry(enabled);
947
+ }
948
+ /**
949
+ * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
950
+ * operation, emitting `auto_retry_end` with `success: false`.
951
+ */
952
+ async function abortRetry(a) {
953
+ return a.adapter.abortRetry();
954
+ }
955
+ /** Abort a currently-executing bash command without cancelling the whole prompt. */
956
+ async function abortBash(a) {
957
+ return a.adapter.abortBash();
958
+ }
959
+ /**
960
+ * Control how Pi processes queued steering messages.
961
+ * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
962
+ */
963
+ async function setSteeringMode(a, mode) {
964
+ return a.adapter.setSteeringMode(mode);
965
+ }
966
+ /**
967
+ * Control how Pi processes queued follow-up messages.
968
+ * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
969
+ */
970
+ async function setFollowUpMode(a, mode) {
971
+ return a.adapter.setFollowUpMode(mode);
972
+ }
973
+ /** Set a display name for the current Pi session. */
974
+ async function setSessionName(a, name) {
975
+ return a.adapter.setSessionName(name);
976
+ }
977
+ //#endregion
978
+ //#region src/agent/model.ts
979
+ /** Set Pi's reasoning level (for models that support extended thinking). */
980
+ async function setThinkingLevel(a, level) {
981
+ return a.adapter.setThinkingLevel(level);
982
+ }
983
+ /** Switch Pi to a specific model. Returns the activated model. */
984
+ async function setModel(a, provider, modelId) {
985
+ return a.adapter.setModel(provider, modelId);
986
+ }
987
+ /** Cycle Pi to the next available model. Returns null if only one model is configured. */
988
+ async function cycleModel(a) {
989
+ return a.adapter.cycleModel();
990
+ }
991
+ /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
992
+ async function cycleThinkingLevel(a) {
993
+ return a.adapter.cycleThinkingLevel();
994
+ }
995
+ /** List all models available to Pi under the current provider configuration. */
996
+ async function getAvailableModels(a) {
997
+ return a.adapter.getAvailableModels();
998
+ }
999
+ //#endregion
1000
+ //#region src/agent/introspection.ts
1001
+ /** Retrieve token usage, cost, and message counts for the current session. */
1002
+ async function getSessionStats(a) {
1003
+ return a.adapter.getSessionStats();
1004
+ }
1005
+ /** Retrieve the text of Pi's most recent assistant response. Returns `null` if none yet. */
1006
+ async function getLastAssistantText(a) {
1007
+ return a.adapter.getLastAssistantText();
1008
+ }
1009
+ /**
1010
+ * List the fork entry points available in the current session.
1011
+ * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
1012
+ */
1013
+ async function getForkMessages(a) {
1014
+ return a.adapter.getForkMessages();
1015
+ }
1016
+ /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
1017
+ async function getCommands(a) {
1018
+ return a.adapter.getCommands();
1019
+ }
1020
+ /** Retrieve Pi's full conversation history for the current session. */
1021
+ async function getMessages(a) {
1022
+ return a.adapter.getMessages();
1023
+ }
1024
+ /**
1025
+ * Retrieve Pi's current session state: active model, thinking level, streaming/compaction
1026
+ * status, queue modes, and session identity. The only piece of Pi's RPC surface with no
1027
+ * other way to observe the *current* model or thinking level (as opposed to the full list).
1028
+ */
1029
+ async function getState(a) {
1030
+ return a.adapter.getState();
1031
+ }
1032
+ /** Retrieve recent bridge logs (ring-buffered, last 200 entries). */
1033
+ async function getLogs(a) {
1034
+ return a.adapter.getLogs();
1035
+ }
1036
+ //#endregion
1037
+ //#region src/agent/lifecycle.ts
1038
+ /**
1039
+ * Fork Pi's session at the given entry ID, creating a new branch.
1040
+ * Returns the text of the forked message and whether the fork was cancelled.
1041
+ */
1042
+ async function fork(a, entryId) {
1043
+ return a.adapter.fork(entryId);
1044
+ }
1045
+ /** Clone the current Pi session into a new branch at the current position. */
1046
+ async function clone(a) {
1047
+ return a.adapter.clone();
1048
+ }
1049
+ /** Switch Pi to a different session file on disk. */
1050
+ async function switchSession(a, sessionPath) {
1051
+ return a.adapter.switchSession(sessionPath);
1052
+ }
1053
+ /**
1054
+ * Export a static HTML transcript of the current session to the sandbox filesystem.
1055
+ * Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
1056
+ * to retrieve it.
1057
+ */
1058
+ async function exportHtml(a, outputPath) {
1059
+ return a.adapter.exportHtml(outputPath);
1060
+ }
1061
+ /** Manually trigger Pi's context compaction. */
1062
+ async function compact(a, customInstructions) {
1063
+ return a.adapter.compact(customInstructions);
1064
+ }
1065
+ /**
1066
+ * Set or update env vars in the running container. Writes to /etc/alineo-env and restarts
1067
+ * the Pi subprocess so it picks up the new env. Waits until Pi is ready before returning.
1068
+ */
1069
+ async function setEnv(a, vars) {
1070
+ a.env = {
1071
+ ...a.env,
1072
+ ...vars
1073
+ };
1074
+ await a.sandbox.writeFile("/etc/alineo-env", toShellExports(a.env));
1075
+ await a.adapter.reloadEnv(a.env);
1076
+ }
1077
+ /** Delete the sandbox container and release all resources. Always call in a `finally` block. */
1078
+ async function close(a) {
1079
+ a.adapter.disposeConnections();
1080
+ await a.sandbox.close();
1081
+ }
1082
+ //#endregion
1083
+ //#region src/agent/agent.ts
1084
+ /**
1085
+ * A live AI coding agent running inside an OpenSandbox container.
1086
+ *
1087
+ * Wraps a Pi CLI process (`pi --mode rpc --approve`) in an HTTP bridge so the
1088
+ * host can send prompts and receive streamed responses over a stable API,
1089
+ * while Pi manages its own tool use, file writes, and code execution inside the
1090
+ * sandbox.
1091
+ *
1092
+ * Create an agent with `Alineo.load(spec)`. Always call `close()` when done
1093
+ * to release the underlying sandbox container.
86
1094
  *
87
1095
  * @example
88
1096
  * ```ts
89
1097
  * import { Alineo } from "alineo";
90
- * import { SQLiteAdapter } from "@alineo-labs/sqlite";
91
1098
  *
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();
1099
+ * const spec = await Bun.file("./agents/my-agent.json").json();
1100
+ * const agent = await Alineo.load(spec, { adapter });
1101
+ * try {
1102
+ * for await (const chunk of agent.prompt("Explain this codebase")) {
1103
+ * process.stdout.write(chunk);
1104
+ * }
1105
+ * } finally {
1106
+ * await agent.close();
1107
+ * }
102
1108
  * ```
103
1109
  */
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
- });
1110
+ var Alineo = class Alineo {
1111
+ /** OpenSandbox container ID for this agent's sandbox. */
1112
+ sandboxId;
1113
+ name;
1114
+ /**
1115
+ * Direct access to the underlying `SandboxHandle` — full alineo SandboxHandle API, bypasses Pi.
1116
+ * Use this to read or write files, run shell commands, or inspect container state
1117
+ * independently of the Pi conversation.
1118
+ */
1119
+ sandbox;
1120
+ /**
1121
+ * `true` when this agent was loaded from a cached snapshot (fast path).
1122
+ * `false` on the first load for a given spec, or after `{ rebuild: true }`.
1123
+ */
1124
+ fromSnapshot;
1125
+ adapter;
1126
+ env;
1127
+ /**
1128
+ * Identifies the logical run this agent's sandbox belongs to — see
1129
+ * `SandboxDetails.runId`. Always present; a fresh `crypto.randomUUID()` if not
1130
+ * explicitly passed to `load()`/`resume()`. A child from `.spawn()` (and
1131
+ * transitively, `alineo fork`) always inherits its parent's `runId`.
1132
+ */
1133
+ runId;
1134
+ /**
1135
+ * Optional provider-agnostic memory (`@alineo-labs/memory`), wired in via `opts.memory` on
1136
+ * `load()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
1137
+ * constructs a `Memory` on your own behalf, matching this package's "own the pipeline,
1138
+ * don't assume a backend" design. `spawn()` carries the parent's `memory` (if any) onto the
1139
+ * child automatically, the same way it force-computes spawn-depth rather than reading it
1140
+ * back off the child's own spec.
1141
+ */
1142
+ memory;
1143
+ /**
1144
+ * Durable team identity for `.resourceRef` — see `AgentSpec.teamId`. `undefined` unless the
1145
+ * spec this agent was loaded from set it.
1146
+ */
1147
+ teamId;
1148
+ /**
1149
+ * Durable resource identity for `.resourceRef` — see `AgentSpec.resourceId`. Deliberately
1150
+ * separate from `.name`: for a spawned child specifically, `.name` gets overwritten to the
1151
+ * forked sandbox's auto-generated ledger name (`fork-<parent>-<id>`), which is NOT what
1152
+ * memory should be scoped by — see `AgentSpec.resourceId`'s own doc comment for why.
1153
+ */
1154
+ resourceId;
1155
+ /**
1156
+ * Convenience `ResourceRef` scoping `.memory` calls to this agent. `resourceId`/`teamId`
1157
+ * come from `AgentSpec.resourceId`/`AgentSpec.teamId` (`resourceId` defaulting to this
1158
+ * agent's `name` when unset) — `load()`/`resume()`/`spawn()` also thread both into the
1159
+ * ledger (see each field's own doc comment) so this getter and the agent's own episodic
1160
+ * history stay consistent, including across a spawned child whose `.name` differs from its
1161
+ * memory identity.
1162
+ *
1163
+ * Only meaningful once `.memory` is set; pass a different `ResourceRef` explicitly to
1164
+ * `.memory` methods instead if this agent's resourceId/teamId aren't the identity you want.
1165
+ */
1166
+ get resourceRef() {
1167
+ return {
1168
+ resourceId: this.resourceId,
1169
+ teamId: this.teamId
1170
+ };
129
1171
  }
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;
1172
+ constructor(sandbox, spec, env, adapter, fromSnapshot, runId) {
1173
+ this.sandbox = sandbox;
1174
+ this.sandboxId = sandbox.sandboxId;
1175
+ this.name = spec.name;
1176
+ this.teamId = spec.teamId;
1177
+ this.resourceId = spec.resourceId ?? spec.name;
1178
+ this.adapter = adapter;
1179
+ this.env = env;
1180
+ this.fromSnapshot = fromSnapshot;
1181
+ this.runId = runId;
134
1182
  }
135
1183
  /**
136
- * Create a new sandbox container and return a live `Sandbox` object.
1184
+ * Validate `spec` and return a fully initialised `Alineo`.
137
1185
  *
138
- * Waits until the container reaches `Running` state before returning.
139
- * Call `sb.close()` when done to release resources (use try/finally).
1186
+ * `spec` is an already-parsed object, not a file path — `alineo` no longer does its own
1187
+ * file I/O here (see #184). Read one from disk yourself first (`await
1188
+ * Bun.file(path).json()`), fetch it over HTTP, pull it from a database, or build it
1189
+ * programmatically — however you get it, pass the object. It's validated internally
1190
+ * regardless (via `validateAgentSpec()`), so a raw `JSON.parse()`'d object works fine; you
1191
+ * don't need to call `validateAgentSpec()` yourself first unless you want validation errors
1192
+ * to surface before any sandbox/network work starts.
140
1193
  *
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
- * ```
1194
+ * On first load the Pi CLI is installed inside a `node:22` sandbox, then
1195
+ * the sandbox is checkpointed. Subsequent `load()` calls for the same spec
1196
+ * restore from that snapshot — skipping the install and starting in ~3s instead
1197
+ * of ~90s.
1198
+ *
1199
+ * Pass `{ rebuild: true }` to force a full reinstall (e.g. after changing
1200
+ * the spec's `packages` or `cliVersion`).
1201
+ *
1202
+ * Pass `{ spawnDepth }` to override the spec's own `spawnDepth` (e.g. a
1203
+ * `--depth` CLI flag) — standard flag-beats-config precedence. Same for
1204
+ * `{ maxAgents }` and `--max`.
1205
+ *
1206
+ * Logs timing for each phase to stdout via `[agent]` prefixed lines.
151
1207
  */
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
- }
1208
+ static async load(spec, opts) {
1209
+ const r = await loadAgent(spec, opts);
1210
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1211
+ agent.memory = opts.memory;
1212
+ return agent;
203
1213
  }
204
1214
  /**
205
- * Resume a sandbox session from its last checkpoint.
1215
+ * Reconnect to a previously-created agent whose host process has exited.
1216
+ *
1217
+ * The sandbox container must still be running. Pi and any installed packages
1218
+ * are already present — only the bridge process needs to be restarted.
1219
+ * Pi is started with `--continue` so it resumes the most recent session.
206
1220
  *
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.
1221
+ * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
1222
+ * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
1223
+ * `load()`. Takes precedence over `opts.specPath` if both are set.
1224
+ * @param opts.specPath Path to the agent spec JSON, read and validated internally. If
1225
+ * neither `opts.spec` nor `opts.specPath` is set, the ledger is queried for the sandbox's
1226
+ * name and the spec is read from `./agents/<name>.json` — this fallback is the one thing
1227
+ * `resume()` can do that `load()` can't, since a resumed sandbox's original spec may not be
1228
+ * in memory anywhere the caller can hand it over.
211
1229
  *
212
1230
  * @example
213
1231
  * ```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
1232
+ * // Original process:
1233
+ * const spec = await Bun.file("./agents/hello-agent.json").json();
1234
+ * const agent = await Alineo.load(spec, { adapter });
1235
+ * console.log(agent.sandboxId); // save this
1236
+ * // ... process exits ...
219
1237
  *
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();
1238
+ * // New process:
1239
+ * const agent = await Alineo.resume(savedSandboxId, { adapter });
1240
+ * for await (const chunk of agent.prompt("What did we discuss earlier?")) {
1241
+ * process.stdout.write(chunk);
1242
+ * }
1243
+ * await agent.close();
225
1244
  * ```
226
1245
  */
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
- }
1246
+ static async resume(sandboxId, opts) {
1247
+ const r = await resumeAgent(sandboxId, opts);
1248
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1249
+ agent.memory = opts.memory;
1250
+ return agent;
320
1251
  }
321
1252
  /**
322
- * Attach to an already-running sandbox container without creating or restoring anything.
1253
+ * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
1254
+ * `resume()`, which kills and restarts the bridge process. Use this when you only
1255
+ * need `.spawn()`/`.sandbox`, not `.prompt()`/`.bash()`.
323
1256
  *
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.
1257
+ * The main caller is `alineo fork`: it runs as a fresh CLI process started BY the
1258
+ * very Pi bash-tool call it's attaching to (a master agent spawning a child from
1259
+ * inside its own turn). Going through `resume()` there would `pkill` the bridge
1260
+ * that's currently running the Pi process making the call — self-destructive.
327
1261
  *
328
- * @throws `AlineoError` (409) if the sandbox is not in Running state.
1262
+ * The returned `Alineo` has no bridge, so `.prompt()`/`.bash()`/etc. all throw.
1263
+ * Its env is read back from `/etc/alineo-env` on the sandbox itself (the ground
1264
+ * truth for what's actually running there) rather than re-derived from a spec
1265
+ * file, which may not even exist inside this particular sandbox.
329
1266
  *
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.
1267
+ * When `sandboxId` matches `ALINEO_SANDBOX_ID` in this process's own env (true
1268
+ * self-attach, e.g. `alineo fork` running from inside its own container),
1269
+ * `/etc/alineo-env` is read straight off the local filesystem instead of via
1270
+ * `sb.readFile()`. A self-referential exec call would need this sandbox to
1271
+ * reach itself through its own externally-facing bridge IP, which Docker's
1272
+ * default bridge network generally can't hairpin back to the originating
1273
+ * container — sibling-to-sibling traffic works fine, only this exact
1274
+ * self-connect case doesn't, and the caller already has the file locally.
340
1275
  *
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
- * ```
1276
+ * `opts.resources` sizes a subsequent `.spawn()`'s forked container — the
1277
+ * control API doesn't echo back a running sandbox's own resource limits, so
1278
+ * there's no way to discover this agent's *actual* footprint here. Defaults to
1279
+ * `alineo.config.json`'s `defaults.resources`, same fallback `Alineo.load()` uses
1280
+ * for a spec that doesn't set its own.
348
1281
  */
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
- });
1282
+ static async attach(sandboxId, opts) {
1283
+ const r = await attachAgent(sandboxId, opts);
1284
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1285
+ agent.memory = opts.memory;
1286
+ return agent;
362
1287
  }
363
1288
  /**
364
- * Create a fresh sandbox from a snapshot ID without exec replay.
1289
+ * Fork this agent's live sandbox — filesystem, installed packages, checked-out
1290
+ * state, everything currently on disk — into a brand-new independent sandbox
1291
+ * running its own Pi bridge, per `childSpecPath`. Unlike `Alineo.load()` (always
1292
+ * starts from a spec's own snapshot) or `fork()`/`clone()` below (Pi's own
1293
+ * conversation-branching — same container, same bridge, new session branch),
1294
+ * this is sandbox-level forking: the child sees exactly what this agent's
1295
+ * sandbox sees right now, including any uncommitted work.
365
1296
  *
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.
1297
+ * The child's environment is resolved fresh from its OWN spec — nothing is
1298
+ * inherited from this agent except the spawn-depth counter, which is
1299
+ * force-computed (`current - 1`) regardless of what the child's spec or
1300
+ * `opts.spawnDepth` says. Every name this agent's own env declares is also
1301
+ * explicitly `unset` in the shell command that starts the child's bridge, since
1302
+ * the forked container's OS-level env still carries whatever was baked in at
1303
+ * snapshot time independent of what gets written to `/etc/alineo-env`.
369
1304
  *
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.
1305
+ * Refuses immediately unless this agent's own spawn-depth budget
1306
+ * (`ALINEO_SPAWN_DEPTH`, or `opts.spawnDepth` to override it) is a positive
1307
+ * integer — `0` means no budget left, `undefined` means spawning was never
1308
+ * enabled for this agent.
375
1309
  *
376
- * @example
377
- * ```ts
378
- * const snapshotId = await sb.checkpoint();
379
- * await sb.close();
1310
+ * If `ALINEO_MAX_AGENTS` (or `opts.maxAgents`) is set, also refuses once it
1311
+ * hits `0` — a separate, optional ceiling on total descendants for this
1312
+ * lineage, independent of nesting depth. Unset means uncapped for this
1313
+ * dimension; only `spawnDepth` gates whether spawning is allowed at all.
1314
+ * Not coordinated across sibling branches spawned in parallel.
380
1315
  *
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
- * ```
1316
+ * No install/setup steps run — the child inherits Pi (and anything else)
1317
+ * already installed on this agent's sandbox. If the child needs packages this
1318
+ * agent's own sandbox doesn't have, add them to a setup step on the spec THIS
1319
+ * agent was loaded from, not on the child's spec.
386
1320
  */
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
- }
1321
+ async spawn(childSpecPath, opts = {}) {
1322
+ const r = await spawnChild(this, childSpecPath, opts);
1323
+ const child = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1324
+ child.memory = this.memory;
1325
+ await forkChildMemory(this.memory, this.resourceRef, child);
1326
+ return child;
1327
+ }
1328
+ /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
1329
+ prompt(message, opts) {
1330
+ return prompt(this, message, opts);
421
1331
  }
422
1332
  /**
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
- * ```
1333
+ * Run a shell command inside Pi's working context. Not incrementally
1334
+ * streamed — Pi returns bash output synchronously, so the full output
1335
+ * arrives as a single `text` event once the command completes.
431
1336
  */
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
- };
1337
+ bash(command) {
1338
+ return bash(this, command);
1339
+ }
1340
+ /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
1341
+ async steer(message) {
1342
+ return steer(this, message);
1343
+ }
1344
+ /** Abort Pi's current operation. */
1345
+ async abort() {
1346
+ return abort(this);
1347
+ }
1348
+ /** Queue a message to be sent to Pi after it finishes its current task. */
1349
+ async followUp(message) {
1350
+ return followUp(this, message);
1351
+ }
1352
+ /** Start a fresh Pi session, clearing all prior context. */
1353
+ async newSession() {
1354
+ return newSession(this);
1355
+ }
1356
+ /** Set Pi's reasoning level (for models that support extended thinking). */
1357
+ async setThinkingLevel(level) {
1358
+ return setThinkingLevel(this, level);
1359
+ }
1360
+ /** Enable or disable Pi's automatic context compaction. */
1361
+ async setAutoCompaction(enabled) {
1362
+ return setAutoCompaction(this, enabled);
1363
+ }
454
1364
  /**
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
- * ```
1365
+ * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
1366
+ * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
1367
+ * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
1368
+ * events in the stream.
479
1369
  */
480
- environment(name, opts) {
481
- return new Environment(name, opts, this);
1370
+ async setAutoRetry(enabled) {
1371
+ return setAutoRetry(this, enabled);
482
1372
  }
483
1373
  /**
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
- * ```
1374
+ * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
1375
+ * operation, emitting `auto_retry_end` with `success: false`.
491
1376
  */
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;
1377
+ async abortRetry() {
1378
+ return abortRetry(this);
553
1379
  }
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
- }
1380
+ /** Abort a currently-executing bash command without cancelling the whole prompt. */
1381
+ async abortBash() {
1382
+ return abortBash(this);
594
1383
  }
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
- }
1384
+ /** Retrieve token usage, cost, and message counts for the current session. */
1385
+ async getSessionStats() {
1386
+ return getSessionStats(this);
630
1387
  }
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);
1388
+ /** Retrieve the text of Pi's most recent assistant response. Returns `null` if none yet. */
1389
+ async getLastAssistantText() {
1390
+ return getLastAssistantText(this);
642
1391
  }
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++;
1392
+ /**
1393
+ * List the fork entry points available in the current session.
1394
+ * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
1395
+ */
1396
+ async getForkMessages() {
1397
+ return getForkMessages(this);
1398
+ }
1399
+ /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
1400
+ async getCommands() {
1401
+ return getCommands(this);
1402
+ }
1403
+ /** Set a display name for the current Pi session. */
1404
+ async setSessionName(name) {
1405
+ return setSessionName(this, name);
650
1406
  }
651
- _releaseSlot() {
652
- this._activeCount--;
653
- this._waiters.shift()?.();
1407
+ /**
1408
+ * Control how Pi processes queued steering messages.
1409
+ * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
1410
+ */
1411
+ async setSteeringMode(mode) {
1412
+ return setSteeringMode(this, mode);
1413
+ }
1414
+ /**
1415
+ * Control how Pi processes queued follow-up messages.
1416
+ * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
1417
+ */
1418
+ async setFollowUpMode(mode) {
1419
+ return setFollowUpMode(this, mode);
1420
+ }
1421
+ /**
1422
+ * Export a static HTML transcript of the current session to the sandbox filesystem.
1423
+ * Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
1424
+ * to retrieve it.
1425
+ */
1426
+ async exportHtml(outputPath) {
1427
+ return exportHtml(this, outputPath);
1428
+ }
1429
+ /**
1430
+ * Fork Pi's session at the given entry ID, creating a new branch.
1431
+ * Returns the text of the forked message and whether the fork was cancelled.
1432
+ */
1433
+ async fork(entryId) {
1434
+ return fork(this, entryId);
1435
+ }
1436
+ /** Clone the current Pi session into a new branch at the current position. */
1437
+ async clone() {
1438
+ return clone(this);
1439
+ }
1440
+ /** Switch Pi to a different session file on disk. */
1441
+ async switchSession(sessionPath) {
1442
+ return switchSession(this, sessionPath);
1443
+ }
1444
+ /** Switch Pi to a specific model. Returns the activated model. */
1445
+ async setModel(provider, modelId) {
1446
+ return setModel(this, provider, modelId);
1447
+ }
1448
+ /** Cycle Pi to the next available model. Returns null if only one model is configured. */
1449
+ async cycleModel() {
1450
+ return cycleModel(this);
1451
+ }
1452
+ /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
1453
+ async cycleThinkingLevel() {
1454
+ return cycleThinkingLevel(this);
1455
+ }
1456
+ /** Manually trigger Pi's context compaction. */
1457
+ async compact(customInstructions) {
1458
+ return compact(this, customInstructions);
1459
+ }
1460
+ /** Retrieve Pi's full conversation history for the current session. */
1461
+ async getMessages() {
1462
+ return getMessages(this);
1463
+ }
1464
+ /** List all models available to Pi under the current provider configuration. */
1465
+ async getAvailableModels() {
1466
+ return getAvailableModels(this);
1467
+ }
1468
+ /**
1469
+ * Retrieve Pi's current session state: active model, thinking level, streaming/compaction
1470
+ * status, queue modes, and session identity. The only piece of Pi's RPC surface with no
1471
+ * other way to observe the *current* model or thinking level (as opposed to the full list).
1472
+ */
1473
+ async getState() {
1474
+ return getState(this);
1475
+ }
1476
+ /**
1477
+ * Set or update env vars in the running container. Writes to /etc/alineo-env and restarts
1478
+ * the Pi subprocess so it picks up the new env. Waits until Pi is ready before returning.
1479
+ */
1480
+ async setEnv(vars) {
1481
+ return setEnv(this, vars);
1482
+ }
1483
+ /** Retrieve recent bridge logs (ring-buffered, last 200 entries). */
1484
+ async getLogs() {
1485
+ return getLogs(this);
1486
+ }
1487
+ /** Delete the sandbox container and release all resources. Always call in a `finally` block. */
1488
+ async close() {
1489
+ return close(this);
654
1490
  }
655
1491
  };
656
1492
  //#endregion
657
- export { Alineo, AlineoError, BashSession, CodeLanguage, CommandError, Environment, ExecConnectionError, LedgerEvent, Sandbox, SandboxError, SandboxStatus, StepTimeoutError };
1493
+ //#region src/types.ts
1494
+ /** Filter an `AgentStream` down to just text chunks. */
1495
+ async function* textOnly(stream) {
1496
+ for await (const ev of stream) if (ev.type === "text") yield ev.text;
1497
+ }
1498
+ //#endregion
1499
+ export { AgentSnapshotStore, AgentSpecValidationError, Alineo, PromptTimeoutError, computeSetupHash, snapshotsPath, textOnly, validateAgentSpec };