alineo 0.7.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.d.mts CHANGED
@@ -1,16 +1,8 @@
1
- import { AgentSpec, AgentSpec as AgentSpec$1, PermissionAction, PermissionMode, PermissionPolicy, PermissionRule, ProjectConfig, SetupStep } from "@alineo-labs/schema";
2
- import { CredentialBinding, CredentialSource, ExecOptions, ExecResult, IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
1
+ import { CredentialBinding, CredentialSource, DEFAULT_PROVIDER_ID, ExecOptions, ExecResult, IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
2
+ import { AgentSpec, AgentSpec as AgentSpec$1, AgentSpecInput, HarnessId, HarnessRef, ModelRef, PermissionAction, PermissionMode, PermissionPolicy, PermissionRule, ProjectConfig, SetupStep } from "@alineo-labs/schema";
3
3
  import { z } from "zod";
4
4
  import { Memory, ResourceRef } from "@alineo-labs/memory";
5
5
  //#endregion
6
- //#region src/schema.d.ts
7
- /**
8
- * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
9
- * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
10
- * `.issues` array) rather than a bare `Error` — see #185.
11
- */
12
- export declare function validateAgentSpec(data: unknown): AgentSpec$1;
13
- //#endregion
14
6
  //#region src/types.d.ts
15
7
  /**
16
8
  * A single event emitted by an agent stream. Discriminated on `type`.
@@ -270,49 +262,431 @@ interface PiSessionState {
270
262
  pendingMessageCount: number;
271
263
  }
272
264
  //#endregion
273
- //#region src/adapters/pi.d.ts
274
- /** The subset of `SandboxHandle` that `PiAdapter` calls. `exec` only needs to be awaitable, so
275
- * callers (and tests) don't have to supply a full `ExecHandle`. */
276
- interface PiSandbox {
265
+ //#region src/harness/events.d.ts
266
+ /**
267
+ * What a harness turn yields, whichever harness runs it (Pi, Claude Code, Codex).
268
+ *
269
+ * The set is small on purpose. An event every harness can produce has its own `type`. A
270
+ * thing only one harness has goes in `vendor`, so a new harness never widens this union.
271
+ * Anything a harness reports that this union cannot hold stays in `raw`.
272
+ *
273
+ * Contract: a turn ends with exactly one `done`, including after an abort.
274
+ *
275
+ * @experimental The harness layer is being built. Expect changes before it is stable.
276
+ */
277
+ type HarnessEvent = HarnessEventBody & {
278
+ /** The harness's own event this one came from, untouched. For debugging and `vendor` use. */
279
+ raw?: unknown;
280
+ };
281
+ type HarnessEventBody =
282
+ /**
283
+ * The run began. Pi: `agent_start`. `sessionRef` is the id to resume this conversation
284
+ * with, when the harness has one.
285
+ */
286
+ {
287
+ type: "run_start";
288
+ sessionRef?: string;
289
+ } |
290
+ /** A chunk of assistant prose. */
291
+ {
292
+ type: "text";
293
+ text: string;
294
+ } |
295
+ /** A chunk of the model's reasoning, for harnesses that expose it. */
296
+ {
297
+ type: "reasoning";
298
+ text: string;
299
+ } | {
300
+ type: "turn_start";
301
+ turnIndex: number;
302
+ } | {
303
+ type: "turn_end";
304
+ turnIndex: number;
305
+ } |
306
+ /**
307
+ * An assistant message began. `messageId` is the id to hand back when forking at this
308
+ * message. It is `null` when the harness gives none. A caller must never invent one.
309
+ */
310
+ {
311
+ type: "message_start";
312
+ messageId: string | null;
313
+ } | {
314
+ type: "message_end";
315
+ messageId: string | null;
316
+ } | {
317
+ type: "tool_start";
318
+ toolCallId: string;
319
+ toolName: string;
320
+ args: unknown;
321
+ } | {
322
+ type: "tool_update";
323
+ toolCallId: string;
324
+ toolName: string;
325
+ partial: unknown;
326
+ } | {
327
+ type: "tool_end";
328
+ toolCallId: string;
329
+ toolName: string;
330
+ result: unknown;
331
+ isError: boolean;
332
+ } | {
333
+ type: "permission_request";
334
+ requestId: string;
335
+ tool: string;
336
+ target: string;
337
+ title: string;
338
+ } | {
339
+ type: "permission_resolved";
340
+ requestId: string;
341
+ decision: PermissionDecision;
342
+ } | {
343
+ type: "compaction";
344
+ phase: "start" | "end";
345
+ reason: string;
346
+ /** Only on `end`. */
347
+ aborted?: boolean;
348
+ /** Only on `end`. */
349
+ willRetry?: boolean;
350
+ } | {
351
+ type: "retry";
352
+ phase: "start" | "end";
353
+ attempt: number;
354
+ /** Only on `start`. */
355
+ maxAttempts?: number;
356
+ /** Only on `start`. */
357
+ delayMs?: number;
358
+ /** Only on `end`. */
359
+ success?: boolean;
360
+ /** The error that caused the retry (`start`) or ended it (`end`). */
361
+ error?: string;
362
+ } |
363
+ /** The steering and follow-up queues changed. */
364
+ {
365
+ type: "queue";
366
+ steering: string[];
367
+ followUp: string[];
368
+ } |
369
+ /** Something only this harness has. Callers who do not know `harness` ignore it. */
370
+ {
371
+ type: "vendor";
372
+ harness: string;
373
+ name: string;
374
+ data: unknown;
375
+ } |
376
+ /** The harness failed. A `done` with `reason: "error"` follows. */
377
+ {
378
+ type: "error";
379
+ message: string;
380
+ } |
381
+ /** The one terminal event of a turn. */
382
+ {
383
+ type: "done";
384
+ reason: "completed" | "aborted" | "error";
385
+ };
386
+ //#endregion
387
+ //#region src/harness/capabilities.d.ts
388
+ /**
389
+ * What a harness can do. Declared by the adapter, never probed. A method behind a
390
+ * capability the adapter declares `false` is never called: the SDK refuses first.
391
+ *
392
+ * `false` means "does not do it". A harness that cannot say whether it does must declare
393
+ * `false` too. It must never claim `true` to be safe.
394
+ *
395
+ * @experimental The harness layer is being built. Expect changes before it is stable.
396
+ */
397
+ interface HarnessCapabilities {
398
+ /** Inject a message into the turn that is running now. */
399
+ steer: boolean;
400
+ /** Queue a message to run after the current turn. */
401
+ followUp: boolean;
402
+ /** Continue a prior session by its `sessionRef`. */
403
+ resume: boolean;
404
+ /** Start a new session from a point in an old one, by `messageId`. */
405
+ fork: boolean;
406
+ /** Compact the context on request. */
407
+ compact: boolean;
408
+ /** Change the model of a live session. */
409
+ setModel: boolean;
410
+ /** The harness asks before running a tool, through `permission_request`. */
411
+ permissions: boolean;
412
+ /** The harness exposes the model's reasoning as `reasoning` events. */
413
+ reasoning: boolean;
414
+ }
415
+ type HarnessCapability = keyof HarnessCapabilities;
416
+ /**
417
+ * What Pi declares. Each value is what `PiAdapter` and `pi-bridge.ts` do today:
418
+ * `/steer`, `/follow-up`, `/fork`, `/compact`, `/set-model`, the permission gate, and
419
+ * `thinking_delta` events.
420
+ */
421
+ export declare const PI_CAPABILITIES: HarnessCapabilities;
422
+ //#endregion
423
+ //#region src/harness/pi-events.d.ts
424
+ /**
425
+ * Map one event of Pi's bridge stream to harness events. Zero, one or more come back.
426
+ *
427
+ * Every Pi event maps to exactly one harness event, and that event carries the Pi event as
428
+ * `raw`. Nothing is dropped. A `thinking_delta` inside `message_update` is `reasoning`.
429
+ * Every other `message_update` delta (text, tool-call, and so on) is a `vendor` event
430
+ * named `message_update`: the text of a `text_delta` already arrives as its own `text`
431
+ * event, so a neutral consumer ignores the vendor one.
432
+ *
433
+ * `agent_end` becomes `done`. The bridge ends a turn with `agent_end`. The error path
434
+ * (a bridge `{error}` frame, a timeout, an abort) is not an event on this stream. The
435
+ * adapter that reads the stream must emit `done` with `reason: "error"` or `"aborted"`.
436
+ */
437
+ export declare function fromPiEvent(ev: AgentEvent): HarnessEvent[];
438
+ //#endregion
439
+ //#region src/harness/sandbox.d.ts
440
+ /**
441
+ * The slice of `SandboxHandle` a harness adapter calls. `exec` only needs to be awaitable,
442
+ * so callers (and tests) do not have to supply a full `ExecHandle`. It keeps the harness
443
+ * layer testable with a stub.
444
+ *
445
+ * @experimental The harness layer is being built. Expect changes before it is stable.
446
+ */
447
+ interface HarnessSandbox {
277
448
  exec(cmd: string, opts?: ExecOptions): PromiseLike<ExecResult>;
278
449
  proxy: SandboxHandle["proxy"];
279
450
  writeFile: SandboxHandle["writeFile"];
280
451
  }
281
- declare class PiAdapter {
452
+ //#endregion
453
+ //#region src/schema.d.ts
454
+ /**
455
+ * Validate an unknown value as an `AgentSpec`, aggregating every problem found in one pass.
456
+ * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
457
+ * `.issues` array) rather than a bare `Error` — see #185.
458
+ */
459
+ export declare function validateAgentSpec(data: unknown): AgentSpec$1;
460
+ //#endregion
461
+ //#region src/harness/adapter.d.ts
462
+ /** One turn to run. */
463
+ interface TurnInput {
464
+ message: string;
465
+ /**
466
+ * How long a turn may go without a real event before it fails. Keep-alive pings do not
467
+ * count. Unset means the adapter's default.
468
+ */
469
+ inactivityTimeoutMs?: number;
470
+ /**
471
+ * Send `message` into the turn that is running, or queue it, instead of starting a turn.
472
+ * Needs the matching capability (`steer` or `followUp`). The returned stream ends with
473
+ * `done` once the harness has accepted the message.
474
+ */
475
+ streamingBehavior?: "steer" | "followUp";
476
+ }
477
+ /**
478
+ * One harness (Pi, Claude Code, Codex) driven inside a sandbox the SDK provisions.
479
+ *
480
+ * An adapter is created per agent and holds that agent's connection, so one instance
481
+ * serves one sandbox. Create it with `createHarness()`.
482
+ *
483
+ * Contract:
484
+ * - A turn yields exactly one `done` event, last, including after `abort()` and after a
485
+ * failure. A failure is an `error` event then `done`. `runTurn` does not throw for it.
486
+ * - `steer`, `followUp`, `compact` and `forkAt` exist only when the matching capability is `true`. Calling
487
+ * `steer` between turns throws. It never queues for the next turn.
488
+ * - A capability declared `false` is never called. Use `requireHarnessCapability()`.
489
+ *
490
+ * @experimental The harness layer is being built. Expect changes before it is stable.
491
+ */
492
+ interface HarnessAdapter {
493
+ /** A label for logs and errors. Never branch on it: branch on `capabilities`. */
494
+ readonly id: string;
495
+ /** Declared by the adapter, never probed. */
496
+ readonly capabilities: HarnessCapabilities;
497
+ /** Install the harness and spec packages. Slow. The result is captured by a snapshot. */
498
+ install(sb: HarnessSandbox, spec: AgentSpec): Promise<void>;
499
+ /**
500
+ * Write config, env and the in-sandbox bridge. Runs on every start, fresh install and
501
+ * snapshot resume alike, so env, model and bridge code stay current.
502
+ */
503
+ configure(sb: HarnessSandbox, spec: AgentSpec, resolvedEnv: Record<string, string>, opts?: {
504
+ resume?: boolean;
505
+ }): Promise<void>;
506
+ /**
507
+ * Start the in-sandbox process. `unsetVars` are cleared in the same command that starts it,
508
+ * so a forked sandbox's baked-in env does not leak into the harness.
509
+ */
510
+ start(sb: HarnessSandbox, opts?: {
511
+ unsetVars?: string[];
512
+ }): Promise<void>;
513
+ /** Bind to a process that is already running. Starts nothing. Follow with `waitReady()`. */
514
+ reattach(sb: Pick<HarnessSandbox, "proxy">): Promise<void>;
515
+ /** Resolve once the process answers, or throw after `timeoutMs`. */
516
+ waitReady(timeoutMs?: number): Promise<void>;
517
+ /** Run one turn. See the contract above. */
518
+ runTurn(input: TurnInput): AsyncIterable<HarnessEvent>;
519
+ /** Stop the turn that is running. Its stream ends with `done` and reason `aborted`. */
520
+ abort(): Promise<void>;
521
+ /** Inject a message into the running turn. Present iff `capabilities.steer`. */
522
+ steer?(message: string): Promise<void>;
523
+ /** Queue a message for after the running turn. Present iff `capabilities.followUp`. */
524
+ followUp?(message: string): Promise<void>;
525
+ /**
526
+ * Compact the context now. Present iff `capabilities.compact`. `instructions` steers what
527
+ * the summary keeps, where the harness takes them. The result is harness-specific.
528
+ */
529
+ compact?(instructions?: string): Promise<unknown>;
530
+ /**
531
+ * Continue from an earlier point as a new session, by the `messageId` of a `message_start`.
532
+ * Present iff `capabilities.fork`. The id must come from this adapter's own events: a
533
+ * harness's fork point is not always the id of the message a user sees.
534
+ * `sessionRef` is the id to resume the new session with, or `null` when the harness has none.
535
+ */
536
+ forkAt?(messageId: string): Promise<{
537
+ sessionRef: string | null;
538
+ }>;
539
+ /** Answer a `permission_request`. */
540
+ resolvePermission(requestId: string, decision: PermissionDecision): Promise<void>;
541
+ /** Tool calls paused awaiting a decision. */
542
+ listPendingPermissions(): Promise<PendingPermission[]>;
543
+ /** Close the connections this adapter left open. Call once, as the agent closes. */
544
+ dispose(): void;
545
+ }
546
+ //#endregion
547
+ //#region src/harness/bridge.d.ts
548
+ /**
549
+ * What every harness that runs behind an in-sandbox HTTP bridge shares: finding the bridge,
550
+ * waiting for it, streaming a turn from it, closing the streams it leaves open, and the
551
+ * permission endpoints. A subclass adds its own install, configure and turn mapping.
552
+ *
553
+ * The bridge contract (what a bridge script must serve):
554
+ * - `GET /health` returns `{ ok: true }` once it can take a turn.
555
+ * - `POST /abort` ends the running turn.
556
+ * - `POST /permission-response` takes `{ requestId, decision }`.
557
+ * - `GET /pending-permissions` returns `{ ok, data: { pending: PendingPermission[] } }`.
558
+ * - A turn is an SSE stream of JSON frames, ended by `data: [DONE]`. A frame `{ error }` fails it.
559
+ */
560
+ declare abstract class BridgeHarness<E extends {
561
+ type?: string;
562
+ requestId?: string;
563
+ }> {
564
+ /** The path the bridge script is written to in the sandbox. */
565
+ protected abstract readonly bridgeScriptPath: string;
282
566
  private _bridgeUrl;
283
567
  /**
284
- * Controllers for prompt/bash streams `sseStream` deliberately left open (its early
285
- * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
286
- * documents — see that method's comment). `AbortController.abort()`, not
287
- * `reader.cancel()`: Bun's `fetch()` tears down the underlying connection (and unrefs the
288
- * poll keeping the event loop alive) reliably on an abort signal, but was observed to
289
- * leave the socket referenced after `reader.cancel()` alone on this bridge's specific
290
- * long-lived, heartbeat-pinged connections (unlike execd's exec/code streams, which
291
- * self-resolve within execd's own bounded post-completion sleep either way — see
292
- * disposeConnections() below).
568
+ * Controllers for streams `sseStream` deliberately left open (its early return on `[DONE]`,
569
+ * to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE` documents).
570
+ * `AbortController.abort()`, not `reader.cancel()`: Bun's `fetch()` tears down the
571
+ * underlying connection reliably on an abort signal, but was observed to leave the socket
572
+ * referenced after `reader.cancel()` on the bridge's long-lived, heartbeat-pinged
573
+ * connections.
293
574
  *
294
- * Known limitation: this reliably lets a process exit after exactly one prompt()/bash()
295
- * call per agent lifetime (verified). A script making two or more such calls before
296
- * close() can still hang even though every controller here does abort cleanly on the
297
- * client side -- root cause traced to the same class of bug as
298
- * opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination confusing the
299
- * OpenSandbox control server's own proxy relay, which is what `bridgeUrl` is proxied
300
- * through). Tracked in our own #189; not fixable from this file alone.
575
+ * Known limitation: a script making two or more such calls before close() can still hang
576
+ * even though every controller here aborts cleanly on the client side. Root cause is the
577
+ * same class of bug as opensandbox-group/OpenSandbox#1277 (execd's chunked-SSE termination
578
+ * confusing the control server's proxy relay). Tracked in our own #189.
301
579
  */
302
- private pendingStreams;
303
- private get bridgeUrl();
580
+ protected readonly pendingStreams: Set<AbortController>;
581
+ abstract readonly id: string;
582
+ protected get bridgeUrl(): string;
304
583
  /**
305
- * Force-close any prompt/bash streams `sseStream` deliberately left open (its early
306
- * return on `[DONE]`, to dodge the same OpenSandbox proxy behavior `ExecClient.parseSSE`
307
- * documents — see that method's comment). Those connections sit ESTABLISHED, keeping
308
- * Bun's event loop alive indefinitely, until something force-closes them -- unlike
309
- * execd's exec/code streams (see `ExecClient.disposeConnections()`), the bridge's own
310
- * `: ping` heartbeat (every 3s, see pi-bridge.js) means there's no bounded server-side
311
- * timeout to eventually resolve a dangling one on its own. Call this once the agent is
312
- * being torn down anyway (from `agent.close()`) instead of leaving the process to hang
313
- * forever on whichever stream's `[DONE]` arrived last.
584
+ * Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the *same*
585
+ * exec command that starts `node`, which a forked sandbox needs: the container's OS-level
586
+ * env still carries whatever the parent had baked in at snapshot time. A plain
587
+ * `sb.exec("unset ...")` beforehand would not work: each `exec()` is its own shell session.
314
588
  */
315
- disposeConnections(): void;
589
+ start(sb: HarnessSandbox, opts?: {
590
+ unsetVars?: string[];
591
+ }): Promise<void>;
592
+ /**
593
+ * Rebind to a bridge that is already running. `sb.proxy(port)` is a pure URL lookup: it
594
+ * starts nothing, so nothing in the sandbox changes. Follow with `waitReady()`, because the
595
+ * container can be alive while the bridge process inside it is not.
596
+ */
597
+ reattach(sb: Pick<HarnessSandbox, "proxy">): Promise<void>;
598
+ waitReady(timeoutMs?: number): Promise<void>;
599
+ /**
600
+ * Force-close the streams left open (see `pendingStreams`). They sit ESTABLISHED, keeping
601
+ * the event loop alive, because the bridge's own `: ping` heartbeat means no server-side
602
+ * timeout ever ends a dangling one. Call once, as the agent closes.
603
+ */
604
+ dispose(): void;
605
+ abort(): Promise<void>;
606
+ resolvePermission(requestId: string, decision: PermissionDecision): Promise<void>;
607
+ listPendingPermissions(): Promise<PendingPermission[]>;
608
+ /** Open a turn stream on the bridge. */
609
+ protected stream(path: string, body: unknown, inactivityTimeoutMs?: number): AsyncGenerator<E>;
610
+ }
611
+ //#endregion
612
+ //#region src/adapters/claude-code.d.ts
613
+ /**
614
+ * What Claude Code declares. Each `false` is a thing the bridge does not do today, not a
615
+ * limit of the SDK: `steer` and `followUp` have no mid-turn injection in single-prompt mode,
616
+ * `compact` and `setModel` are not wired, and `reasoning` needs extended thinking turned on.
617
+ */
618
+ export declare const CLAUDE_CODE_CAPABILITIES: HarnessCapabilities;
619
+ /**
620
+ * Claude Code, driven through the Claude Agent SDK by a bridge in the sandbox. The bridge's
621
+ * frames are already `HarnessEvent`s, so `runTurn` forwards them.
622
+ *
623
+ * @experimental The harness layer is being built. Expect changes before it is stable.
624
+ */
625
+ export declare class ClaudeCodeAdapter extends BridgeHarness<HarnessEvent & {
626
+ requestId?: string;
627
+ }> implements HarnessAdapter {
628
+ readonly id = "claude-code";
629
+ readonly capabilities: HarnessCapabilities;
630
+ protected readonly bridgeScriptPath = "/alineo-bridge.js";
631
+ /** Install the Agent SDK globally, and any spec packages. Slow: a snapshot captures it. */
632
+ install(sb: HarnessSandbox, spec: AgentSpec): Promise<void>;
633
+ configure(sb: HarnessSandbox, spec: AgentSpec, resolvedEnv: Record<string, string>, opts?: {
634
+ resume?: boolean;
635
+ }): Promise<void>;
636
+ /**
637
+ * One turn as harness events. The bridge already speaks `HarnessEvent`, so the frames pass
638
+ * through. A bridge error frame, timeout or dropped stream is an `error` then `done`, and
639
+ * does not throw. A stream that ends with no `done` is `aborted`.
640
+ */
641
+ runTurn(input: TurnInput): AsyncGenerator<HarnessEvent>;
642
+ forkAt(messageId: string): Promise<{
643
+ sessionRef: string | null;
644
+ }>;
645
+ }
646
+ //#endregion
647
+ //#region src/adapters/codex.d.ts
648
+ /**
649
+ * What Codex declares, each backed by an `app-server` method: `turn/steer`,
650
+ * `thread/compact/start`, `thread/fork`, the approval requests, and reasoning deltas.
651
+ * `followUp` and `setModel` are not wired.
652
+ */
653
+ export declare const CODEX_CAPABILITIES: HarnessCapabilities;
654
+ /**
655
+ * Codex, driven through `codex app-server` (JSON-RPC over stdio) by a bridge in the sandbox.
656
+ * The bridge's frames are already `HarnessEvent`s, so `runTurn` forwards them.
657
+ *
658
+ * Fork granularity is the turn: every message of a turn has the turn id as its `messageId`,
659
+ * because `thread/fork` takes `lastTurnId`.
660
+ *
661
+ * @experimental The harness layer is being built. Expect changes before it is stable.
662
+ */
663
+ export declare class CodexAdapter extends BridgeHarness<HarnessEvent & {
664
+ requestId?: string;
665
+ }> implements HarnessAdapter {
666
+ readonly id = "codex";
667
+ readonly capabilities: HarnessCapabilities;
668
+ protected readonly bridgeScriptPath = "/alineo-bridge.js";
669
+ install(sb: HarnessSandbox, spec: AgentSpec): Promise<void>;
670
+ configure(sb: HarnessSandbox, spec: AgentSpec, resolvedEnv: Record<string, string>, opts?: {
671
+ resume?: boolean;
672
+ }): Promise<void>;
673
+ runTurn(input: TurnInput): AsyncGenerator<HarnessEvent>;
674
+ /** `turn/steer` into the running turn. Refused with `no turn in progress` between turns. */
675
+ steer(message: string): Promise<void>;
676
+ compact(): Promise<unknown>;
677
+ /** `thread/fork`. `messageId` is a turn id, from a `message_start` of this adapter. */
678
+ forkAt(messageId: string): Promise<{
679
+ sessionRef: string | null;
680
+ }>;
681
+ }
682
+ //#endregion
683
+ //#region src/adapters/pi.d.ts
684
+ /** The subset of `SandboxHandle` that `PiAdapter` calls. Kept as an alias of `HarnessSandbox`. */
685
+ type PiSandbox = HarnessSandbox;
686
+ declare class PiAdapter extends BridgeHarness<AgentEvent> implements HarnessAdapter {
687
+ readonly id = "pi";
688
+ readonly capabilities: HarnessCapabilities;
689
+ protected readonly bridgeScriptPath = "/alineo-bridge.js";
316
690
  /** Install Pi CLI and any spec packages. Slow — result is captured by checkpoint(). */
317
691
  install(sb: PiSandbox, spec: AgentSpec): Promise<void>;
318
692
  /**
@@ -322,41 +696,32 @@ declare class PiAdapter {
322
696
  configure(sb: PiSandbox, spec: AgentSpec, resolvedEnv: Record<string, string>, opts?: {
323
697
  resume?: boolean;
324
698
  }): Promise<void>;
325
- /**
326
- * Start the bridge. `unsetVars`, when given, is prefixed as `unset A B C; ` on the
327
- * *same* exec command that starts `node` — required for `Alineo.spawn()`'s forked
328
- * sandboxes, where the container's OS-level env still carries whatever the parent
329
- * had baked into it at snapshot time (`env` passed to `createSandbox` at fork time
330
- * has no effect on this — verified live, see `plans/alineo-rlm-substrate.md`). A
331
- * plain `sb.exec("unset ...")` beforehand would not work: `unset` only clears the
332
- * shell session it runs in, and each `exec()` call is its own session — it has to
333
- * be part of the exact command that spawns the bridge process so the bridge (and
334
- * everything it in turn spawns, including Pi itself) inherits the already-clean env.
335
- */
699
+ /** `start()` under its older name. */
336
700
  startBridge(sb: PiSandbox, unsetVars?: string[]): Promise<void>;
701
+ /** `fork(entryId)` in the harness-neutral shape. Pi switches its own session in place. */
702
+ forkAt(messageId: string): Promise<{
703
+ sessionRef: string | null;
704
+ }>;
705
+ /** `reattach()` under its older name. */
706
+ reattachBridge(sb: Pick<HarnessSandbox, "proxy">): Promise<void>;
707
+ /** `dispose()` under its older name. */
708
+ disposeConnections(): void;
337
709
  /**
338
- * Rebind to a bridge that's already running (as opposed to `startBridge()`, which execs a
339
- * fresh `node /alineo-bridge.js`). `sb.proxy(port)` is a pure URL lookup against the
340
- * sandbox's control plane — it starts nothing — so this has zero effect on the sandbox
341
- * itself: no killed process, no dropped in-flight turn, no reset Pi conversation state.
710
+ * One turn as harness events, ending in exactly one `done`. A failure (the bridge sends an
711
+ * error frame, the stream times out or drops) becomes an `error` event then `done`: it
712
+ * does not throw, and the `error` event's `raw` is the original error.
342
713
  *
343
- * Call `waitReady()` afterwards to confirm the bridge is actually still there before relying
344
- * on it — the container can be alive while the bridge process inside it isn't (e.g. it
345
- * crashed independently), and this method alone can't tell the difference.
714
+ * A stream that ends with no `agent_end` is `aborted`. The bridge ends a stream that way
715
+ * only when someone called `/abort`, from this process or another. A message sent with
716
+ * `streamingBehavior` also ends with no `agent_end`: that is `completed`.
346
717
  */
347
- reattachBridge(sb: SandboxHandle): Promise<void>;
348
- waitReady(timeoutMs?: number): Promise<void>;
718
+ runTurn(input: TurnInput): AsyncGenerator<HarnessEvent>;
349
719
  prompt(message: string, opts?: {
350
720
  streamingBehavior?: "steer" | "followUp";
351
721
  inactivityTimeoutMs?: number;
352
722
  }): AgentStream;
353
723
  bash(command: string): AgentStream;
354
724
  steer(message: string): Promise<void>;
355
- abort(): Promise<void>;
356
- /** Resolve a pending `permission_request` (see `AgentEvent`'s `permission_request`). */
357
- resolvePermission(requestId: string, decision: PermissionDecision): Promise<void>;
358
- /** Tool calls currently paused awaiting a human decision. */
359
- listPendingPermissions(): Promise<PendingPermission[]>;
360
725
  followUp(message: string): Promise<void>;
361
726
  newSession(): Promise<void>;
362
727
  setThinkingLevel(level: ThinkingLevel): Promise<void>;
@@ -404,6 +769,91 @@ declare class PiAdapter {
404
769
  getLogs(): Promise<string>;
405
770
  }
406
771
  //#endregion
772
+ //#region src/harness/registry.d.ts
773
+ /**
774
+ * Every harness the SDK can drive, by id, and the concrete adapter class for each.
775
+ *
776
+ * The concrete type is here, not just `HarnessAdapter`, because `Alineo` still calls Pi-only
777
+ * methods. When those move behind `agent.harness<"pi">()`, this map is what types that call.
778
+ */
779
+ interface HarnessRegistry {
780
+ pi: PiAdapter;
781
+ "claude-code": ClaudeCodeAdapter;
782
+ codex: CodexAdapter;
783
+ }
784
+ /** The ids `createHarness()` accepts. */
785
+ export declare function registeredHarnesses(): string[];
786
+ /**
787
+ * Create the adapter for a harness id. The only place an adapter class is constructed.
788
+ * Throws `SPEC_INVALID` for an id nothing registered.
789
+ */
790
+ export declare function createHarness<K extends keyof HarnessRegistry>(id: K): HarnessRegistry[K];
791
+ /**
792
+ * Refuse a call the harness declared it cannot do, before anything is sent. Same idea as
793
+ * `requireCapability` for sandbox providers.
794
+ */
795
+ export declare function requireHarnessCapability(adapter: Pick<HarnessAdapter, "id" | "capabilities">, capability: HarnessCapability): void;
796
+ //#endregion
797
+ //#region src/harness/fake.d.ts
798
+ /** What a `FakeHarness` does on its next turn. */
799
+ type FakeScenario = {
800
+ kind: "text";
801
+ text: string;
802
+ } | {
803
+ kind: "tool";
804
+ toolName: string;
805
+ result: string;
806
+ } |
807
+ /** Starts, then waits until `abort()`. */
808
+ {
809
+ kind: "hang";
810
+ } | {
811
+ kind: "fail";
812
+ message: string;
813
+ } |
814
+ /** Asks for permission to run `tool`, then runs it only if the answer allows. */
815
+ {
816
+ kind: "permission";
817
+ tool: string;
818
+ target: string;
819
+ };
820
+ /**
821
+ * A harness that runs no process: it plays a `FakeScenario` in memory. For tests that need
822
+ * a `HarnessAdapter` and for proving the conformance suite itself is satisfiable. It is not
823
+ * registered, so a spec cannot select it.
824
+ *
825
+ * @experimental The harness layer is being built. Expect changes before it is stable.
826
+ */
827
+ export declare class FakeHarness implements HarnessAdapter {
828
+ private readonly scenario;
829
+ readonly id = "fake";
830
+ readonly capabilities: HarnessCapabilities;
831
+ /** Lifecycle calls in order, for assertions. */
832
+ readonly calls: string[];
833
+ /** Messages `steer` and `followUp` accepted. */
834
+ readonly received: string[];
835
+ steer?: (message: string) => Promise<void>;
836
+ followUp?: (message: string) => Promise<void>;
837
+ forkAt?: (messageId: string) => Promise<{
838
+ sessionRef: string | null;
839
+ }>;
840
+ compact?: (instructions?: string) => Promise<unknown>;
841
+ private turnActive;
842
+ private release;
843
+ private pending;
844
+ constructor(scenario: FakeScenario, capabilities?: Partial<HarnessCapabilities>);
845
+ install(_sb: HarnessSandbox, _spec: AgentSpec): Promise<void>;
846
+ configure(): Promise<void>;
847
+ start(): Promise<void>;
848
+ reattach(): Promise<void>;
849
+ waitReady(): Promise<void>;
850
+ runTurn(_input: TurnInput): AsyncGenerator<HarnessEvent>;
851
+ abort(): Promise<void>;
852
+ resolvePermission(requestId: string, decision: PermissionDecision): Promise<void>;
853
+ listPendingPermissions(): Promise<PendingPermission[]>;
854
+ dispose(): void;
855
+ }
856
+ //#endregion
407
857
  //#region src/config.d.ts
408
858
  /**
409
859
  * Shape of `alineo.config.json`, merged with built-in defaults.
@@ -415,6 +865,103 @@ declare class PiAdapter {
415
865
  */
416
866
  type AlineoAgentConfig = ProjectConfig;
417
867
  //#endregion
868
+ //#region src/blob-store.d.ts
869
+ /**
870
+ * Where a checkpoint tarball (or any backup file) lives when it is not on the host's disk.
871
+ *
872
+ * durability-roadmap M4, 4.1. A checkpoint on the host disk survives a lost container. It does not
873
+ * survive a lost disk. `BlobStore` is the small surface the checkpoint and restore code needs from
874
+ * object storage, so the S3 client stays behind one interface: another store, or a fake in a test,
875
+ * is one class.
876
+ *
877
+ * Keys are relative to the store. A store may sit under a prefix in its bucket, and `refOf()` /
878
+ * `keyOf()` convert between a key and the full reference written to the ledger.
879
+ */
880
+ interface BlobInfo {
881
+ /** Relative to the store, the same key `put()` took. */
882
+ key: string;
883
+ /** Unix ms. */
884
+ lastModified: number;
885
+ }
886
+ interface BlobStore {
887
+ /** `string` is the path of a local file, streamed from disk. Bytes are sent as they are. */
888
+ put(key: string, body: string | Uint8Array): Promise<void>;
889
+ /** Throws if the key does not exist. */
890
+ get(key: string): Promise<Uint8Array>;
891
+ /** Not an error when the key is already gone. */
892
+ delete(key: string): Promise<void>;
893
+ /** Every blob whose key starts with `prefix`, in no particular order. */
894
+ list(prefix: string): Promise<BlobInfo[]>;
895
+ /** The reference recorded in the ledger for `key`. Stable across processes and hosts. */
896
+ refOf(key: string): string;
897
+ /** The inverse of `refOf()`, or `undefined` when this store did not produce `ref`. */
898
+ keyOf(ref: string): string | undefined;
899
+ }
900
+ /**
901
+ * The slice of `Bun.S3Client` that `S3BlobStore` calls. A test passes a fake instead of a bucket.
902
+ */
903
+ interface S3ClientLike {
904
+ file(key: string): {
905
+ write(data: Blob | Uint8Array | string): Promise<number>;
906
+ bytes(): Promise<Uint8Array>;
907
+ };
908
+ delete(key: string): Promise<void>;
909
+ list(options: {
910
+ prefix?: string;
911
+ continuationToken?: string;
912
+ }): Promise<{
913
+ contents?: Array<{
914
+ key: string;
915
+ lastModified?: string;
916
+ }>;
917
+ isTruncated?: boolean;
918
+ nextContinuationToken?: string;
919
+ }>;
920
+ }
921
+ interface S3BlobStoreOptions {
922
+ bucket: string;
923
+ /** Everything this store writes goes under it. No leading or trailing slash needed. */
924
+ prefix?: string;
925
+ /** For R2, MinIO and other S3-compatible services. Leave out for AWS. */
926
+ endpoint?: string;
927
+ region?: string;
928
+ accessKeyId?: string;
929
+ secretAccessKey?: string;
930
+ /** A fake in tests. Production code leaves it out and gets a `Bun.S3Client`. */
931
+ client?: S3ClientLike;
932
+ }
933
+ /** S3, R2, MinIO: anything `Bun.S3Client` talks to. Runs under Bun only. */
934
+ export declare class S3BlobStore implements BlobStore {
935
+ private readonly client;
936
+ private readonly bucket;
937
+ private readonly prefix;
938
+ constructor(opts: S3BlobStoreOptions);
939
+ private full;
940
+ put(key: string, body: string | Uint8Array): Promise<void>;
941
+ get(key: string): Promise<Uint8Array>;
942
+ delete(key: string): Promise<void>;
943
+ list(prefix: string): Promise<BlobInfo[]>;
944
+ refOf(key: string): string;
945
+ keyOf(ref: string): string | undefined;
946
+ }
947
+ /**
948
+ * Keeps blobs in a Map. The store the unit tests use, and a reference for what a `BlobStore` must
949
+ * do. `now` lets a test age a blob without waiting.
950
+ */
951
+ export declare class MemoryBlobStore implements BlobStore {
952
+ private readonly now;
953
+ private readonly blobs;
954
+ constructor(now?: () => number);
955
+ put(key: string, body: string | Uint8Array): Promise<void>;
956
+ get(key: string): Promise<Uint8Array>;
957
+ delete(key: string): Promise<void>;
958
+ list(prefix: string): Promise<BlobInfo[]>;
959
+ refOf(key: string): string;
960
+ keyOf(ref: string): string | undefined;
961
+ /** Test seam: every key, so a test can assert what was written or deleted. */
962
+ keys(): string[];
963
+ }
964
+ //#endregion
418
965
  //#region src/agent/egress-approval.d.ts
419
966
  /** The subset of `SandboxHandle` the gate calls. */
420
967
  type EgressApprovalSandbox = Pick<SandboxHandle, "egress" | "credentials" | "emit">;
@@ -513,12 +1060,163 @@ export declare class EgressApprovalGate {
513
1060
  * exported interface within the package.
514
1061
  */
515
1062
  interface AgentInternal {
516
- readonly adapter: PiAdapter;
1063
+ readonly adapter: HarnessAdapter;
517
1064
  readonly sandbox: SandboxHandle;
518
1065
  env: Record<string, string>;
519
1066
  /** Present when the spec has `approval: "hold"` credential bindings. */
520
1067
  readonly egressGate?: EgressApprovalGate;
521
1068
  }
1069
+ declare namespace factory_d_exports {
1070
+ export { AgentConstructorArgs, AgentRestore, attachAgent, forkChildMemory, loadAgent, reattachAgent, reconcileDroppedPermissions, resumeAgent, spawnChild };
1071
+ }
1072
+ /** Constructor arguments for `Alineo` — returned by each factory function below so the actual
1073
+ * `new Alineo(...)` call stays inside `Alineo`'s own static methods, which alone have access to
1074
+ * its private constructor. */
1075
+ interface AgentConstructorArgs {
1076
+ sandbox: SandboxHandle;
1077
+ spec: AgentSpec;
1078
+ env: Record<string, string>;
1079
+ adapter: HarnessAdapter;
1080
+ fromSnapshot: boolean;
1081
+ /** Run-correlation ID for this agent's sandbox — see `SandboxDetails.runId`. */
1082
+ runId: string;
1083
+ /** Started when the spec has `approval: "hold"` bindings; stopped by `agent.close()`. */
1084
+ egressGate?: EgressApprovalGate;
1085
+ /**
1086
+ * Set only when the sandbox was gone and a fresh one replaced it (`restoreFromCheckpoint`).
1087
+ * `checkpointTurn` is the turn restored from, or `null` when there was no checkpoint and the
1088
+ * agent came back blank.
1089
+ */
1090
+ restore?: AgentRestore;
1091
+ }
1092
+ interface AgentRestore {
1093
+ checkpointTurn: number | null;
1094
+ }
1095
+ /**
1096
+ * Validate `specInput` and return everything needed to construct a fully initialised `Alineo`.
1097
+ * See `Alineo.start()` for the public-facing docs.
1098
+ */
1099
+ declare function loadAgent(specInput: AgentSpec | Record<string, unknown>, opts: {
1100
+ adapter: IStorageAdapter;
1101
+ /**
1102
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
1103
+ * tests that must not depend on the working directory.
1104
+ */
1105
+ config?: AlineoAgentConfig;
1106
+ rebuild?: boolean;
1107
+ spawnDepth?: number;
1108
+ maxAgents?: number;
1109
+ runId?: string;
1110
+ /** Required when the spec has `approval: "hold"` credential bindings — decides each
1111
+ * first outbound request to a held host. See `EgressApprovalGate`. */
1112
+ onEgressRequest?: EgressRequestHandler;
1113
+ }): Promise<AgentConstructorArgs>;
1114
+ /**
1115
+ * Reconnect to a previously-created agent whose host process has exited. See
1116
+ * `Alineo.resume()` for the public-facing docs.
1117
+ */
1118
+ declare function resumeAgent(sandboxId: string, opts: {
1119
+ adapter: IStorageAdapter;
1120
+ spec?: AgentSpec | Record<string, unknown>;
1121
+ specPath?: string;
1122
+ runId?: string;
1123
+ /**
1124
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
1125
+ * tests that must not depend on the working directory.
1126
+ */
1127
+ config?: AlineoAgentConfig;
1128
+ /**
1129
+ * Where off-box checkpoints are fetched from when the sandbox is gone and the host's own
1130
+ * checkpoint file is too (a new machine after a disk loss). Without it, only checkpoints on
1131
+ * this host's disk can be restored.
1132
+ */
1133
+ blobStore?: BlobStore;
1134
+ }): Promise<AgentConstructorArgs>;
1135
+ /**
1136
+ * durability-roadmap.md M1.3: this used to resolve a dropped request with
1137
+ * `decision: { kind: "reject" }` — `PermissionDecision`'s `"reject"` is documented as *a
1138
+ * human's answer*, and no human answered this one. Nobody could: the tool call it was about
1139
+ * died with the old Pi process (OpenSandbox restore is rootfs-only, so it isn't still parked
1140
+ * anywhere to answer). `"dropped"` says what actually happened instead of fabricating a
1141
+ * decision nobody made.
1142
+ *
1143
+ * This is the narrow fix — an honest ledger, not a re-opened decision. The better path forward
1144
+ * is giving a human an actual chance to weigh in: alineod has no live route to answer a
1145
+ * permission request at all today (`driveTurn` calls `agent.prompt()` with no `onPermission`),
1146
+ * so there's nothing yet for a "re-issue this to an operator" version of this function to
1147
+ * re-issue *into*. Once that live path exists, this should queue the same way
1148
+ * `agent.supervision_needed` already does, instead of resolving anything here.
1149
+ */
1150
+ declare function reconcileDroppedPermissions(adapter: IStorageAdapter, sb: SandboxHandle, name: string, sandboxId: string): Promise<void>;
1151
+ /**
1152
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge. See
1153
+ * `Alineo.reattach()` for the public-facing docs. Structurally `resumeAgent()` minus its two
1154
+ * destructive steps (the `pkill` and the fresh `startBridge()`) — everything else (spec
1155
+ * resolution, env, `client.connect()`) is identical.
1156
+ */
1157
+ declare function reattachAgent(sandboxId: string, opts: {
1158
+ adapter: IStorageAdapter;
1159
+ spec?: AgentSpec | Record<string, unknown>;
1160
+ specPath?: string;
1161
+ runId?: string;
1162
+ skipReadyCheck?: boolean;
1163
+ /**
1164
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
1165
+ * tests that must not depend on the working directory.
1166
+ */
1167
+ config?: AlineoAgentConfig;
1168
+ /**
1169
+ * Where off-box checkpoints are fetched from when the sandbox is gone and the host's own
1170
+ * checkpoint file is too (a new machine after a disk loss). Without it, only checkpoints on
1171
+ * this host's disk can be restored.
1172
+ */
1173
+ blobStore?: BlobStore;
1174
+ }): Promise<AgentConstructorArgs>;
1175
+ /**
1176
+ * Connect to an already-running sandbox WITHOUT touching its Pi bridge. See
1177
+ * `Alineo.attach()` for the public-facing docs.
1178
+ */
1179
+ declare function attachAgent(sandboxId: string, opts: {
1180
+ adapter: IStorageAdapter;
1181
+ name: string;
1182
+ resources?: {
1183
+ cpu: string;
1184
+ memory: string;
1185
+ gpu?: string;
1186
+ };
1187
+ /**
1188
+ * Skip `alineo.config.json` discovery and use this instead — for embedded callers and
1189
+ * tests that must not depend on the working directory.
1190
+ */
1191
+ config?: AlineoAgentConfig;
1192
+ }): Promise<AgentConstructorArgs>;
1193
+ /**
1194
+ * Fork `self`'s live sandbox into a brand-new independent sandbox running its
1195
+ * own Pi bridge, per `childSpecPath`. See `Alineo.spawn()` for the public-facing docs.
1196
+ */
1197
+ declare function spawnChild(self: AgentInternal, childSpecPath: string, opts?: {
1198
+ spawnDepth?: number;
1199
+ maxAgents?: number;
1200
+ }): Promise<AgentConstructorArgs>;
1201
+ /**
1202
+ * Seed a just-constructed spawn child's memory from its parent — the memory-layer
1203
+ * counterpart to `spawnChild()`'s sandbox-level fork above. Called from `Alineo.spawn()`
1204
+ * after the child is constructed (not from `spawnChild()` itself, which runs before the
1205
+ * child exists and so has no `child.resourceRef` to fork into yet).
1206
+ *
1207
+ * A no-op when `parentMemory` is `undefined` — most agents don't have `.memory` configured.
1208
+ * Otherwise forks an independent snapshot copy the child can mutate on its own, not a live
1209
+ * share of the parent's scope (`child.resourceRef` already names a different resource — the
1210
+ * child spec's own name — so this seeds that scope rather than overwriting the parent's).
1211
+ *
1212
+ * The sandbox fork has already succeeded by the time this runs (`child.sandbox` is live) —
1213
+ * if the memory-layer fork throws, close the child sandbox before rethrowing rather than
1214
+ * leaving it orphaned with nothing left to close it.
1215
+ */
1216
+ declare function forkChildMemory(parentMemory: Memory | undefined, parentRef: ResourceRef, child: {
1217
+ resourceRef: ResourceRef;
1218
+ close: () => Promise<void>;
1219
+ }): Promise<void>;
522
1220
  declare namespace session_control_d_exports {
523
1221
  export { PermissionHandler, abort, abortBash, abortRetry, bash, followUp, listPendingPermissions, newSession, prompt, resolvePermission, setAutoCompaction, setAutoRetry, setFollowUpMode, setSessionName, setSteeringMode, steer };
524
1222
  }
@@ -627,7 +1325,11 @@ export declare class Alineo {
627
1325
  * `false` on the first load for a given spec, or after `{ rebuild: true }`.
628
1326
  */
629
1327
  readonly fromSnapshot: boolean;
630
- readonly adapter: PiAdapter;
1328
+ /**
1329
+ * The harness this agent runs, as the harness-neutral interface. For a harness's own
1330
+ * methods use `harness()`.
1331
+ */
1332
+ readonly adapter: HarnessAdapter;
631
1333
  env: Record<string, string>;
632
1334
  /**
633
1335
  * Identifies the logical run this agent's sandbox belongs to — see
@@ -675,6 +1377,12 @@ export declare class Alineo {
675
1377
  * Stopped by `close()`.
676
1378
  */
677
1379
  readonly egressGate?: EgressApprovalGate;
1380
+ /**
1381
+ * Set when `resume()` or `reattach()` found the sandbox gone and returned an agent on a fresh
1382
+ * one. `checkpointTurn` is the turn it was restored from, or `null` when there was no
1383
+ * checkpoint and the session is blank. Absent on every other agent.
1384
+ */
1385
+ readonly restore?: AgentRestore;
678
1386
  private constructor();
679
1387
  /** Egress requests currently awaiting a decision (see `AgentSpec.env` `approval: "hold"`). */
680
1388
  pendingEgressRequests(): EgressRequest[];
@@ -775,6 +1483,11 @@ export declare class Alineo {
775
1483
  * tests that must not depend on the working directory.
776
1484
  */
777
1485
  config?: AlineoAgentConfig;
1486
+ /**
1487
+ * Where off-box checkpoints are fetched from when the sandbox is gone and this host's own
1488
+ * checkpoint file is too (a new machine after a disk loss). See `BlobStore`.
1489
+ */
1490
+ blobStore?: BlobStore;
778
1491
  }): Promise<Alineo>;
779
1492
  /**
780
1493
  * Reconnect to a previously-created agent WITHOUT restarting its bridge — the crash-only
@@ -817,6 +1530,11 @@ export declare class Alineo {
817
1530
  * tests that must not depend on the working directory.
818
1531
  */
819
1532
  config?: AlineoAgentConfig;
1533
+ /**
1534
+ * Where off-box checkpoints are fetched from when the sandbox is gone and this host's own
1535
+ * checkpoint file is too (a new machine after a disk loss). See `BlobStore`.
1536
+ */
1537
+ blobStore?: BlobStore;
820
1538
  /**
821
1539
  * Don't probe the bridge before returning, and accept a Paused sandbox. For a paused
822
1540
  * sandbox, whose frozen bridge can't answer until `agent.sandbox.resume()` — check it
@@ -908,6 +1626,17 @@ export declare class Alineo {
908
1626
  spawnDepth?: number;
909
1627
  maxAgents?: number;
910
1628
  }): Promise<Alineo>;
1629
+ /**
1630
+ * The harness's own adapter, typed for that harness, for what it has and the others do not.
1631
+ * `agent.harness("pi")` gives Pi's `exportHtml()`, `cycleModel()`, `getCommands()` and the
1632
+ * rest. Throws `CAPABILITY_UNSUPPORTED` when this agent runs a different harness.
1633
+ *
1634
+ * Prefer the methods on `Alineo` itself where they exist: they work on every harness
1635
+ * that declares the capability.
1636
+ *
1637
+ * @experimental The harness layer is being built. Expect changes before it is stable.
1638
+ */
1639
+ harness<K extends keyof HarnessRegistry>(id: K): HarnessRegistry[K];
911
1640
  /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
912
1641
  prompt(message: string, opts?: {
913
1642
  streamingBehavior?: "steer" | "followUp";
@@ -923,6 +1652,8 @@ export declare class Alineo {
923
1652
  * Run a shell command inside Pi's working context. Not incrementally
924
1653
  * streamed — Pi returns bash output synchronously, so the full output
925
1654
  * arrives as a single `text` event once the command completes.
1655
+ *
1656
+ * @deprecated Use `agent.harness("pi").bash()`. Moves off `Alineo` because only Pi has it.
926
1657
  */
927
1658
  bash(command: string): AgentStream;
928
1659
  /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
@@ -955,21 +1686,31 @@ export declare class Alineo {
955
1686
  newSession(): Promise<void>;
956
1687
  /** Set Pi's reasoning level (for models that support extended thinking). */
957
1688
  setThinkingLevel(level: ThinkingLevel): Promise<void>;
958
- /** Enable or disable Pi's automatic context compaction. */
1689
+ /** Enable or disable Pi's automatic context compaction.
1690
+ *
1691
+ * @deprecated Use `agent.harness("pi").setAutoCompaction()`. Moves off `Alineo` because only Pi has it.
1692
+ */
959
1693
  setAutoCompaction(enabled: boolean): Promise<void>;
960
1694
  /**
961
1695
  * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
962
1696
  * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
963
1697
  * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
964
1698
  * events in the stream.
1699
+ *
1700
+ * @deprecated Use `agent.harness("pi").setAutoRetry()`. Moves off `Alineo` because only Pi has it.
965
1701
  */
966
1702
  setAutoRetry(enabled: boolean): Promise<void>;
967
1703
  /**
968
1704
  * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
969
1705
  * operation, emitting `auto_retry_end` with `success: false`.
1706
+ *
1707
+ * @deprecated Use `agent.harness("pi").abortRetry()`. Moves off `Alineo` because only Pi has it.
970
1708
  */
971
1709
  abortRetry(): Promise<void>;
972
- /** Abort a currently-executing bash command without cancelling the whole prompt. */
1710
+ /** Abort a currently-executing bash command without cancelling the whole prompt.
1711
+ *
1712
+ * @deprecated Use `agent.harness("pi").abortBash()`. Moves off `Alineo` because only Pi has it.
1713
+ */
973
1714
  abortBash(): Promise<void>;
974
1715
  /** Retrieve token usage, cost, and message counts for the current session. */
975
1716
  getSessionStats(): Promise<SessionStats>;
@@ -983,24 +1724,36 @@ export declare class Alineo {
983
1724
  entryId: string;
984
1725
  text: string;
985
1726
  }[]>;
986
- /** List Pi's available slash commands, including extensions, prompt templates, and skills. */
1727
+ /** List Pi's available slash commands, including extensions, prompt templates, and skills.
1728
+ *
1729
+ * @deprecated Use `agent.harness("pi").getCommands()`. Moves off `Alineo` because only Pi has it.
1730
+ */
987
1731
  getCommands(): Promise<PiSlashCommand[]>;
988
- /** Set a display name for the current Pi session. */
1732
+ /** Set a display name for the current Pi session.
1733
+ *
1734
+ * @deprecated Use `agent.harness("pi").setSessionName()`. Moves off `Alineo` because only Pi has it.
1735
+ */
989
1736
  setSessionName(name: string): Promise<void>;
990
1737
  /**
991
1738
  * Control how Pi processes queued steering messages.
992
1739
  * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
1740
+ *
1741
+ * @deprecated Use `agent.harness("pi").setSteeringMode()`. Moves off `Alineo` because only Pi has it.
993
1742
  */
994
1743
  setSteeringMode(mode: "all" | "one-at-a-time"): Promise<void>;
995
1744
  /**
996
1745
  * Control how Pi processes queued follow-up messages.
997
1746
  * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
1747
+ *
1748
+ * @deprecated Use `agent.harness("pi").setFollowUpMode()`. Moves off `Alineo` because only Pi has it.
998
1749
  */
999
1750
  setFollowUpMode(mode: "all" | "one-at-a-time"): Promise<void>;
1000
1751
  /**
1001
1752
  * Export a static HTML transcript of the current session to the sandbox filesystem.
1002
1753
  * Returns the container path of the generated file — use `agent.sandbox.readFile(path)`
1003
1754
  * to retrieve it.
1755
+ *
1756
+ * @deprecated Use `agent.harness("pi").exportHtml()`. Moves off `Alineo` because only Pi has it.
1004
1757
  */
1005
1758
  exportHtml(outputPath?: string): Promise<{
1006
1759
  path: string;
@@ -1029,13 +1782,19 @@ export declare class Alineo {
1029
1782
  }>;
1030
1783
  /** Switch Pi to a specific model. Returns the activated model. */
1031
1784
  setModel(provider: string, modelId: string): Promise<PiModel>;
1032
- /** Cycle Pi to the next available model. Returns null if only one model is configured. */
1785
+ /** Cycle Pi to the next available model. Returns null if only one model is configured.
1786
+ *
1787
+ * @deprecated Use `agent.harness("pi").cycleModel()`. Moves off `Alineo` because only Pi has it.
1788
+ */
1033
1789
  cycleModel(): Promise<{
1034
1790
  model: PiModel;
1035
1791
  thinkingLevel: ThinkingLevel;
1036
1792
  isScoped: boolean;
1037
1793
  } | null>;
1038
- /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking. */
1794
+ /** Cycle Pi's thinking level. Returns null if the current model doesn't support thinking.
1795
+ *
1796
+ * @deprecated Use `agent.harness("pi").cycleThinkingLevel()`. Moves off `Alineo` because only Pi has it.
1797
+ */
1039
1798
  cycleThinkingLevel(): Promise<{
1040
1799
  level: ThinkingLevel;
1041
1800
  } | null>;
@@ -1066,7 +1825,7 @@ export declare class Alineo {
1066
1825
  /**
1067
1826
  * Best-effort read-vs-write triage of a shell command. `true` = every sub-command is a
1068
1827
  * recognised pure reader with no output redirection; `false` = something needs a human.
1069
- * Mirrored verbatim in `adapters/pi-permission-gate.js`.
1828
+ * Mirrored verbatim in `bridge/pi-permission-gate.ts`.
1070
1829
  */
1071
1830
  export declare function isReadOnlyBashCommand(command: string): boolean;
1072
1831
  //#endregion
@@ -1074,6 +1833,12 @@ export declare function isReadOnlyBashCommand(command: string): boolean;
1074
1833
  interface AgentSnapshotRecord {
1075
1834
  specName: string;
1076
1835
  setupHash: string;
1836
+ /**
1837
+ * The sandbox provider that owns `snapshotId`. A snapshot id is meaningless to any other
1838
+ * provider, so it is part of the cache key. Absent on records written before this field
1839
+ * existed, which all came from OpenSandbox.
1840
+ */
1841
+ provider?: string;
1077
1842
  /** OpenSandbox snapshot ID returned by `sb.checkpoint()`. Pass to `client.restoreSnapshot()`. */
1078
1843
  snapshotId: string;
1079
1844
  createdAt: number;
@@ -1098,8 +1863,21 @@ export declare class AgentSnapshotStore {
1098
1863
  constructor(path: string);
1099
1864
  private _read;
1100
1865
  private _write;
1866
+ /**
1867
+ * OpenSandbox keeps the key it always had, so every existing file keeps working. Another
1868
+ * provider's records get its id as a prefix, so two providers sharing one file never read
1869
+ * or replace each other's snapshot ids.
1870
+ */
1101
1871
  private _key;
1102
- get(specName: string, setupHash: string): Promise<AgentSnapshotRecord | null>;
1872
+ get(specName: string, setupHash: string, provider?: string): Promise<AgentSnapshotRecord | null>;
1873
+ /**
1874
+ * Writes are read-modify-write on one file. Two at once (several specs finishing their setup
1875
+ * together, as when alineod restores a whole swarm onto a new machine) would each read the old
1876
+ * file and the second write would drop the first record. This chain runs them one at a time.
1877
+ * It guards one process: a second process on the same file is not supported.
1878
+ */
1879
+ private writing;
1880
+ private serialized;
1103
1881
  save(record: AgentSnapshotRecord): Promise<void>;
1104
1882
  /** Remove all snapshot records for the given spec name. */
1105
1883
  delete(specName: string): Promise<void>;
@@ -1186,19 +1964,44 @@ export declare const CHECKPOINT_ROOT = "root";
1186
1964
  * exclusion list applies), and is cheap to revisit if real retention pressure ever shows up.
1187
1965
  */
1188
1966
  export declare const DEFAULT_CHECKPOINT_RETENTION = 3;
1967
+ /**
1968
+ * durability-roadmap M4, 4.1: an off-box blob is deleted only when it is both beyond the retention
1969
+ * count AND at least this old. The ledger can be restored from a replica that trails the live one
1970
+ * by a few seconds, so after a disk loss it may name a checkpoint that is no longer the newest. The
1971
+ * margin keeps that older blob alive long enough to be found. The restore also falls back from a
1972
+ * missing blob to the next older checkpoint, so this is a second line of defence.
1973
+ */
1974
+ export declare const DEFAULT_REMOTE_PRUNE_MIN_AGE_MS: number;
1189
1975
  interface CheckpointRecord {
1190
1976
  /** Monotonic within this `Alineo` instance's lifetime — an ordinal for humans reading
1191
1977
  * `alineo logs`, not the mechanism restore uses to find the latest one (that's ledger
1192
1978
  * append order, via `AgentCheckpointed` events). Resets to 0 across a resume/reattach — a
1193
1979
  * fresh process starting its own count at 0 again causes no restore-correctness issue. */
1194
1980
  turn: number;
1195
- /** A path on the host filesystem today (single-node M3 scope). M4 moves this off-box. */
1981
+ /** A path on the host filesystem. Always set: the local copy is kept (M4 decision D5). */
1196
1982
  snapshotRef: string;
1983
+ /**
1984
+ * Where the same tarball lives off the box (M4, 4.1), when a `BlobStore` was given and the
1985
+ * upload worked. `undefined` means this checkpoint exists on the host disk only.
1986
+ */
1987
+ remoteRef?: string;
1988
+ /** Why the upload failed, when a `BlobStore` was given and it did. */
1989
+ uploadError?: string;
1197
1990
  createdAt: number;
1198
1991
  }
1199
1992
  /** Derive the checkpoints directory from the ledger adapter's own path, same convention as
1200
1993
  * `./snapshots.ts`'s `snapshotsPath()`. */
1201
1994
  export declare function checkpointsPath(adapterPath: string): string;
1995
+ /**
1996
+ * Delete this sandbox's old off-box checkpoints: all but the newest `retain`, and only those older
1997
+ * than `minAgeMs`. Best-effort like the local prune: a failure is returned to the caller to log and
1998
+ * never thrown, because the checkpoint it follows already succeeded.
1999
+ */
2000
+ export declare function pruneRemoteCheckpoints(store: BlobStore, sandboxId: string, opts: {
2001
+ retain: number;
2002
+ minAgeMs: number;
2003
+ now?: number;
2004
+ }): Promise<string[]>;
1202
2005
  /**
1203
2006
  * Tar `CHECKPOINT_ROOT` (minus the default excludes) inside the sandbox, pull the bytes out
1204
2007
  * byte-safe (`sb.readFileBytes()`, never `readFile()`'s UTF-8 path — a gzip tarball is not
@@ -1219,6 +2022,14 @@ export declare function takeCheckpoint(sb: SandboxHandle, checkpointsDir: string
1219
2022
  turn: number;
1220
2023
  excludeGlobs?: string[];
1221
2024
  retain?: number;
2025
+ /**
2026
+ * Also send the tarball to this store (M4, 4.1). The host copy is still written and still
2027
+ * pruned. A failed upload does not fail the checkpoint: it is recorded as `uploadError` and the
2028
+ * checkpoint stays local-only, which is what M3 did.
2029
+ */
2030
+ blobStore?: BlobStore;
2031
+ /** Override `DEFAULT_REMOTE_PRUNE_MIN_AGE_MS`. */
2032
+ remoteMinAgeMs?: number;
1222
2033
  }): Promise<CheckpointRecord>;
1223
2034
  //#endregion
1224
2035
  //#region src/sandbox-gone.d.ts
@@ -1230,6 +2041,10 @@ export declare function takeCheckpoint(sb: SandboxHandle, checkpointsDir: string
1230
2041
  * (M3, 3.4 — same question, same answer), which previously had its own private copy covering
1231
2042
  * only the first case below.
1232
2043
  *
2044
+ * The stable signal is an alineo error code: `SANDBOX_NOT_FOUND`, or `SANDBOX_NOT_RUNNING` with
2045
+ * `details.state` of `Terminated` or `Failed`. The message and `.code` string checks below are a
2046
+ * fallback for errors that carry no alineo code, and may go once every thrower sets one.
2047
+ *
1233
2048
  * Two distinct ways a sandbox can be "gone," both confirmed against OpenSandbox's actual
1234
2049
  * behavior (DeepWiki, not just its higher-level docs — same discipline M1.4/M2's research used):
1235
2050
  *
@@ -1253,20 +2068,61 @@ export declare function isSandboxGone(err: unknown): boolean;
1253
2068
  * not, since the ledger is exactly what's supposed to survive it) and extracts the tarball
1254
2069
  * into a *different*, already-running container — the one a fresh snapshot restore just
1255
2070
  * provisioned, per `resumeAgent()`'s fallback in `./agent/factory.ts`.
2071
+ *
2072
+ * M4, 4.1: a checkpoint may also carry a `remoteRef` into object storage. On the same host the
2073
+ * local file is read first. After a disk loss the local file is gone and the blob is fetched.
1256
2074
  */
1257
2075
  interface LatestCheckpoint {
1258
2076
  turn: number;
2077
+ /** A path on the host that took the checkpoint. */
1259
2078
  snapshotRef: string;
2079
+ /** The same tarball in object storage, when the upload worked (M4, 4.1). */
2080
+ remoteRef?: string;
1260
2081
  }
2082
+ /**
2083
+ * Every checkpoint recorded for this sandbox, newest first. Restore tries them in this order, so
2084
+ * one lost or unreadable tarball costs a turn of history and not the whole conversation.
2085
+ */
2086
+ export declare function findCheckpoints(adapter: IStorageAdapter, name: string, sandboxId: string): Promise<LatestCheckpoint[]>;
1261
2087
  /** `undefined` if this sandbox was never checkpointed — not an error; the caller falls back
1262
2088
  * to whatever state a bare snapshot restore already produced. */
1263
2089
  export declare function findLatestCheckpoint(adapter: IStorageAdapter, name: string, sandboxId: string): Promise<LatestCheckpoint | undefined>;
2090
+ interface RestoreOptions {
2091
+ /** Where a `remoteRef` is fetched from. Without it, only the local file can be used. */
2092
+ blobStore?: BlobStore;
2093
+ }
2094
+ /**
2095
+ * The bytes of one checkpoint. Local file first, because it needs no network. If that is gone (a
2096
+ * new host, a wiped disk) and the checkpoint has a `remoteRef` the store recognises, download it.
2097
+ *
2098
+ * @throws if neither source has it. The message names both attempts.
2099
+ */
2100
+ export declare function fetchCheckpoint(checkpoint: LatestCheckpoint, opts?: RestoreOptions): Promise<Uint8Array>;
2101
+ /**
2102
+ * The newest checkpoint whose tarball can be read, with its bytes, or `undefined` when none can.
2103
+ * `skipped` lists what was passed over and why, for the caller to log.
2104
+ */
2105
+ export declare function pickRestorable(candidates: LatestCheckpoint[], opts?: RestoreOptions): Promise<{
2106
+ checkpoint: LatestCheckpoint;
2107
+ bytes: Uint8Array;
2108
+ skipped: Array<{
2109
+ turn: number;
2110
+ reason: string;
2111
+ }>;
2112
+ } | null>;
2113
+ /**
2114
+ * Extract checkpoint bytes into `sb`, overwriting whatever a fresh container's own setup left in
2115
+ * place at the same paths. Byte-safe on both ends (`writeFileBytes`/raw `tar xzf`) — the same
2116
+ * corruption risk `takeCheckpoint()`'s doc comment already covers on the capture side applies
2117
+ * symmetrically here on restore.
2118
+ */
2119
+ export declare function extractCheckpoint(sb: SandboxHandle, bytes: Uint8Array): Promise<void>;
1264
2120
  /**
1265
- * Extract a checkpoint tarball (from the host path `takeCheckpoint()` stored it at) into `sb`,
1266
- * overwriting whatever a fresh container's own setup left in place at the same paths. Byte-safe
1267
- * on both ends (`writeFileBytes`/raw `tar xzf`) — the same corruption risk `takeCheckpoint()`'s
1268
- * doc comment already covers on the capture side applies symmetrically here on restore.
2121
+ * Extract a checkpoint tarball into `sb`. `snapshotRef` is the host path `takeCheckpoint()` stored
2122
+ * it at. Pass `remoteRef` and `blobStore` to fall back to object storage when that file is gone.
1269
2123
  */
1270
- export declare function restoreCheckpoint(sb: SandboxHandle, snapshotRef: string): Promise<void>;
2124
+ export declare function restoreCheckpoint(sb: SandboxHandle, snapshotRef: string, opts?: RestoreOptions & {
2125
+ remoteRef?: string;
2126
+ }): Promise<void>;
1271
2127
  //#endregion
1272
- export type { AgentEvent, AgentSnapshotRecord, AgentSpec, AgentStream, CheckpointRecord, CompactResult, EgressApprovalGateOptions, EgressDecision, EgressRequest, EgressRequestHandler, HeldCredential, LatestCheckpoint, PendingPermission, PermissionAction, PermissionDecision, PermissionHandler, PermissionMode, PermissionPolicy, PermissionRequest, PermissionRule, PiMessage, PiModel, PiSessionState, PiSlashCommand, PromptStream, SessionStats, SetupStep, ThinkingLevel };
2128
+ export { type AgentEvent, type AgentRestore, type AgentSnapshotRecord, type AgentSpec, type AgentSpecInput, type AgentStream, type BlobInfo, type BlobStore, type CheckpointRecord, type CompactResult, DEFAULT_PROVIDER_ID, type EgressApprovalGateOptions, type EgressDecision, type EgressRequest, type EgressRequestHandler, type FakeScenario, type HarnessAdapter, type HarnessCapabilities, type HarnessCapability, type HarnessEvent, type HarnessEventBody, type HarnessId, type HarnessRef, type HarnessRegistry, type HarnessSandbox, type HeldCredential, type LatestCheckpoint, type ModelRef, type PendingPermission, type PermissionAction, type PermissionDecision, type PermissionHandler, type PermissionMode, type PermissionPolicy, type PermissionRequest, type PermissionRule, type PiMessage, type PiModel, type PiSessionState, type PiSlashCommand, type PromptStream, type RestoreOptions, type S3BlobStoreOptions, type S3ClientLike, type SessionStats, type SetupStep, type ThinkingLevel, type TurnInput };