alineo 0.4.0 → 0.5.1

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,7 +1,7 @@
1
- import { CredentialBinding, CredentialSource, IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
1
+ import { CredentialBinding, CredentialSource, ExecOptions, ExecResult, IStorageAdapter, SandboxHandle, WorkflowError } from "@alineo-labs/core";
2
2
  import { z } from "zod";
3
3
  import { Memory, ResourceRef } from "@alineo-labs/memory";
4
-
4
+ //#endregion
5
5
  //#region src/permissions.d.ts
6
6
  /**
7
7
  * Human-in-the-loop tool-call policy — the host-side half.
@@ -76,7 +76,7 @@ interface PermissionPolicy {
76
76
  * recognised pure reader with no output redirection; `false` = something needs a human.
77
77
  * Mirrored verbatim in `adapters/pi-permission-gate.js`.
78
78
  */
79
- declare function isReadOnlyBashCommand(command: string): boolean;
79
+ export declare function isReadOnlyBashCommand(command: string): boolean;
80
80
  //#endregion
81
81
  //#region src/schema.d.ts
82
82
  /**
@@ -271,7 +271,7 @@ interface AgentSpec {
271
271
  * Throws `AgentSpecValidationError` (with a pre-formatted `.message` and a structured
272
272
  * `.issues` array) rather than a bare `Error` — see #185.
273
273
  */
274
- declare function validateAgentSpec(data: unknown): AgentSpec;
274
+ export declare function validateAgentSpec(data: unknown): AgentSpec;
275
275
  //#endregion
276
276
  //#region src/types.d.ts
277
277
  /**
@@ -330,10 +330,14 @@ type AgentEvent = {
330
330
  isDialog: boolean;
331
331
  requestId?: string;
332
332
  } | {
333
- type: "permission_request"; /** Pass to `agent.resolvePermission()`. */
334
- requestId: string; /** The tool Pi is about to run, e.g. `"bash"`. */
335
- tool: string; /** Tool-specific target: the command for `bash`, the path for file tools. */
336
- target: string; /** Human-readable one-line summary for a prompt. */
333
+ type: "permission_request";
334
+ /** Pass to `agent.resolvePermission()`. */
335
+ requestId: string;
336
+ /** The tool Pi is about to run, e.g. `"bash"`. */
337
+ tool: string;
338
+ /** Tool-specific target: the command for `bash`, the path for file tools. */
339
+ target: string;
340
+ /** Human-readable one-line summary for a prompt. */
337
341
  title: string;
338
342
  } | {
339
343
  type: "permission_resolved";
@@ -454,7 +458,7 @@ interface PendingPermission {
454
458
  */
455
459
  type AgentStream = AsyncIterable<AgentEvent>;
456
460
  /** Filter an `AgentStream` down to just text chunks. */
457
- declare function textOnly(stream: AgentStream): AsyncIterable<string>;
461
+ export declare function textOnly(stream: AgentStream): AsyncIterable<string>;
458
462
  /**
459
463
  * @deprecated Use `AgentStream`. `PromptStream` will be removed in a future minor.
460
464
  */
@@ -529,6 +533,13 @@ interface PiSessionState {
529
533
  }
530
534
  //#endregion
531
535
  //#region src/adapters/pi.d.ts
536
+ /** The subset of `SandboxHandle` that `PiAdapter` calls. `exec` only needs to be awaitable, so
537
+ * callers (and tests) don't have to supply a full `ExecHandle`. */
538
+ interface PiSandbox {
539
+ exec(cmd: string, opts?: ExecOptions): PromiseLike<ExecResult>;
540
+ proxy: SandboxHandle["proxy"];
541
+ writeFile: SandboxHandle["writeFile"];
542
+ }
532
543
  declare class PiAdapter {
533
544
  private _bridgeUrl;
534
545
  /**
@@ -565,12 +576,12 @@ declare class PiAdapter {
565
576
  */
566
577
  disposeConnections(): void;
567
578
  /** Install Pi CLI and any spec packages. Slow — result is captured by checkpoint(). */
568
- install(sb: SandboxHandle, spec: AgentSpec): Promise<void>;
579
+ install(sb: PiSandbox, spec: AgentSpec): Promise<void>;
569
580
  /**
570
581
  * Write config files and the bridge script. Always runs on every start (fresh install
571
582
  * and snapshot resume alike) so env values, model/provider, and bridge code stay current.
572
583
  */
573
- configure(sb: SandboxHandle, spec: AgentSpec, resolvedEnv: Record<string, string>, opts?: {
584
+ configure(sb: PiSandbox, spec: AgentSpec, resolvedEnv: Record<string, string>, opts?: {
574
585
  resume?: boolean;
575
586
  }): Promise<void>;
576
587
  /**
@@ -584,7 +595,18 @@ declare class PiAdapter {
584
595
  * be part of the exact command that spawns the bridge process so the bridge (and
585
596
  * everything it in turn spawns, including Pi itself) inherits the already-clean env.
586
597
  */
587
- startBridge(sb: SandboxHandle, unsetVars?: string[]): Promise<void>;
598
+ startBridge(sb: PiSandbox, unsetVars?: string[]): Promise<void>;
599
+ /**
600
+ * Rebind to a bridge that's already running (as opposed to `startBridge()`, which execs a
601
+ * fresh `node /alineo-bridge.js`). `sb.proxy(port)` is a pure URL lookup against the
602
+ * sandbox's control plane — it starts nothing — so this has zero effect on the sandbox
603
+ * itself: no killed process, no dropped in-flight turn, no reset Pi conversation state.
604
+ *
605
+ * Call `waitReady()` afterwards to confirm the bridge is actually still there before relying
606
+ * on it — the container can be alive while the bridge process inside it isn't (e.g. it
607
+ * crashed independently), and this method alone can't tell the difference.
608
+ */
609
+ reattachBridge(sb: SandboxHandle): Promise<void>;
588
610
  waitReady(timeoutMs?: number): Promise<void>;
589
611
  prompt(message: string, opts?: {
590
612
  streamingBehavior?: "steer" | "followUp";
@@ -657,11 +679,11 @@ interface AgentSnapshotRecord {
657
679
  * setup: cli, cliVersion, packages, and setup. Excludes env (hot-reloadable),
658
680
  * model/provider (CLI flags only), and cosmetic fields.
659
681
  */
660
- declare function computeSetupHash(spec: AgentSpec): string;
682
+ export declare function computeSetupHash(spec: AgentSpec): string;
661
683
  /** Derive the agent-snapshots.json path from the ledger adapter path. */
662
- declare function snapshotsPath(adapterPath: string): string;
684
+ export declare function snapshotsPath(adapterPath: string): string;
663
685
  /** File-backed store for agent snapshot records, keyed by specName + setupHash. */
664
- declare class AgentSnapshotStore {
686
+ export declare class AgentSnapshotStore {
665
687
  private readonly path;
666
688
  constructor(path: string);
667
689
  private _read;
@@ -675,6 +697,8 @@ declare class AgentSnapshotStore {
675
697
  }
676
698
  //#endregion
677
699
  //#region src/agent/egress-approval.d.ts
700
+ /** The subset of `SandboxHandle` the gate calls. */
701
+ type EgressApprovalSandbox = Pick<SandboxHandle, "egress" | "credentials" | "emit">;
678
702
  /**
679
703
  * Human-in-the-loop gate for a sandboxed agent's outbound network access.
680
704
  *
@@ -726,7 +750,7 @@ interface EgressApprovalGateOptions {
726
750
  */
727
751
  webhookHost?: string;
728
752
  }
729
- declare class EgressApprovalGate {
753
+ export declare class EgressApprovalGate {
730
754
  private server;
731
755
  private port;
732
756
  private sandbox;
@@ -744,7 +768,7 @@ declare class EgressApprovalGate {
744
768
  private readonly onceApproved;
745
769
  constructor(opts: EgressApprovalGateOptions);
746
770
  /** Attach the sandbox whose egress this gate manages. Called once its handle exists. */
747
- bind(sandbox: SandboxHandle): void;
771
+ bind(sandbox: EgressApprovalSandbox): void;
748
772
  private sb;
749
773
  /** Start the listener. Idempotent. */
750
774
  start(): Promise<void>;
@@ -762,13 +786,85 @@ declare class EgressApprovalGate {
762
786
  private onDenied;
763
787
  }
764
788
  //#endregion
765
- //#region src/agent/session-control.d.ts
789
+ //#region src/agent/internal.d.ts
790
+ /**
791
+ * Narrow surface that `session-control.ts`/`model.ts`/`introspection.ts`/
792
+ * `lifecycle.ts` need from `Alineo` — deliberately not exported from the
793
+ * package barrel, so it never becomes public API even though it's a real
794
+ * exported interface within the package.
795
+ */
796
+ interface AgentInternal {
797
+ readonly adapter: PiAdapter;
798
+ readonly sandbox: SandboxHandle;
799
+ env: Record<string, string>;
800
+ /** Present when the spec has `approval: "hold"` credential bindings. */
801
+ readonly egressGate?: EgressApprovalGate;
802
+ }
803
+ declare namespace session_control_d_exports {
804
+ export { PermissionHandler, abort, abortBash, abortRetry, bash, followUp, listPendingPermissions, newSession, prompt, resolvePermission, setAutoCompaction, setAutoRetry, setFollowUpMode, setSessionName, setSteeringMode, steer };
805
+ }
766
806
  /**
767
807
  * Called for each `permission_request` on a `prompt()`/`bash()` stream when passed as
768
808
  * `opts.onPermission`. Return the decision; the SDK resolves the request for you. The
769
809
  * `permission_request` / `permission_resolved` events still flow through the stream.
770
810
  */
771
811
  type PermissionHandler = (req: PermissionRequest) => PermissionDecision | Promise<PermissionDecision>;
812
+ /** Send a prompt to Pi and stream the response. Pi manages its own session context. */
813
+ declare function prompt(a: AgentInternal, message: string, opts?: {
814
+ streamingBehavior?: "steer" | "followUp";
815
+ inactivityTimeoutMs?: number;
816
+ /** Auto-resolve each `permission_request` with this handler's decision. */
817
+ onPermission?: PermissionHandler;
818
+ }): AgentStream;
819
+ /**
820
+ * Run a shell command inside Pi's working context. Not incrementally
821
+ * streamed — Pi returns bash output synchronously, so the full output
822
+ * arrives as a single `text` event once the command completes.
823
+ */
824
+ declare function bash(a: AgentInternal, command: string): AgentStream;
825
+ /** Snapshot of tool calls currently paused awaiting a human decision. */
826
+ declare function listPendingPermissions(a: AgentInternal): Promise<PendingPermission[]>;
827
+ /** Steer Pi's current response mid-flight. Waits for Pi's RPC acknowledgment. */
828
+ declare function steer(a: AgentInternal, message: string): Promise<void>;
829
+ /** Abort Pi's current operation. */
830
+ declare function abort(a: AgentInternal): Promise<void>;
831
+ /**
832
+ * Resolve a pending `permission_request` emitted by the permission gate. `decision` is
833
+ * `{ kind: "once" }`, `{ kind: "always" }`, or `{ kind: "reject", feedback? }`.
834
+ */
835
+ declare function resolvePermission(a: AgentInternal, requestId: string, decision: PermissionDecision): Promise<void>;
836
+ /** Queue a message to be sent to Pi after it finishes its current task. */
837
+ declare function followUp(a: AgentInternal, message: string): Promise<void>;
838
+ /** Start a fresh Pi session, clearing all prior context. */
839
+ declare function newSession(a: AgentInternal): Promise<void>;
840
+ /** Enable or disable Pi's automatic context compaction. */
841
+ declare function setAutoCompaction(a: AgentInternal, enabled: boolean): Promise<void>;
842
+ /**
843
+ * Enable or disable Pi's automatic retry on transient errors (429, 500, 502, 503, 504).
844
+ * Auto-retry is ON by default: 3 attempts with exponential backoff (2 s / 4 s / 8 s).
845
+ * Disable it when you want to handle errors yourself via `auto_retry_start`/`auto_retry_end`
846
+ * events in the stream.
847
+ */
848
+ declare function setAutoRetry(a: AgentInternal, enabled: boolean): Promise<void>;
849
+ /**
850
+ * Abort an in-progress auto-retry immediately. Pi stops waiting and fails the current
851
+ * operation, emitting `auto_retry_end` with `success: false`.
852
+ */
853
+ declare function abortRetry(a: AgentInternal): Promise<void>;
854
+ /** Abort a currently-executing bash command without cancelling the whole prompt. */
855
+ declare function abortBash(a: AgentInternal): Promise<void>;
856
+ /**
857
+ * Control how Pi processes queued steering messages.
858
+ * `"all"` applies all queued steers at once; `"one-at-a-time"` applies them sequentially.
859
+ */
860
+ declare function setSteeringMode(a: AgentInternal, mode: "all" | "one-at-a-time"): Promise<void>;
861
+ /**
862
+ * Control how Pi processes queued follow-up messages.
863
+ * `"all"` sends all queued follow-ups at once; `"one-at-a-time"` sends them sequentially.
864
+ */
865
+ declare function setFollowUpMode(a: AgentInternal, mode: "all" | "one-at-a-time"): Promise<void>;
866
+ /** Set a display name for the current Pi session. */
867
+ declare function setSessionName(a: AgentInternal, name: string): Promise<void>;
772
868
  //#endregion
773
869
  //#region src/agent/agent.d.ts
774
870
  /**
@@ -797,7 +893,7 @@ type PermissionHandler = (req: PermissionRequest) => PermissionDecision | Promis
797
893
  * }
798
894
  * ```
799
895
  */
800
- declare class Alineo {
896
+ export declare class Alineo {
801
897
  /** OpenSandbox container ID for this agent's sandbox. */
802
898
  readonly sandboxId: string;
803
899
  readonly name: string;
@@ -893,7 +989,8 @@ declare class Alineo {
893
989
  rebuild?: boolean;
894
990
  spawnDepth?: number;
895
991
  maxAgents?: number;
896
- runId?: string; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
992
+ runId?: string;
993
+ /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
897
994
  memory?: Memory;
898
995
  /**
899
996
  * Required when the spec has `approval: "hold"` credential bindings — decides each
@@ -910,6 +1007,12 @@ declare class Alineo {
910
1007
  * are already present — only the bridge process needs to be restarted.
911
1008
  * Pi is started with `--continue` so it resumes the most recent session.
912
1009
  *
1010
+ * **Kills and restarts the bridge process** — anything mid-flight when the previous host
1011
+ * process exited (a streaming turn, a tool call parked on a human decision) is dropped.
1012
+ * If the bridge might still be alive and you'd rather preserve that, try `Alineo.reattach()`
1013
+ * first and fall back to this only if it fails (e.g. the whole sandbox — not just this
1014
+ * process — actually restarted).
1015
+ *
913
1016
  * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
914
1017
  * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
915
1018
  * `load()`. Takes precedence over `opts.specPath` if both are set.
@@ -939,9 +1042,54 @@ declare class Alineo {
939
1042
  adapter: IStorageAdapter;
940
1043
  spec?: AgentSpec | Record<string, unknown>;
941
1044
  specPath?: string;
942
- runId?: string; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
1045
+ runId?: string;
1046
+ /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
943
1047
  memory?: Memory;
944
1048
  }): Promise<Alineo>;
1049
+ /**
1050
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge — the crash-only
1051
+ * counterpart to `resume()`. Use this when the caller's own process exited or restarted
1052
+ * (e.g. a control-plane daemon coming back up) but has good reason to believe the sandbox,
1053
+ * and the bridge process inside it, never stopped: nothing here kills or re-execs anything.
1054
+ * `sb.proxy()` is a pure URL lookup, so the only network activity is re-deriving the proxy
1055
+ * URL and one health-check request.
1056
+ *
1057
+ * The returned `Alineo` is fully functional — `.prompt()`/`.bash()` work exactly as they
1058
+ * would have on the original handle, continuing the same Pi conversation, because it's
1059
+ * still the same process.
1060
+ *
1061
+ * **Fails fast (5s) if the bridge doesn't answer** — the container can be `Running` while
1062
+ * the bridge process inside it has independently died, and this can't distinguish that from
1063
+ * a slow-to-respond-but-fine bridge on its own. On failure, fall back to `Alineo.resume()`.
1064
+ *
1065
+ * @param sandboxId The sandbox ID returned by the original `Alineo.load()`/`.spawn()`.
1066
+ * @param opts.spec / opts.specPath Same three-way fallback as `resume()` — see its docs.
1067
+ *
1068
+ * @example
1069
+ * ```ts
1070
+ * let agent: Alineo;
1071
+ * try {
1072
+ * agent = await Alineo.reattach(savedSandboxId, { adapter });
1073
+ * } catch {
1074
+ * agent = await Alineo.resume(savedSandboxId, { adapter }); // bridge really is gone
1075
+ * }
1076
+ * ```
1077
+ */
1078
+ static reattach(sandboxId: string, opts: {
1079
+ adapter: IStorageAdapter;
1080
+ spec?: AgentSpec | Record<string, unknown>;
1081
+ specPath?: string;
1082
+ runId?: string;
1083
+ /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
1084
+ memory?: Memory;
1085
+ /**
1086
+ * Don't probe the bridge before returning, and accept a Paused sandbox. For a paused
1087
+ * sandbox, whose frozen bridge can't answer until `agent.sandbox.resume()` — check it
1088
+ * yourself after resuming (`agent.adapter.waitReady()`), and fall back to
1089
+ * `Alineo.resume()` if it's gone.
1090
+ */
1091
+ skipReadyCheck?: boolean;
1092
+ }): Promise<Alineo>;
945
1093
  /**
946
1094
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
947
1095
  * `resume()`, which kills and restarts the bridge process. Use this when you only
@@ -979,7 +1127,8 @@ declare class Alineo {
979
1127
  cpu: string;
980
1128
  memory: string;
981
1129
  gpu?: string;
982
- }; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
1130
+ };
1131
+ /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
983
1132
  memory?: Memory;
984
1133
  }): Promise<Alineo>;
985
1134
  /**
@@ -1178,7 +1327,7 @@ declare class Alineo {
1178
1327
  * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo fork --prompt` --
1179
1328
  * forever, with no error and no partial output.
1180
1329
  */
1181
- declare class PromptTimeoutError extends WorkflowError {
1330
+ export declare class PromptTimeoutError extends WorkflowError {
1182
1331
  readonly timeoutMs: number;
1183
1332
  readonly bridgeUrl: string;
1184
1333
  constructor(timeoutMs: number, bridgeUrl: string);
@@ -1190,9 +1339,9 @@ declare class PromptTimeoutError extends WorkflowError {
1190
1339
  * multi-line summary (via `z.prettifyError()`) suitable for printing as-is; `.issues` is for
1191
1340
  * callers that want to handle failures programmatically (e.g. highlight specific fields in a UI).
1192
1341
  */
1193
- declare class AgentSpecValidationError extends WorkflowError {
1342
+ export declare class AgentSpecValidationError extends WorkflowError {
1194
1343
  readonly issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[];
1195
1344
  constructor(message: string, issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[]);
1196
1345
  }
1197
1346
  //#endregion
1198
- export { type AgentEvent, type AgentSnapshotRecord, AgentSnapshotStore, type AgentSpec, AgentSpecValidationError, type AgentStream, Alineo, type CompactResult, EgressApprovalGate, type EgressApprovalGateOptions, type EgressDecision, type EgressRequest, type EgressRequestHandler, type HeldCredential, 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, PromptTimeoutError, type SessionStats, type SetupStep, type ThinkingLevel, computeSetupHash, isReadOnlyBashCommand, snapshotsPath, textOnly, validateAgentSpec };
1347
+ export type { AgentEvent, AgentSnapshotRecord, AgentSpec, AgentStream, CompactResult, EgressApprovalGateOptions, EgressDecision, EgressRequest, EgressRequestHandler, HeldCredential, PendingPermission, PermissionAction, PermissionDecision, PermissionHandler, PermissionMode, PermissionPolicy, PermissionRequest, PermissionRule, PiMessage, PiModel, PiSessionState, PiSlashCommand, PromptStream, SessionStats, SetupStep, ThinkingLevel };
package/dist/index.mjs CHANGED
@@ -509,6 +509,20 @@ var PiAdapter = class {
509
509
  const { url } = await sb.proxy(3001);
510
510
  this._bridgeUrl = url;
511
511
  }
512
+ /**
513
+ * Rebind to a bridge that's already running (as opposed to `startBridge()`, which execs a
514
+ * fresh `node /alineo-bridge.js`). `sb.proxy(port)` is a pure URL lookup against the
515
+ * sandbox's control plane — it starts nothing — so this has zero effect on the sandbox
516
+ * itself: no killed process, no dropped in-flight turn, no reset Pi conversation state.
517
+ *
518
+ * Call `waitReady()` afterwards to confirm the bridge is actually still there before relying
519
+ * on it — the container can be alive while the bridge process inside it isn't (e.g. it
520
+ * crashed independently), and this method alone can't tell the difference.
521
+ */
522
+ async reattachBridge(sb) {
523
+ const { url } = await sb.proxy(3001);
524
+ this._bridgeUrl = url;
525
+ }
512
526
  async waitReady(timeoutMs = 3e4) {
513
527
  const deadline = Date.now() + timeoutMs;
514
528
  while (Date.now() < deadline) {
@@ -1099,41 +1113,61 @@ async function loadAgent(specInput, opts) {
1099
1113
  teamId: spec.teamId
1100
1114
  });
1101
1115
  console.log(`[agent] sandbox ready ${elapsed(t1)} (${sb.sandboxId})`);
1102
- console.log(`[agent] installing Pi CLI...`);
1103
- const t2 = Date.now();
1104
- await adapter.install(sb, spec);
1105
- console.log(`[agent] Pi CLI ready ${elapsed(t2)}`);
1106
- for (const step of spec.setup ?? []) {
1107
- console.log(`[agent] setup: ${step.name}...`);
1108
- const ts = Date.now();
1109
- const cmd = step.cwd ? `cd ${step.cwd} && ${step.run}` : step.run;
1110
- await sb.exec(cmd);
1111
- console.log(`[agent] setup done ${elapsed(ts)} (${step.name})`);
1116
+ const created = sb;
1117
+ try {
1118
+ console.log(`[agent] installing Pi CLI...`);
1119
+ const t2 = Date.now();
1120
+ await adapter.install(created, spec);
1121
+ console.log(`[agent] Pi CLI ready ${elapsed(t2)}`);
1122
+ for (const step of spec.setup ?? []) {
1123
+ console.log(`[agent] setup: ${step.name}...`);
1124
+ const ts = Date.now();
1125
+ const cmd = step.cwd ? `cd ${step.cwd} && ${step.run}` : step.run;
1126
+ await created.exec(cmd);
1127
+ console.log(`[agent] setup done ${elapsed(ts)} (${step.name})`);
1128
+ }
1129
+ console.log(`[agent] checkpointing...`);
1130
+ const t3 = Date.now();
1131
+ const snapshotId = await created.checkpoint();
1132
+ await store.save({
1133
+ specName: spec.name,
1134
+ setupHash,
1135
+ snapshotId,
1136
+ createdAt: Date.now()
1137
+ });
1138
+ console.log(`[agent] checkpoint done ${elapsed(t3)}`);
1139
+ } catch (err) {
1140
+ await created.close().catch(() => {});
1141
+ await egressGate?.stop().catch(() => {});
1142
+ throw err;
1112
1143
  }
1113
- console.log(`[agent] checkpointing...`);
1114
- const t3 = Date.now();
1115
- const snapshotId = await sb.checkpoint();
1116
- await store.save({
1117
- specName: spec.name,
1118
- setupHash,
1119
- snapshotId,
1120
- createdAt: Date.now()
1121
- });
1122
- console.log(`[agent] checkpoint done ${elapsed(t3)}`);
1123
1144
  }
1124
1145
  if (!sb) throw new Error("internal error: sandbox was neither restored nor created");
1125
1146
  egressGate?.bind(sb);
1126
- for (const cb of credentialBindings) {
1127
- if (cb.approval === "hold") continue;
1128
- await sb.credentials.set(cb.name, cb.value, cb.binding, cb.source);
1147
+ try {
1148
+ for (const cb of credentialBindings) {
1149
+ if (cb.approval === "hold") continue;
1150
+ await sb.credentials.set(cb.name, cb.value, cb.binding, cb.source);
1151
+ }
1152
+ resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
1153
+ await adapter.configure(sb, spec, resolvedEnv);
1154
+ console.log(`[agent] starting bridge...`);
1155
+ const t4 = Date.now();
1156
+ await adapter.startBridge(sb);
1157
+ await adapter.waitReady();
1158
+ console.log(`[agent] bridge ready ${elapsed(t4)}`);
1159
+ } catch (err) {
1160
+ await sb.close().catch(() => {});
1161
+ await egressGate?.stop().catch(() => {});
1162
+ if (!fromSnapshot) throw err;
1163
+ const reason = err instanceof Error ? err.message : String(err);
1164
+ console.log(`[agent] restored snapshot didn't start (${reason}) — discarding it and rebuilding...`);
1165
+ await store.delete(spec.name);
1166
+ return loadAgent(specInput, {
1167
+ ...opts,
1168
+ rebuild: true
1169
+ });
1129
1170
  }
1130
- resolvedEnv.ALINEO_SANDBOX_ID = sb.sandboxId;
1131
- await adapter.configure(sb, spec, resolvedEnv);
1132
- console.log(`[agent] starting bridge...`);
1133
- const t4 = Date.now();
1134
- await adapter.startBridge(sb);
1135
- await adapter.waitReady();
1136
- console.log(`[agent] bridge ready ${elapsed(t4)}`);
1137
1171
  console.log(`[agent] total ${elapsed(t0)}${fromSnapshot ? " (from snapshot)" : ""}`);
1138
1172
  return {
1139
1173
  sandbox: sb,
@@ -1181,6 +1215,7 @@ async function resumeAgent(sandboxId, opts) {
1181
1215
  const t1 = Date.now();
1182
1216
  const sb = await client.connect(sandboxId, spec.name, {
1183
1217
  runId,
1218
+ resources: spec.resources ?? config.defaults.resources,
1184
1219
  resourceId: spec.resourceId ?? spec.name,
1185
1220
  teamId: spec.teamId
1186
1221
  });
@@ -1225,6 +1260,66 @@ async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
1225
1260
  } catch {}
1226
1261
  }
1227
1262
  /**
1263
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge. See
1264
+ * `Alineo.reattach()` for the public-facing docs. Structurally `resumeAgent()` minus its two
1265
+ * destructive steps (the `pkill` and the fresh `startBridge()`) — everything else (spec
1266
+ * resolution, env, `client.connect()`) is identical.
1267
+ */
1268
+ async function reattachAgent(sandboxId, opts) {
1269
+ const t0 = Date.now();
1270
+ const config = await readProjectConfig();
1271
+ const client = new Sandbox({
1272
+ baseUrl: config.serverUrl,
1273
+ apiKey: config.apiKey,
1274
+ adapter: opts.adapter,
1275
+ useServerProxy: config.useServerProxy
1276
+ });
1277
+ let spec;
1278
+ if (opts.spec) spec = validateAgentSpec(opts.spec);
1279
+ else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
1280
+ else {
1281
+ const session = (await client.sandboxes.list()).find((s) => s.sandboxId === sandboxId);
1282
+ if (!session) throw new Error(`No ledger record for sandbox ${sandboxId} — pass opts.spec or opts.specPath explicitly`);
1283
+ spec = validateAgentSpec(await Bun.file(`./agents/${session.name}.json`).json());
1284
+ }
1285
+ const resolvedEnv = resolveEnv(spec.env ?? {});
1286
+ if (spec.maxAgents !== void 0) {
1287
+ assertValidMaxAgents(spec.maxAgents, "Alineo.reattach()");
1288
+ resolvedEnv.ALINEO_MAX_AGENTS = String(spec.maxAgents);
1289
+ }
1290
+ if (spec.spawnDepth !== void 0) {
1291
+ assertValidSpawnDepth(spec.spawnDepth, "Alineo.reattach()");
1292
+ resolvedEnv.ALINEO_SPAWN_DEPTH = String(spec.spawnDepth);
1293
+ }
1294
+ const runId = opts.runId ?? crypto.randomUUID();
1295
+ resolvedEnv.ALINEO_RUN_ID = runId;
1296
+ resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
1297
+ console.log(`[agent] reattaching to ${sandboxId}...`);
1298
+ const t1 = Date.now();
1299
+ const sb = await client.connect(sandboxId, spec.name, {
1300
+ runId,
1301
+ resourceId: spec.resourceId ?? spec.name,
1302
+ teamId: spec.teamId,
1303
+ resources: spec.resources ?? config.defaults.resources,
1304
+ allowPaused: opts.skipReadyCheck === true
1305
+ });
1306
+ console.log(`[agent] connected ${elapsed(t1)}`);
1307
+ const adapter = new PiAdapter();
1308
+ await adapter.reattachBridge(sb);
1309
+ const t2 = Date.now();
1310
+ if (!opts.skipReadyCheck) await adapter.waitReady(5e3);
1311
+ console.log(`[agent] bridge reattached ${elapsed(t2)}${opts.skipReadyCheck ? " (not probed)" : ""}`);
1312
+ console.log(`[agent] total ${elapsed(t0)}`);
1313
+ return {
1314
+ sandbox: sb,
1315
+ spec,
1316
+ env: resolvedEnv,
1317
+ adapter,
1318
+ fromSnapshot: false,
1319
+ runId
1320
+ };
1321
+ }
1322
+ /**
1228
1323
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge. See
1229
1324
  * `Alineo.attach()` for the public-facing docs.
1230
1325
  */
@@ -1283,15 +1378,20 @@ async function spawnChild(self, childSpecPath, opts = {}) {
1283
1378
  teamId: childSpec.teamId
1284
1379
  });
1285
1380
  console.log(`[agent] fork ready ${elapsed(t0)} (${forkedSb.sandboxId})`);
1286
- for (const { name, value, binding, source } of childCredentialBindings) await forkedSb.credentials.set(name, value, binding, source);
1287
1381
  const adapter = new PiAdapter();
1288
- childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
1289
- await adapter.configure(forkedSb, childSpec, childEnv);
1290
- console.log(`[agent] starting bridge...`);
1291
- const t1 = Date.now();
1292
- await adapter.startBridge(forkedSb, Object.keys(self.env));
1293
- await adapter.waitReady();
1294
- console.log(`[agent] bridge ready ${elapsed(t1)}`);
1382
+ try {
1383
+ for (const { name, value, binding, source } of childCredentialBindings) await forkedSb.credentials.set(name, value, binding, source);
1384
+ childEnv.ALINEO_SANDBOX_ID = forkedSb.sandboxId;
1385
+ await adapter.configure(forkedSb, childSpec, childEnv);
1386
+ console.log(`[agent] starting bridge...`);
1387
+ const t1 = Date.now();
1388
+ await adapter.startBridge(forkedSb, Object.keys(self.env));
1389
+ await adapter.waitReady();
1390
+ console.log(`[agent] bridge ready ${elapsed(t1)}`);
1391
+ } catch (err) {
1392
+ await forkedSb.close().catch(() => {});
1393
+ throw err;
1394
+ }
1295
1395
  return {
1296
1396
  sandbox: forkedSb,
1297
1397
  spec: {
@@ -1701,6 +1801,12 @@ var Alineo = class Alineo {
1701
1801
  * are already present — only the bridge process needs to be restarted.
1702
1802
  * Pi is started with `--continue` so it resumes the most recent session.
1703
1803
  *
1804
+ * **Kills and restarts the bridge process** — anything mid-flight when the previous host
1805
+ * process exited (a streaming turn, a tool call parked on a human decision) is dropped.
1806
+ * If the bridge might still be alive and you'd rather preserve that, try `Alineo.reattach()`
1807
+ * first and fall back to this only if it fails (e.g. the whole sandbox — not just this
1808
+ * process — actually restarted).
1809
+ *
1704
1810
  * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
1705
1811
  * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
1706
1812
  * `load()`. Takes precedence over `opts.specPath` if both are set.
@@ -1733,6 +1839,41 @@ var Alineo = class Alineo {
1733
1839
  return agent;
1734
1840
  }
1735
1841
  /**
1842
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge — the crash-only
1843
+ * counterpart to `resume()`. Use this when the caller's own process exited or restarted
1844
+ * (e.g. a control-plane daemon coming back up) but has good reason to believe the sandbox,
1845
+ * and the bridge process inside it, never stopped: nothing here kills or re-execs anything.
1846
+ * `sb.proxy()` is a pure URL lookup, so the only network activity is re-deriving the proxy
1847
+ * URL and one health-check request.
1848
+ *
1849
+ * The returned `Alineo` is fully functional — `.prompt()`/`.bash()` work exactly as they
1850
+ * would have on the original handle, continuing the same Pi conversation, because it's
1851
+ * still the same process.
1852
+ *
1853
+ * **Fails fast (5s) if the bridge doesn't answer** — the container can be `Running` while
1854
+ * the bridge process inside it has independently died, and this can't distinguish that from
1855
+ * a slow-to-respond-but-fine bridge on its own. On failure, fall back to `Alineo.resume()`.
1856
+ *
1857
+ * @param sandboxId The sandbox ID returned by the original `Alineo.load()`/`.spawn()`.
1858
+ * @param opts.spec / opts.specPath Same three-way fallback as `resume()` — see its docs.
1859
+ *
1860
+ * @example
1861
+ * ```ts
1862
+ * let agent: Alineo;
1863
+ * try {
1864
+ * agent = await Alineo.reattach(savedSandboxId, { adapter });
1865
+ * } catch {
1866
+ * agent = await Alineo.resume(savedSandboxId, { adapter }); // bridge really is gone
1867
+ * }
1868
+ * ```
1869
+ */
1870
+ static async reattach(sandboxId, opts) {
1871
+ const r = await reattachAgent(sandboxId, opts);
1872
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1873
+ agent.memory = opts.memory;
1874
+ return agent;
1875
+ }
1876
+ /**
1736
1877
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
1737
1878
  * `resume()`, which kills and restarts the bridge process. Use this when you only
1738
1879
  * need `.spawn()`/`.sandbox`, not `.prompt()`/`.bash()`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "alineo",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -28,14 +28,14 @@
28
28
  "test": "bun test"
29
29
  },
30
30
  "dependencies": {
31
- "@alineo-labs/core": "0.4.0",
32
- "@alineo-labs/memory": "0.2.1",
33
- "@alineo-labs/sandbox": "0.4.0",
31
+ "@alineo-labs/core": "0.4.1",
32
+ "@alineo-labs/memory": "0.2.2",
33
+ "@alineo-labs/sandbox": "0.4.2",
34
34
  "zod": "^4.4.3"
35
35
  },
36
36
  "devDependencies": {
37
- "bun-types": "1.3.14",
38
- "tsdown": "0.22.3",
37
+ "bun-types": "1.4.2",
38
+ "tsdown": "0.23.0",
39
39
  "typescript": "6.0.3"
40
40
  }
41
41
  }