alineo 0.4.0 → 0.5.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,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,7 +1042,45 @@ 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`. */
1047
+ memory?: Memory;
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`. */
943
1084
  memory?: Memory;
944
1085
  }): Promise<Alineo>;
945
1086
  /**
@@ -979,7 +1120,8 @@ declare class Alineo {
979
1120
  cpu: string;
980
1121
  memory: string;
981
1122
  gpu?: string;
982
- }; /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
1123
+ };
1124
+ /** Wire a `Memory` instance onto the returned agent — see `Alineo.memory`. */
983
1125
  memory?: Memory;
984
1126
  }): Promise<Alineo>;
985
1127
  /**
@@ -1178,7 +1320,7 @@ declare class Alineo {
1178
1320
  * every caller up the chain -- `Alineo.prompt()`, `collectReply()`, `alineo fork --prompt` --
1179
1321
  * forever, with no error and no partial output.
1180
1322
  */
1181
- declare class PromptTimeoutError extends WorkflowError {
1323
+ export declare class PromptTimeoutError extends WorkflowError {
1182
1324
  readonly timeoutMs: number;
1183
1325
  readonly bridgeUrl: string;
1184
1326
  constructor(timeoutMs: number, bridgeUrl: string);
@@ -1190,9 +1332,9 @@ declare class PromptTimeoutError extends WorkflowError {
1190
1332
  * multi-line summary (via `z.prettifyError()`) suitable for printing as-is; `.issues` is for
1191
1333
  * callers that want to handle failures programmatically (e.g. highlight specific fields in a UI).
1192
1334
  */
1193
- declare class AgentSpecValidationError extends WorkflowError {
1335
+ export declare class AgentSpecValidationError extends WorkflowError {
1194
1336
  readonly issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[];
1195
1337
  constructor(message: string, issues: readonly Pick<z.core.$ZodIssue, "path" | "message" | "code">[]);
1196
1338
  }
1197
1339
  //#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 };
1340
+ 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) {
@@ -1181,6 +1195,7 @@ async function resumeAgent(sandboxId, opts) {
1181
1195
  const t1 = Date.now();
1182
1196
  const sb = await client.connect(sandboxId, spec.name, {
1183
1197
  runId,
1198
+ resources: spec.resources ?? config.defaults.resources,
1184
1199
  resourceId: spec.resourceId ?? spec.name,
1185
1200
  teamId: spec.teamId
1186
1201
  });
@@ -1225,6 +1240,65 @@ async function reconcileDroppedPermissions(adapter, sb, name, sandboxId) {
1225
1240
  } catch {}
1226
1241
  }
1227
1242
  /**
1243
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge. See
1244
+ * `Alineo.reattach()` for the public-facing docs. Structurally `resumeAgent()` minus its two
1245
+ * destructive steps (the `pkill` and the fresh `startBridge()`) — everything else (spec
1246
+ * resolution, env, `client.connect()`) is identical.
1247
+ */
1248
+ async function reattachAgent(sandboxId, opts) {
1249
+ const t0 = Date.now();
1250
+ const config = await readProjectConfig();
1251
+ const client = new Sandbox({
1252
+ baseUrl: config.serverUrl,
1253
+ apiKey: config.apiKey,
1254
+ adapter: opts.adapter,
1255
+ useServerProxy: config.useServerProxy
1256
+ });
1257
+ let spec;
1258
+ if (opts.spec) spec = validateAgentSpec(opts.spec);
1259
+ else if (opts.specPath) spec = validateAgentSpec(await Bun.file(opts.specPath).json());
1260
+ else {
1261
+ const session = (await client.sandboxes.list()).find((s) => s.sandboxId === sandboxId);
1262
+ if (!session) throw new Error(`No ledger record for sandbox ${sandboxId} — pass opts.spec or opts.specPath explicitly`);
1263
+ spec = validateAgentSpec(await Bun.file(`./agents/${session.name}.json`).json());
1264
+ }
1265
+ const resolvedEnv = resolveEnv(spec.env ?? {});
1266
+ if (spec.maxAgents !== void 0) {
1267
+ assertValidMaxAgents(spec.maxAgents, "Alineo.reattach()");
1268
+ resolvedEnv.ALINEO_MAX_AGENTS = String(spec.maxAgents);
1269
+ }
1270
+ if (spec.spawnDepth !== void 0) {
1271
+ assertValidSpawnDepth(spec.spawnDepth, "Alineo.reattach()");
1272
+ resolvedEnv.ALINEO_SPAWN_DEPTH = String(spec.spawnDepth);
1273
+ }
1274
+ const runId = opts.runId ?? crypto.randomUUID();
1275
+ resolvedEnv.ALINEO_RUN_ID = runId;
1276
+ resolvedEnv.ALINEO_SANDBOX_ID = sandboxId;
1277
+ console.log(`[agent] reattaching to ${sandboxId}...`);
1278
+ const t1 = Date.now();
1279
+ const sb = await client.connect(sandboxId, spec.name, {
1280
+ runId,
1281
+ resourceId: spec.resourceId ?? spec.name,
1282
+ teamId: spec.teamId,
1283
+ resources: spec.resources ?? config.defaults.resources
1284
+ });
1285
+ console.log(`[agent] connected ${elapsed(t1)}`);
1286
+ const adapter = new PiAdapter();
1287
+ await adapter.reattachBridge(sb);
1288
+ const t2 = Date.now();
1289
+ await adapter.waitReady(5e3);
1290
+ console.log(`[agent] bridge reattached ${elapsed(t2)}`);
1291
+ console.log(`[agent] total ${elapsed(t0)}`);
1292
+ return {
1293
+ sandbox: sb,
1294
+ spec,
1295
+ env: resolvedEnv,
1296
+ adapter,
1297
+ fromSnapshot: false,
1298
+ runId
1299
+ };
1300
+ }
1301
+ /**
1228
1302
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge. See
1229
1303
  * `Alineo.attach()` for the public-facing docs.
1230
1304
  */
@@ -1701,6 +1775,12 @@ var Alineo = class Alineo {
1701
1775
  * are already present — only the bridge process needs to be restarted.
1702
1776
  * Pi is started with `--continue` so it resumes the most recent session.
1703
1777
  *
1778
+ * **Kills and restarts the bridge process** — anything mid-flight when the previous host
1779
+ * process exited (a streaming turn, a tool call parked on a human decision) is dropped.
1780
+ * If the bridge might still be alive and you'd rather preserve that, try `Alineo.reattach()`
1781
+ * first and fall back to this only if it fails (e.g. the whole sandbox — not just this
1782
+ * process — actually restarted).
1783
+ *
1704
1784
  * @param sandboxId The sandbox ID returned by the original `Alineo.load()`.
1705
1785
  * @param opts.spec An already-parsed agent spec object — skips file I/O entirely, same as
1706
1786
  * `load()`. Takes precedence over `opts.specPath` if both are set.
@@ -1733,6 +1813,41 @@ var Alineo = class Alineo {
1733
1813
  return agent;
1734
1814
  }
1735
1815
  /**
1816
+ * Reconnect to a previously-created agent WITHOUT restarting its bridge — the crash-only
1817
+ * counterpart to `resume()`. Use this when the caller's own process exited or restarted
1818
+ * (e.g. a control-plane daemon coming back up) but has good reason to believe the sandbox,
1819
+ * and the bridge process inside it, never stopped: nothing here kills or re-execs anything.
1820
+ * `sb.proxy()` is a pure URL lookup, so the only network activity is re-deriving the proxy
1821
+ * URL and one health-check request.
1822
+ *
1823
+ * The returned `Alineo` is fully functional — `.prompt()`/`.bash()` work exactly as they
1824
+ * would have on the original handle, continuing the same Pi conversation, because it's
1825
+ * still the same process.
1826
+ *
1827
+ * **Fails fast (5s) if the bridge doesn't answer** — the container can be `Running` while
1828
+ * the bridge process inside it has independently died, and this can't distinguish that from
1829
+ * a slow-to-respond-but-fine bridge on its own. On failure, fall back to `Alineo.resume()`.
1830
+ *
1831
+ * @param sandboxId The sandbox ID returned by the original `Alineo.load()`/`.spawn()`.
1832
+ * @param opts.spec / opts.specPath Same three-way fallback as `resume()` — see its docs.
1833
+ *
1834
+ * @example
1835
+ * ```ts
1836
+ * let agent: Alineo;
1837
+ * try {
1838
+ * agent = await Alineo.reattach(savedSandboxId, { adapter });
1839
+ * } catch {
1840
+ * agent = await Alineo.resume(savedSandboxId, { adapter }); // bridge really is gone
1841
+ * }
1842
+ * ```
1843
+ */
1844
+ static async reattach(sandboxId, opts) {
1845
+ const r = await reattachAgent(sandboxId, opts);
1846
+ const agent = new Alineo(r.sandbox, r.spec, r.env, r.adapter, r.fromSnapshot, r.runId);
1847
+ agent.memory = opts.memory;
1848
+ return agent;
1849
+ }
1850
+ /**
1736
1851
  * Connect to an already-running sandbox WITHOUT touching its Pi bridge — unlike
1737
1852
  * `resume()`, which kills and restarts the bridge process. Use this when you only
1738
1853
  * 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.0",
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.1",
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
  }