alineo 0.6.0 → 0.8.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,48 +1,266 @@
1
- import { Sandbox } from "@alineo-labs/sandbox";
2
- import { readFileSync } from "node:fs";
3
- import { LedgerEvent, WorkflowError } from "@alineo-labs/core";
1
+ import { DEFAULT_PROVIDER_ID, DEFAULT_PROVIDER_ID as DEFAULT_PROVIDER_ID$1, LedgerEvent, WorkflowError, requireCapability } from "@alineo-labs/core";
2
+ import { AgentSpecSchema, ProjectConfigSchema, deprecatedSpecFields, normalizeAgentSpec, resourceRefOf } from "@alineo-labs/schema";
3
+ import { clientFromConfig } from "@alineo-labs/sandbox";
4
+ import { existsSync, readFileSync } from "node:fs";
4
5
  import { getLogger } from "@alineo-labs/logger";
5
- import { existsSync } from "fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, join, resolve } from "node:path";
6
8
  import * as z$1 from "zod";
9
+ import "zod";
7
10
  import { fileURLToPath } from "node:url";
8
11
  import { createHash } from "node:crypto";
9
- import { mkdir, readFile, writeFile } from "node:fs/promises";
10
- import { dirname } from "node:path";
12
+ import { mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
13
+ import { errorCodeOf } from "@alineo-labs/errors";
11
14
  import { createServer } from "node:http";
12
- //#region src/config.ts
13
- const CONFIG_FILE = "alineo.config.json";
14
- const DEFAULT_CONFIG = {
15
- serverUrl: "http://127.0.0.1:8080",
16
- apiKey: "",
17
- adapterPath: "./.alineo/ledger.db",
18
- useServerProxy: true,
19
- agentsDir: "./agents",
20
- defaults: { resources: {
21
- cpu: "1000m",
22
- memory: "1Gi"
23
- } }
24
- };
15
+ //#region ../config-shared/dist/index.mjs
16
+ /** The file name every alineo project config uses. */
17
+ const PROJECT_CONFIG_FILE = "alineo.config.json";
25
18
  /**
26
- * Read `alineo.config.json` from the current working directory and merge it with
27
- * built-in defaults. Missing fields fall back to the defaults — the config file
28
- * is fully optional.
19
+ * Walk up from `startDir` looking for `alineo.config.json`.
20
+ *
21
+ * Before this existed, `packages/agent` only ever checked `process.cwd()`, so running a script
22
+ * from a subdirectory silently fell back to built-in defaults — a wrong `serverUrl` looked
23
+ * exactly like no config at all.
24
+ *
25
+ * The walk is **bounded**, which matters as much as the walk itself: an unbounded search would
26
+ * let an unrelated `alineo.config.json` several levels up configure a run. It stops after
27
+ * examining:
28
+ *
29
+ * - a directory containing `.git` (the project boundary),
30
+ * - the user's home directory (global config is a separate, explicit source), or
31
+ * - the filesystem root.
32
+ *
33
+ * The stop directory is itself checked before the walk ends, so a config file sitting next to
34
+ * `.git` is still found.
29
35
  */
30
- async function readProjectConfig() {
31
- if (!existsSync(CONFIG_FILE)) return DEFAULT_CONFIG;
32
- const data = await Bun.file(CONFIG_FILE).json();
33
- return {
34
- ...DEFAULT_CONFIG,
35
- ...data,
36
- defaults: {
37
- ...DEFAULT_CONFIG.defaults,
38
- ...data.defaults ?? {},
39
- resources: {
40
- ...DEFAULT_CONFIG.defaults.resources,
41
- ...data.defaults?.resources ?? {}
36
+ function findProjectConfig(startDir = process.cwd()) {
37
+ const home = resolve(homedir());
38
+ let dir = resolve(startDir);
39
+ for (;;) {
40
+ const candidate = join(dir, PROJECT_CONFIG_FILE);
41
+ if (existsSync(candidate)) return candidate;
42
+ if (existsSync(join(dir, ".git"))) return null;
43
+ if (dir === home) return null;
44
+ const parent = dirname(dir);
45
+ if (parent === dir) return null;
46
+ dir = parent;
47
+ }
48
+ }
49
+ /** Absolute path of the user-level config, `~/.config/alineo/config.json`. */
50
+ function globalConfigPath() {
51
+ return join(homedir(), ".config", "alineo", "config.json");
52
+ }
53
+ /**
54
+ * Read and JSON-parse a config file, or return `null` when it isn't there.
55
+ * A file that exists but is malformed throws — a typo in config should be loud, not silently
56
+ * ignored in favour of defaults.
57
+ */
58
+ function readJsonFile(path) {
59
+ if (!existsSync(path)) return null;
60
+ const raw = readFileSync(path, "utf8");
61
+ try {
62
+ return JSON.parse(raw);
63
+ } catch (err) {
64
+ const message = err instanceof Error ? err.message : String(err);
65
+ throw new Error(`${path} is not valid JSON: ${message}`);
66
+ }
67
+ }
68
+ function isPlainObject(value) {
69
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
70
+ const proto = Object.getPrototypeOf(value);
71
+ return proto === Object.prototype || proto === null;
72
+ }
73
+ /**
74
+ * Merge config sources, lowest precedence first. Plain objects merge key by key; everything
75
+ * else (arrays, strings, numbers) is replaced wholesale by the later source.
76
+ *
77
+ * `undefined` never overwrites — an absent key in a higher-precedence source leaves the lower
78
+ * one intact, which is what makes "env var not set" mean "don't override" rather than "clear".
79
+ * An explicit `null` *does* overwrite, so a config file can blank a value on purpose.
80
+ */
81
+ function mergeDeep(...sources) {
82
+ let result = void 0;
83
+ for (const source of sources) {
84
+ if (source === void 0) continue;
85
+ if (isPlainObject(source) && isPlainObject(result)) {
86
+ const merged = { ...result };
87
+ for (const [key, value] of Object.entries(source)) {
88
+ if (value === void 0) continue;
89
+ merged[key] = key in merged ? mergeDeep(merged[key], value) : value;
42
90
  }
91
+ result = merged;
92
+ } else result = source;
93
+ }
94
+ return result;
95
+ }
96
+ /**
97
+ * Freeze an object and everything reachable from it, so a resolved config can't be mutated
98
+ * after validation. Cycles are impossible in JSON-derived data, so no seen-set is needed.
99
+ */
100
+ function deepFreeze(value) {
101
+ if (value === null || typeof value !== "object") return value;
102
+ if (Object.isFrozen(value)) return value;
103
+ Object.freeze(value);
104
+ for (const key of Object.getOwnPropertyNames(value)) deepFreeze(value[key]);
105
+ return value;
106
+ }
107
+ /** Env var holding a whole config document inline, as JSON. */
108
+ const CONFIG_CONTENT_ENV = "ALINEO_CONFIG_CONTENT";
109
+ /**
110
+ * Resolve configuration from every source, lowest precedence first:
111
+ *
112
+ * ```
113
+ * schema defaults
114
+ * < ~/.config/alineo/config.json (user)
115
+ * < alineo.config.json (project — found by bounded walk-up)
116
+ * < ALINEO_CONFIG_CONTENT (inline JSON)
117
+ * < ALINEO_* env vars (ops)
118
+ * < overrides (flags / explicit call-site object)
119
+ * ```
120
+ *
121
+ * Validated once, then deep-frozen. **This function is pure with respect to module state** —
122
+ * nothing is cached here and there is no installed singleton, so two bundled copies of this
123
+ * package cannot drift apart. Callers hold the result for as long as they need it.
124
+ */
125
+ function loadConfigWithSources(options) {
126
+ const { schema, cwd = process.cwd(), env = process.env, fromEnv, overrides, globalPath = globalConfigPath(), discover = true, label = "config" } = options;
127
+ const sources = {
128
+ globalFile: null,
129
+ projectFile: null,
130
+ inlineEnv: false,
131
+ envVars: false,
132
+ overrides: overrides !== void 0
133
+ };
134
+ const layers = [];
135
+ if (discover) {
136
+ if (globalPath) {
137
+ const globalData = readJsonFile(globalPath);
138
+ if (globalData !== null) {
139
+ layers.push(globalData);
140
+ sources.globalFile = globalPath;
141
+ }
142
+ }
143
+ const projectFile = findProjectConfig(cwd);
144
+ if (projectFile) {
145
+ const projectData = readJsonFile(projectFile);
146
+ if (projectData !== null) {
147
+ layers.push(projectData);
148
+ sources.projectFile = projectFile;
149
+ }
150
+ }
151
+ const inline = env[CONFIG_CONTENT_ENV];
152
+ if (inline !== void 0 && inline.trim() !== "") {
153
+ try {
154
+ layers.push(JSON.parse(inline));
155
+ } catch (err) {
156
+ const message = err instanceof Error ? err.message : String(err);
157
+ throw new Error(`${CONFIG_CONTENT_ENV} is not valid JSON: ${message}`);
158
+ }
159
+ sources.inlineEnv = true;
43
160
  }
161
+ if (fromEnv) {
162
+ const fromEnvData = fromEnv(env);
163
+ if (fromEnvData !== void 0) {
164
+ layers.push(fromEnvData);
165
+ sources.envVars = true;
166
+ }
167
+ }
168
+ }
169
+ if (overrides !== void 0) layers.push(overrides);
170
+ const merged = layers.length > 0 ? mergeDeep(...layers) : {};
171
+ const parsed = schema.safeParse(merged ?? {});
172
+ if (!parsed.success) {
173
+ const details = parsed.error.issues.map((issue) => {
174
+ return ` ${issue.path.length > 0 ? issue.path.join(".") : "(root)"}: ${issue.message}`;
175
+ }).join("\n");
176
+ const from = describeSources(sources);
177
+ throw new Error(`Invalid ${label}${from}:\n${details}`);
178
+ }
179
+ return {
180
+ config: deepFreeze(parsed.data),
181
+ sources
44
182
  };
45
183
  }
184
+ /** `loadConfigWithSources` without the provenance — the common case. */
185
+ function loadConfig(options) {
186
+ return loadConfigWithSources(options).config;
187
+ }
188
+ function describeSources(sources) {
189
+ const parts = [];
190
+ if (sources.globalFile) parts.push(sources.globalFile);
191
+ if (sources.projectFile) parts.push(sources.projectFile);
192
+ if (sources.inlineEnv) parts.push(CONFIG_CONTENT_ENV);
193
+ if (sources.envVars) parts.push("environment");
194
+ if (sources.overrides) parts.push("explicit options");
195
+ return parts.length > 0 ? ` (from ${parts.join(", ")})` : "";
196
+ }
197
+ function parseBoolean(raw, name) {
198
+ const value = raw.trim().toLowerCase();
199
+ if ([
200
+ "true",
201
+ "1",
202
+ "yes",
203
+ "on"
204
+ ].includes(value)) return true;
205
+ if ([
206
+ "false",
207
+ "0",
208
+ "no",
209
+ "off"
210
+ ].includes(value)) return false;
211
+ throw new Error(`${name}=${JSON.stringify(raw)} is not a boolean (use true or false)`);
212
+ }
213
+ /**
214
+ * Project-config fields settable from the environment. These are what
215
+ * `apps/alineod/docker-entrypoint.sh` writes into a generated config file before starting the
216
+ * server; reading them directly means the container no longer has to write a file at all.
217
+ */
218
+ function projectConfigFromEnv(env) {
219
+ const out = {};
220
+ if (env.ALINEO_PROVIDER !== void 0) out.provider = env.ALINEO_PROVIDER;
221
+ if (env.ALINEO_SERVER_URL !== void 0) out.serverUrl = env.ALINEO_SERVER_URL;
222
+ if (env.ALINEO_API_KEY !== void 0) out.apiKey = env.ALINEO_API_KEY;
223
+ if (env.ALINEO_USE_SERVER_PROXY !== void 0) out.useServerProxy = parseBoolean(env.ALINEO_USE_SERVER_PROXY, "ALINEO_USE_SERVER_PROXY");
224
+ return Object.keys(out).length > 0 ? out : void 0;
225
+ }
226
+ /** Resolve `alineo.config.json` from every source. Validated once, then frozen. */
227
+ function loadProjectConfig(options = {}) {
228
+ return loadConfig({
229
+ schema: ProjectConfigSchema,
230
+ fromEnv: projectConfigFromEnv,
231
+ label: "alineo config",
232
+ ...options
233
+ });
234
+ }
235
+ //#endregion
236
+ //#region src/config.ts
237
+ /**
238
+ * Resolved configs, keyed by the directory they were resolved from.
239
+ *
240
+ * The previous implementation re-read the file on every `load`/`resume`/`attach`/`spawn`. The
241
+ * cache lives here rather than in `config-shared` on purpose: that package is bundled separately
242
+ * into each consumer, so a cache inside it would be a different cache per copy. Keeping the
243
+ * state here means one cache per process that actually uses it.
244
+ */
245
+ const cache = /* @__PURE__ */ new Map();
246
+ /**
247
+ * Resolve the project config once per working directory.
248
+ *
249
+ * Unlike the old reader, this walks up from the current directory to find
250
+ * `alineo.config.json` (bounded by a `.git` directory, `$HOME`, or the filesystem root), so
251
+ * running a script from a subdirectory no longer silently falls back to defaults. Pass
252
+ * `override` — `opts.config` on the public methods — to skip file and environment discovery
253
+ * entirely, which is what an embedded caller or a test wants.
254
+ */
255
+ function resolveProjectConfig(override) {
256
+ if (override) return override;
257
+ const cwd = process.cwd();
258
+ const cached = cache.get(cwd);
259
+ if (cached) return cached;
260
+ const config = loadProjectConfig({ cwd });
261
+ cache.set(cwd, config);
262
+ return config;
263
+ }
46
264
  //#endregion
47
265
  //#region src/errors.ts
48
266
  /**
@@ -52,20 +270,38 @@ async function readProjectConfig() {
52
270
  * about whether Pi itself is making progress) for that long. Previously this surfaced as an
53
271
  * indefinite hang with zero visibility: `sseStream()` had no timeout at all, so a genuinely
54
272
  * stuck Pi process (e.g. blocked in a credential refresh, or any other silent stall) blocked
55
- * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo fork --prompt` --
273
+ * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo spawn --prompt` --
56
274
  * forever, with no error and no partial output.
57
275
  */
58
276
  var PromptTimeoutError = class extends WorkflowError {
59
277
  timeoutMs;
60
278
  bridgeUrl;
61
279
  constructor(timeoutMs, bridgeUrl) {
62
- super(`Prompt produced no activity for ${timeoutMs / 1e3}s (bridge ${bridgeUrl}) -- the underlying agent process may be stuck`);
280
+ super(`Prompt produced no activity for ${timeoutMs / 1e3}s (bridge ${bridgeUrl}) -- the underlying agent process may be stuck`, "PROMPT_TIMEOUT", { details: { timeoutMs } });
63
281
  this.timeoutMs = timeoutMs;
64
282
  this.bridgeUrl = bridgeUrl;
65
283
  this.name = "PromptTimeoutError";
66
284
  }
67
285
  };
68
286
  /**
287
+ * Thrown when a prompt/bash SSE stream's underlying connection closes (`reader.read()` reports
288
+ * `done: true`) without the bridge ever having sent its own `[DONE]` sentinel first -- the
289
+ * signal that the bridge process died mid-stream (e.g. a crash, an OOM kill), not that Pi
290
+ * actually finished the turn. Previously `sseStream()` treated this exactly like a clean finish
291
+ * (durability-roadmap M2.1, verified live on `my-vps` 2026-10-03: `kill -9`ing the bridge process
292
+ * mid-tool-call settled the turn as a false `success` with no text, in under 20s, instead of
293
+ * ever reaching the inactivity-timeout/catch-up path at all) -- a TCP-level EOF and an
294
+ * application-level `[DONE]` are indistinguishable to a bare `for await` without this.
295
+ */
296
+ var BridgeDisconnectedError = class extends WorkflowError {
297
+ bridgeUrl;
298
+ constructor(bridgeUrl) {
299
+ super(`Bridge connection closed (${bridgeUrl}) before signalling the turn was done -- the underlying agent process likely died`, "BRIDGE_DISCONNECTED");
300
+ this.bridgeUrl = bridgeUrl;
301
+ this.name = "BridgeDisconnectedError";
302
+ }
303
+ };
304
+ /**
69
305
  * Thrown by `validateAgentSpec()` when a spec object fails schema validation. Carries every
70
306
  * failing field in one pass (`.issues`, mirroring `z.ZodIssue[]` shape) rather than surfacing
71
307
  * only the first problem found -- see #185. `.message` is a pre-formatted, human-readable
@@ -75,109 +311,33 @@ var PromptTimeoutError = class extends WorkflowError {
75
311
  var AgentSpecValidationError = class extends WorkflowError {
76
312
  issues;
77
313
  constructor(message, issues) {
78
- super(message);
314
+ super(message, "SPEC_INVALID");
79
315
  this.issues = issues;
80
316
  this.name = "AgentSpecValidationError";
81
317
  }
82
318
  };
83
319
  //#endregion
84
320
  //#region src/schema.ts
85
- /** Renders an arbitrary invalid field value for an error message without risking "[object Object]". */
86
- function describeValue(value) {
87
- if (typeof value === "string") return value;
88
- try {
89
- const json = JSON.stringify(value);
90
- if (json !== void 0) return json;
91
- } catch {}
92
- return typeof value === "object" && value !== null ? Object.prototype.toString.call(value) : String(value);
93
- }
94
- /**
95
- * Runtime schema for `SetupStep`/`AgentSpec` above. Kept as a separate Zod schema rather than
96
- * generating the interfaces from it (`z.infer<>`) so the hand-written interfaces above can carry
97
- * full field-level JSDoc — TypeScript doesn't propagate comments through generic type inference,
98
- * and that documentation is load-bearing (it's what IDE hover/autocomplete shows spec authors).
99
- * If you add/change/remove a field on `AgentSpec`/`SetupStep`, update the matching schema field
100
- * here too — `packages/agent/test/schema.test.ts` is the drift check.
101
- */
102
- const CredentialEnvBindingSchema = z$1.object({
103
- credential: z$1.string({ error: "Each credential env binding must have a 'credential' string" }),
104
- host: z$1.string({ error: "Each credential env binding must have a 'host' string" }),
105
- pathPrefix: z$1.string().optional(),
106
- injection: z$1.union([z$1.object({
107
- type: z$1.literal("header"),
108
- name: z$1.string()
109
- }), z$1.object({
110
- type: z$1.literal("substitution"),
111
- placeholder: z$1.string(),
112
- in: z$1.array(z$1.enum([
113
- "path",
114
- "query",
115
- "header",
116
- "body"
117
- ])).min(1)
118
- })]),
119
- approval: z$1.literal("hold").optional()
120
- }).loose();
121
- const SetupStepSchema = z$1.object({
122
- name: z$1.string({ error: "Each setup step must have a 'name' string" }),
123
- run: z$1.string({ error: "Each setup step must have a 'run' string" }),
124
- cwd: z$1.string().optional()
125
- }).loose();
126
- const PermissionActionSchema = z$1.enum([
127
- "allow",
128
- "ask",
129
- "deny",
130
- "rate_limit",
131
- "classify"
132
- ]);
133
- const PermissionRuleSchema = z$1.object({
134
- tool: z$1.string({ error: "Each permission rule must have a 'tool' string" }),
135
- pattern: z$1.string().optional(),
136
- action: PermissionActionSchema,
137
- limit: z$1.object({
138
- count: z$1.number().int().positive(),
139
- windowMs: z$1.number().int().positive()
140
- }).optional()
141
- }).loose();
142
- const PermissionPolicySchema = z$1.object({
143
- default: PermissionActionSchema.optional(),
144
- rules: z$1.array(PermissionRuleSchema).optional(),
145
- disabledTools: z$1.array(z$1.string()).optional(),
146
- restrictToTools: z$1.array(z$1.string()).optional()
147
- }).loose();
148
- const PermissionsSchema = z$1.union([z$1.enum([
149
- "auto",
150
- "ask",
151
- "readonly"
152
- ]), PermissionPolicySchema]);
153
- 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();
154
- const AgentSpecSchema = z$1.object({
155
- $schema: z$1.string().optional(),
156
- 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"),
157
- title: z$1.string().optional(),
158
- description: z$1.string().optional(),
159
- author: z$1.string().optional(),
160
- categories: z$1.array(z$1.string()).optional(),
161
- 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` }),
162
- cliVersion: z$1.string().optional(),
163
- provider: z$1.string().optional(),
164
- model: z$1.string().optional(),
165
- packages: z$1.array(z$1.string()).optional(),
166
- env: z$1.record(z$1.string(), z$1.union([z$1.string(), CredentialEnvBindingSchema])).optional(),
167
- resources: z$1.object({
168
- cpu: z$1.string(),
169
- memory: z$1.string(),
170
- gpu: z$1.string().optional()
171
- }).optional(),
172
- metadata: z$1.record(z$1.string(), z$1.string()).optional(),
173
- registryDependencies: z$1.array(z$1.string()).optional(),
174
- setup: z$1.array(SetupStepSchema).optional(),
175
- spawnDepth: nonNegativeIntSpecField("spawnDepth"),
176
- maxAgents: nonNegativeIntSpecField("maxAgents"),
177
- teamId: z$1.string().optional(),
178
- resourceId: z$1.string().optional(),
179
- permissions: PermissionsSchema.optional()
180
- }).loose();
321
+ /**
322
+ * Validation for `AgentSpec` — the behaviour half.
323
+ *
324
+ * The shapes themselves (`AgentSpec`, `AgentSpecSchema`, `SetupStep`, `CredentialEnvBinding`)
325
+ * live in `@alineo-labs/schema` and are re-exported here, so every existing import keeps
326
+ * working. What stays is what actually does something: validation, and the error it throws.
327
+ */
328
+ /**
329
+ * The old spec field names, and what each became. There is no alias — an old spec is
330
+ * rejected — but "must have a 'harness' field" is an unhelpful thing to read while looking
331
+ * at a spec that plainly has a `cli` field. Name the rename instead.
332
+ */
333
+ const RENAMED_FIELDS = [["cli", "harness"], ["cliVersion", "harnessVersion"]];
334
+ function renamedFieldHint(data) {
335
+ if (typeof data !== "object" || data === null) return "";
336
+ const stale = RENAMED_FIELDS.filter(([from, to]) => from in data && !(to in data));
337
+ if (stale.length === 0) return "";
338
+ const list = (pick) => stale.map((pair) => `'${pair[pick]}'`).join(" and ");
339
+ return `\n\nThis spec uses ${list(0)}, renamed to ${list(1)}: the field names the agent-loop driver, which is not always a CLI.`;
340
+ }
181
341
  /**
182
342
  * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
183
343
  * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
@@ -185,15 +345,221 @@ const AgentSpecSchema = z$1.object({
185
345
  */
186
346
  function validateAgentSpec(data) {
187
347
  const result = AgentSpecSchema.safeParse(data);
188
- if (!result.success) throw new AgentSpecValidationError(`Invalid agent spec:\n${z$1.prettifyError(result.error)}`, result.error.issues.map((issue) => ({
348
+ if (!result.success) throw new AgentSpecValidationError(`Invalid agent spec:\n${z$1.prettifyError(result.error)}${renamedFieldHint(data)}`, result.error.issues.map((issue) => ({
189
349
  path: issue.path,
190
350
  message: issue.message,
191
351
  code: issue.code
192
352
  })));
193
- return result.data;
353
+ const input = result.data;
354
+ const spec = normalizeAgentSpec(input);
355
+ for (const { field, use } of deprecatedSpecFields(input)) {
356
+ if (warned.has(`${spec.name}:${field}`)) continue;
357
+ warned.add(`${spec.name}:${field}`);
358
+ log$2.warn(`agent spec "${spec.name}" sets '${field}', which is deprecated. Use '${use}'.`);
359
+ }
360
+ return spec;
361
+ }
362
+ const log$2 = getLogger("agent");
363
+ /** One warning per spec and field per process, not one per start. */
364
+ const warned = /* @__PURE__ */ new Set();
365
+ //#endregion
366
+ //#region src/harness/capabilities.ts
367
+ /**
368
+ * What Pi declares. Each value is what `PiAdapter` and `pi-bridge.ts` do today:
369
+ * `/steer`, `/follow-up`, `/fork`, `/compact`, `/set-model`, the permission gate, and
370
+ * `thinking_delta` events.
371
+ */
372
+ const PI_CAPABILITIES = {
373
+ steer: true,
374
+ followUp: true,
375
+ resume: true,
376
+ fork: true,
377
+ compact: true,
378
+ setModel: true,
379
+ permissions: true,
380
+ reasoning: true
381
+ };
382
+ //#endregion
383
+ //#region src/harness/pi-events.ts
384
+ /** The text of an error-ish `unknown`. */
385
+ function messageOf(e) {
386
+ return typeof e === "string" ? e : "";
387
+ }
388
+ /** A message's id, when Pi gives one. Pi's message shape is open, so check before use. */
389
+ function messageIdOf(message) {
390
+ if (message && typeof message === "object" && "id" in message) {
391
+ const id = message.id;
392
+ if (typeof id === "string" && id.length > 0) return id;
393
+ }
394
+ return null;
395
+ }
396
+ /**
397
+ * Map one event of Pi's bridge stream to harness events. Zero, one or more come back.
398
+ *
399
+ * Every Pi event maps to exactly one harness event, and that event carries the Pi event as
400
+ * `raw`. Nothing is dropped. A `thinking_delta` inside `message_update` is `reasoning`.
401
+ * Every other `message_update` delta (text, tool-call, and so on) is a `vendor` event
402
+ * named `message_update`: the text of a `text_delta` already arrives as its own `text`
403
+ * event, so a neutral consumer ignores the vendor one.
404
+ *
405
+ * `agent_end` becomes `done`. The bridge ends a turn with `agent_end`. The error path
406
+ * (a bridge `{error}` frame, a timeout, an abort) is not an event on this stream. The
407
+ * adapter that reads the stream must emit `done` with `reason: "error"` or `"aborted"`.
408
+ */
409
+ function fromPiEvent(ev) {
410
+ const raw = ev;
411
+ switch (ev.type) {
412
+ case "agent_start": return [{
413
+ type: "run_start",
414
+ raw
415
+ }];
416
+ case "agent_end": return [{
417
+ type: "done",
418
+ reason: "completed",
419
+ raw
420
+ }];
421
+ case "text": return [{
422
+ type: "text",
423
+ text: ev.text,
424
+ raw
425
+ }];
426
+ case "turn_start": return [{
427
+ type: "turn_start",
428
+ turnIndex: ev.turnIndex,
429
+ raw
430
+ }];
431
+ case "turn_end": return [{
432
+ type: "turn_end",
433
+ turnIndex: ev.turnIndex,
434
+ raw
435
+ }];
436
+ case "message_start": return [{
437
+ type: "message_start",
438
+ messageId: messageIdOf(ev.message),
439
+ raw
440
+ }];
441
+ case "message_end": return [{
442
+ type: "message_end",
443
+ messageId: messageIdOf(ev.message),
444
+ raw
445
+ }];
446
+ case "message_update": {
447
+ const delta = ev.delta;
448
+ if (delta && typeof delta === "object" && "type" in delta) {
449
+ const d = delta;
450
+ if (d.type === "thinking_delta" && typeof d.delta === "string") return [{
451
+ type: "reasoning",
452
+ text: d.delta,
453
+ raw
454
+ }];
455
+ }
456
+ return [{
457
+ type: "vendor",
458
+ harness: "pi",
459
+ name: "message_update",
460
+ data: ev,
461
+ raw
462
+ }];
463
+ }
464
+ case "tool_start": return [{
465
+ type: "tool_start",
466
+ toolCallId: ev.toolCallId,
467
+ toolName: ev.toolName,
468
+ args: ev.args,
469
+ raw
470
+ }];
471
+ case "tool_update": return [{
472
+ type: "tool_update",
473
+ toolCallId: ev.toolCallId,
474
+ toolName: ev.toolName,
475
+ partial: ev.partialResult,
476
+ raw
477
+ }];
478
+ case "tool_end": return [{
479
+ type: "tool_end",
480
+ toolCallId: ev.toolCallId,
481
+ toolName: ev.toolName,
482
+ result: ev.result,
483
+ isError: ev.isError,
484
+ raw
485
+ }];
486
+ case "permission_request": return [{
487
+ type: "permission_request",
488
+ requestId: ev.requestId,
489
+ tool: ev.tool,
490
+ target: ev.target,
491
+ title: ev.title,
492
+ raw
493
+ }];
494
+ case "permission_resolved": return [{
495
+ type: "permission_resolved",
496
+ requestId: ev.requestId,
497
+ decision: ev.decision,
498
+ raw
499
+ }];
500
+ case "compaction_start": return [{
501
+ type: "compaction",
502
+ phase: "start",
503
+ reason: ev.reason,
504
+ raw
505
+ }];
506
+ case "compaction_end": return [{
507
+ type: "compaction",
508
+ phase: "end",
509
+ reason: ev.reason,
510
+ aborted: ev.aborted,
511
+ willRetry: ev.willRetry,
512
+ raw
513
+ }];
514
+ case "auto_retry_start": return [{
515
+ type: "retry",
516
+ phase: "start",
517
+ attempt: ev.attempt,
518
+ maxAttempts: ev.maxAttempts,
519
+ delayMs: ev.delayMs,
520
+ error: messageOf(ev.errorMessage),
521
+ raw
522
+ }];
523
+ case "auto_retry_end": return [{
524
+ type: "retry",
525
+ phase: "end",
526
+ attempt: ev.attempt,
527
+ success: ev.success,
528
+ error: messageOf(ev.finalError),
529
+ raw
530
+ }];
531
+ case "queue_update": return [{
532
+ type: "queue",
533
+ steering: ev.steering,
534
+ followUp: ev.followUp,
535
+ raw
536
+ }];
537
+ case "extension_ui": return [{
538
+ type: "vendor",
539
+ harness: "pi",
540
+ name: "extension_ui",
541
+ data: ev,
542
+ raw
543
+ }];
544
+ case "extension_error": return [{
545
+ type: "vendor",
546
+ harness: "pi",
547
+ name: "extension_error",
548
+ data: ev,
549
+ raw
550
+ }];
551
+ }
194
552
  }
195
553
  //#endregion
196
554
  //#region src/permissions.ts
555
+ /**
556
+ * Shorthand for the common cases:
557
+ * - `"auto"` — never ask (the default; identical to not setting `permissions` at all)
558
+ * - `"ask"` — ask before every tool call
559
+ * - `"readonly"` — auto-allow the read-only tools (`read`/`grep`/`find`/`ls`), ask before
560
+ * `write`/`edit`/`bash`/`powershell`. Pi has no network tool — an agent reaches the
561
+ * network through `bash`, so `"readonly"` gates that by gating `bash`, not as a category.
562
+ */
197
563
  /** Read-only built-in tools — auto-allowed (and the entire toolset) under `"readonly"`. */
198
564
  const READ_ONLY_TOOLS = [
199
565
  "read",
@@ -344,7 +710,7 @@ function hasOutputRedirect(seg) {
344
710
  /**
345
711
  * Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
346
712
  * recognised pure reader with no output redirection; `false` = something needs a human.
347
- * Mirrored verbatim in `adapters/pi-permission-gate.js`.
713
+ * Mirrored verbatim in `bridge/pi-permission-gate.ts`.
348
714
  */
349
715
  function isReadOnlyBashCommand(command) {
350
716
  const segments = command.split(/&&|\|\||[;\n|]/).map((s) => s.trim()).filter(Boolean);
@@ -365,9 +731,218 @@ function isReadOnlyBashCommand(command) {
365
731
  });
366
732
  }
367
733
  //#endregion
734
+ //#region src/harness/bridge.ts
735
+ /**
736
+ * Read a script the build produced (`dist/<name>`), to write into a sandbox. Resolved beside
737
+ * this module first (the published package, where `index.mjs` sits in `dist/`), then in the
738
+ * package's own `dist/` (running from `src/` in dev and tests). Read lazily, so importing
739
+ * this module does not need a build.
740
+ */
741
+ function readBuiltScript(name) {
742
+ const candidates = [new URL(`./${name}`, import.meta.url), new URL(`../../dist/${name}`, import.meta.url)];
743
+ for (const url of candidates) try {
744
+ return readFileSync(fileURLToPath(url), "utf8");
745
+ } catch {}
746
+ throw new Error(`alineo: ${name} not found. Run \`bun run build\` in packages/agent.`);
747
+ }
748
+ /**
749
+ * What every harness that runs behind an in-sandbox HTTP bridge shares: finding the bridge,
750
+ * waiting for it, streaming a turn from it, closing the streams it leaves open, and the
751
+ * permission endpoints. A subclass adds its own install, configure and turn mapping.
752
+ *
753
+ * The bridge contract (what a bridge script must serve):
754
+ * - `GET /health` returns `{ ok: true }` once it can take a turn.
755
+ * - `POST /abort` ends the running turn.
756
+ * - `POST /permission-response` takes `{ requestId, decision }`.
757
+ * - `GET /pending-permissions` returns `{ ok, data: { pending: PendingPermission[] } }`.
758
+ * - A turn is an SSE stream of JSON frames, ended by `data: [DONE]`. A frame `{ error }` fails it.
759
+ */
760
+ var BridgeHarness = class {
761
+ _bridgeUrl = null;
762
+ /**
763
+ * Controllers for streams `sseStream` deliberately left open (its early return on `[DONE]`,
764
+ * to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE` documents).
765
+ * `AbortController.abort()`, not `reader.cancel()`: Bun's `fetch()` tears down the
766
+ * underlying connection reliably on an abort signal, but was observed to leave the socket
767
+ * referenced after `reader.cancel()` on the bridge's long-lived, heartbeat-pinged
768
+ * connections.
769
+ *
770
+ * Known limitation: a script making two or more such calls before close() can still hang
771
+ * even though every controller here aborts cleanly on the client side. Root cause is the
772
+ * same class of bug as opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination
773
+ * confusing the control server's proxy relay). Tracked in our own #189.
774
+ */
775
+ pendingStreams = /* @__PURE__ */ new Set();
776
+ get bridgeUrl() {
777
+ if (!this._bridgeUrl) throw new Error(`${this.id}: bridge not started`);
778
+ return this._bridgeUrl;
779
+ }
780
+ /**
781
+ * Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the *same*
782
+ * exec command that starts `node`, which a forked sandbox needs: the container's OS-level
783
+ * env still carries whatever the parent had baked in at snapshot time. A plain
784
+ * `sb.exec("unset ...")` beforehand would not work: each `exec()` is its own shell session.
785
+ */
786
+ async start(sb, opts) {
787
+ const vars = opts?.unsetVars;
788
+ const prefix = vars && vars.length > 0 ? `unset ${vars.join(" ")}; ` : "";
789
+ await sb.exec(`${prefix}node ${this.bridgeScriptPath} &`);
790
+ const { url } = await sb.proxy(3001);
791
+ this._bridgeUrl = url;
792
+ }
793
+ /**
794
+ * Rebind to a bridge that is already running. `sb.proxy(port)` is a pure URL lookup: it
795
+ * starts nothing, so nothing in the sandbox changes. Follow with `waitReady()`, because the
796
+ * container can be alive while the bridge process inside it is not.
797
+ */
798
+ async reattach(sb) {
799
+ const { url } = await sb.proxy(3001);
800
+ this._bridgeUrl = url;
801
+ }
802
+ async waitReady(timeoutMs = 3e4) {
803
+ const deadline = Date.now() + timeoutMs;
804
+ while (Date.now() < deadline) {
805
+ try {
806
+ const res = await fetch(`${this.bridgeUrl}/health`);
807
+ if (res.ok) {
808
+ if ((await res.json()).ok) return;
809
+ }
810
+ } catch {}
811
+ await new Promise((r) => setTimeout(r, 500));
812
+ }
813
+ throw new Error(`alineo-bridge did not become ready within ${timeoutMs / 1e3}s`);
814
+ }
815
+ /**
816
+ * Force-close the streams left open (see `pendingStreams`). They sit ESTABLISHED, keeping
817
+ * the event loop alive, because the bridge's own `: ping` heartbeat means no server-side
818
+ * timeout ever ends a dangling one. Call once, as the agent closes.
819
+ */
820
+ dispose() {
821
+ for (const controller of this.pendingStreams) controller.abort();
822
+ this.pendingStreams.clear();
823
+ }
824
+ async abort() {
825
+ await rpcPost(this.bridgeUrl, "/abort");
826
+ }
827
+ async resolvePermission(requestId, decision) {
828
+ await rpcPost(this.bridgeUrl, "/permission-response", {
829
+ requestId,
830
+ decision
831
+ });
832
+ }
833
+ async listPendingPermissions() {
834
+ return (await rpcGet(this.bridgeUrl, "/pending-permissions")).pending;
835
+ }
836
+ /** Open a turn stream on the bridge. */
837
+ stream(path, body, inactivityTimeoutMs) {
838
+ return sseStream(this.bridgeUrl, path, body, this.pendingStreams, inactivityTimeoutMs);
839
+ }
840
+ };
841
+ async function rpcPost(bridgeUrl, path, body = {}) {
842
+ const res = await fetch(`${bridgeUrl}${path}`, {
843
+ method: "POST",
844
+ headers: { "Content-Type": "application/json" },
845
+ body: JSON.stringify(body)
846
+ });
847
+ if (!res.ok) {
848
+ const err = await res.json().catch(() => ({}));
849
+ throw new Error(`${path} failed: ${err.error ?? res.status}`);
850
+ }
851
+ return (await res.json()).data;
852
+ }
853
+ async function rpcGet(bridgeUrl, path) {
854
+ const res = await fetch(`${bridgeUrl}${path}`);
855
+ if (!res.ok) throw new Error(`${path} failed: ${res.status}`);
856
+ return (await res.json()).data;
857
+ }
858
+ /**
859
+ * How long to tolerate zero real `AgentEvent`s before treating the stream as stuck. The
860
+ * bridge's own `: ping` keep-alive (every 3s, see bridge/pi-bridge.ts's `startHeartbeat`) exists only
861
+ * to defeat OpenSandbox's proxy idle-timeout -- it keeps `reader.read()` resolving regardless
862
+ * of whether Pi itself is making progress, so this can't just be "no read() in N seconds". The
863
+ * timer below is instead reset only when a real event is parsed and yielded (or `[DONE]`
864
+ * arrives), so a connection that's alive-but-silent for this long still times out.
865
+ *
866
+ * 60s (the original default) was too tight for a common, legitimate pattern: Pi's own `bash`
867
+ * tool is not incrementally streamed (see the `bash()` doc comment in session-control.ts), so
868
+ * a single tool call that spins up a whole child sandbox -- e.g. a master session running
869
+ * `alineo spawn` on itself, as in examples/rlm-repo-fanout -- produces zero AgentEvents for as
870
+ * long as that tool call takes, which regularly exceeded 60s (child sandbox provisioning +
871
+ * Pi CLI install alone routinely took 30-150s+ in practice) and tripped this timeout mid-run
872
+ * even though the session was making real progress. Raised to 3 minutes as a still-bounded
873
+ * but realistic ceiling for that pattern; pass `inactivityTimeoutMs` explicitly to `prompt()`
874
+ * for sessions that need something tighter or looser.
875
+ */
876
+ const DEFAULT_INACTIVITY_TIMEOUT_MS = 18e4;
877
+ async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeoutMs = DEFAULT_INACTIVITY_TIMEOUT_MS) {
878
+ const controller = new AbortController();
879
+ const res = await fetch(`${bridgeUrl}${path}`, {
880
+ method: "POST",
881
+ headers: { "Content-Type": "application/json" },
882
+ body: JSON.stringify(body),
883
+ signal: controller.signal,
884
+ keepalive: false
885
+ });
886
+ if (!res.ok || !res.body) throw new Error(`Bridge ${path} error: ${res.status}`);
887
+ pendingStreams.add(controller);
888
+ const reader = res.body.getReader();
889
+ const decoder = new TextDecoder();
890
+ let buf = "";
891
+ let lastEventAt = Date.now();
892
+ const pendingPermissions = /* @__PURE__ */ new Set();
893
+ let reachedNaturalEnd = false;
894
+ try {
895
+ while (true) {
896
+ const awaitingHuman = pendingPermissions.size > 0;
897
+ const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
898
+ if (!awaitingHuman && remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
899
+ const result = await Promise.race([reader.read(), new Promise((resolve) => {
900
+ setTimeout(() => {
901
+ resolve("timeout");
902
+ }, awaitingHuman ? inactivityTimeoutMs : Math.max(remainingMs, 1));
903
+ })]);
904
+ if (result === "timeout") {
905
+ if (pendingPermissions.size > 0) {
906
+ lastEventAt = Date.now();
907
+ continue;
908
+ }
909
+ throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
910
+ }
911
+ const { done, value } = result;
912
+ if (done) {
913
+ reachedNaturalEnd = true;
914
+ throw new BridgeDisconnectedError(bridgeUrl);
915
+ }
916
+ buf += decoder.decode(value, { stream: true });
917
+ const lines = buf.split("\n");
918
+ buf = lines.pop() ?? "";
919
+ for (const line of lines) {
920
+ if (!line.startsWith("data: ")) continue;
921
+ const payload = line.slice(6).trim();
922
+ if (payload === "[DONE]") return;
923
+ const raw = JSON.parse(payload);
924
+ if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
925
+ if (raw.requestId !== void 0) {
926
+ if (raw.type === "permission_request") pendingPermissions.add(raw.requestId);
927
+ else if (raw.type === "permission_resolved") pendingPermissions.delete(raw.requestId);
928
+ }
929
+ lastEventAt = Date.now();
930
+ yield raw;
931
+ }
932
+ }
933
+ } finally {
934
+ if (reachedNaturalEnd) {
935
+ pendingStreams.delete(controller);
936
+ reader.releaseLock();
937
+ }
938
+ }
939
+ }
940
+ //#endregion
368
941
  //#region src/adapters/pi.ts
369
- const BRIDGE_SCRIPT = readFileSync(fileURLToPath(new URL("./pi-bridge.js", import.meta.url)), "utf8");
370
- const PERMISSION_GATE_SCRIPT = readFileSync(fileURLToPath(new URL("./pi-permission-gate.js", import.meta.url)), "utf8");
942
+ /** Node CJS bridge script: written to `/alineo-bridge.js` and run with `node`. */
943
+ const bridgeScript$2 = () => readBuiltScript("pi-bridge.cjs");
944
+ /** The permission-gate extension: written to `/alineo-permission-gate.js`, loaded by Pi via `-e`. */
945
+ const permissionGateScript = () => readBuiltScript("pi-permission-gate.mjs");
371
946
  function toShellExports(env) {
372
947
  return Object.entries(env).map(([k, v]) => `export ${k}="${v.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`).join("\n") + "\n";
373
948
  }
@@ -428,54 +1003,29 @@ function parseShellExports(content) {
428
1003
  while (m = re.exec(content)) result[m[1]] = m[2].replace(/\\"/g, "\"").replace(/\\\\/g, "\\");
429
1004
  return result;
430
1005
  }
431
- var PiAdapter = class {
432
- _bridgeUrl = null;
433
- /**
434
- * Controllers for prompt/bash streams `sseStream` deliberately left open (its early
435
- * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
436
- * documents — see that method's comment). `AbortController.abort()`, not
437
- * `reader.cancel()`: Bun's `fetch()` tears down the underlying connection (and unrefs the
438
- * poll keeping the event loop alive) reliably on an abort signal, but was observed to
439
- * leave the socket referenced after `reader.cancel()` alone on this bridge's specific
440
- * long-lived, heartbeat-pinged connections (unlike execd's exec/code streams, which
441
- * self-resolve within execd's own bounded post-completion sleep either way — see
442
- * disposeConnections() below).
443
- *
444
- * Known limitation: this reliably lets a process exit after exactly one prompt()/bash()
445
- * call per agent lifetime (verified). A script making two or more such calls before
446
- * close() can still hang even though every controller here does abort cleanly on the
447
- * client side -- root cause traced to the same class of bug as
448
- * opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination confusing the
449
- * OpenSandbox control server's own proxy relay, which is what `bridgeUrl` is proxied
450
- * through). Tracked in our own #189; not fixable from this file alone.
451
- */
452
- pendingStreams = /* @__PURE__ */ new Set();
453
- get bridgeUrl() {
454
- if (!this._bridgeUrl) throw new Error("PiAdapter: bridge not started");
455
- return this._bridgeUrl;
456
- }
457
- /**
458
- * Force-close any prompt/bash streams `sseStream` deliberately left open (its early
459
- * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
460
- * documents — see that method's comment). Those connections sit ESTABLISHED, keeping
461
- * Bun's event loop alive indefinitely, until something force-closes them -- unlike
462
- * execd's exec/code streams (see `ExecClient.disposeConnections()`), the bridge's own
463
- * `: ping` heartbeat (every 3s, see pi-bridge.js) means there's no bounded server-side
464
- * timeout to eventually resolve a dangling one on its own. Call this once the agent is
465
- * being torn down anyway (from `agent.close()`) instead of leaving the process to hang
466
- * forever on whichever stream's `[DONE]` arrived last.
467
- */
468
- disposeConnections() {
469
- for (const controller of this.pendingStreams) controller.abort();
470
- this.pendingStreams.clear();
471
- }
1006
+ /**
1007
+ * Pi 1.2.x depends on `@aws-sdk/credential-provider-http@^3.972.77`, a version the npm registry
1008
+ * does not serve (newest is 3.972.76), so a fresh `npm install -g` of 1.2.x fails with ETARGET.
1009
+ * Naming 3.972.76 in the same command makes npm resolve to it. Drop this once the registry
1010
+ * serves a version that satisfies Pi 1.2.x.
1011
+ */
1012
+ const PI_1_2_AWS_SDK_PIN = "@aws-sdk/credential-provider-http@3.972.76";
1013
+ /** True for an exact, caret, or tilde specifier on the 1.2 line, such as `1.2.0` or `^1.2.0`. */
1014
+ function needsAwsSdkPin(versionSpecifier) {
1015
+ return versionSpecifier !== void 0 && /^[\^~]?1\.2(\.|$)/.test(versionSpecifier);
1016
+ }
1017
+ var PiAdapter = class extends BridgeHarness {
1018
+ id = "pi";
1019
+ capabilities = PI_CAPABILITIES;
1020
+ bridgeScriptPath = "/alineo-bridge.js";
472
1021
  /** Install Pi CLI and any spec packages. Slow — result is captured by checkpoint(). */
473
1022
  async install(sb, spec) {
474
1023
  const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
475
1024
  if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
476
- const versionSpecifier = spec.cliVersion?.trim();
1025
+ const versionSpecifier = spec.harnessVersion?.trim();
477
1026
  const pkg = versionSpecifier ? `@earendil-works/pi-coding-agent@${versionSpecifier}` : "@earendil-works/pi-coding-agent";
478
- await sb.exec(`npm install -g --ignore-scripts ${pkg}`);
1027
+ const extra = needsAwsSdkPin(versionSpecifier) ? ` ${PI_1_2_AWS_SDK_PIN}` : "";
1028
+ await sb.exec(`npm install -g --ignore-scripts ${pkg}${extra}`);
479
1029
  }
480
1030
  /**
481
1031
  * Write config files and the bridge script. Always runs on every start (fresh install
@@ -484,67 +1034,77 @@ var PiAdapter = class {
484
1034
  async configure(sb, spec, resolvedEnv, opts) {
485
1035
  const piConfig = {};
486
1036
  if (spec.provider) piConfig.provider = spec.provider;
487
- if (spec.model) piConfig.model = spec.model;
1037
+ piConfig.model = spec.model;
488
1038
  if (opts?.resume) piConfig.resume = true;
489
1039
  const permissions = normalizePermissions(spec.permissions);
490
1040
  if (permissions) piConfig.permissions = permissions;
491
1041
  await sb.writeFile("/etc/alineo-pi.json", JSON.stringify(piConfig));
492
1042
  await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
493
- await sb.writeFile("/alineo-bridge.js", BRIDGE_SCRIPT);
494
- if (permissions) await sb.writeFile("/alineo-permission-gate.js", PERMISSION_GATE_SCRIPT);
1043
+ await sb.writeFile("/alineo-bridge.js", bridgeScript$2());
1044
+ if (permissions) await sb.writeFile("/alineo-permission-gate.js", permissionGateScript());
495
1045
  }
496
- /**
497
- * Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the
498
- * *same* exec command that starts `node` — required for `Alineo.spawn()`'s forked
499
- * sandboxes, where the container's OS-level env still carries whatever the parent
500
- * had baked into it at snapshot time (`env` passed to `createSandbox` at fork time
501
- * has no effect on this — verified live, see `plans/alineo-rlm-substrate.md`). A
502
- * plain `sb.exec("unset ...")` beforehand would not work: `unset` only clears the
503
- * shell session it runs in, and each `exec()` call is its own session — it has to
504
- * be part of the exact command that spawns the bridge process so the bridge (and
505
- * everything it in turn spawns, including Pi itself) inherits the already-clean env.
506
- */
507
- async startBridge(sb, unsetVars) {
508
- const prefix = unsetVars && unsetVars.length > 0 ? `unset ${unsetVars.join(" ")}; ` : "";
509
- await sb.exec(`${prefix}node /alineo-bridge.js &`);
510
- const { url } = await sb.proxy(3001);
511
- this._bridgeUrl = url;
1046
+ /** `start()` under its older name. */
1047
+ startBridge(sb, unsetVars) {
1048
+ return this.start(sb, { unsetVars });
1049
+ }
1050
+ /** `fork(entryId)` in the harness-neutral shape. Pi switches its own session in place. */
1051
+ async forkAt(messageId) {
1052
+ await this.fork(messageId);
1053
+ return { sessionRef: null };
1054
+ }
1055
+ /** `reattach()` under its older name. */
1056
+ reattachBridge(sb) {
1057
+ return this.reattach(sb);
1058
+ }
1059
+ /** `dispose()` under its older name. */
1060
+ disposeConnections() {
1061
+ this.dispose();
512
1062
  }
513
1063
  /**
514
- * Rebind to a bridge that's already running (as opposed to `startBridge()`, which execs a
515
- * fresh `node /alineo-bridge.js`). `sb.proxy(port)` is a pure URL lookup against the
516
- * sandbox's control plane — it starts nothing — so this has zero effect on the sandbox
517
- * itself: no killed process, no dropped in-flight turn, no reset Pi conversation state.
1064
+ * One turn as harness events, ending in exactly one `done`. A failure (the bridge sends an
1065
+ * error frame, the stream times out or drops) becomes an `error` event then `done`: it
1066
+ * does not throw, and the `error` event's `raw` is the original error.
518
1067
  *
519
- * Call `waitReady()` afterwards to confirm the bridge is actually still there before relying
520
- * on it — the container can be alive while the bridge process inside it isn't (e.g. it
521
- * crashed independently), and this method alone can't tell the difference.
1068
+ * A stream that ends with no `agent_end` is `aborted`. The bridge ends a stream that way
1069
+ * only when someone called `/abort`, from this process or another. A message sent with
1070
+ * `streamingBehavior` also ends with no `agent_end`: that is `completed`.
522
1071
  */
523
- async reattachBridge(sb) {
524
- const { url } = await sb.proxy(3001);
525
- this._bridgeUrl = url;
526
- }
527
- async waitReady(timeoutMs = 3e4) {
528
- const deadline = Date.now() + timeoutMs;
529
- while (Date.now() < deadline) {
530
- try {
531
- const res = await fetch(`${this.bridgeUrl}/health`);
532
- if (res.ok) {
533
- if ((await res.json()).ok) return;
534
- }
535
- } catch {}
536
- await new Promise((r) => setTimeout(r, 500));
1072
+ async *runTurn(input) {
1073
+ let finished = false;
1074
+ try {
1075
+ const stream = this.prompt(input.message, {
1076
+ streamingBehavior: input.streamingBehavior,
1077
+ inactivityTimeoutMs: input.inactivityTimeoutMs
1078
+ });
1079
+ for await (const ev of stream) for (const out of fromPiEvent(ev)) {
1080
+ if (out.type === "done") finished = true;
1081
+ yield out;
1082
+ }
1083
+ } catch (e) {
1084
+ yield {
1085
+ type: "error",
1086
+ message: e instanceof Error ? e.message : String(e),
1087
+ raw: e
1088
+ };
1089
+ yield {
1090
+ type: "done",
1091
+ reason: "error"
1092
+ };
1093
+ return;
537
1094
  }
538
- throw new Error(`alineo-bridge did not become ready within ${timeoutMs / 1e3}s`);
1095
+ if (!finished) yield {
1096
+ type: "done",
1097
+ reason: input.streamingBehavior ? "completed" : "aborted"
1098
+ };
539
1099
  }
540
1100
  prompt(message, opts) {
541
- return sseStream(this.bridgeUrl, "/prompt", {
1101
+ return this.stream("/prompt", {
542
1102
  message,
543
1103
  streamingBehavior: opts?.streamingBehavior
544
- }, this.pendingStreams, opts?.inactivityTimeoutMs);
1104
+ }, opts?.inactivityTimeoutMs);
545
1105
  }
546
1106
  bash(command) {
547
- return sseStream(this.bridgeUrl, "/bash", { command }, this.pendingStreams);
1107
+ return this.stream("/bash", { command });
548
1108
  }
549
1109
  async steer(message) {
550
1110
  const res = await fetch(`${this.bridgeUrl}/steer`, {
@@ -557,20 +1117,6 @@ var PiAdapter = class {
557
1117
  throw new Error(`steer failed: ${body.error ?? res.status}`);
558
1118
  }
559
1119
  }
560
- async abort() {
561
- await rpcPost(this.bridgeUrl, "/abort");
562
- }
563
- /** Resolve a pending `permission_request` (see `AgentEvent`'s `permission_request`). */
564
- async resolvePermission(requestId, decision) {
565
- await rpcPost(this.bridgeUrl, "/permission-response", {
566
- requestId,
567
- decision
568
- });
569
- }
570
- /** Tool calls currently paused awaiting a human decision. */
571
- async listPendingPermissions() {
572
- return (await rpcGet(this.bridgeUrl, "/pending-permissions")).pending;
573
- }
574
1120
  async followUp(message) {
575
1121
  await rpcPost(this.bridgeUrl, "/follow-up", { message });
576
1122
  }
@@ -657,114 +1203,559 @@ var PiAdapter = class {
657
1203
  return (await fetch(`${this.bridgeUrl}/logs`)).text();
658
1204
  }
659
1205
  };
660
- async function rpcPost(bridgeUrl, path, body = {}) {
661
- const res = await fetch(`${bridgeUrl}${path}`, {
662
- method: "POST",
663
- headers: { "Content-Type": "application/json" },
664
- body: JSON.stringify(body)
665
- });
666
- if (!res.ok) {
667
- const err = await res.json().catch(() => ({}));
668
- throw new Error(`${path} failed: ${err.error ?? res.status}`);
669
- }
670
- return (await res.json()).data;
671
- }
672
- async function rpcGet(bridgeUrl, path) {
673
- const res = await fetch(`${bridgeUrl}${path}`);
674
- if (!res.ok) throw new Error(`${path} failed: ${res.status}`);
675
- return (await res.json()).data;
676
- }
1206
+ //#endregion
1207
+ //#region src/adapters/claude-code.ts
677
1208
  /**
678
- * How long to tolerate zero real `AgentEvent`s before treating the stream as stuck. The
679
- * bridge's own `: ping` keep-alive (every 3s, see pi-bridge.js's `startHeartbeat`) exists only
680
- * to defeat OpenSandbox's proxy idle-timeout -- it keeps `reader.read()` resolving regardless
681
- * of whether Pi itself is making progress, so this can't just be "no read() in N seconds". The
682
- * timer below is instead reset only when a real event is parsed and yielded (or `[DONE]`
683
- * arrives), so a connection that's alive-but-silent for this long still times out.
1209
+ * What Claude Code declares. Each `false` is a thing the bridge does not do today, not a
1210
+ * limit of the SDK: `steer` and `followUp` have no mid-turn injection in single-prompt mode,
1211
+ * `compact` and `setModel` are not wired, and `reasoning` needs extended thinking turned on.
1212
+ */
1213
+ const CLAUDE_CODE_CAPABILITIES = {
1214
+ steer: false,
1215
+ followUp: false,
1216
+ resume: true,
1217
+ fork: true,
1218
+ compact: false,
1219
+ setModel: false,
1220
+ permissions: true,
1221
+ reasoning: false
1222
+ };
1223
+ const SDK_PACKAGE = "@anthropic-ai/claude-agent-sdk";
1224
+ /** Node CJS bridge script: written to `/alineo-bridge.js` and run with `node`. */
1225
+ const bridgeScript$1 = () => readBuiltScript("claude-bridge.cjs");
1226
+ /**
1227
+ * Claude Code, driven through the Claude Agent SDK by a bridge in the sandbox. The bridge's
1228
+ * frames are already `HarnessEvent`s, so `runTurn` forwards them.
684
1229
  *
685
- * 60s (the original default) was too tight for a common, legitimate pattern: Pi's own `bash`
686
- * tool is not incrementally streamed (see the `bash()` doc comment in session-control.ts), so
687
- * a single tool call that spins up a whole child sandbox -- e.g. a master session running
688
- * `alineo fork` on itself, as in examples/rlm-repo-fanout -- produces zero AgentEvents for as
689
- * long as that tool call takes, which regularly exceeded 60s (child sandbox provisioning +
690
- * Pi CLI install alone routinely took 30-150s+ in practice) and tripped this timeout mid-run
691
- * even though the session was making real progress. Raised to 3 minutes as a still-bounded
692
- * but realistic ceiling for that pattern; pass `inactivityTimeoutMs` explicitly to `prompt()`
693
- * for sessions that need something tighter or looser.
1230
+ * @experimental The harness layer is being built. Expect changes before it is stable.
694
1231
  */
695
- const DEFAULT_INACTIVITY_TIMEOUT_MS = 18e4;
696
- async function* sseStream(bridgeUrl, path, body, pendingStreams, inactivityTimeoutMs = DEFAULT_INACTIVITY_TIMEOUT_MS) {
697
- const controller = new AbortController();
698
- const res = await fetch(`${bridgeUrl}${path}`, {
699
- method: "POST",
700
- headers: { "Content-Type": "application/json" },
701
- body: JSON.stringify(body),
702
- signal: controller.signal,
703
- keepalive: false
704
- });
705
- if (!res.ok || !res.body) throw new Error(`Bridge ${path} error: ${res.status}`);
706
- pendingStreams.add(controller);
707
- const reader = res.body.getReader();
708
- const decoder = new TextDecoder();
709
- let buf = "";
710
- let lastEventAt = Date.now();
711
- const pendingPermissions = /* @__PURE__ */ new Set();
712
- let reachedNaturalEnd = false;
713
- try {
714
- while (true) {
715
- const awaitingHuman = pendingPermissions.size > 0;
716
- const remainingMs = inactivityTimeoutMs - (Date.now() - lastEventAt);
717
- if (!awaitingHuman && remainingMs <= 0) throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
718
- const result = await Promise.race([reader.read(), new Promise((resolve) => {
719
- setTimeout(() => {
720
- resolve("timeout");
721
- }, awaitingHuman ? inactivityTimeoutMs : Math.max(remainingMs, 1));
722
- })]);
723
- if (result === "timeout") {
724
- if (pendingPermissions.size > 0) {
725
- lastEventAt = Date.now();
726
- continue;
1232
+ var ClaudeCodeAdapter = class extends BridgeHarness {
1233
+ id = "claude-code";
1234
+ capabilities = CLAUDE_CODE_CAPABILITIES;
1235
+ bridgeScriptPath = "/alineo-bridge.js";
1236
+ /** Install the Agent SDK globally, and any spec packages. Slow: a snapshot captures it. */
1237
+ async install(sb, spec) {
1238
+ const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
1239
+ if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
1240
+ const version = spec.harnessVersion?.trim();
1241
+ const pkg = version ? `${SDK_PACKAGE}@${version}` : SDK_PACKAGE;
1242
+ await sb.exec(`npm install -g --ignore-scripts ${pkg}`);
1243
+ }
1244
+ async configure(sb, spec, resolvedEnv, opts) {
1245
+ const config = { model: spec.model };
1246
+ if (opts?.resume) config.resume = true;
1247
+ const permissions = normalizePermissions(spec.permissions);
1248
+ if (permissions) config.permissions = permissions;
1249
+ await sb.writeFile("/etc/alineo-claude.json", JSON.stringify(config));
1250
+ await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
1251
+ await sb.writeFile("/alineo-bridge.js", bridgeScript$1());
1252
+ }
1253
+ /**
1254
+ * One turn as harness events. The bridge already speaks `HarnessEvent`, so the frames pass
1255
+ * through. A bridge error frame, timeout or dropped stream is an `error` then `done`, and
1256
+ * does not throw. A stream that ends with no `done` is `aborted`.
1257
+ */
1258
+ async *runTurn(input) {
1259
+ let finished = false;
1260
+ try {
1261
+ for await (const frame of this.stream("/prompt", { message: input.message }, input.inactivityTimeoutMs)) {
1262
+ yield frame;
1263
+ if (frame.type === "done") {
1264
+ finished = true;
1265
+ return;
727
1266
  }
728
- throw new PromptTimeoutError(inactivityTimeoutMs, bridgeUrl);
729
1267
  }
730
- const { done, value } = result;
731
- if (done) {
732
- reachedNaturalEnd = true;
733
- break;
1268
+ } catch (e) {
1269
+ yield {
1270
+ type: "error",
1271
+ message: e instanceof Error ? e.message : String(e),
1272
+ raw: e
1273
+ };
1274
+ yield {
1275
+ type: "done",
1276
+ reason: "error"
1277
+ };
1278
+ return;
1279
+ }
1280
+ if (!finished) yield {
1281
+ type: "done",
1282
+ reason: "aborted"
1283
+ };
1284
+ }
1285
+ async forkAt(messageId) {
1286
+ return { sessionRef: (await rpcPost(this.bridgeUrl, "/fork", { entryId: messageId })).sessionRef };
1287
+ }
1288
+ };
1289
+ //#endregion
1290
+ //#region src/adapters/codex.ts
1291
+ /**
1292
+ * What Codex declares, each backed by an `app-server` method: `turn/steer`,
1293
+ * `thread/compact/start`, `thread/fork`, the approval requests, and reasoning deltas.
1294
+ * `followUp` and `setModel` are not wired.
1295
+ */
1296
+ const CODEX_CAPABILITIES = {
1297
+ steer: true,
1298
+ followUp: false,
1299
+ resume: true,
1300
+ fork: true,
1301
+ compact: true,
1302
+ setModel: false,
1303
+ permissions: true,
1304
+ reasoning: true
1305
+ };
1306
+ const CODEX_PACKAGE = "@openai/codex";
1307
+ /** Node CJS bridge script: written to `/alineo-bridge.js` and run with `node`. */
1308
+ const bridgeScript = () => readBuiltScript("codex-bridge.cjs");
1309
+ /**
1310
+ * Codex, driven through `codex app-server` (JSON-RPC over stdio) by a bridge in the sandbox.
1311
+ * The bridge's frames are already `HarnessEvent`s, so `runTurn` forwards them.
1312
+ *
1313
+ * Fork granularity is the turn: every message of a turn has the turn id as its `messageId`,
1314
+ * because `thread/fork` takes `lastTurnId`.
1315
+ *
1316
+ * @experimental The harness layer is being built. Expect changes before it is stable.
1317
+ */
1318
+ var CodexAdapter = class extends BridgeHarness {
1319
+ id = "codex";
1320
+ capabilities = CODEX_CAPABILITIES;
1321
+ bridgeScriptPath = "/alineo-bridge.js";
1322
+ async install(sb, spec) {
1323
+ const pkgs = [...new Set(spec.packages ?? [])].filter((p) => p !== "nodejs_22" && p !== "nodejs");
1324
+ if (pkgs.length > 0) await sb.exec(`apt-get update -qq && apt-get install -y --no-install-recommends ${pkgs.join(" ")}`);
1325
+ const version = spec.harnessVersion?.trim();
1326
+ const pkg = version ? `${CODEX_PACKAGE}@${version}` : CODEX_PACKAGE;
1327
+ await sb.exec(`npm install -g --ignore-scripts ${pkg}`);
1328
+ }
1329
+ async configure(sb, spec, resolvedEnv, opts) {
1330
+ const config = { model: spec.model };
1331
+ if (opts?.resume) config.resume = true;
1332
+ const permissions = normalizePermissions(spec.permissions);
1333
+ if (permissions) config.permissions = permissions;
1334
+ await sb.writeFile("/etc/alineo-codex.json", JSON.stringify(config));
1335
+ await sb.writeFile("/etc/alineo-env", toShellExports(resolvedEnv));
1336
+ await sb.writeFile("/alineo-bridge.js", bridgeScript());
1337
+ }
1338
+ async *runTurn(input) {
1339
+ let finished = false;
1340
+ try {
1341
+ for await (const frame of this.stream("/prompt", { message: input.message }, input.inactivityTimeoutMs)) {
1342
+ yield frame;
1343
+ if (frame.type === "done") {
1344
+ finished = true;
1345
+ return;
1346
+ }
734
1347
  }
735
- buf += decoder.decode(value, { stream: true });
736
- const lines = buf.split("\n");
737
- buf = lines.pop() ?? "";
738
- for (const line of lines) {
739
- if (!line.startsWith("data: ")) continue;
740
- const payload = line.slice(6).trim();
741
- if (payload === "[DONE]") return;
742
- const raw = JSON.parse(payload);
743
- if (raw.error) throw new Error(`Bridge error: ${raw.error}`);
744
- if (raw.type === "permission_request") pendingPermissions.add(raw.requestId);
745
- else if (raw.type === "permission_resolved") pendingPermissions.delete(raw.requestId);
746
- lastEventAt = Date.now();
747
- yield raw;
1348
+ } catch (e) {
1349
+ yield {
1350
+ type: "error",
1351
+ message: e instanceof Error ? e.message : String(e),
1352
+ raw: e
1353
+ };
1354
+ yield {
1355
+ type: "done",
1356
+ reason: "error"
1357
+ };
1358
+ return;
1359
+ }
1360
+ if (!finished) yield {
1361
+ type: "done",
1362
+ reason: "aborted"
1363
+ };
1364
+ }
1365
+ /** `turn/steer` into the running turn. Refused with `no turn in progress` between turns. */
1366
+ async steer(message) {
1367
+ await rpcPost(this.bridgeUrl, "/steer", { message });
1368
+ }
1369
+ async compact() {
1370
+ await rpcPost(this.bridgeUrl, "/compact");
1371
+ return {};
1372
+ }
1373
+ /** `thread/fork`. `messageId` is a turn id, from a `message_start` of this adapter. */
1374
+ async forkAt(messageId) {
1375
+ return { sessionRef: (await rpcPost(this.bridgeUrl, "/fork", { entryId: messageId })).sessionRef };
1376
+ }
1377
+ };
1378
+ //#endregion
1379
+ //#region src/harness/registry.ts
1380
+ const constructors = {
1381
+ pi: () => new PiAdapter(),
1382
+ "claude-code": () => new ClaudeCodeAdapter(),
1383
+ codex: () => new CodexAdapter()
1384
+ };
1385
+ /** The ids `createHarness()` accepts. */
1386
+ function registeredHarnesses() {
1387
+ return Object.keys(constructors);
1388
+ }
1389
+ /**
1390
+ * Create the adapter for a harness id. The only place an adapter class is constructed.
1391
+ * Throws `SPEC_INVALID` for an id nothing registered.
1392
+ */
1393
+ function createHarness(id) {
1394
+ const make = constructors[id];
1395
+ if (!make) throw new WorkflowError(`Unknown harness "${String(id)}"`, "SPEC_INVALID", {
1396
+ details: {
1397
+ harness: String(id),
1398
+ registered: registeredHarnesses().join(",")
1399
+ },
1400
+ hint: `Set "harness" to one of: ${registeredHarnesses().join(", ")}.`
1401
+ });
1402
+ return make();
1403
+ }
1404
+ /**
1405
+ * Refuse a call the harness declared it cannot do, before anything is sent. Same idea as
1406
+ * `requireCapability` for sandbox providers.
1407
+ */
1408
+ function requireHarnessCapability(adapter, capability) {
1409
+ if (adapter.capabilities[capability]) return;
1410
+ throw new WorkflowError(`The ${adapter.id} harness does not support ${capability}`, "CAPABILITY_UNSUPPORTED", { details: {
1411
+ capability,
1412
+ harness: adapter.id
1413
+ } });
1414
+ }
1415
+ //#endregion
1416
+ //#region src/harness/fake.ts
1417
+ const ALL_ON = {
1418
+ steer: true,
1419
+ followUp: true,
1420
+ resume: true,
1421
+ fork: true,
1422
+ compact: true,
1423
+ setModel: true,
1424
+ permissions: true,
1425
+ reasoning: true
1426
+ };
1427
+ /**
1428
+ * A harness that runs no process: it plays a `FakeScenario` in memory. For tests that need
1429
+ * a `HarnessAdapter` and for proving the conformance suite itself is satisfiable. It is not
1430
+ * registered, so a spec cannot select it.
1431
+ *
1432
+ * @experimental The harness layer is being built. Expect changes before it is stable.
1433
+ */
1434
+ var FakeHarness = class {
1435
+ scenario;
1436
+ id = "fake";
1437
+ capabilities;
1438
+ /** Lifecycle calls in order, for assertions. */
1439
+ calls = [];
1440
+ /** Messages `steer` and `followUp` accepted. */
1441
+ received = [];
1442
+ steer;
1443
+ followUp;
1444
+ forkAt;
1445
+ compact;
1446
+ turnActive = false;
1447
+ release = null;
1448
+ pending = /* @__PURE__ */ new Map();
1449
+ constructor(scenario, capabilities = {}) {
1450
+ this.scenario = scenario;
1451
+ this.capabilities = {
1452
+ ...ALL_ON,
1453
+ ...capabilities
1454
+ };
1455
+ if (this.capabilities.steer) this.steer = (message) => {
1456
+ if (!this.turnActive) return Promise.reject(/* @__PURE__ */ new Error("no turn in progress"));
1457
+ this.received.push(message);
1458
+ return Promise.resolve();
1459
+ };
1460
+ if (this.capabilities.compact) this.compact = () => {
1461
+ this.received.push("compact");
1462
+ return Promise.resolve({});
1463
+ };
1464
+ if (this.capabilities.fork) this.forkAt = (messageId) => {
1465
+ this.received.push(`fork:${messageId}`);
1466
+ return Promise.resolve({ sessionRef: `fake-fork-of-${messageId}` });
1467
+ };
1468
+ if (this.capabilities.followUp) this.followUp = (message) => {
1469
+ this.received.push(message);
1470
+ return Promise.resolve();
1471
+ };
1472
+ }
1473
+ install(_sb, _spec) {
1474
+ this.calls.push("install");
1475
+ return Promise.resolve();
1476
+ }
1477
+ configure() {
1478
+ this.calls.push("configure");
1479
+ return Promise.resolve();
1480
+ }
1481
+ start() {
1482
+ this.calls.push("start");
1483
+ return Promise.resolve();
1484
+ }
1485
+ reattach() {
1486
+ this.calls.push("reattach");
1487
+ return Promise.resolve();
1488
+ }
1489
+ waitReady() {
1490
+ this.calls.push("waitReady");
1491
+ return Promise.resolve();
1492
+ }
1493
+ async *runTurn(_input) {
1494
+ this.turnActive = true;
1495
+ const s = this.scenario;
1496
+ try {
1497
+ yield { type: "run_start" };
1498
+ switch (s.kind) {
1499
+ case "text":
1500
+ yield {
1501
+ type: "text",
1502
+ text: s.text
1503
+ };
1504
+ break;
1505
+ case "tool":
1506
+ yield {
1507
+ type: "tool_start",
1508
+ toolCallId: "t1",
1509
+ toolName: s.toolName,
1510
+ args: {}
1511
+ };
1512
+ yield {
1513
+ type: "tool_end",
1514
+ toolCallId: "t1",
1515
+ toolName: s.toolName,
1516
+ result: s.result,
1517
+ isError: false
1518
+ };
1519
+ break;
1520
+ case "fail":
1521
+ yield {
1522
+ type: "error",
1523
+ message: s.message
1524
+ };
1525
+ yield {
1526
+ type: "done",
1527
+ reason: "error"
1528
+ };
1529
+ return;
1530
+ case "hang":
1531
+ await new Promise((resolve) => {
1532
+ this.release = resolve;
1533
+ });
1534
+ yield {
1535
+ type: "done",
1536
+ reason: "aborted"
1537
+ };
1538
+ return;
1539
+ case "permission": {
1540
+ const requestId = "perm-1";
1541
+ const info = {
1542
+ requestId,
1543
+ tool: s.tool,
1544
+ target: s.target,
1545
+ title: `Run ${s.tool}: ${s.target}`,
1546
+ since: Date.now()
1547
+ };
1548
+ const decided = new Promise((settle) => {
1549
+ this.pending.set(requestId, {
1550
+ info,
1551
+ settle
1552
+ });
1553
+ });
1554
+ yield {
1555
+ type: "permission_request",
1556
+ requestId,
1557
+ tool: s.tool,
1558
+ target: s.target,
1559
+ title: info.title
1560
+ };
1561
+ const decision = await decided;
1562
+ this.pending.delete(requestId);
1563
+ yield {
1564
+ type: "permission_resolved",
1565
+ requestId,
1566
+ decision
1567
+ };
1568
+ if (decision.kind === "reject") yield {
1569
+ type: "text",
1570
+ text: "The call was declined."
1571
+ };
1572
+ else {
1573
+ yield {
1574
+ type: "tool_start",
1575
+ toolCallId: "t1",
1576
+ toolName: s.tool,
1577
+ args: { target: s.target }
1578
+ };
1579
+ yield {
1580
+ type: "tool_end",
1581
+ toolCallId: "t1",
1582
+ toolName: s.tool,
1583
+ result: "ok",
1584
+ isError: false
1585
+ };
1586
+ }
1587
+ break;
1588
+ }
748
1589
  }
1590
+ yield {
1591
+ type: "done",
1592
+ reason: "completed"
1593
+ };
1594
+ } finally {
1595
+ this.turnActive = false;
749
1596
  }
750
- } finally {
751
- if (reachedNaturalEnd) {
752
- pendingStreams.delete(controller);
753
- reader.releaseLock();
754
- }
1597
+ }
1598
+ abort() {
1599
+ this.release?.();
1600
+ this.release = null;
1601
+ return Promise.resolve();
1602
+ }
1603
+ resolvePermission(requestId, decision) {
1604
+ const p = this.pending.get(requestId);
1605
+ if (!p) return Promise.reject(/* @__PURE__ */ new Error("no such pending permission"));
1606
+ p.settle(decision);
1607
+ return Promise.resolve();
1608
+ }
1609
+ listPendingPermissions() {
1610
+ return Promise.resolve([...this.pending.values()].map((p) => p.info));
1611
+ }
1612
+ dispose() {
1613
+ this.calls.push("dispose");
1614
+ }
1615
+ };
1616
+ //#endregion
1617
+ //#region src/harness/legacy.ts
1618
+ /**
1619
+ * Project a harness event onto the public `AgentEvent` that `prompt()` has always yielded.
1620
+ * `null` means the event has no `AgentEvent` form.
1621
+ *
1622
+ * Pi's events pass through unchanged: `fromPiEvent` keeps each one as `raw`, so the
1623
+ * projection is the identity and no Pi caller sees a difference. Every other harness is
1624
+ * projected from the neutral fields. This is a bridge for compatibility. It is removed
1625
+ * when `AgentEvent` is retired in favor of `HarnessEvent`.
1626
+ */
1627
+ function toAgentEvent(ev, harnessId) {
1628
+ if (harnessId === "pi" && ev.raw !== void 0) return ev.raw;
1629
+ switch (ev.type) {
1630
+ case "run_start": return { type: "agent_start" };
1631
+ case "done": return ev.reason === "completed" ? {
1632
+ type: "agent_end",
1633
+ messages: []
1634
+ } : null;
1635
+ case "text": return {
1636
+ type: "text",
1637
+ text: ev.text
1638
+ };
1639
+ case "reasoning": return null;
1640
+ case "turn_start": return {
1641
+ type: "turn_start",
1642
+ turnIndex: ev.turnIndex,
1643
+ timestamp: Date.now()
1644
+ };
1645
+ case "turn_end": return {
1646
+ type: "turn_end",
1647
+ turnIndex: ev.turnIndex,
1648
+ message: null,
1649
+ toolResults: []
1650
+ };
1651
+ case "message_start": return {
1652
+ type: "message_start",
1653
+ message: {
1654
+ role: "assistant",
1655
+ id: ev.messageId
1656
+ }
1657
+ };
1658
+ case "message_end": return {
1659
+ type: "message_end",
1660
+ message: {
1661
+ role: "assistant",
1662
+ id: ev.messageId
1663
+ }
1664
+ };
1665
+ case "tool_start": return {
1666
+ type: "tool_start",
1667
+ toolCallId: ev.toolCallId,
1668
+ toolName: ev.toolName,
1669
+ args: ev.args
1670
+ };
1671
+ case "tool_update": return {
1672
+ type: "tool_update",
1673
+ toolCallId: ev.toolCallId,
1674
+ toolName: ev.toolName,
1675
+ partialResult: ev.partial
1676
+ };
1677
+ case "tool_end": return {
1678
+ type: "tool_end",
1679
+ toolCallId: ev.toolCallId,
1680
+ toolName: ev.toolName,
1681
+ result: ev.result,
1682
+ isError: ev.isError
1683
+ };
1684
+ case "permission_request": return {
1685
+ type: "permission_request",
1686
+ requestId: ev.requestId,
1687
+ tool: ev.tool,
1688
+ target: ev.target,
1689
+ title: ev.title
1690
+ };
1691
+ case "permission_resolved": return {
1692
+ type: "permission_resolved",
1693
+ requestId: ev.requestId,
1694
+ decision: ev.decision
1695
+ };
1696
+ case "compaction": return ev.phase === "start" ? {
1697
+ type: "compaction_start",
1698
+ reason: asCompactionReason(ev.reason)
1699
+ } : {
1700
+ type: "compaction_end",
1701
+ reason: asCompactionReason(ev.reason),
1702
+ result: null,
1703
+ aborted: ev.aborted ?? false,
1704
+ willRetry: ev.willRetry ?? false
1705
+ };
1706
+ case "retry": return ev.phase === "start" ? {
1707
+ type: "auto_retry_start",
1708
+ attempt: ev.attempt,
1709
+ maxAttempts: ev.maxAttempts ?? ev.attempt,
1710
+ delayMs: ev.delayMs ?? 0,
1711
+ errorMessage: ev.error ?? ""
1712
+ } : {
1713
+ type: "auto_retry_end",
1714
+ success: ev.success ?? false,
1715
+ attempt: ev.attempt,
1716
+ finalError: ev.error
1717
+ };
1718
+ case "queue": return {
1719
+ type: "queue_update",
1720
+ steering: ev.steering,
1721
+ followUp: ev.followUp
1722
+ };
1723
+ case "vendor":
1724
+ case "error": return null;
1725
+ }
1726
+ }
1727
+ function asCompactionReason(reason) {
1728
+ return reason === "threshold" || reason === "overflow" ? reason : "manual";
1729
+ }
1730
+ /**
1731
+ * Run a turn and yield `AgentEvent`s, as `prompt()` always has. A failed turn throws the
1732
+ * original error, so callers that catch `PromptTimeoutError` or `BridgeDisconnectedError`
1733
+ * keep working. A failure with no error object throws a plain `Error` with its message.
1734
+ */
1735
+ async function* legacyStream(adapter, input) {
1736
+ for await (const h of adapter.runTurn(input)) {
1737
+ if (h.type === "error") throw h.raw instanceof Error ? h.raw : new Error(h.message);
1738
+ const ev = toAgentEvent(h, adapter.id);
1739
+ if (ev) yield ev;
755
1740
  }
756
1741
  }
757
1742
  //#endregion
758
1743
  //#region src/snapshots.ts
759
1744
  /**
760
- * Hash of the fields that require re-installing the agent CLI or rerunning
761
- * setup: cli, cliVersion, packages, and setup. Excludes env (hot-reloadable),
762
- * model/provider (CLI flags only), and cosmetic fields.
1745
+ * Hash of the fields that require re-installing the harness or rerunning
1746
+ * setup: harness, harnessVersion, packages, and setup. Excludes env (hot-reloadable),
1747
+ * model/provider (harness flags only), and cosmetic fields.
1748
+ *
1749
+ * The hashed object deliberately keeps the **old** key names. This is a cache key, not a
1750
+ * vocabulary surface — nobody reads it — and changing the keys would change every existing
1751
+ * snapshot's hash, so the `harness` rename would silently cost every user a ~90s rebuild of
1752
+ * every agent instead of a ~3s snapshot restore. The values are what identify the install;
1753
+ * the key spelling is incidental.
763
1754
  */
764
1755
  function computeSetupHash(spec) {
765
1756
  return createHash("sha256").update(JSON.stringify({
766
- cli: spec.cli,
767
- cliVersion: spec.cliVersion ?? "latest",
1757
+ cli: spec.harness,
1758
+ cliVersion: spec.harnessVersion ?? "latest",
768
1759
  packages: [...spec.packages ?? []].sort(),
769
1760
  setup: spec.setup ?? []
770
1761
  })).digest("hex").slice(0, 12);
@@ -790,29 +1781,176 @@ var AgentSnapshotStore = class {
790
1781
  await mkdir(dirname(this.path), { recursive: true });
791
1782
  await writeFile(this.path, JSON.stringify(data, null, 2));
792
1783
  }
793
- _key(specName, setupHash) {
794
- return `${specName}:${setupHash}`;
1784
+ /**
1785
+ * OpenSandbox keeps the key it always had, so every existing file keeps working. Another
1786
+ * provider's records get its id as a prefix, so two providers sharing one file never read
1787
+ * or replace each other's snapshot ids.
1788
+ */
1789
+ _key(specName, setupHash, provider) {
1790
+ return provider === DEFAULT_PROVIDER_ID$1 ? `${specName}:${setupHash}` : `${provider}:${specName}:${setupHash}`;
795
1791
  }
796
- async get(specName, setupHash) {
797
- return (await this._read())[this._key(specName, setupHash)] ?? null;
1792
+ async get(specName, setupHash, provider = DEFAULT_PROVIDER_ID$1) {
1793
+ return (await this._read())[this._key(specName, setupHash, provider)] ?? null;
798
1794
  }
799
- async save(record) {
800
- const data = await this._read();
801
- for (const k of Object.keys(data)) if (data[k].specName === record.specName) delete data[k];
802
- data[this._key(record.specName, record.setupHash)] = record;
803
- await this._write(data);
1795
+ /**
1796
+ * Writes are read-modify-write on one file. Two at once (several specs finishing their setup
1797
+ * together, as when alineod restores a whole swarm onto a new machine) would each read the old
1798
+ * file and the second write would drop the first record. This chain runs them one at a time.
1799
+ * It guards one process: a second process on the same file is not supported.
1800
+ */
1801
+ writing = Promise.resolve();
1802
+ serialized(fn) {
1803
+ const run = this.writing.then(fn, fn);
1804
+ this.writing = run.catch(() => {});
1805
+ return run;
1806
+ }
1807
+ save(record) {
1808
+ return this.serialized(async () => {
1809
+ const data = await this._read();
1810
+ const provider = record.provider ?? DEFAULT_PROVIDER_ID$1;
1811
+ for (const k of Object.keys(data)) if (data[k].specName === record.specName && (data[k].provider ?? DEFAULT_PROVIDER_ID$1) === provider) delete data[k];
1812
+ data[this._key(record.specName, record.setupHash, provider)] = record;
1813
+ await this._write(data);
1814
+ });
804
1815
  }
805
1816
  /** Remove all snapshot records for the given spec name. */
806
- async delete(specName) {
807
- const data = await this._read();
808
- for (const k of Object.keys(data)) if (data[k].specName === specName) delete data[k];
809
- await this._write(data);
1817
+ delete(specName) {
1818
+ return this.serialized(async () => {
1819
+ const data = await this._read();
1820
+ for (const k of Object.keys(data)) if (data[k].specName === specName) delete data[k];
1821
+ await this._write(data);
1822
+ });
810
1823
  }
811
1824
  async list() {
812
1825
  return Object.values(await this._read());
813
1826
  }
814
1827
  };
815
1828
  //#endregion
1829
+ //#region src/sandbox-gone.ts
1830
+ /**
1831
+ * Classifies an error from `client.connect()` (or any other sandbox-control call) as "no live
1832
+ * container to reattach or resume into" — as opposed to a transient failure that might clear on
1833
+ * retry. Shared between `resumeAgent()`/`reattachAgent()` (M3, 3.3 — falls through to
1834
+ * restore-from-checkpoint on this) and `apps/alineod/src/engine/rehydrate.ts`'s restore ladder
1835
+ * (M3, 3.4 — same question, same answer), which previously had its own private copy covering
1836
+ * only the first case below.
1837
+ *
1838
+ * The stable signal is an alineo error code: `SANDBOX_NOT_FOUND`, or `SANDBOX_NOT_RUNNING` with
1839
+ * `details.state` of `Terminated` or `Failed`. The message and `.code` string checks below are a
1840
+ * fallback for errors that carry no alineo code, and may go once every thrower sets one.
1841
+ *
1842
+ * Two distinct ways a sandbox can be "gone," both confirmed against OpenSandbox's actual
1843
+ * behavior (DeepWiki, not just its higher-level docs — same discipline M1.4/M2's research used):
1844
+ *
1845
+ * 1. Truly deleted/unknown (`docker rm -f`, expired and reaped): a 404, surfaced as
1846
+ * `<RUNTIME>::SANDBOX_NOT_FOUND` on the error's `code` or in its message.
1847
+ * 2. `Exited` after a host reboot or Docker daemon restart (durability-roadmap's former M2
1848
+ * 2.3, moved here): **not** a 404 — a `200 OK` with `state: "Terminated"`/`"Failed"`.
1849
+ * `@alineo-labs/sandbox`'s `client.connect()` (`packages/sdks/typescript/src/client.ts`)
1850
+ * already surfaces this as a `SandboxClientError` with `status: 409` and a message of the
1851
+ * shape `"SandboxHandle <id> is <state> — can only connect to Running sandboxes"` — this
1852
+ * classifier matches that message shape rather than re-deriving the state check itself, so
1853
+ * it stays correct if `connect()`'s own wording ever changes without this file knowing.
1854
+ */
1855
+ function isSandboxGone(err) {
1856
+ if (!err || typeof err !== "object") return false;
1857
+ const alineoCode = errorCodeOf(err);
1858
+ if (alineoCode === "SANDBOX_NOT_FOUND") return true;
1859
+ if (alineoCode === "SANDBOX_NOT_RUNNING") {
1860
+ const state = err.details?.state;
1861
+ return typeof state === "string" && ["terminated", "failed"].includes(state.toLowerCase());
1862
+ }
1863
+ const code = err.code;
1864
+ if (typeof code === "string" && code.endsWith("SANDBOX_NOT_FOUND")) return true;
1865
+ const message = err.message;
1866
+ if (typeof message !== "string") return false;
1867
+ if (message.includes("SANDBOX_NOT_FOUND")) return true;
1868
+ return /is (?:Terminated|Failed) — can only connect to Running sandboxes/.test(message);
1869
+ }
1870
+ //#endregion
1871
+ //#region src/restore.ts
1872
+ /**
1873
+ * Every checkpoint recorded for this sandbox, newest first. Restore tries them in this order, so
1874
+ * one lost or unreadable tarball costs a turn of history and not the whole conversation.
1875
+ */
1876
+ async function findCheckpoints(adapter, name, sandboxId) {
1877
+ return (await adapter.readAll(name, sandboxId)).filter((e) => e.event === LedgerEvent.AgentCheckpointed).map((e) => e.payload).reverse();
1878
+ }
1879
+ /** `undefined` if this sandbox was never checkpointed — not an error; the caller falls back
1880
+ * to whatever state a bare snapshot restore already produced. */
1881
+ async function findLatestCheckpoint(adapter, name, sandboxId) {
1882
+ return (await findCheckpoints(adapter, name, sandboxId))[0];
1883
+ }
1884
+ /**
1885
+ * The bytes of one checkpoint. Local file first, because it needs no network. If that is gone (a
1886
+ * new host, a wiped disk) and the checkpoint has a `remoteRef` the store recognises, download it.
1887
+ *
1888
+ * @throws if neither source has it. The message names both attempts.
1889
+ */
1890
+ async function fetchCheckpoint(checkpoint, opts = {}) {
1891
+ let localError;
1892
+ try {
1893
+ return await readFile(checkpoint.snapshotRef);
1894
+ } catch (err) {
1895
+ localError = err;
1896
+ }
1897
+ const key = checkpoint.remoteRef && opts.blobStore ? opts.blobStore.keyOf(checkpoint.remoteRef) : void 0;
1898
+ if (key === void 0 || !opts.blobStore) throw new Error(`checkpoint for turn ${checkpoint.turn} is not on this host (${checkpoint.snapshotRef}: ${localError instanceof Error ? localError.message : String(localError)})` + (checkpoint.remoteRef ? ` and ${checkpoint.remoteRef} cannot be fetched: no BlobStore that owns it was given` : " and it has no off-box copy"));
1899
+ try {
1900
+ return await opts.blobStore.get(key);
1901
+ } catch (err) {
1902
+ throw new Error(`checkpoint for turn ${checkpoint.turn} is not on this host and ${checkpoint.remoteRef} could not be fetched: ${err instanceof Error ? err.message : String(err)}`);
1903
+ }
1904
+ }
1905
+ /**
1906
+ * The newest checkpoint whose tarball can be read, with its bytes, or `undefined` when none can.
1907
+ * `skipped` lists what was passed over and why, for the caller to log.
1908
+ */
1909
+ async function pickRestorable(candidates, opts = {}) {
1910
+ const skipped = [];
1911
+ for (const checkpoint of candidates) try {
1912
+ return {
1913
+ checkpoint,
1914
+ bytes: await fetchCheckpoint(checkpoint, opts),
1915
+ skipped
1916
+ };
1917
+ } catch (err) {
1918
+ skipped.push({
1919
+ turn: checkpoint.turn,
1920
+ reason: err instanceof Error ? err.message : String(err)
1921
+ });
1922
+ }
1923
+ return null;
1924
+ }
1925
+ /**
1926
+ * Extract checkpoint bytes into `sb`, overwriting whatever a fresh container's own setup left in
1927
+ * place at the same paths. Byte-safe on both ends (`writeFileBytes`/raw `tar xzf`) — the same
1928
+ * corruption risk `takeCheckpoint()`'s doc comment already covers on the capture side applies
1929
+ * symmetrically here on restore.
1930
+ */
1931
+ async function extractCheckpoint(sb, bytes) {
1932
+ const tmpTarPath = `/tmp/alineo-restore-${crypto.randomUUID()}.tar.gz`;
1933
+ try {
1934
+ await sb.writeFileBytes(tmpTarPath, bytes);
1935
+ await sb.exec(`tar xzf ${tmpTarPath} -C /`);
1936
+ } finally {
1937
+ try {
1938
+ await sb.exec(`rm -f ${tmpTarPath}`, { strict: false });
1939
+ } catch {}
1940
+ }
1941
+ }
1942
+ /**
1943
+ * Extract a checkpoint tarball into `sb`. `snapshotRef` is the host path `takeCheckpoint()` stored
1944
+ * it at. Pass `remoteRef` and `blobStore` to fall back to object storage when that file is gone.
1945
+ */
1946
+ async function restoreCheckpoint(sb, snapshotRef, opts = {}) {
1947
+ await extractCheckpoint(sb, await fetchCheckpoint({
1948
+ turn: 0,
1949
+ snapshotRef,
1950
+ remoteRef: opts.remoteRef
1951
+ }, { blobStore: opts.blobStore }));
1952
+ }
1953
+ //#endregion
816
1954
  //#region src/agent/validation.ts
817
1955
  /**
818
1956
  * The durable resource identity for a spawned child, frozen from the child spec BEFORE
@@ -825,7 +1963,7 @@ var AgentSnapshotStore = class {
825
1963
  * agree on the exact same value — is independently unit-testable.
826
1964
  */
827
1965
  function resolveChildResourceId(childSpec) {
828
- return childSpec.resourceId ?? childSpec.name;
1966
+ return resourceRefOf(childSpec).resourceId;
829
1967
  }
830
1968
  function assertValidSpawnDepth(value, context) {
831
1969
  if (!Number.isInteger(value) || value < 0) throw new Error(`${context}: spawnDepth must be a non-negative integer (got ${value})`);
@@ -836,7 +1974,7 @@ function assertValidMaxAgents(value, context) {
836
1974
  /**
837
1975
  * Resolves and validates the spawn-depth budget available to `Alineo.spawn()` —
838
1976
  * `override` (a `--depth` CLI flag) wins if given, else whatever value was
839
- * materialised into `ALINEO_SPAWN_DEPTH` by `Alineo.load()`/`Alineo.resume()`. Throws
1977
+ * materialised into `ALINEO_SPAWN_DEPTH` by `Alineo.start()`/`Alineo.resume()`. Throws
840
1978
  * unless the result is a positive integer: `0` means "no budget left", not "spawn
841
1979
  * one more time" — spawning stops one level before the counter would go negative.
842
1980
  */
@@ -1026,21 +2164,21 @@ function elapsed(t) {
1026
2164
  }
1027
2165
  /**
1028
2166
  * Validate `specInput` and return everything needed to construct a fully initialised `Alineo`.
1029
- * See `Alineo.load()` for the public-facing docs.
2167
+ * See `Alineo.start()` for the public-facing docs.
1030
2168
  */
1031
2169
  async function loadAgent(specInput, opts) {
1032
2170
  const t0 = Date.now();
1033
2171
  const spec = validateAgentSpec(specInput);
1034
- const config = await readProjectConfig();
2172
+ const config = resolveProjectConfig(opts.config);
1035
2173
  const resolvedEnv = resolveEnv(spec.env ?? {});
1036
2174
  const effectiveSpawnDepth = opts.spawnDepth ?? spec.spawnDepth;
1037
2175
  if (effectiveSpawnDepth !== void 0) {
1038
- assertValidSpawnDepth(effectiveSpawnDepth, "Alineo.load()");
2176
+ assertValidSpawnDepth(effectiveSpawnDepth, "Alineo.start()");
1039
2177
  resolvedEnv.ALINEO_SPAWN_DEPTH = String(effectiveSpawnDepth);
1040
2178
  }
1041
2179
  const effectiveMaxAgents = opts.maxAgents ?? spec.maxAgents;
1042
2180
  if (effectiveMaxAgents !== void 0) {
1043
- assertValidMaxAgents(effectiveMaxAgents, "Alineo.load()");
2181
+ assertValidMaxAgents(effectiveMaxAgents, "Alineo.start()");
1044
2182
  resolvedEnv.ALINEO_MAX_AGENTS = String(effectiveMaxAgents);
1045
2183
  }
1046
2184
  const runId = opts.runId ?? crypto.randomUUID();
@@ -1057,7 +2195,7 @@ async function loadAgent(specInput, opts) {
1057
2195
  const needsCredentialProxy = credentialBindings.length > 0;
1058
2196
  const heldCredentials = credentialBindings.filter((b) => b.approval === "hold");
1059
2197
  const heldHosts = [...new Set(heldCredentials.map((b) => b.binding.host.trim().replace(/\.$/, "").toLowerCase()))];
1060
- if (heldCredentials.length > 0 && !opts.onEgressRequest) throw new Error(`AgentSpec.env has ${heldCredentials.length} credential binding(s) with approval: "hold" (${heldHosts.join(", ")}) but Alineo.load() was called without an onEgressRequest handler.`);
2198
+ if (heldCredentials.length > 0 && !opts.onEgressRequest) throw new Error(`AgentSpec.env has ${heldCredentials.length} credential binding(s) with approval: "hold" (${heldHosts.join(", ")}) but Alineo.start() was called without an onEgressRequest handler.`);
1061
2199
  const networkPolicy = needsCredentialProxy || heldHosts.length > 0 ? {
1062
2200
  defaultAction: "allow",
1063
2201
  egress: heldHosts.map((target) => ({
@@ -1065,6 +2203,8 @@ async function loadAgent(specInput, opts) {
1065
2203
  target
1066
2204
  }))
1067
2205
  } : void 0;
2206
+ const client = clientFromConfig(config, { adapter: opts.adapter });
2207
+ if (heldCredentials.length > 0 && opts.onEgressRequest) requireCapability(client.provider, "egress");
1068
2208
  const egressGate = heldCredentials.length > 0 && opts.onEgressRequest ? new EgressApprovalGate({
1069
2209
  heldCredentials: heldCredentials.map((b) => ({
1070
2210
  name: b.name,
@@ -1079,15 +2219,9 @@ async function loadAgent(specInput, opts) {
1079
2219
  await egressGate.start();
1080
2220
  egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK = egressGate.webhookUrl;
1081
2221
  }
1082
- const client = new Sandbox({
1083
- baseUrl: config.serverUrl,
1084
- apiKey: config.apiKey,
1085
- adapter: opts.adapter,
1086
- useServerProxy: config.useServerProxy
1087
- });
1088
2222
  const store = new AgentSnapshotStore(snapshotsPath(config.adapterPath));
1089
2223
  const setupHash = computeSetupHash(spec);
1090
- const adapter = new PiAdapter();
2224
+ const adapter = createHarness(spec.harness);
1091
2225
  let sb;
1092
2226
  let fromSnapshot = false;
1093
2227
  if (!opts.rebuild) {
@@ -1099,7 +2233,7 @@ async function loadAgent(specInput, opts) {
1099
2233
  networkPolicy,
1100
2234
  ...egressEnv.OPENSANDBOX_EGRESS_DENY_WEBHOOK ? { env: egressEnv } : {},
1101
2235
  credentialProxy: needsCredentialProxy,
1102
- resourceId: spec.resourceId ?? spec.name,
2236
+ resourceId: resourceRefOf(spec).resourceId,
1103
2237
  teamId: spec.teamId
1104
2238
  });
1105
2239
  log.info("snapshot ready", {
@@ -1127,7 +2261,7 @@ async function loadAgent(specInput, opts) {
1127
2261
  runId,
1128
2262
  networkPolicy,
1129
2263
  credentialProxy: needsCredentialProxy,
1130
- resourceId: spec.resourceId ?? spec.name,
2264
+ resourceId: resourceRefOf(spec).resourceId,
1131
2265
  teamId: spec.teamId
1132
2266
  });
1133
2267
  log.info("sandbox ready", {
@@ -1156,6 +2290,7 @@ async function loadAgent(specInput, opts) {
1156
2290
  await store.save({
1157
2291
  specName: spec.name,
1158
2292
  setupHash,
2293
+ provider: DEFAULT_PROVIDER_ID$1,
1159
2294
  snapshotId,
1160
2295
  createdAt: Date.now()
1161
2296
  });
@@ -1177,7 +2312,7 @@ async function loadAgent(specInput, opts) {
1177
2312
  await adapter.configure(sb, spec, resolvedEnv);
1178
2313
  log.info("starting bridge");
1179
2314
  const t4 = Date.now();
1180
- await adapter.startBridge(sb);
2315
+ await adapter.start(sb);
1181
2316
  await adapter.waitReady();
1182
2317
  log.info("bridge ready", { elapsed: elapsed(t4) });
1183
2318
  } catch (err) {
@@ -1207,18 +2342,77 @@ async function loadAgent(specInput, opts) {
1207
2342
  };
1208
2343
  }
1209
2344
  /**
2345
+ * durability-roadmap M3, 3.3: `resumeAgent()`/`reattachAgent()`'s fallback when the sandbox
2346
+ * itself is gone (`isSandboxGone`), not merely unreachable — provisions a fresh container from
2347
+ * the cached setup snapshot (`loadAgent()`'s own fast path, the same mechanism a first
2348
+ * `Alineo.start()` cache hit already uses) and, if this agent was ever checkpointed, restores
2349
+ * the latest one into it before returning — continuing the conversation instead of starting
2350
+ * blank. If it was never checkpointed, returns the fresh (blank) agent rather than failing —
2351
+ * losing the conversation is still better than losing the agent entirely.
2352
+ *
2353
+ * Known gap, not this chunk's scope: `loadAgent()` throws if the spec has `approval: "hold"`
2354
+ * credential bindings and no `onEgressRequest` is given, which neither `resumeAgent()` nor
2355
+ * `reattachAgent()` accepts today — restoring such a spec from a fully-gone container isn't
2356
+ * handled yet.
2357
+ */
2358
+ async function restoreFromCheckpoint(originalSandboxId, spec, opts, runId, log) {
2359
+ log.warn("sandbox is gone — provisioning a fresh one and restoring from checkpoint", { originalSandboxId });
2360
+ const fresh = await loadAgent(spec, {
2361
+ adapter: opts.adapter,
2362
+ config: opts.config,
2363
+ runId
2364
+ });
2365
+ const candidates = await findCheckpoints(opts.adapter, spec.name, originalSandboxId);
2366
+ if (candidates.length === 0) {
2367
+ log.warn("no checkpoint found for this agent — continuing with a blank session", { originalSandboxId });
2368
+ return {
2369
+ ...fresh,
2370
+ restore: { checkpointTurn: null }
2371
+ };
2372
+ }
2373
+ const picked = await pickRestorable(candidates, { blobStore: opts.blobStore });
2374
+ for (const s of picked?.skipped ?? []) log.warn("checkpoint is unavailable — trying an older one", {
2375
+ turn: s.turn,
2376
+ reason: s.reason
2377
+ });
2378
+ if (!picked) {
2379
+ log.warn("no checkpoint tarball could be read — continuing with a blank session", {
2380
+ originalSandboxId,
2381
+ tried: candidates.length
2382
+ });
2383
+ return {
2384
+ ...fresh,
2385
+ restore: { checkpointTurn: null }
2386
+ };
2387
+ }
2388
+ const latest = picked.checkpoint;
2389
+ log.info("restoring checkpoint", {
2390
+ turn: latest.turn,
2391
+ sandboxId: fresh.sandbox.sandboxId
2392
+ });
2393
+ try {
2394
+ await fresh.sandbox.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
2395
+ await extractCheckpoint(fresh.sandbox, picked.bytes);
2396
+ await fresh.adapter.configure(fresh.sandbox, spec, fresh.env, { resume: true });
2397
+ await fresh.adapter.start(fresh.sandbox);
2398
+ await fresh.adapter.waitReady();
2399
+ return {
2400
+ ...fresh,
2401
+ restore: { checkpointTurn: latest.turn }
2402
+ };
2403
+ } catch (err) {
2404
+ await fresh.sandbox.close().catch(cleanupFailed(log, { sandboxId: fresh.sandbox.sandboxId }));
2405
+ throw err;
2406
+ }
2407
+ }
2408
+ /**
1210
2409
  * Reconnect to a previously-created agent whose host process has exited. See
1211
2410
  * `Alineo.resume()` for the public-facing docs.
1212
2411
  */
1213
2412
  async function resumeAgent(sandboxId, opts) {
1214
2413
  const t0 = Date.now();
1215
- const config = await readProjectConfig();
1216
- const client = new Sandbox({
1217
- baseUrl: config.serverUrl,
1218
- apiKey: config.apiKey,
1219
- adapter: opts.adapter,
1220
- useServerProxy: config.useServerProxy
1221
- });
2414
+ const config = resolveProjectConfig(opts.config);
2415
+ const client = clientFromConfig(config, { adapter: opts.adapter });
1222
2416
  let spec;
1223
2417
  if (opts.spec) spec = validateAgentSpec(opts.spec);
1224
2418
  else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
@@ -1244,20 +2438,26 @@ async function resumeAgent(sandboxId, opts) {
1244
2438
  resolvedEnv.ALINEO_RUN_ID = runId;
1245
2439
  log.info("reconnecting", { sandboxId });
1246
2440
  const t1 = Date.now();
1247
- const sb = await client.connect(sandboxId, spec.name, {
1248
- runId,
1249
- resources: spec.resources ?? config.defaults.resources,
1250
- resourceId: spec.resourceId ?? spec.name,
1251
- teamId: spec.teamId
1252
- });
2441
+ let sb;
2442
+ try {
2443
+ sb = await client.connect(sandboxId, spec.name, {
2444
+ runId,
2445
+ resources: spec.resources ?? config.defaults.resources,
2446
+ resourceId: resourceRefOf(spec).resourceId,
2447
+ teamId: spec.teamId
2448
+ });
2449
+ } catch (err) {
2450
+ if (isSandboxGone(err)) return restoreFromCheckpoint(sandboxId, spec, opts, runId, log);
2451
+ throw err;
2452
+ }
1253
2453
  log.info("connected", { elapsed: elapsed(t1) });
1254
2454
  await sb.exec("pkill -f 'node /alineo-bridge.js' 2>/dev/null; sleep 0.1; true", { strict: false });
1255
- const adapter = new PiAdapter();
2455
+ const adapter = createHarness(spec.harness);
1256
2456
  resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
1257
2457
  await adapter.configure(sb, spec, resolvedEnv, { resume: true });
1258
2458
  log.info("starting bridge");
1259
2459
  const t2 = Date.now();
1260
- await adapter.startBridge(sb);
2460
+ await adapter.start(sb);
1261
2461
  await adapter.waitReady();
1262
2462
  log.info("bridge ready", { elapsed: elapsed(t2) });
1263
2463
  await reconcileDroppedPermissions(opts.adapter, sb, spec.name, sandboxId);
@@ -1271,6 +2471,21 @@ async function resumeAgent(sandboxId, opts) {
1271
2471
  runId
1272
2472
  };
1273
2473
  }
2474
+ /**
2475
+ * durability-roadmap.md M1.3: this used to resolve a dropped request with
2476
+ * `decision: { kind: "reject" }` — `PermissionDecision`'s `"reject"` is documented as *a
2477
+ * human's answer*, and no human answered this one. Nobody could: the tool call it was about
2478
+ * died with the old Pi process (OpenSandbox restore is rootfs-only, so it isn't still parked
2479
+ * anywhere to answer). `"dropped"` says what actually happened instead of fabricating a
2480
+ * decision nobody made.
2481
+ *
2482
+ * This is the narrow fix — an honest ledger, not a re-opened decision. The better path forward
2483
+ * is giving a human an actual chance to weigh in: alineod has no live route to answer a
2484
+ * permission request at all today (`driveTurn` calls `agent.prompt()` with no `onPermission`),
2485
+ * so there's nothing yet for a "re-issue this to an operator" version of this function to
2486
+ * re-issue *into*. Once that live path exists, this should queue the same way
2487
+ * `agent.supervision_needed` already does, instead of resolving anything here.
2488
+ */
1274
2489
  async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
1275
2490
  try {
1276
2491
  const events = await adapter.readAll(name, sandboxId);
@@ -1284,8 +2499,8 @@ async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
1284
2499
  const rid = e.payload?.requestId;
1285
2500
  if (rid && !resolved.has(rid)) await sb.emit(LedgerEvent.PermissionResolved, -1, {
1286
2501
  requestId: rid,
1287
- decision: { kind: "reject" },
1288
- note: "session resumed — pending approval dropped"
2502
+ decision: { kind: "dropped" },
2503
+ note: "session resumed — the tool call this was about is gone; no one answered it"
1289
2504
  });
1290
2505
  }
1291
2506
  } catch {}
@@ -1298,13 +2513,8 @@ async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
1298
2513
  */
1299
2514
  async function reattachAgent(sandboxId, opts) {
1300
2515
  const t0 = Date.now();
1301
- const config = await readProjectConfig();
1302
- const client = new Sandbox({
1303
- baseUrl: config.serverUrl,
1304
- apiKey: config.apiKey,
1305
- adapter: opts.adapter,
1306
- useServerProxy: config.useServerProxy
1307
- });
2516
+ const config = resolveProjectConfig(opts.config);
2517
+ const client = clientFromConfig(config, { adapter: opts.adapter });
1308
2518
  let spec;
1309
2519
  if (opts.spec) spec = validateAgentSpec(opts.spec);
1310
2520
  else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
@@ -1331,16 +2541,22 @@ async function reattachAgent(sandboxId, opts) {
1331
2541
  resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
1332
2542
  log.info("reattaching", { sandboxId });
1333
2543
  const t1 = Date.now();
1334
- const sb = await client.connect(sandboxId, spec.name, {
1335
- runId,
1336
- resourceId: spec.resourceId ?? spec.name,
1337
- teamId: spec.teamId,
1338
- resources: spec.resources ?? config.defaults.resources,
1339
- allowPaused: opts.skipReadyCheck === true
1340
- });
2544
+ let sb;
2545
+ try {
2546
+ sb = await client.connect(sandboxId, spec.name, {
2547
+ runId,
2548
+ resourceId: resourceRefOf(spec).resourceId,
2549
+ teamId: spec.teamId,
2550
+ resources: spec.resources ?? config.defaults.resources,
2551
+ allowPaused: opts.skipReadyCheck === true
2552
+ });
2553
+ } catch (err) {
2554
+ if (isSandboxGone(err)) return restoreFromCheckpoint(sandboxId, spec, opts, runId, log);
2555
+ throw err;
2556
+ }
1341
2557
  log.info("connected", { elapsed: elapsed(t1) });
1342
- const adapter = new PiAdapter();
1343
- await adapter.reattachBridge(sb);
2558
+ const adapter = createHarness(spec.harness);
2559
+ await adapter.reattach(sb);
1344
2560
  const t2 = Date.now();
1345
2561
  if (!opts.skipReadyCheck) await adapter.waitReady(5e3);
1346
2562
  log.info("bridge reattached", {
@@ -1362,13 +2578,8 @@ async function reattachAgent(sandboxId, opts) {
1362
2578
  * `Alineo.attach()` for the public-facing docs.
1363
2579
  */
1364
2580
  async function attachAgent(sandboxId, opts) {
1365
- const config = await readProjectConfig();
1366
- const client = new Sandbox({
1367
- baseUrl: config.serverUrl,
1368
- apiKey: config.apiKey,
1369
- adapter: opts.adapter,
1370
- useServerProxy: config.useServerProxy
1371
- });
2581
+ const config = resolveProjectConfig(opts.config);
2582
+ const client = clientFromConfig(config, { adapter: opts.adapter });
1372
2583
  const resources = opts.resources ?? config.defaults.resources;
1373
2584
  const sb = await client.connect(sandboxId, opts.name, { resources });
1374
2585
  let envFile;
@@ -1379,14 +2590,21 @@ async function attachAgent(sandboxId, opts) {
1379
2590
  }
1380
2591
  const env = parseShellExports(envFile);
1381
2592
  const runId = env.ALINEO_RUN_ID ?? crypto.randomUUID();
2593
+ let model = "unknown";
2594
+ try {
2595
+ const piConfig = JSON.parse(await sb.readFile("/etc/alineo-pi.json"));
2596
+ if (piConfig.model) model = piConfig.model;
2597
+ } catch {}
2598
+ const stubSpec = {
2599
+ name: opts.name,
2600
+ harness: "pi",
2601
+ model
2602
+ };
1382
2603
  return {
1383
2604
  sandbox: sb,
1384
- spec: {
1385
- name: opts.name,
1386
- cli: "pi"
1387
- },
2605
+ spec: stubSpec,
1388
2606
  env,
1389
- adapter: new PiAdapter(),
2607
+ adapter: createHarness(stubSpec.harness),
1390
2608
  fromSnapshot: false,
1391
2609
  runId
1392
2610
  };
@@ -1423,14 +2641,14 @@ async function spawnChild(self, childSpecPath, opts = {}) {
1423
2641
  elapsed: elapsed(t0),
1424
2642
  sandboxId: forkedSb.sandboxId
1425
2643
  });
1426
- const adapter = new PiAdapter();
2644
+ const adapter = createHarness(childSpec.harness);
1427
2645
  try {
1428
2646
  for (const { name, value, binding, source } of childCredentialBindings) await forkedSb.credentials.set(name, value, binding, source);
1429
2647
  childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
1430
2648
  await adapter.configure(forkedSb, childSpec, childEnv);
1431
2649
  log.info("starting bridge");
1432
2650
  const t1 = Date.now();
1433
- await adapter.startBridge(forkedSb, Object.keys(self.env));
2651
+ await adapter.start(forkedSb, { unsetVars: Object.keys(self.env) });
1434
2652
  await adapter.waitReady();
1435
2653
  log.info("bridge ready", { elapsed: elapsed(t1) });
1436
2654
  } catch (err) {
@@ -1475,8 +2693,23 @@ async function forkChildMemory(parentMemory, parentRef, child) {
1475
2693
  }
1476
2694
  }
1477
2695
  //#endregion
2696
+ //#region src/agent/pi.ts
2697
+ /**
2698
+ * The agent's adapter as a `PiAdapter`, for an operation only Pi has (`exportHtml`,
2699
+ * `cycleModel`, and so on). Throws `CAPABILITY_UNSUPPORTED` naming the operation and the
2700
+ * harness when the agent runs a different one. It is the single place `Alineo` narrows from
2701
+ * `HarnessAdapter` to a concrete class.
2702
+ */
2703
+ function pi(a, operation) {
2704
+ if (a.adapter instanceof PiAdapter) return a.adapter;
2705
+ throw new WorkflowError(`The ${a.adapter.id} harness does not support ${operation}`, "CAPABILITY_UNSUPPORTED", { details: {
2706
+ operation,
2707
+ harness: a.adapter.id
2708
+ } });
2709
+ }
2710
+ //#endregion
1478
2711
  //#region src/agent/session-control.ts
1479
- const log = getLogger("agent");
2712
+ const log$1 = getLogger("agent");
1480
2713
  /**
1481
2714
  * Wrap a raw adapter stream so that every permission event is mirrored to the ledger
1482
2715
  * (`PermissionRequested` / `PermissionResolved`) and, when `onPermission` is given, each
@@ -1499,7 +2732,7 @@ async function* instrument(a, stream, onPermission) {
1499
2732
  title: ev.title
1500
2733
  };
1501
2734
  Promise.resolve(onPermission(req)).then((decision) => a.adapter.resolvePermission(ev.requestId, decision)).catch((err) => {
1502
- log.warn("onPermission handler failed", {
2735
+ log$1.warn("onPermission handler failed", {
1503
2736
  requestId: ev.requestId,
1504
2737
  err
1505
2738
  });
@@ -1517,7 +2750,11 @@ async function* instrument(a, stream, onPermission) {
1517
2750
  }
1518
2751
  /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
1519
2752
  function prompt(a, message, opts) {
1520
- return instrument(a, a.adapter.prompt(message, opts), opts?.onPermission);
2753
+ return instrument(a, legacyStream(a.adapter, {
2754
+ message,
2755
+ streamingBehavior: opts?.streamingBehavior,
2756
+ inactivityTimeoutMs: opts?.inactivityTimeoutMs
2757
+ }), opts?.onPermission);
1521
2758
  }
1522
2759
  /**
1523
2760
  * Run a shell command inside Pi's working context. Not incrementally
@@ -1525,7 +2762,7 @@ function prompt(a, message, opts) {
1525
2762
  * arrives as a single `text` event once the command completes.
1526
2763
  */
1527
2764
  function bash(a, command) {
1528
- return instrument(a, a.adapter.bash(command));
2765
+ return instrument(a, pi(a, "bash").bash(command));
1529
2766
  }
1530
2767
  /** Snapshot of tool calls currently paused awaiting a human decision. */
1531
2768
  async function listPendingPermissions(a) {
@@ -1533,7 +2770,8 @@ async function listPendingPermissions(a) {
1533
2770
  }
1534
2771
  /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
1535
2772
  async function steer(a, message) {
1536
- return a.adapter.steer(message);
2773
+ requireHarnessCapability(a.adapter, "steer");
2774
+ await a.adapter.steer?.(message);
1537
2775
  }
1538
2776
  /** Abort Pi's current operation. */
1539
2777
  async function abort(a) {
@@ -1548,15 +2786,16 @@ async function resolvePermission(a, requestId, decision) {
1548
2786
  }
1549
2787
  /** Queue a message to be sent to Pi after it finishes its current task. */
1550
2788
  async function followUp(a, message) {
1551
- return a.adapter.followUp(message);
2789
+ requireHarnessCapability(a.adapter, "followUp");
2790
+ await a.adapter.followUp?.(message);
1552
2791
  }
1553
2792
  /** Start a fresh Pi session, clearing all prior context. */
1554
2793
  async function newSession(a) {
1555
- return a.adapter.newSession();
2794
+ return pi(a, "newSession").newSession();
1556
2795
  }
1557
2796
  /** Enable or disable Pi's automatic context compaction. */
1558
2797
  async function setAutoCompaction(a, enabled) {
1559
- return a.adapter.setAutoCompaction(enabled);
2798
+ return pi(a, "setAutoCompaction").setAutoCompaction(enabled);
1560
2799
  }
1561
2800
  /**
1562
2801
  * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
@@ -1565,83 +2804,86 @@ async function setAutoCompaction(a, enabled) {
1565
2804
  * events in the stream.
1566
2805
  */
1567
2806
  async function setAutoRetry(a, enabled) {
1568
- return a.adapter.setAutoRetry(enabled);
2807
+ return pi(a, "setAutoRetry").setAutoRetry(enabled);
1569
2808
  }
1570
2809
  /**
1571
2810
  * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
1572
2811
  * operation, emitting `auto_retry_end` with `success: false`.
1573
2812
  */
1574
2813
  async function abortRetry(a) {
1575
- return a.adapter.abortRetry();
2814
+ return pi(a, "abortRetry").abortRetry();
1576
2815
  }
1577
2816
  /** Abort a currently-executing bash command without cancelling the whole prompt. */
1578
2817
  async function abortBash(a) {
1579
- return a.adapter.abortBash();
2818
+ return pi(a, "abortBash").abortBash();
1580
2819
  }
1581
2820
  /**
1582
2821
  * Control how Pi processes queued steering messages.
1583
2822
  * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
1584
2823
  */
1585
2824
  async function setSteeringMode(a, mode) {
1586
- return a.adapter.setSteeringMode(mode);
2825
+ return pi(a, "setSteeringMode").setSteeringMode(mode);
1587
2826
  }
1588
2827
  /**
1589
2828
  * Control how Pi processes queued follow-up messages.
1590
2829
  * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
1591
2830
  */
1592
2831
  async function setFollowUpMode(a, mode) {
1593
- return a.adapter.setFollowUpMode(mode);
2832
+ return pi(a, "setFollowUpMode").setFollowUpMode(mode);
1594
2833
  }
1595
2834
  /** Set a display name for the current Pi session. */
1596
2835
  async function setSessionName(a, name) {
1597
- return a.adapter.setSessionName(name);
2836
+ return pi(a, "setSessionName").setSessionName(name);
1598
2837
  }
1599
2838
  //#endregion
1600
2839
  //#region src/agent/model.ts
1601
2840
  /** Set Pi's reasoning level (for models that support extended thinking). */
1602
2841
  async function setThinkingLevel(a, level) {
1603
- return a.adapter.setThinkingLevel(level);
2842
+ return pi(a, "setThinkingLevel").setThinkingLevel(level);
1604
2843
  }
1605
2844
  /** Switch Pi to a specific model. Returns the activated model. */
1606
2845
  async function setModel(a, provider, modelId) {
1607
- return a.adapter.setModel(provider, modelId);
2846
+ return pi(a, "setModel").setModel(provider, modelId);
1608
2847
  }
1609
2848
  /** Cycle Pi to the next available model. Returns null if only one model is configured. */
1610
2849
  async function cycleModel(a) {
1611
- return a.adapter.cycleModel();
2850
+ return pi(a, "cycleModel").cycleModel();
1612
2851
  }
1613
2852
  /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
1614
2853
  async function cycleThinkingLevel(a) {
1615
- return a.adapter.cycleThinkingLevel();
2854
+ return pi(a, "cycleThinkingLevel").cycleThinkingLevel();
1616
2855
  }
1617
2856
  /** List all models available to Pi under the current provider configuration. */
1618
2857
  async function getAvailableModels(a) {
1619
- return a.adapter.getAvailableModels();
2858
+ return pi(a, "getAvailableModels").getAvailableModels();
1620
2859
  }
1621
2860
  //#endregion
1622
2861
  //#region src/agent/introspection.ts
1623
2862
  /** Retrieve token usage, cost, and message counts for the current session. */
1624
2863
  async function getSessionStats(a) {
1625
- return a.adapter.getSessionStats();
2864
+ return pi(a, "getSessionStats").getSessionStats();
1626
2865
  }
1627
2866
  /** Retrieve the text of Pi's most recent assistant response. Returns `null` if none yet. */
1628
2867
  async function getLastAssistantText(a) {
1629
- return a.adapter.getLastAssistantText();
2868
+ return pi(a, "getLastAssistantText").getLastAssistantText();
1630
2869
  }
1631
2870
  /**
1632
- * List the fork entry points available in the current session.
1633
- * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
2871
+ * List the points in the current session a conversation can be branched from.
2872
+ * Each entry has `entryId` (pass to `branchSession()`) and `text` (the message there).
2873
+ *
2874
+ * `a.adapter.getForkMessages` keeps Pi's own name — the adapter speaks the harness's
2875
+ * vocabulary, alineo speaks its own on the way out.
1634
2876
  */
1635
- async function getForkMessages(a) {
1636
- return a.adapter.getForkMessages();
2877
+ async function getBranchPoints(a) {
2878
+ return pi(a, "getForkMessages").getForkMessages();
1637
2879
  }
1638
2880
  /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
1639
2881
  async function getCommands(a) {
1640
- return a.adapter.getCommands();
2882
+ return pi(a, "getCommands").getCommands();
1641
2883
  }
1642
2884
  /** Retrieve Pi's full conversation history for the current session. */
1643
2885
  async function getMessages(a) {
1644
- return a.adapter.getMessages();
2886
+ return pi(a, "getMessages").getMessages();
1645
2887
  }
1646
2888
  /**
1647
2889
  * Retrieve Pi's current session state: active model, thinking level, streaming/compaction
@@ -1649,28 +2891,30 @@ async function getMessages(a) {
1649
2891
  * other way to observe the *current* model or thinking level (as opposed to the full list).
1650
2892
  */
1651
2893
  async function getState(a) {
1652
- return a.adapter.getState();
2894
+ return pi(a, "getState").getState();
1653
2895
  }
1654
2896
  /** Retrieve recent bridge logs (ring-buffered, last 200 entries). */
1655
2897
  async function getLogs(a) {
1656
- return a.adapter.getLogs();
2898
+ return pi(a, "getLogs").getLogs();
1657
2899
  }
1658
2900
  //#endregion
1659
2901
  //#region src/agent/lifecycle.ts
1660
2902
  /**
1661
- * Fork Pi's session at the given entry ID, creating a new branch.
1662
- * Returns the text of the forked message and whether the fork was cancelled.
2903
+ * Branch the harness conversation at the given entry ID.
2904
+ *
2905
+ * `a.adapter.fork` keeps Pi's own name: the adapter speaks the harness's vocabulary (its
2906
+ * bridge endpoint is literally `/fork`), and alineo speaks its own on the way out.
1663
2907
  */
1664
- async function fork(a, entryId) {
1665
- return a.adapter.fork(entryId);
2908
+ async function branchSession(a, entryId) {
2909
+ return pi(a, "fork").fork(entryId);
1666
2910
  }
1667
- /** Clone the current Pi session into a new branch at the current position. */
1668
- async function clone(a) {
1669
- return a.adapter.clone();
2911
+ /** Branch the harness conversation at its current position. */
2912
+ async function duplicateSession(a) {
2913
+ return pi(a, "clone").clone();
1670
2914
  }
1671
2915
  /** Switch Pi to a different session file on disk. */
1672
2916
  async function switchSession(a, sessionPath) {
1673
- return a.adapter.switchSession(sessionPath);
2917
+ return pi(a, "switchSession").switchSession(sessionPath);
1674
2918
  }
1675
2919
  /**
1676
2920
  * Export a static HTML transcript of the current session to the sandbox filesystem.
@@ -1678,11 +2922,11 @@ async function switchSession(a, sessionPath) {
1678
2922
  * to retrieve it.
1679
2923
  */
1680
2924
  async function exportHtml(a, outputPath) {
1681
- return a.adapter.exportHtml(outputPath);
2925
+ return pi(a, "exportHtml").exportHtml(outputPath);
1682
2926
  }
1683
2927
  /** Manually trigger Pi's context compaction. */
1684
2928
  async function compact(a, customInstructions) {
1685
- return a.adapter.compact(customInstructions);
2929
+ return pi(a, "compact").compact(customInstructions);
1686
2930
  }
1687
2931
  /**
1688
2932
  * Set or update env vars in the running container. Writes to /etc/alineo-env and restarts
@@ -1694,11 +2938,11 @@ async function setEnv(a, vars) {
1694
2938
  ...vars
1695
2939
  };
1696
2940
  await a.sandbox.writeFile("/etc/alineo-env", toShellExports(a.env));
1697
- await a.adapter.reloadEnv(a.env);
2941
+ await pi(a, "reloadEnv").reloadEnv(a.env);
1698
2942
  }
1699
2943
  /** Delete the sandbox container and release all resources. Always call in a `finally` block. */
1700
2944
  async function close(a) {
1701
- a.adapter.disposeConnections();
2945
+ a.adapter.dispose();
1702
2946
  await a.egressGate?.stop().catch(() => {});
1703
2947
  await a.sandbox.close();
1704
2948
  }
@@ -1712,7 +2956,7 @@ async function close(a) {
1712
2956
  * while Pi manages its own tool use, file writes, and code execution inside the
1713
2957
  * sandbox.
1714
2958
  *
1715
- * Create an agent with `Alineo.load(spec)`. Always call `close()` when done
2959
+ * Create an agent with `Alineo.start(spec)`. Always call `close()` when done
1716
2960
  * to release the underlying sandbox container.
1717
2961
  *
1718
2962
  * @example
@@ -1720,7 +2964,7 @@ async function close(a) {
1720
2964
  * import { Alineo } from "alineo";
1721
2965
  *
1722
2966
  * const spec = await Bun.file("./agents/my-agent.json").json();
1723
- * const agent = await Alineo.load(spec, { adapter });
2967
+ * const agent = await Alineo.start(spec, { adapter });
1724
2968
  * try {
1725
2969
  * for await (const chunk of agent.prompt("Explain this codebase")) {
1726
2970
  * process.stdout.write(chunk);
@@ -1745,18 +2989,22 @@ var Alineo = class Alineo {
1745
2989
  * `false` on the first load for a given spec, or after `{ rebuild: true }`.
1746
2990
  */
1747
2991
  fromSnapshot;
2992
+ /**
2993
+ * The harness this agent runs, as the harness-neutral interface. For a harness's own
2994
+ * methods use `harness()`.
2995
+ */
1748
2996
  adapter;
1749
2997
  env;
1750
2998
  /**
1751
2999
  * Identifies the logical run this agent's sandbox belongs to — see
1752
3000
  * `SandboxDetails.runId`. Always present; a fresh `crypto.randomUUID()` if not
1753
- * explicitly passed to `load()`/`resume()`. A child from `.spawn()` (and
1754
- * transitively, `alineo fork`) always inherits its parent's `runId`.
3001
+ * explicitly passed to `start()`/`resume()`. A child from `.spawn()` (and
3002
+ * transitively, `alineo spawn`) always inherits its parent's `runId`.
1755
3003
  */
1756
3004
  runId;
1757
3005
  /**
1758
3006
  * Optional provider-agnostic memory (`@alineo-labs/memory`), wired in via `opts.memory` on
1759
- * `load()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
3007
+ * `start()`/`resume()`/`attach()`. `undefined` unless explicitly configured — `alineo` never
1760
3008
  * constructs a `Memory` on your own behalf, matching this package's "own the pipeline,
1761
3009
  * don't assume a backend" design. `spawn()` carries the parent's `memory` (if any) onto the
1762
3010
  * child automatically, the same way it force-computes spawn-depth rather than reading it
@@ -1778,7 +3026,7 @@ var Alineo = class Alineo {
1778
3026
  /**
1779
3027
  * Convenience `ResourceRef` scoping `.memory` calls to this agent. `resourceId`/`teamId`
1780
3028
  * come from `AgentSpec.resourceId`/`AgentSpec.teamId` (`resourceId` defaulting to this
1781
- * agent's `name` when unset) — `load()`/`resume()`/`spawn()` also thread both into the
3029
+ * agent's `name` when unset) — `start()`/`resume()`/`spawn()` also thread both into the
1782
3030
  * ledger (see each field's own doc comment) so this getter and the agent's own episodic
1783
3031
  * history stay consistent, including across a spawned child whose `.name` differs from its
1784
3032
  * memory identity.
@@ -1798,17 +3046,24 @@ var Alineo = class Alineo {
1798
3046
  * Stopped by `close()`.
1799
3047
  */
1800
3048
  egressGate;
1801
- constructor(sandbox, spec, env, adapter, fromSnapshot, runId, egressGate) {
3049
+ /**
3050
+ * Set when `resume()` or `reattach()` found the sandbox gone and returned an agent on a fresh
3051
+ * one. `checkpointTurn` is the turn it was restored from, or `null` when there was no
3052
+ * checkpoint and the session is blank. Absent on every other agent.
3053
+ */
3054
+ restore;
3055
+ constructor(sandbox, spec, env, adapter, fromSnapshot, runId, egressGate, restore) {
1802
3056
  this.sandbox = sandbox;
1803
3057
  this.sandboxId = sandbox.sandboxId;
1804
3058
  this.name = spec.name;
1805
3059
  this.teamId = spec.teamId;
1806
- this.resourceId = spec.resourceId ?? spec.name;
3060
+ this.resourceId = resourceRefOf(spec).resourceId;
1807
3061
  this.adapter = adapter;
1808
3062
  this.env = env;
1809
3063
  this.fromSnapshot = fromSnapshot;
1810
3064
  this.runId = runId;
1811
3065
  this.egressGate = egressGate;
3066
+ this.restore = restore;
1812
3067
  }
1813
3068
  /** Egress requests currently awaiting a decision (see `AgentSpec.env` `approval: "hold"`). */
1814
3069
  pendingEgressRequests() {
@@ -1825,13 +3080,13 @@ var Alineo = class Alineo {
1825
3080
  * don't need to call `validateAgentSpec()` yourself first unless you want validation errors
1826
3081
  * to surface before any sandbox/network work starts.
1827
3082
  *
1828
- * On first load the Pi CLI is installed inside a `node:22` sandbox, then
1829
- * the sandbox is checkpointed. Subsequent `load()` calls for the same spec
3083
+ * On first start the Pi CLI is installed inside a `node:22` sandbox, then
3084
+ * the sandbox is checkpointed. Subsequent `start()` calls for the same spec
1830
3085
  * restore from that snapshot — skipping the install and starting in ~3s instead
1831
3086
  * of ~90s.
1832
3087
  *
1833
3088
  * Pass `{ rebuild: true }` to force a full reinstall (e.g. after changing
1834
- * the spec's `packages` or `cliVersion`).
3089
+ * the spec's `packages` or `harnessVersion`).
1835
3090
  *
1836
3091
  * Pass `{ spawnDepth }` to override the spec's own `spawnDepth` (e.g. a
1837
3092
  * `--depth` CLI flag) — standard flag-beats-config precedence. Same for
@@ -1840,7 +3095,7 @@ var Alineo = class Alineo {
1840
3095
  * Reports timing for each phase through `@alineo-labs/logger` (component `agent`, tagged with
1841
3096
  * the spec `name`). Silent by default — set `ALINEO_LOG_LEVEL=info` to see it.
1842
3097
  */
1843
- static async load(spec, opts) {
3098
+ static async start(spec, opts) {
1844
3099
  const r = await loadAgent(spec, opts);
1845
3100
  const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, r.egressGate);
1846
3101
  agent.memory = opts.memory;
@@ -1859,20 +3114,20 @@ var Alineo = class Alineo {
1859
3114
  * first and fall back to this only if it fails (e.g. the whole sandbox — not just this
1860
3115
  * process — actually restarted).
1861
3116
  *
1862
- * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
3117
+ * @param sandboxId The sandbox ID returned by the original `Alineo.start()`.
1863
3118
  * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
1864
- * `load()`. Takes precedence over `opts.specPath` if both are set.
3119
+ * `start()`. Takes precedence over `opts.specPath` if both are set.
1865
3120
  * @param opts.specPath Path to the agent spec JSON, read and validated internally. If
1866
3121
  * neither `opts.spec` nor `opts.specPath` is set, the ledger is queried for the sandbox's
1867
3122
  * name and the spec is read from `./agents/<name>.json` — this fallback is the one thing
1868
- * `resume()` can do that `load()` can't, since a resumed sandbox's original spec may not be
3123
+ * `resume()` can do that `start()` can't, since a resumed sandbox's original spec may not be
1869
3124
  * in memory anywhere the caller can hand it over.
1870
3125
  *
1871
3126
  * @example
1872
3127
  * ```ts
1873
3128
  * // Original process:
1874
3129
  * const spec = await Bun.file("./agents/hello-agent.json").json();
1875
- * const agent = await Alineo.load(spec, { adapter });
3130
+ * const agent = await Alineo.start(spec, { adapter });
1876
3131
  * console.log(agent.sandboxId); // save this
1877
3132
  * // ... process exits ...
1878
3133
  *
@@ -1886,7 +3141,7 @@ var Alineo = class Alineo {
1886
3141
  */
1887
3142
  static async resume(sandboxId, opts) {
1888
3143
  const r = await resumeAgent(sandboxId, opts);
1889
- const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
3144
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, void 0, r.restore);
1890
3145
  agent.memory = opts.memory;
1891
3146
  return agent;
1892
3147
  }
@@ -1906,7 +3161,7 @@ var Alineo = class Alineo {
1906
3161
  * the bridge process inside it has independently died, and this can't distinguish that from
1907
3162
  * a slow-to-respond-but-fine bridge on its own. On failure, fall back to `Alineo.resume()`.
1908
3163
  *
1909
- * @param sandboxId The sandbox ID returned by the original `Alineo.load()`/`.spawn()`.
3164
+ * @param sandboxId The sandbox ID returned by the original `Alineo.start()`/`.spawn()`.
1910
3165
  * @param opts.spec / opts.specPath Same three-way fallback as `resume()` — see its docs.
1911
3166
  *
1912
3167
  * @example
@@ -1921,7 +3176,7 @@ var Alineo = class Alineo {
1921
3176
  */
1922
3177
  static async reattach(sandboxId, opts) {
1923
3178
  const r = await reattachAgent(sandboxId, opts);
1924
- const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
3179
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId, void 0, r.restore);
1925
3180
  agent.memory = opts.memory;
1926
3181
  return agent;
1927
3182
  }
@@ -1930,7 +3185,7 @@ var Alineo = class Alineo {
1930
3185
  * `resume()`, which kills and restarts the bridge process. Use this when you only
1931
3186
  * need `.spawn()`/`.sandbox`, not `.prompt()`/`.bash()`.
1932
3187
  *
1933
- * The main caller is `alineo fork`: it runs as a fresh CLI process started BY the
3188
+ * The main caller is `alineo spawn`: it runs as a fresh CLI process started BY the
1934
3189
  * very Pi bash-tool call it's attaching to (a master agent spawning a child from
1935
3190
  * inside its own turn). Going through `resume()` there would `pkill` the bridge
1936
3191
  * that's currently running the Pi process making the call — self-destructive.
@@ -1941,7 +3196,7 @@ var Alineo = class Alineo {
1941
3196
  * file, which may not even exist inside this particular sandbox.
1942
3197
  *
1943
3198
  * When `sandboxId` matches `ALINEO_SANDBOX_ID` in this process's own env (true
1944
- * self-attach, e.g. `alineo fork` running from inside its own container),
3199
+ * self-attach, e.g. `alineo spawn` running from inside its own container),
1945
3200
  * `/etc/alineo-env` is read straight off the local filesystem instead of via
1946
3201
  * `sb.readFile()`. A self-referential exec call would need this sandbox to
1947
3202
  * reach itself through its own externally-facing bridge IP, which Docker's
@@ -1952,7 +3207,7 @@ var Alineo = class Alineo {
1952
3207
  * `opts.resources` sizes a subsequent `.spawn()`'s forked container — the
1953
3208
  * control API doesn't echo back a running sandbox's own resource limits, so
1954
3209
  * there's no way to discover this agent's *actual* footprint here. Defaults to
1955
- * `alineo.config.json`'s `defaults.resources`, same fallback `Alineo.load()` uses
3210
+ * `alineo.config.json`'s `defaults.resources`, same fallback `Alineo.start()` uses
1956
3211
  * for a spec that doesn't set its own.
1957
3212
  */
1958
3213
  static async attach(sandboxId, opts) {
@@ -1964,7 +3219,7 @@ var Alineo = class Alineo {
1964
3219
  /**
1965
3220
  * Fork this agent's live sandbox — filesystem, installed packages, checked-out
1966
3221
  * state, everything currently on disk — into a brand-new independent sandbox
1967
- * running its own Pi bridge, per `childSpecPath`. Unlike `Alineo.load()` (always
3222
+ * running its own Pi bridge, per `childSpecPath`. Unlike `Alineo.start()` (always
1968
3223
  * starts from a spec's own snapshot) or `fork()`/`clone()` below (Pi's own
1969
3224
  * conversation-branching — same container, same bridge, new session branch),
1970
3225
  * this is sandbox-level forking: the child sees exactly what this agent's
@@ -2001,6 +3256,23 @@ var Alineo = class Alineo {
2001
3256
  await forkChildMemory(this.memory, this.resourceRef, child);
2002
3257
  return child;
2003
3258
  }
3259
+ /**
3260
+ * The harness's own adapter, typed for that harness, for what it has and the others do not.
3261
+ * `agent.harness("pi")` gives Pi's `exportHtml()`, `cycleModel()`, `getCommands()` and the
3262
+ * rest. Throws `CAPABILITY_UNSUPPORTED` when this agent runs a different harness.
3263
+ *
3264
+ * Prefer the methods on `Alineo` itself where they exist: they work on every harness
3265
+ * that declares the capability.
3266
+ *
3267
+ * @experimental The harness layer is being built. Expect changes before it is stable.
3268
+ */
3269
+ harness(id) {
3270
+ if (this.adapter.id !== id) throw new WorkflowError(`This agent runs the ${this.adapter.id} harness, not ${String(id)}`, "CAPABILITY_UNSUPPORTED", { details: {
3271
+ harness: this.adapter.id,
3272
+ requested: String(id)
3273
+ } });
3274
+ return this.adapter;
3275
+ }
2004
3276
  /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
2005
3277
  prompt(message, opts) {
2006
3278
  return prompt(this, message, opts);
@@ -2009,6 +3281,8 @@ var Alineo = class Alineo {
2009
3281
  * Run a shell command inside Pi's working context. Not incrementally
2010
3282
  * streamed — Pi returns bash output synchronously, so the full output
2011
3283
  * arrives as a single `text` event once the command completes.
3284
+ *
3285
+ * @deprecated Use `agent.harness("pi").bash()`. Moves off `Alineo` because only Pi has it.
2012
3286
  */
2013
3287
  bash(command) {
2014
3288
  return bash(this, command);
@@ -2057,7 +3331,10 @@ var Alineo = class Alineo {
2057
3331
  async setThinkingLevel(level) {
2058
3332
  return setThinkingLevel(this, level);
2059
3333
  }
2060
- /** Enable or disable Pi's automatic context compaction. */
3334
+ /** Enable or disable Pi's automatic context compaction.
3335
+ *
3336
+ * @deprecated Use `agent.harness("pi").setAutoCompaction()`. Moves off `Alineo` because only Pi has it.
3337
+ */
2061
3338
  async setAutoCompaction(enabled) {
2062
3339
  return setAutoCompaction(this, enabled);
2063
3340
  }
@@ -2066,6 +3343,8 @@ var Alineo = class Alineo {
2066
3343
  * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
2067
3344
  * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
2068
3345
  * events in the stream.
3346
+ *
3347
+ * @deprecated Use `agent.harness("pi").setAutoRetry()`. Moves off `Alineo` because only Pi has it.
2069
3348
  */
2070
3349
  async setAutoRetry(enabled) {
2071
3350
  return setAutoRetry(this, enabled);
@@ -2073,11 +3352,16 @@ var Alineo = class Alineo {
2073
3352
  /**
2074
3353
  * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
2075
3354
  * operation, emitting `auto_retry_end` with `success: false`.
3355
+ *
3356
+ * @deprecated Use `agent.harness("pi").abortRetry()`. Moves off `Alineo` because only Pi has it.
2076
3357
  */
2077
3358
  async abortRetry() {
2078
3359
  return abortRetry(this);
2079
3360
  }
2080
- /** Abort a currently-executing bash command without cancelling the whole prompt. */
3361
+ /** Abort a currently-executing bash command without cancelling the whole prompt.
3362
+ *
3363
+ * @deprecated Use `agent.harness("pi").abortBash()`. Moves off `Alineo` because only Pi has it.
3364
+ */
2081
3365
  async abortBash() {
2082
3366
  return abortBash(this);
2083
3367
  }
@@ -2093,20 +3377,28 @@ var Alineo = class Alineo {
2093
3377
  * List the fork entry points available in the current session.
2094
3378
  * Each entry has `entryId` (pass to `fork()`) and `text` (the message at that point).
2095
3379
  */
2096
- async getForkMessages() {
2097
- return getForkMessages(this);
3380
+ async getBranchPoints() {
3381
+ return getBranchPoints(this);
2098
3382
  }
2099
- /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
3383
+ /** List Pi's available slash commands, including extensions, prompt templates, and skills.
3384
+ *
3385
+ * @deprecated Use `agent.harness("pi").getCommands()`. Moves off `Alineo` because only Pi has it.
3386
+ */
2100
3387
  async getCommands() {
2101
3388
  return getCommands(this);
2102
3389
  }
2103
- /** Set a display name for the current Pi session. */
3390
+ /** Set a display name for the current Pi session.
3391
+ *
3392
+ * @deprecated Use `agent.harness("pi").setSessionName()`. Moves off `Alineo` because only Pi has it.
3393
+ */
2104
3394
  async setSessionName(name) {
2105
3395
  return setSessionName(this, name);
2106
3396
  }
2107
3397
  /**
2108
3398
  * Control how Pi processes queued steering messages.
2109
3399
  * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
3400
+ *
3401
+ * @deprecated Use `agent.harness("pi").setSteeringMode()`. Moves off `Alineo` because only Pi has it.
2110
3402
  */
2111
3403
  async setSteeringMode(mode) {
2112
3404
  return setSteeringMode(this, mode);
@@ -2114,6 +3406,8 @@ var Alineo = class Alineo {
2114
3406
  /**
2115
3407
  * Control how Pi processes queued follow-up messages.
2116
3408
  * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
3409
+ *
3410
+ * @deprecated Use `agent.harness("pi").setFollowUpMode()`. Moves off `Alineo` because only Pi has it.
2117
3411
  */
2118
3412
  async setFollowUpMode(mode) {
2119
3413
  return setFollowUpMode(this, mode);
@@ -2122,20 +3416,28 @@ var Alineo = class Alineo {
2122
3416
  * Export a static HTML transcript of the current session to the sandbox filesystem.
2123
3417
  * Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
2124
3418
  * to retrieve it.
3419
+ *
3420
+ * @deprecated Use `agent.harness("pi").exportHtml()`. Moves off `Alineo` because only Pi has it.
2125
3421
  */
2126
3422
  async exportHtml(outputPath) {
2127
3423
  return exportHtml(this, outputPath);
2128
3424
  }
2129
3425
  /**
2130
- * Fork Pi's session at the given entry ID, creating a new branch.
2131
- * Returns the text of the forked message and whether the fork was cancelled.
3426
+ * Branch the harness conversation at the given entry ID.
3427
+ *
3428
+ * Named for what it touches. This never leaves the container: it is the harness's own
3429
+ * session that branches, not the sandbox — `agent.sandbox.fork()` is the one that copies a
3430
+ * filesystem. Unqualified `fork` meant both for a while, which is the confusion this name
3431
+ * exists to end.
3432
+ *
3433
+ * Returns the text of the branched message and whether the branch was cancelled.
2132
3434
  */
2133
- async fork(entryId) {
2134
- return fork(this, entryId);
3435
+ async branchSession(entryId) {
3436
+ return branchSession(this, entryId);
2135
3437
  }
2136
- /** Clone the current Pi session into a new branch at the current position. */
2137
- async clone() {
2138
- return clone(this);
3438
+ /** Branch the harness conversation at its current position. Same container, same bridge. */
3439
+ async duplicateSession() {
3440
+ return duplicateSession(this);
2139
3441
  }
2140
3442
  /** Switch Pi to a different session file on disk. */
2141
3443
  async switchSession(sessionPath) {
@@ -2145,11 +3447,17 @@ var Alineo = class Alineo {
2145
3447
  async setModel(provider, modelId) {
2146
3448
  return setModel(this, provider, modelId);
2147
3449
  }
2148
- /** Cycle Pi to the next available model. Returns null if only one model is configured. */
3450
+ /** Cycle Pi to the next available model. Returns null if only one model is configured.
3451
+ *
3452
+ * @deprecated Use `agent.harness("pi").cycleModel()`. Moves off `Alineo` because only Pi has it.
3453
+ */
2149
3454
  async cycleModel() {
2150
3455
  return cycleModel(this);
2151
3456
  }
2152
- /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
3457
+ /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking.
3458
+ *
3459
+ * @deprecated Use `agent.harness("pi").cycleThinkingLevel()`. Moves off `Alineo` because only Pi has it.
3460
+ */
2153
3461
  async cycleThinkingLevel() {
2154
3462
  return cycleThinkingLevel(this);
2155
3463
  }
@@ -2196,4 +3504,304 @@ async function* textOnly(stream) {
2196
3504
  for await (const ev of stream) if (ev.type === "text") yield ev.text;
2197
3505
  }
2198
3506
  //#endregion
2199
- export { AgentSnapshotStore, AgentSpecValidationError, Alineo, EgressApprovalGate, PromptTimeoutError, computeSetupHash, isReadOnlyBashCommand, snapshotsPath, textOnly, validateAgentSpec };
3507
+ //#region src/blob-store.ts
3508
+ /** `s` without leading and trailing slashes. A loop, not a regex: no backtracking on odd input. */
3509
+ function trimSlashes(s) {
3510
+ let start = 0;
3511
+ let end = s.length;
3512
+ while (start < end && s[start] === "/") start++;
3513
+ while (end > start && s[end - 1] === "/") end--;
3514
+ return s.slice(start, end);
3515
+ }
3516
+ /** Joins path parts with one `/` between them, ignoring empty parts and stray slashes. */
3517
+ function joinKey(...parts) {
3518
+ return parts.map(trimSlashes).filter((p) => p !== "").join("/");
3519
+ }
3520
+ /** S3, R2, MinIO: anything `Bun.S3Client` talks to. Runs under Bun only. */
3521
+ var S3BlobStore = class {
3522
+ client;
3523
+ bucket;
3524
+ prefix;
3525
+ constructor(opts) {
3526
+ this.bucket = opts.bucket;
3527
+ this.prefix = joinKey(opts.prefix ?? "");
3528
+ this.client = opts.client ?? new Bun.S3Client({
3529
+ bucket: opts.bucket,
3530
+ endpoint: opts.endpoint,
3531
+ region: opts.region,
3532
+ accessKeyId: opts.accessKeyId,
3533
+ secretAccessKey: opts.secretAccessKey
3534
+ });
3535
+ }
3536
+ full(key) {
3537
+ return joinKey(this.prefix, key);
3538
+ }
3539
+ async put(key, body) {
3540
+ await this.client.file(this.full(key)).write(typeof body === "string" ? Bun.file(body) : body);
3541
+ }
3542
+ async get(key) {
3543
+ return this.client.file(this.full(key)).bytes();
3544
+ }
3545
+ async delete(key) {
3546
+ await this.client.delete(this.full(key));
3547
+ }
3548
+ async list(prefix) {
3549
+ const out = [];
3550
+ const root = this.prefix === "" ? "" : `${this.prefix}/`;
3551
+ let token;
3552
+ do {
3553
+ const page = await this.client.list({
3554
+ prefix: this.full(prefix),
3555
+ continuationToken: token
3556
+ });
3557
+ for (const item of page.contents ?? []) out.push({
3558
+ key: item.key.startsWith(root) ? item.key.slice(root.length) : item.key,
3559
+ lastModified: item.lastModified ? Date.parse(item.lastModified) : 0
3560
+ });
3561
+ token = page.isTruncated ? page.nextContinuationToken : void 0;
3562
+ } while (token);
3563
+ return out;
3564
+ }
3565
+ refOf(key) {
3566
+ return `s3://${this.bucket}/${this.full(key)}`;
3567
+ }
3568
+ keyOf(ref) {
3569
+ const head = `s3://${this.bucket}/${this.prefix === "" ? "" : `${this.prefix}/`}`;
3570
+ return ref.startsWith(head) ? ref.slice(head.length) : void 0;
3571
+ }
3572
+ };
3573
+ /**
3574
+ * Keeps blobs in a Map. The store the unit tests use, and a reference for what a `BlobStore` must
3575
+ * do. `now` lets a test age a blob without waiting.
3576
+ */
3577
+ var MemoryBlobStore = class {
3578
+ now;
3579
+ blobs = /* @__PURE__ */ new Map();
3580
+ constructor(now = Date.now) {
3581
+ this.now = now;
3582
+ }
3583
+ async put(key, body) {
3584
+ const bytes = typeof body === "string" ? await Bun.file(body).bytes() : body.slice();
3585
+ this.blobs.set(key, {
3586
+ bytes,
3587
+ at: this.now()
3588
+ });
3589
+ }
3590
+ get(key) {
3591
+ const hit = this.blobs.get(key);
3592
+ if (!hit) return Promise.reject(/* @__PURE__ */ new Error(`no such blob: ${key}`));
3593
+ return Promise.resolve(hit.bytes.slice());
3594
+ }
3595
+ delete(key) {
3596
+ this.blobs.delete(key);
3597
+ return Promise.resolve();
3598
+ }
3599
+ list(prefix) {
3600
+ return Promise.resolve([...this.blobs].filter(([key]) => key.startsWith(prefix)).map(([key, v]) => ({
3601
+ key,
3602
+ lastModified: v.at
3603
+ })));
3604
+ }
3605
+ refOf(key) {
3606
+ return `mem://${key}`;
3607
+ }
3608
+ keyOf(ref) {
3609
+ return ref.startsWith("mem://") ? ref.slice(6) : void 0;
3610
+ }
3611
+ /** Test seam: every key, so a test can assert what was written or deleted. */
3612
+ keys() {
3613
+ return [...this.blobs.keys()].sort();
3614
+ }
3615
+ };
3616
+ //#endregion
3617
+ //#region src/checkpoint.ts
3618
+ const log = getLogger("checkpoint");
3619
+ /**
3620
+ * Turn-level checkpointing (durability-roadmap.md M3, 3.2) — deliberately NOT
3621
+ * `sb.checkpoint()`. That method calls OpenSandbox's own snapshot primitive, which on the
3622
+ * Docker runtime is literally `docker commit` (confirmed against OpenSandbox's own source,
3623
+ * M3's 3.1 research) — measured at 44.3s for a 236MB container, re-exporting the whole
3624
+ * filesystem every time regardless of how much actually changed. Calling that every turn would
3625
+ * silently reintroduce the exact cost 3.1 ruled out. This module tars a few directories via
3626
+ * `sb.exec()` instead — measured at well under 2s even unfiltered.
3627
+ *
3628
+ * This is a different mechanism from the agent SDK's other "snapshot" concept, the setup
3629
+ * snapshot (`./snapshots.ts`'s `AgentSnapshotStore`) — that one is taken once per unique
3630
+ * `(specName, setupHash)` to skip reinstalling Pi/packages on every `Alineo.start()`. This one
3631
+ * is taken after every completed turn, captures that specific conversation's state (not a
3632
+ * shared install), and is what `Alineo.resume()` restores from when the container itself is
3633
+ * gone (3.3) — the setup snapshot only gets a fresh, *empty* container, not this agent's actual
3634
+ * conversation.
3635
+ */
3636
+ /** Directories/globs left out of every checkpoint tarball by default — universally-safe
3637
+ * package/toolchain caches, nothing else (3.1's decision: err toward inclusion, since the
3638
+ * measured unfiltered cost is already cheap — losing real workspace state by over-excluding is
3639
+ * a worse mistake than a few extra seconds). Paths are relative to `CHECKPOINT_ROOT`. */
3640
+ const DEFAULT_CHECKPOINT_EXCLUDES = [
3641
+ ".npm",
3642
+ ".cache",
3643
+ ".cargo/registry/cache",
3644
+ "go/pkg/mod/cache/download"
3645
+ ];
3646
+ /** Matched at any depth, not just directly under `CHECKPOINT_ROOT` — unlike the excludes
3647
+ * above, these can recur inside a workspace's own subdirectories (e.g. a cloned repo's own
3648
+ * `__pycache__`), not only at the top level. */
3649
+ const DEFAULT_CHECKPOINT_EXCLUDE_GLOBS = ["__pycache__", ".pytest_cache"];
3650
+ /**
3651
+ * The directory tarred into every checkpoint — Pi's home directory, where its session file
3652
+ * (`.pi/agent/sessions/...`) and whatever the agent wrote both live. Every sandbox measured for
3653
+ * 3.1 ran Pi as root; a spec that runs as a different user is a known simplification this
3654
+ * chunk doesn't yet handle (no portable way to ask a sandbox its $HOME without an extra exec
3655
+ * round trip on every checkpoint, and nothing in the current fleet needs it).
3656
+ */
3657
+ const CHECKPOINT_ROOT = "root";
3658
+ /**
3659
+ * `/workspace` is the working directory most specs and cookbooks use, and it sits outside
3660
+ * `/root`, so a checkpoint of `/root` alone restored the Pi conversation but not the files the
3661
+ * agent had worked on (confirmed live, 2026-10-16). It is tarred too when it exists. Measured
3662
+ * cost: a cloned repo is 3.5 MB and 0.5 s. A web app's `node_modules` is nearly all of the cost
3663
+ * (20 MB and 5 s for 417 packages, against 0.1 MB and 0.03 s without), so dependency
3664
+ * directories are left out of this path only. Under `/root` they can hold Pi's own packages, so
3665
+ * they stay in.
3666
+ */
3667
+ const CHECKPOINT_WORKSPACE = "workspace";
3668
+ /** Left out of `CHECKPOINT_WORKSPACE`. The agent installs these again after a restore. */
3669
+ const DEFAULT_WORKSPACE_EXCLUDES = [`${CHECKPOINT_WORKSPACE}/node_modules`, `${CHECKPOINT_WORKSPACE}/*/node_modules`];
3670
+ /**
3671
+ * durability-roadmap M3, 3.5: restore (3.3) only ever reads the *latest* checkpoint — an older
3672
+ * one is slack for debugging/manual rollback, not a live requirement. 3 was decided without
3673
+ * real usage data to justify more (measured sizes are sub-30MB, typically far less once the
3674
+ * exclusion list applies), and is cheap to revisit if real retention pressure ever shows up.
3675
+ */
3676
+ const DEFAULT_CHECKPOINT_RETENTION = 3;
3677
+ /**
3678
+ * durability-roadmap M4, 4.1: an off-box blob is deleted only when it is both beyond the retention
3679
+ * count AND at least this old. The ledger can be restored from a replica that trails the live one
3680
+ * by a few seconds, so after a disk loss it may name a checkpoint that is no longer the newest. The
3681
+ * margin keeps that older blob alive long enough to be found. The restore also falls back from a
3682
+ * missing blob to the next older checkpoint, so this is a second line of defence.
3683
+ */
3684
+ const DEFAULT_REMOTE_PRUNE_MIN_AGE_MS = 6e5;
3685
+ /** Derive the checkpoints directory from the ledger adapter's own path, same convention as
3686
+ * `./snapshots.ts`'s `snapshotsPath()`. */
3687
+ function checkpointsPath(adapterPath) {
3688
+ return join(dirname(adapterPath), "checkpoints");
3689
+ }
3690
+ /**
3691
+ * Keep only the newest `retain` checkpoint files in `dir`, deleting the rest — called after
3692
+ * every successful `takeCheckpoint()` so disk use stays bounded across a long-running agent
3693
+ * instead of growing forever. Sorted by file mtime (set at write time, monotonic regardless of
3694
+ * process restarts), not by the `turn` number embedded in the filename — `turn` resets to 0
3695
+ * across a resume/reattach (see `CheckpointRecord.turn`'s doc comment), so two checkpoints
3696
+ * from different process lifetimes can share the same `turn` without actually being the same
3697
+ * age. Best-effort: a failure here (e.g. a concurrent delete) is logged by the caller, not
3698
+ * thrown — pruning old checkpoints is cleanup, never allowed to fail the checkpoint that just
3699
+ * succeeded.
3700
+ */
3701
+ async function pruneOldCheckpoints(dir, retain) {
3702
+ const names = await readdir(dir);
3703
+ if (names.length <= retain) return;
3704
+ const withTimes = await Promise.all(names.map(async (name) => ({
3705
+ name,
3706
+ mtimeMs: (await stat(join(dir, name))).mtimeMs
3707
+ })));
3708
+ withTimes.sort((a, b) => b.mtimeMs - a.mtimeMs);
3709
+ await Promise.all(withTimes.slice(retain).map((f) => rm(join(dir, f.name), { force: true })));
3710
+ }
3711
+ /**
3712
+ * Delete this sandbox's old off-box checkpoints: all but the newest `retain`, and only those older
3713
+ * than `minAgeMs`. Best-effort like the local prune: a failure is returned to the caller to log and
3714
+ * never thrown, because the checkpoint it follows already succeeded.
3715
+ */
3716
+ async function pruneRemoteCheckpoints(store, sandboxId, opts) {
3717
+ const now = opts.now ?? Date.now();
3718
+ const blobs = await store.list(`${sandboxId}/`);
3719
+ blobs.sort((a, b) => b.lastModified - a.lastModified);
3720
+ const doomed = blobs.slice(opts.retain).filter((b) => now - b.lastModified >= opts.minAgeMs).map((b) => b.key);
3721
+ await Promise.all(doomed.map((key) => store.delete(key)));
3722
+ return doomed;
3723
+ }
3724
+ /**
3725
+ * Tar `CHECKPOINT_ROOT` (minus the default excludes) inside the sandbox, pull the bytes out
3726
+ * byte-safe (`sb.readFileBytes()`, never `readFile()`'s UTF-8 path — a gzip tarball is not
3727
+ * valid UTF-8), write them to `checkpointsDir`, and record `AgentCheckpointed` on the sandbox's
3728
+ * own ledger — in that order, snapshot-then-event, so a checkpoint event is never written
3729
+ * pointing at a tarball that doesn't actually exist on disk.
3730
+ *
3731
+ * Throws on any step's failure (tar inside the sandbox, the byte-safe download, or the host
3732
+ * write) — the caller decides whether a failed checkpoint should interrupt the turn it was
3733
+ * taken after (3.2's own call site treats it as best-effort and logs rather than throws
3734
+ * further, since a checkpoint failing is not the same failure as the turn itself failing).
3735
+ * Retention (3.5) runs only after a successful write+event, pruning this sandbox's own
3736
+ * directory down to `opts.retain` (default `DEFAULT_CHECKPOINT_RETENTION`). A pruning failure
3737
+ * is swallowed, not thrown — the checkpoint this call was actually for already succeeded, and
3738
+ * a cleanup failure must never retroactively turn that into an error.
3739
+ */
3740
+ async function takeCheckpoint(sb, checkpointsDir, opts) {
3741
+ const tmpTarPath = `/tmp/alineo-checkpoint-${crypto.randomUUID()}.tar.gz`;
3742
+ const excludeArgs = [
3743
+ ...DEFAULT_CHECKPOINT_EXCLUDES.map((p) => `--exclude=${CHECKPOINT_ROOT}/${p}`),
3744
+ ...DEFAULT_CHECKPOINT_EXCLUDE_GLOBS.map((p) => `--exclude=*/${p}`),
3745
+ ...DEFAULT_WORKSPACE_EXCLUDES.map((p) => `--exclude=${p}`),
3746
+ ...(opts.excludeGlobs ?? []).map((p) => `--exclude=${p}`)
3747
+ ];
3748
+ try {
3749
+ await sb.exec(`tar czf ${tmpTarPath} -C / ${excludeArgs.join(" ")} ${CHECKPOINT_ROOT} $([ -d /${CHECKPOINT_WORKSPACE} ] && echo ${CHECKPOINT_WORKSPACE})`);
3750
+ const bytes = await sb.readFileBytes(tmpTarPath);
3751
+ const createdAt = Date.now();
3752
+ const dir = join(checkpointsDir, sb.sandboxId);
3753
+ await mkdir(dir, { recursive: true });
3754
+ const snapshotRef = join(dir, `${opts.turn}-${createdAt}.tar.gz`);
3755
+ await writeFile(snapshotRef, bytes);
3756
+ let remoteRef;
3757
+ let uploadError;
3758
+ const retain = opts.retain ?? 3;
3759
+ if (opts.blobStore) {
3760
+ const key = `${sb.sandboxId}/${opts.turn}-${createdAt}.tar.gz`;
3761
+ try {
3762
+ await opts.blobStore.put(key, snapshotRef);
3763
+ remoteRef = opts.blobStore.refOf(key);
3764
+ } catch (err) {
3765
+ uploadError = err instanceof Error ? err.message : String(err);
3766
+ log.warn("off-box upload failed -- the checkpoint stays on the host disk only", {
3767
+ sandboxId: sb.sandboxId,
3768
+ turn: opts.turn,
3769
+ error: uploadError
3770
+ });
3771
+ }
3772
+ }
3773
+ await sb.emit(LedgerEvent.AgentCheckpointed, -1, {
3774
+ turn: opts.turn,
3775
+ snapshotRef,
3776
+ ...remoteRef ? { remoteRef } : {},
3777
+ ...uploadError ? { uploadError } : {}
3778
+ });
3779
+ try {
3780
+ await pruneOldCheckpoints(dir, retain);
3781
+ } catch {}
3782
+ if (opts.blobStore && remoteRef) try {
3783
+ await pruneRemoteCheckpoints(opts.blobStore, sb.sandboxId, {
3784
+ retain,
3785
+ minAgeMs: opts.remoteMinAgeMs ?? 6e5
3786
+ });
3787
+ } catch (err) {
3788
+ log.warn("off-box checkpoint pruning failed", {
3789
+ sandboxId: sb.sandboxId,
3790
+ error: err instanceof Error ? err.message : String(err)
3791
+ });
3792
+ }
3793
+ return {
3794
+ turn: opts.turn,
3795
+ snapshotRef,
3796
+ remoteRef,
3797
+ uploadError,
3798
+ createdAt
3799
+ };
3800
+ } finally {
3801
+ try {
3802
+ await sb.exec(`rm -f ${tmpTarPath}`, { strict: false });
3803
+ } catch {}
3804
+ }
3805
+ }
3806
+ //#endregion
3807
+ export { AgentSnapshotStore, AgentSpecValidationError, Alineo, BridgeDisconnectedError, CHECKPOINT_ROOT, CLAUDE_CODE_CAPABILITIES, CODEX_CAPABILITIES, ClaudeCodeAdapter, CodexAdapter, DEFAULT_CHECKPOINT_EXCLUDES, DEFAULT_CHECKPOINT_RETENTION, DEFAULT_PROVIDER_ID, DEFAULT_REMOTE_PRUNE_MIN_AGE_MS, EgressApprovalGate, FakeHarness, MemoryBlobStore, PI_CAPABILITIES, PromptTimeoutError, S3BlobStore, checkpointsPath, computeSetupHash, createHarness, extractCheckpoint, fetchCheckpoint, findCheckpoints, findLatestCheckpoint, fromPiEvent, isReadOnlyBashCommand, isSandboxGone, pickRestorable, pruneRemoteCheckpoints, registeredHarnesses, requireHarnessCapability, restoreCheckpoint, snapshotsPath, takeCheckpoint, textOnly, validateAgentSpec };