@alineo-labs/core 0.5.0 → 0.6.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 +119 -33
- package/dist/index.mjs +246 -106
- package/package.json +4 -3
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,14 @@
|
|
|
1
1
|
import { ConsoleLogger, ILogger, LogLevel, noopLogger } from "@alineo-labs/logger";
|
|
2
|
-
import {
|
|
2
|
+
import { AlineoError, AlineoError as AlineoError$1, AlineoErrorOptions, ErrorCode, ErrorCode as ErrorCode$1, errorCodeOf, isRetryable } from "@alineo-labs/errors";
|
|
3
|
+
import { CodeContext, CodeLanguage, DiagnosticEvent, DiagnosticEvent as DiagnosticEvent$1, DiagnosticLog, DiagnosticLog as DiagnosticLog$1, EgressPolicyStatus, ExecChannel, ExecEvent, FileInfo, FileInfo as FileInfo$1, Metrics, Metrics as Metrics$1, NetworkPolicy, NetworkRule, PtyChannel, SandboxProvider, SandboxProviderCapabilities } from "@alineo-labs/provider";
|
|
3
4
|
import { LedgerEnvelope } from "@alineo-labs/schema/types";
|
|
4
5
|
//#region src/ledger.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* The provider a ledger row belongs to when it records none. Rows written before provider ids
|
|
8
|
+
* existed all came from OpenSandbox, so an absent `provider` means this. Readers apply it on
|
|
9
|
+
* read; nothing in the ledger is migrated.
|
|
10
|
+
*/
|
|
11
|
+
export declare const DEFAULT_PROVIDER_ID = "opensandbox";
|
|
5
12
|
/** Status of a sandbox session derived from its ledger events. */
|
|
6
13
|
export declare enum SandboxStatus {
|
|
7
14
|
Running = "running",
|
|
@@ -54,6 +61,12 @@ interface SandboxDetails {
|
|
|
54
61
|
* `episodicRecall`) walk a fork lineage rather than only seeing one flat session.
|
|
55
62
|
*/
|
|
56
63
|
parentSandboxId?: string;
|
|
64
|
+
/**
|
|
65
|
+
* The sandbox provider that owns `sandboxId` (`"opensandbox"`). Always set by the official
|
|
66
|
+
* adapters, which apply {@link DEFAULT_PROVIDER_ID} to rows that recorded none. Optional in
|
|
67
|
+
* the type so a third-party `IStorageAdapter` written before this field still compiles.
|
|
68
|
+
*/
|
|
69
|
+
provider?: string;
|
|
57
70
|
}
|
|
58
71
|
/** Options for filtering session listings. */
|
|
59
72
|
interface ListSandboxOptions {
|
|
@@ -68,6 +81,8 @@ interface ListSandboxOptions {
|
|
|
68
81
|
resourceId?: string;
|
|
69
82
|
/** Return only sessions scoped to this team — see `SandboxDetails.teamId`. */
|
|
70
83
|
teamId?: string;
|
|
84
|
+
/** Return only sessions owned by this sandbox provider — see `SandboxDetails.provider`. */
|
|
85
|
+
provider?: string;
|
|
71
86
|
}
|
|
72
87
|
/** Events emitted during execution and stored in the ledger. */
|
|
73
88
|
export declare enum LedgerEvent {
|
|
@@ -122,7 +137,9 @@ export declare enum LedgerEvent {
|
|
|
122
137
|
* (workspace + session-file tarball, NOT `sb.checkpoint()`'s OpenSandbox snapshot — see
|
|
123
138
|
* `CheckpointCreated` above and `packages/agent/src/checkpoint.ts`'s doc comment for why the
|
|
124
139
|
* two are deliberately separate mechanisms) is captured and durably stored. Payload is
|
|
125
|
-
* `{ turn, snapshotRef }` —
|
|
140
|
+
* `{ turn, snapshotRef, remoteRef?, uploadError? }` — `snapshotRef` is the host file and `remoteRef`
|
|
141
|
+
* the same tarball in object storage, when a store was given and the upload worked. Written only
|
|
142
|
+
* once the tarball is confirmed stored, since a
|
|
126
143
|
* snapshot without this event pointing at it is unreachable garbage. Shares the same
|
|
127
144
|
* `IStorageAdapter`-backed ledger `PermissionRequested`/`PermissionResolved` already use, so
|
|
128
145
|
* a standalone SDK caller and alineod both read it back the same way (`adapter.readAll`).
|
|
@@ -391,11 +408,29 @@ interface ExecResult {
|
|
|
391
408
|
stdout: string;
|
|
392
409
|
stderr: string;
|
|
393
410
|
exitCode: number;
|
|
411
|
+
/** How long the command ran, in milliseconds, measured by the client. */
|
|
412
|
+
durationMs?: number;
|
|
413
|
+
/** True when the command was ended by a signal (a timeout, a `kill`, the OOM killer). */
|
|
414
|
+
killed?: boolean;
|
|
415
|
+
/** The signal that ended it, as the server reported it (`"killed"`). Set with `killed`. */
|
|
416
|
+
signal?: string;
|
|
417
|
+
/**
|
|
418
|
+
* True when the command was killed after running for about as long as `timeoutMs` allowed.
|
|
419
|
+
*
|
|
420
|
+
* **A best guess, not a report.** A timeout and a kill from inside the sandbox (the OOM
|
|
421
|
+
* killer, a `kill -9`) look the same on the wire: both are `signal: killed`, exit code -1. So
|
|
422
|
+
* this is inferred from the elapsed time, and a kill that lands close to the limit reads as a
|
|
423
|
+
* timeout. Use it to explain a failure to a person, not to decide whether a retry is safe.
|
|
424
|
+
* Never set for a command that had no limit.
|
|
425
|
+
*/
|
|
426
|
+
timedOut?: boolean;
|
|
394
427
|
}
|
|
395
428
|
type ExecDriver = {
|
|
396
429
|
type: "stream";
|
|
397
|
-
gen: AsyncGenerator<
|
|
430
|
+
gen: AsyncGenerator<ExecEvent>;
|
|
398
431
|
onDone: (r: ExecResult) => Promise<void>;
|
|
432
|
+
/** The `timeoutMs` the command was started with, so a timeout can be told from a kill. */
|
|
433
|
+
timeoutMs?: number;
|
|
399
434
|
} | {
|
|
400
435
|
type: "replay";
|
|
401
436
|
result: ExecResult;
|
|
@@ -511,6 +546,12 @@ interface ExecOptions {
|
|
|
511
546
|
env?: Record<string, string>;
|
|
512
547
|
/** Abort the command after this many milliseconds. */
|
|
513
548
|
timeoutMs?: number;
|
|
549
|
+
/**
|
|
550
|
+
* Abort the command. On abort the call rejects with the signal's reason (an `AbortError` by
|
|
551
|
+
* default) and the command is interrupted in the sandbox, best effort. A signal that is already
|
|
552
|
+
* aborted rejects before anything is sent.
|
|
553
|
+
*/
|
|
554
|
+
signal?: AbortSignal;
|
|
514
555
|
/**
|
|
515
556
|
* Throw `CommandError` if the command exits with a non-zero code.
|
|
516
557
|
* Defaults to `true`.
|
|
@@ -563,7 +604,8 @@ interface SandboxHooks {
|
|
|
563
604
|
}
|
|
564
605
|
/** Internal dependencies injected by `Sandbox`. */
|
|
565
606
|
interface SandboxDeps {
|
|
566
|
-
|
|
607
|
+
/** The sandbox provider that owns this sandbox. */
|
|
608
|
+
provider: SandboxProvider;
|
|
567
609
|
adapter: IStorageAdapter;
|
|
568
610
|
/**
|
|
569
611
|
* Receives a `LedgerEnvelope` for every event this sandbox emits, beside the ledger write.
|
|
@@ -600,8 +642,6 @@ interface SandboxDeps {
|
|
|
600
642
|
resourceId?: string;
|
|
601
643
|
teamId?: string;
|
|
602
644
|
}) => Promise<SandboxHandle>;
|
|
603
|
-
/** Route execd and proxy calls through the OpenSandbox server. Required when the server runs in Docker. */
|
|
604
|
-
useServerProxy?: boolean;
|
|
605
645
|
}
|
|
606
646
|
//#endregion
|
|
607
647
|
//#region src/sandbox/internal.d.ts
|
|
@@ -618,7 +658,7 @@ interface SandboxInternal {
|
|
|
618
658
|
readonly name: string;
|
|
619
659
|
readonly deps: SandboxDeps;
|
|
620
660
|
readonly openSessionClosers: Set<() => Promise<void>>;
|
|
621
|
-
getExecClient(): Promise<
|
|
661
|
+
getExecClient(signal?: AbortSignal): Promise<ExecChannel>;
|
|
622
662
|
emit(event: LedgerEvent, stepIndex: number, payload?: unknown): Promise<void>;
|
|
623
663
|
waitForRunning(timeoutMs?: number): Promise<void>;
|
|
624
664
|
waitForSnapshot(snapshotId: string, timeoutMs?: number): Promise<void>;
|
|
@@ -675,6 +715,8 @@ export declare class BashSession {
|
|
|
675
715
|
*/
|
|
676
716
|
declare class SandboxCore implements SandboxInternal {
|
|
677
717
|
readonly sandboxId: string;
|
|
718
|
+
/** The id of the sandbox provider that owns this sandbox (`"opensandbox"`). */
|
|
719
|
+
get provider(): string;
|
|
678
720
|
readonly name: string;
|
|
679
721
|
readonly deps: SandboxDeps;
|
|
680
722
|
/** Cached exec results for replay mode (populated by `Sandbox.resume()`). */
|
|
@@ -708,9 +750,14 @@ declare class SandboxCore implements SandboxInternal {
|
|
|
708
750
|
*/
|
|
709
751
|
disposeExecClient(): void;
|
|
710
752
|
nextSeq(): number;
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
753
|
+
/**
|
|
754
|
+
* The channel to this sandbox's `execd`, connecting if there is none yet. `signal` stops the
|
|
755
|
+
* wait for a sandbox that is slow to accept a connection. It does not close a channel that was
|
|
756
|
+
* already connected.
|
|
757
|
+
*/
|
|
758
|
+
getExecClient(signal?: AbortSignal): Promise<ExecChannel>;
|
|
759
|
+
/** Resolve a fresh terminal channel for a new interactive session. Reuses `getExecClient()`'s readiness wait. */
|
|
760
|
+
resolvePtyClient(): Promise<PtyChannel>;
|
|
714
761
|
waitForRunning(timeoutMs?: number): Promise<void>;
|
|
715
762
|
waitForSnapshot(snapshotId: string, timeoutMs?: number): Promise<void>;
|
|
716
763
|
emit(event: LedgerEvent, stepIndex: number, payload?: unknown): Promise<void>;
|
|
@@ -1029,22 +1076,33 @@ export declare class SandboxHandle extends SandboxCore {
|
|
|
1029
1076
|
//#endregion
|
|
1030
1077
|
//#region src/sandbox/resolve.d.ts
|
|
1031
1078
|
/**
|
|
1032
|
-
*
|
|
1033
|
-
*
|
|
1034
|
-
*
|
|
1079
|
+
* A channel to run commands in a sandbox, from its provider.
|
|
1080
|
+
*
|
|
1081
|
+
* The provider owns the wait: it resolves once the sandbox accepts a connection, and rejects with
|
|
1082
|
+
* `EXEC_NOT_READY` when it never does. That failure is re-thrown as `ExecConnectionError`, with
|
|
1083
|
+
* the cause, the attempt count, and the wait the provider recorded, because that class is the
|
|
1084
|
+
* one callers have been catching and it extends `WorkflowError`.
|
|
1085
|
+
*/
|
|
1086
|
+
export declare function resolveExecChannel(provider: SandboxProvider, sandboxId: string, options?: {
|
|
1087
|
+
signal?: AbortSignal;
|
|
1088
|
+
}): Promise<ExecChannel>;
|
|
1089
|
+
//#endregion
|
|
1090
|
+
//#region src/sandbox/capabilities.d.ts
|
|
1091
|
+
/** The capabilities a caller can require of a provider. */
|
|
1092
|
+
type RequiredCapability = keyof SandboxProviderCapabilities;
|
|
1093
|
+
/**
|
|
1094
|
+
* Throw `CAPABILITY_UNSUPPORTED`, naming the capability and the provider, when the provider
|
|
1095
|
+
* declares it cannot do something.
|
|
1096
|
+
*
|
|
1097
|
+
* Only an explicit `false` is a refusal. `"unverified"` (configured, not proven) goes ahead and
|
|
1098
|
+
* may still fail at the call, and a provider with no descriptor, which is what a test double
|
|
1099
|
+
* usually is, is not second-guessed.
|
|
1035
1100
|
*
|
|
1036
|
-
*
|
|
1037
|
-
*
|
|
1038
|
-
*
|
|
1039
|
-
* took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
|
|
1040
|
-
* budget before the exec daemon inside it had actually started accepting connections. An
|
|
1041
|
-
* isolated repro of the identical fork (same snapshot, but from an idle parent with no
|
|
1042
|
-
* concurrent browser load) reached execd-ready in under 400ms -- the parent's own host-resource
|
|
1043
|
-
* contention at fork time, not snapshot size, is what actually eats the budget. This can't be
|
|
1044
|
-
* fixed by scheduling around it from here, so it's addressed by simply affording much more
|
|
1045
|
-
* patience before giving up.
|
|
1101
|
+
* This is the early failure: a spec that needs egress, or a `checkpoint()` on a provider that
|
|
1102
|
+
* cannot snapshot, is refused before anything is created or sent, with a message that names the
|
|
1103
|
+
* missing capability instead of a failure three calls later that reads like a bad spec.
|
|
1046
1104
|
*/
|
|
1047
|
-
export declare function
|
|
1105
|
+
export declare function requireCapability(provider: SandboxProvider, capability: RequiredCapability, sandboxId?: string): void;
|
|
1048
1106
|
//#endregion
|
|
1049
1107
|
//#region src/sandbox/hooks.d.ts
|
|
1050
1108
|
interface ComposeHooksOptions {
|
|
@@ -1081,9 +1139,14 @@ interface ComposeHooksOptions {
|
|
|
1081
1139
|
export declare function composeHooks(hooks: (SandboxHooks | undefined)[], opts?: ComposeHooksOptions): SandboxHooks;
|
|
1082
1140
|
//#endregion
|
|
1083
1141
|
//#region src/errors.d.ts
|
|
1084
|
-
/**
|
|
1085
|
-
|
|
1086
|
-
|
|
1142
|
+
/**
|
|
1143
|
+
* Base class for all alineo workflow runtime errors.
|
|
1144
|
+
*
|
|
1145
|
+
* An {@link AlineoError}, so every subclass carries a stable `code`. A subclass that has not
|
|
1146
|
+
* been given a more specific code reports `INTERNAL`.
|
|
1147
|
+
*/
|
|
1148
|
+
export declare class WorkflowError extends AlineoError$1 {
|
|
1149
|
+
constructor(message: string, code?: ErrorCode$1, options?: AlineoErrorOptions);
|
|
1087
1150
|
}
|
|
1088
1151
|
/**
|
|
1089
1152
|
* Thrown for sandbox lifecycle failures — failing to create, boot, or reach
|
|
@@ -1095,21 +1158,39 @@ export declare class SandboxError extends WorkflowError {
|
|
|
1095
1158
|
readonly sandboxId?: string | undefined;
|
|
1096
1159
|
constructor(message: string,
|
|
1097
1160
|
/** The sandbox ID, if one was assigned before the failure. */
|
|
1098
|
-
sandboxId?: string | undefined);
|
|
1161
|
+
sandboxId?: string | undefined, code?: ErrorCode$1, options?: AlineoErrorOptions);
|
|
1162
|
+
}
|
|
1163
|
+
/** What `ExecConnectionError` knows about the readiness probe that gave up. */
|
|
1164
|
+
interface ExecConnectionFailure {
|
|
1165
|
+
/** The last error the readiness probe saw. */
|
|
1166
|
+
cause?: unknown;
|
|
1167
|
+
/** How many probes ran. */
|
|
1168
|
+
attempts?: number;
|
|
1169
|
+
/** How long the probe waited in total, in milliseconds. */
|
|
1170
|
+
waitedMs?: number;
|
|
1099
1171
|
}
|
|
1100
1172
|
/**
|
|
1101
1173
|
* Thrown when execd inside a sandbox never becomes ready within the retry window.
|
|
1102
1174
|
* The sandbox is `Running` from the control plane's perspective, but the exec
|
|
1103
1175
|
* daemon is not accepting connections.
|
|
1176
|
+
*
|
|
1177
|
+
* Code `EXEC_NOT_READY`. The message keeps its original leading text, and adds how long the
|
|
1178
|
+
* probe waited and the last error it saw, so a failure on a fresh machine says why.
|
|
1104
1179
|
*/
|
|
1105
1180
|
export declare class ExecConnectionError extends WorkflowError {
|
|
1106
1181
|
readonly sandboxId: string;
|
|
1107
|
-
constructor(sandboxId: string);
|
|
1182
|
+
constructor(sandboxId: string, failure?: ExecConnectionFailure);
|
|
1183
|
+
/** How many readiness probes ran before giving up. */
|
|
1184
|
+
readonly attempts?: number;
|
|
1185
|
+
/** How long the readiness probe waited in total, in milliseconds. */
|
|
1186
|
+
readonly waitedMs?: number;
|
|
1108
1187
|
}
|
|
1109
1188
|
/**
|
|
1110
1189
|
* Thrown when a command exits with a non-zero exit code. Carries the exit
|
|
1111
|
-
* code
|
|
1112
|
-
*
|
|
1190
|
+
* code, the original command, and the command's output: `stderr` and `stdout`
|
|
1191
|
+
* hold all of it, and the message ends with the last 2000 characters of `stderr`
|
|
1192
|
+
* (or of `stdout` when `stderr` is empty). For `SandboxHandle.exec()`, only thrown
|
|
1193
|
+
* when `strict` is enabled (the default — pass `{ strict: false }` to opt out). For
|
|
1113
1194
|
* `BashSession.exec()` (a persistent session from `createSession()`), always
|
|
1114
1195
|
* thrown on non-zero exit; there is no `strict` option for session execs.
|
|
1115
1196
|
*/
|
|
@@ -1117,7 +1198,12 @@ export declare class CommandError extends WorkflowError {
|
|
|
1117
1198
|
readonly exitCode: number;
|
|
1118
1199
|
readonly command: string;
|
|
1119
1200
|
readonly sandboxId: string;
|
|
1120
|
-
|
|
1201
|
+
readonly stdout: string;
|
|
1202
|
+
readonly stderr: string;
|
|
1203
|
+
constructor(exitCode: number, command: string, sandboxId: string, output?: {
|
|
1204
|
+
stdout?: string;
|
|
1205
|
+
stderr?: string;
|
|
1206
|
+
});
|
|
1121
1207
|
}
|
|
1122
1208
|
/**
|
|
1123
1209
|
* Reserved for a per-step timeout mechanism — not currently thrown anywhere
|
|
@@ -1130,4 +1216,4 @@ export declare class StepTimeoutError extends WorkflowError {
|
|
|
1130
1216
|
constructor(stepId: string, timeoutMs: number);
|
|
1131
1217
|
}
|
|
1132
1218
|
//#endregion
|
|
1133
|
-
export { type AttachableSource, type BoundCredential, type CheckpointInfo, type ComposeHooksOptions, ConsoleLogger, type CredentialBinding, type CredentialBroker, type CredentialInjection, type CredentialResolver, type CredentialSource, type DiagnosticEvent, type DiagnosticLog, type EngineLedgerEntry, type EngineLedgerRow, type EnvironmentRecord, type ExecCodeOptions, type ExecOptions, type ExecResult, type FileInfo, type IEngineLedger, type ILogger, type IStorageAdapter, type LedgerEntry, type ListSandboxOptions, LogLevel, type Metrics, type PendingInteractiveExec, type PtyControls, type ReconstructedEgress, type SandboxDeps, type SandboxDetails, type SandboxHooks, noopLogger };
|
|
1219
|
+
export { AlineoError, type AttachableSource, type BoundCredential, type CheckpointInfo, type ComposeHooksOptions, ConsoleLogger, type CredentialBinding, type CredentialBroker, type CredentialInjection, type CredentialResolver, type CredentialSource, type DiagnosticEvent, type DiagnosticLog, type EngineLedgerEntry, type EngineLedgerRow, type EnvironmentRecord, type ErrorCode, type ExecCodeOptions, type ExecConnectionFailure, type ExecOptions, type ExecResult, type FileInfo, type IEngineLedger, type ILogger, type IStorageAdapter, type LedgerEntry, type ListSandboxOptions, LogLevel, type Metrics, type PendingInteractiveExec, type PtyControls, type ReconstructedEgress, type SandboxDeps, type SandboxDetails, type SandboxHooks, errorCodeOf, isRetryable, noopLogger };
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { ConsoleLogger, LogLevel, noopLogger } from "@alineo-labs/logger";
|
|
2
|
-
import {
|
|
2
|
+
import { AlineoError, AlineoError as AlineoError$1, errorCodeOf, errorCodeOf as errorCodeOf$1, isRetryable } from "@alineo-labs/errors";
|
|
3
3
|
//#region src/ledger.ts
|
|
4
|
+
/**
|
|
5
|
+
* The provider a ledger row belongs to when it records none. Rows written before provider ids
|
|
6
|
+
* existed all came from OpenSandbox, so an absent `provider` means this. Readers apply it on
|
|
7
|
+
* read; nothing in the ledger is migrated.
|
|
8
|
+
*/
|
|
9
|
+
const DEFAULT_PROVIDER_ID = "opensandbox";
|
|
4
10
|
/** Status of a sandbox session derived from its ledger events. */
|
|
5
11
|
let SandboxStatus = /* @__PURE__ */ function(SandboxStatus) {
|
|
6
12
|
SandboxStatus["Running"] = "running";
|
|
@@ -60,7 +66,9 @@ let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
|
|
|
60
66
|
* (workspace + session-file tarball, NOT `sb.checkpoint()`'s OpenSandbox snapshot — see
|
|
61
67
|
* `CheckpointCreated` above and `packages/agent/src/checkpoint.ts`'s doc comment for why the
|
|
62
68
|
* two are deliberately separate mechanisms) is captured and durably stored. Payload is
|
|
63
|
-
* `{ turn, snapshotRef }` —
|
|
69
|
+
* `{ turn, snapshotRef, remoteRef?, uploadError? }` — `snapshotRef` is the host file and `remoteRef`
|
|
70
|
+
* the same tarball in object storage, when a store was given and the upload worked. Written only
|
|
71
|
+
* once the tarball is confirmed stored, since a
|
|
64
72
|
* snapshot without this event pointing at it is unreachable garbage. Shares the same
|
|
65
73
|
* `IStorageAdapter`-backed ledger `PermissionRequested`/`PermissionResolved` already use, so
|
|
66
74
|
* a standalone SDK caller and alineod both read it back the same way (`adapter.readAll`).
|
|
@@ -70,10 +78,15 @@ let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
|
|
|
70
78
|
}({});
|
|
71
79
|
//#endregion
|
|
72
80
|
//#region src/errors.ts
|
|
73
|
-
/**
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
81
|
+
/**
|
|
82
|
+
* Base class for all alineo workflow runtime errors.
|
|
83
|
+
*
|
|
84
|
+
* An {@link AlineoError}, so every subclass carries a stable `code`. A subclass that has not
|
|
85
|
+
* been given a more specific code reports `INTERNAL`.
|
|
86
|
+
*/
|
|
87
|
+
var WorkflowError = class extends AlineoError$1 {
|
|
88
|
+
constructor(message, code = "INTERNAL", options) {
|
|
89
|
+
super(code, message, options);
|
|
77
90
|
this.name = "WorkflowError";
|
|
78
91
|
}
|
|
79
92
|
};
|
|
@@ -84,8 +97,14 @@ var WorkflowError = class extends Error {
|
|
|
84
97
|
*/
|
|
85
98
|
var SandboxError = class extends WorkflowError {
|
|
86
99
|
sandboxId;
|
|
87
|
-
constructor(message, sandboxId) {
|
|
88
|
-
super(message
|
|
100
|
+
constructor(message, sandboxId, code = "INTERNAL", options) {
|
|
101
|
+
super(message, code, {
|
|
102
|
+
...options,
|
|
103
|
+
details: {
|
|
104
|
+
...sandboxId ? { sandboxId } : {},
|
|
105
|
+
...options?.details
|
|
106
|
+
}
|
|
107
|
+
});
|
|
89
108
|
this.sandboxId = sandboxId;
|
|
90
109
|
this.name = "SandboxError";
|
|
91
110
|
}
|
|
@@ -94,19 +113,59 @@ var SandboxError = class extends WorkflowError {
|
|
|
94
113
|
* Thrown when execd inside a sandbox never becomes ready within the retry window.
|
|
95
114
|
* The sandbox is `Running` from the control plane's perspective, but the exec
|
|
96
115
|
* daemon is not accepting connections.
|
|
116
|
+
*
|
|
117
|
+
* Code `EXEC_NOT_READY`. The message keeps its original leading text, and adds how long the
|
|
118
|
+
* probe waited and the last error it saw, so a failure on a fresh machine says why.
|
|
97
119
|
*/
|
|
98
120
|
var ExecConnectionError = class extends WorkflowError {
|
|
99
121
|
sandboxId;
|
|
100
|
-
constructor(sandboxId) {
|
|
101
|
-
super(
|
|
122
|
+
constructor(sandboxId, failure = {}) {
|
|
123
|
+
super(describeExecConnectionFailure(sandboxId, failure), "EXEC_NOT_READY", {
|
|
124
|
+
cause: failure.cause,
|
|
125
|
+
details: {
|
|
126
|
+
sandboxId,
|
|
127
|
+
...failure.attempts !== void 0 ? { attempts: failure.attempts } : {},
|
|
128
|
+
...failure.waitedMs !== void 0 ? { waitedMs: failure.waitedMs } : {}
|
|
129
|
+
}
|
|
130
|
+
});
|
|
102
131
|
this.sandboxId = sandboxId;
|
|
103
132
|
this.name = "ExecConnectionError";
|
|
133
|
+
this.attempts = failure.attempts;
|
|
134
|
+
this.waitedMs = failure.waitedMs;
|
|
104
135
|
}
|
|
136
|
+
/** How many readiness probes ran before giving up. */
|
|
137
|
+
attempts;
|
|
138
|
+
/** How long the readiness probe waited in total, in milliseconds. */
|
|
139
|
+
waitedMs;
|
|
105
140
|
};
|
|
141
|
+
function describeExecConnectionFailure(sandboxId, f) {
|
|
142
|
+
let text = `execd not ready for sandbox ${sandboxId}`;
|
|
143
|
+
if (f.attempts !== void 0 && f.waitedMs !== void 0) text += ` after ${f.attempts} attempts over ${(f.waitedMs / 1e3).toFixed(0)}s`;
|
|
144
|
+
const reason = describeCause(f.cause);
|
|
145
|
+
if (reason) text += `. Last error: ${reason}`;
|
|
146
|
+
return text;
|
|
147
|
+
}
|
|
148
|
+
/** Text for a thrown value. Never throws: this runs inside an error constructor. */
|
|
149
|
+
function describeCause(cause) {
|
|
150
|
+
if (cause === void 0) return void 0;
|
|
151
|
+
if (cause instanceof Error) return cause.message;
|
|
152
|
+
if (typeof cause === "string") return cause;
|
|
153
|
+
try {
|
|
154
|
+
return JSON.stringify(cause);
|
|
155
|
+
} catch {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function outputTail(output) {
|
|
160
|
+
const text = (output.stderr.trim() || output.stdout.trim()).slice(-2e3);
|
|
161
|
+
return text ? `\n${text}` : "";
|
|
162
|
+
}
|
|
106
163
|
/**
|
|
107
164
|
* Thrown when a command exits with a non-zero exit code. Carries the exit
|
|
108
|
-
* code
|
|
109
|
-
*
|
|
165
|
+
* code, the original command, and the command's output: `stderr` and `stdout`
|
|
166
|
+
* hold all of it, and the message ends with the last 2000 characters of `stderr`
|
|
167
|
+
* (or of `stdout` when `stderr` is empty). For `SandboxHandle.exec()`, only thrown
|
|
168
|
+
* when `strict` is enabled (the default — pass `{ strict: false }` to opt out). For
|
|
110
169
|
* `BashSession.exec()` (a persistent session from `createSession()`), always
|
|
111
170
|
* thrown on non-zero exit; there is no `strict` option for session execs.
|
|
112
171
|
*/
|
|
@@ -114,12 +173,24 @@ var CommandError = class extends WorkflowError {
|
|
|
114
173
|
exitCode;
|
|
115
174
|
command;
|
|
116
175
|
sandboxId;
|
|
117
|
-
|
|
118
|
-
|
|
176
|
+
stdout;
|
|
177
|
+
stderr;
|
|
178
|
+
constructor(exitCode, command, sandboxId, output = {}) {
|
|
179
|
+
const stdout = output.stdout ?? "";
|
|
180
|
+
const stderr = output.stderr ?? "";
|
|
181
|
+
super(`Command exited with code ${exitCode}: ${command}${outputTail({
|
|
182
|
+
stdout,
|
|
183
|
+
stderr
|
|
184
|
+
})}`, "COMMAND_FAILED", { details: {
|
|
185
|
+
exitCode,
|
|
186
|
+
sandboxId
|
|
187
|
+
} });
|
|
119
188
|
this.exitCode = exitCode;
|
|
120
189
|
this.command = command;
|
|
121
190
|
this.sandboxId = sandboxId;
|
|
122
191
|
this.name = "CommandError";
|
|
192
|
+
this.stdout = stdout;
|
|
193
|
+
this.stderr = stderr;
|
|
123
194
|
}
|
|
124
195
|
};
|
|
125
196
|
/**
|
|
@@ -131,7 +202,10 @@ var StepTimeoutError = class extends WorkflowError {
|
|
|
131
202
|
stepId;
|
|
132
203
|
timeoutMs;
|
|
133
204
|
constructor(stepId, timeoutMs) {
|
|
134
|
-
super(`Step "${stepId}" timed out after ${timeoutMs}ms
|
|
205
|
+
super(`Step "${stepId}" timed out after ${timeoutMs}ms`, "STEP_TIMEOUT", { details: {
|
|
206
|
+
stepId,
|
|
207
|
+
timeoutMs
|
|
208
|
+
} });
|
|
135
209
|
this.stepId = stepId;
|
|
136
210
|
this.timeoutMs = timeoutMs;
|
|
137
211
|
this.name = "StepTimeoutError";
|
|
@@ -153,7 +227,7 @@ async function resolveBoundCredential(name, source, resolver, sandboxId) {
|
|
|
153
227
|
}
|
|
154
228
|
const fromResolver = await resolver?.(name, source ?? { type: "external" });
|
|
155
229
|
if (fromResolver !== void 0) return fromResolver;
|
|
156
|
-
throw new SandboxError(`Cannot resolve credential "${name}" for sandbox ${sandboxId}` + (source?.type === "env" ? ` (env var "${source.varName}" is not set)` : ` (source: ${source?.type ?? "unknown"})`) + ` — pass a resolveCredential callback that returns a value for it.`, sandboxId);
|
|
230
|
+
throw new SandboxError(`Cannot resolve credential "${name}" for sandbox ${sandboxId}` + (source?.type === "env" ? ` (env var "${source.varName}" is not set)` : ` (source: ${source?.type ?? "unknown"})`) + ` — pass a resolveCredential callback that returns a value for it.`, sandboxId, "CREDENTIAL_UNRESOLVED", { details: { credential: name } });
|
|
157
231
|
}
|
|
158
232
|
/**
|
|
159
233
|
* Reconstructs the latest bound/revoked state per credential name from a session's ledger
|
|
@@ -213,6 +287,8 @@ function reconstructEgressRules(entries) {
|
|
|
213
287
|
}
|
|
214
288
|
//#endregion
|
|
215
289
|
//#region src/exec-handle.ts
|
|
290
|
+
/** The shell convention for "found the command but could not run it". */
|
|
291
|
+
const START_FAILED_EXIT_CODE = 126;
|
|
216
292
|
/**
|
|
217
293
|
* Returned by `SandboxHandle.exec()` and `SandboxHandle.execCode()`.
|
|
218
294
|
*
|
|
@@ -247,7 +323,7 @@ var ExecHandle = class {
|
|
|
247
323
|
this._promise = this._drainPty(driver);
|
|
248
324
|
this._promise.catch(() => {});
|
|
249
325
|
} else {
|
|
250
|
-
this._promise = this._drain(driver.gen, driver.onDone);
|
|
326
|
+
this._promise = this._drain(driver.gen, driver.onDone, driver.timeoutMs);
|
|
251
327
|
this._promise.catch(() => {});
|
|
252
328
|
}
|
|
253
329
|
}
|
|
@@ -281,19 +357,29 @@ var ExecHandle = class {
|
|
|
281
357
|
});
|
|
282
358
|
});
|
|
283
359
|
}
|
|
284
|
-
async _drain(gen, onDone) {
|
|
360
|
+
async _drain(gen, onDone, timeoutMs) {
|
|
285
361
|
const stderr = [];
|
|
286
362
|
let exitCode = 0;
|
|
363
|
+
let signal;
|
|
364
|
+
const startedAt = Date.now();
|
|
287
365
|
try {
|
|
288
366
|
for await (const ev of gen) {
|
|
289
|
-
if (ev.type ===
|
|
367
|
+
if (ev.type === "stdout" && ev.text) {
|
|
290
368
|
this._chunks.push(ev.text);
|
|
291
369
|
this._notify();
|
|
292
370
|
}
|
|
293
|
-
if (ev.type ===
|
|
294
|
-
if (ev.type ===
|
|
371
|
+
if (ev.type === "stderr" && ev.text) stderr.push(ev.text);
|
|
372
|
+
if (ev.type === "error" && ev.error?.evalue !== void 0) {
|
|
295
373
|
const code = Number(ev.error.evalue);
|
|
296
374
|
if (!isNaN(code)) exitCode = code;
|
|
375
|
+
else {
|
|
376
|
+
exitCode = START_FAILED_EXIT_CODE;
|
|
377
|
+
stderr.push(`${ev.error.evalue}\n`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
for (const line of ev.error?.traceback ?? []) {
|
|
381
|
+
const match = /^signal: (.+)$/.exec(line);
|
|
382
|
+
if (match) signal = match[1];
|
|
297
383
|
}
|
|
298
384
|
}
|
|
299
385
|
} catch (err) {
|
|
@@ -304,10 +390,17 @@ var ExecHandle = class {
|
|
|
304
390
|
this._done = true;
|
|
305
391
|
this._notify();
|
|
306
392
|
}
|
|
393
|
+
const durationMs = Date.now() - startedAt;
|
|
307
394
|
const result = {
|
|
308
395
|
stdout: this._chunks.join(""),
|
|
309
396
|
stderr: stderr.join(""),
|
|
310
|
-
exitCode
|
|
397
|
+
exitCode,
|
|
398
|
+
durationMs,
|
|
399
|
+
...signal !== void 0 ? {
|
|
400
|
+
killed: true,
|
|
401
|
+
signal,
|
|
402
|
+
timedOut: timeoutMs !== void 0 && durationMs >= timeoutMs - 250
|
|
403
|
+
} : {}
|
|
311
404
|
};
|
|
312
405
|
await onDone(result);
|
|
313
406
|
return result;
|
|
@@ -408,39 +501,25 @@ var InteractiveExecHandle = class extends ExecHandle {
|
|
|
408
501
|
//#endregion
|
|
409
502
|
//#region src/sandbox/resolve.ts
|
|
410
503
|
/**
|
|
411
|
-
*
|
|
412
|
-
* returns a different ephemeral proxy port) then polls listContexts until
|
|
413
|
-
* execd is ready to accept connections.
|
|
504
|
+
* A channel to run commands in a sandbox, from its provider.
|
|
414
505
|
*
|
|
415
|
-
*
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
*
|
|
419
|
-
* budget before the exec daemon inside it had actually started accepting connections. An
|
|
420
|
-
* isolated repro of the identical fork (same snapshot, but from an idle parent with no
|
|
421
|
-
* concurrent browser load) reached execd-ready in under 400ms -- the parent's own host-resource
|
|
422
|
-
* contention at fork time, not snapshot size, is what actually eats the budget. This can't be
|
|
423
|
-
* fixed by scheduling around it from here, so it's addressed by simply affording much more
|
|
424
|
-
* patience before giving up.
|
|
506
|
+
* The provider owns the wait: it resolves once the sandbox accepts a connection, and rejects with
|
|
507
|
+
* `EXEC_NOT_READY` when it never does. That failure is re-thrown as `ExecConnectionError`, with
|
|
508
|
+
* the cause, the attempt count, and the wait the provider recorded, because that class is the
|
|
509
|
+
* one callers have been catching and it extends `WorkflowError`.
|
|
425
510
|
*/
|
|
426
|
-
async function
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
return client;
|
|
438
|
-
} catch {
|
|
439
|
-
if (attempt === retries) throw new ExecConnectionError(sandboxId);
|
|
440
|
-
await new Promise((r) => setTimeout(r, delay));
|
|
441
|
-
delay = Math.min(delay * 1.5, delayMs);
|
|
511
|
+
async function resolveExecChannel(provider, sandboxId, options = {}) {
|
|
512
|
+
try {
|
|
513
|
+
return await provider.connectExec(sandboxId, options);
|
|
514
|
+
} catch (err) {
|
|
515
|
+
if (errorCodeOf$1(err) !== "EXEC_NOT_READY") throw err;
|
|
516
|
+
const details = err.details;
|
|
517
|
+
throw new ExecConnectionError(sandboxId, {
|
|
518
|
+
cause: err.cause ?? err,
|
|
519
|
+
attempts: details?.attempts,
|
|
520
|
+
waitedMs: details?.waitedMs
|
|
521
|
+
});
|
|
442
522
|
}
|
|
443
|
-
throw new Error("unreachable");
|
|
444
523
|
}
|
|
445
524
|
//#endregion
|
|
446
525
|
//#region src/sandbox/bash-session.ts
|
|
@@ -492,6 +571,10 @@ var BashSession = class {
|
|
|
492
571
|
*/
|
|
493
572
|
var SandboxCore = class {
|
|
494
573
|
sandboxId;
|
|
574
|
+
/** The id of the sandbox provider that owns this sandbox (`"opensandbox"`). */
|
|
575
|
+
get provider() {
|
|
576
|
+
return this.deps.provider.id;
|
|
577
|
+
}
|
|
495
578
|
name;
|
|
496
579
|
deps;
|
|
497
580
|
/** Cached exec results for replay mode (populated by `Sandbox.resume()`). */
|
|
@@ -545,46 +628,49 @@ var SandboxCore = class {
|
|
|
545
628
|
nextSeq() {
|
|
546
629
|
return ++this._seq;
|
|
547
630
|
}
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
631
|
+
/**
|
|
632
|
+
* The channel to this sandbox's `execd`, connecting if there is none yet. `signal` stops the
|
|
633
|
+
* wait for a sandbox that is slow to accept a connection. It does not close a channel that was
|
|
634
|
+
* already connected.
|
|
635
|
+
*/
|
|
636
|
+
async getExecClient(signal) {
|
|
637
|
+
if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId, "SANDBOX_PAUSED");
|
|
638
|
+
this._execClient ??= await resolveExecChannel(this.deps.provider, this.sandboxId, { signal });
|
|
551
639
|
return this._execClient;
|
|
552
640
|
}
|
|
553
|
-
/** Resolve a fresh
|
|
641
|
+
/** Resolve a fresh terminal channel for a new interactive session. Reuses `getExecClient()`'s readiness wait. */
|
|
554
642
|
async resolvePtyClient() {
|
|
555
|
-
if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId);
|
|
643
|
+
if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId, "SANDBOX_PAUSED");
|
|
556
644
|
await this.getExecClient();
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
accessToken: token
|
|
563
|
-
});
|
|
645
|
+
if (!this.deps.provider.connectPty) throw new SandboxError(`The ${this.deps.provider.id} provider has no interactive terminal`, this.sandboxId, "CAPABILITY_UNSUPPORTED", { details: {
|
|
646
|
+
capability: "pty",
|
|
647
|
+
provider: this.deps.provider.id
|
|
648
|
+
} });
|
|
649
|
+
return this.deps.provider.connectPty(this.sandboxId);
|
|
564
650
|
}
|
|
565
651
|
async waitForRunning(timeoutMs = 12e4) {
|
|
566
652
|
const deadline = Date.now() + timeoutMs;
|
|
567
653
|
let delay = 100;
|
|
568
654
|
while (Date.now() < deadline) {
|
|
569
|
-
const s = await this.deps.
|
|
570
|
-
if (s.
|
|
571
|
-
if (s.
|
|
655
|
+
const s = await this.deps.provider.getSandbox(this.sandboxId);
|
|
656
|
+
if (s.state === "running") return;
|
|
657
|
+
if (s.state === "failed" || s.state === "terminated") throw new SandboxError(`SandboxHandle entered ${s.nativeState ?? s.state}: ${s.message ?? ""}`, this.sandboxId, "SANDBOX_START_FAILED");
|
|
572
658
|
await new Promise((r) => setTimeout(r, delay));
|
|
573
659
|
delay = Math.min(delay * 1.5, 1e3);
|
|
574
660
|
}
|
|
575
|
-
throw new SandboxError(`SandboxHandle did not reach Running within ${timeoutMs}ms`, this.sandboxId);
|
|
661
|
+
throw new SandboxError(`SandboxHandle did not reach Running within ${timeoutMs}ms`, this.sandboxId, "SANDBOX_START_TIMEOUT");
|
|
576
662
|
}
|
|
577
663
|
async waitForSnapshot(snapshotId, timeoutMs = 12e4) {
|
|
578
664
|
const deadline = Date.now() + timeoutMs;
|
|
579
665
|
let delay = 100;
|
|
580
666
|
while (Date.now() < deadline) {
|
|
581
|
-
const snap = await this.deps.
|
|
582
|
-
if (snap.state ===
|
|
583
|
-
if (snap.state ===
|
|
667
|
+
const snap = await this.deps.provider.getSnapshot(snapshotId);
|
|
668
|
+
if (snap.state === "ready") return;
|
|
669
|
+
if (snap.state === "failed") throw new SandboxError(`Snapshot ${snapshotId} failed`, this.sandboxId, "SNAPSHOT_FAILED");
|
|
584
670
|
await new Promise((r) => setTimeout(r, delay));
|
|
585
671
|
delay = Math.min(delay * 1.5, 2e3);
|
|
586
672
|
}
|
|
587
|
-
throw new SandboxError(`Snapshot ${snapshotId} did not become ready within ${timeoutMs}ms`, this.sandboxId);
|
|
673
|
+
throw new SandboxError(`Snapshot ${snapshotId} did not become ready within ${timeoutMs}ms`, this.sandboxId, "SNAPSHOT_TIMEOUT");
|
|
588
674
|
}
|
|
589
675
|
emit(event, stepIndex, payload) {
|
|
590
676
|
const ts = Date.now();
|
|
@@ -623,37 +709,43 @@ var SandboxCore = class {
|
|
|
623
709
|
});
|
|
624
710
|
const self = this;
|
|
625
711
|
async function* stream() {
|
|
626
|
-
|
|
712
|
+
opts.signal?.throwIfAborted();
|
|
713
|
+
const baseClient = await self.getExecClient(opts.signal);
|
|
627
714
|
await self.emit("exec.started", seq, {
|
|
628
715
|
cmd,
|
|
629
716
|
seq
|
|
630
717
|
});
|
|
631
718
|
self.deps.hooks?.onExecStart?.(self.sandboxId, seq, cmd);
|
|
632
|
-
const
|
|
633
|
-
const
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
})
|
|
644
|
-
|
|
719
|
+
const execClient = opts.signal ? baseClient.withSignal(opts.signal) : baseClient;
|
|
720
|
+
const interrupt = () => void baseClient.interruptCommand().catch(() => {});
|
|
721
|
+
opts.signal?.addEventListener("abort", interrupt, { once: true });
|
|
722
|
+
try {
|
|
723
|
+
const sh = opts.shell ?? self.deps.shell ?? "/bin/sh";
|
|
724
|
+
const command = `echo ${Buffer.from(cmd).toString("base64")} | base64 -d | ${sh}`;
|
|
725
|
+
for await (const ev of execClient.executeCommand({
|
|
726
|
+
command,
|
|
727
|
+
cwd: opts.cwd,
|
|
728
|
+
envs: opts.env,
|
|
729
|
+
timeout: opts.timeoutMs
|
|
730
|
+
})) {
|
|
731
|
+
await self.emit("exec.output", seq, {
|
|
732
|
+
seq,
|
|
733
|
+
...ev
|
|
734
|
+
});
|
|
735
|
+
yield ev;
|
|
736
|
+
}
|
|
737
|
+
} finally {
|
|
738
|
+
opts.signal?.removeEventListener("abort", interrupt);
|
|
645
739
|
}
|
|
646
740
|
}
|
|
647
741
|
return new ExecHandle({
|
|
648
742
|
type: "stream",
|
|
649
743
|
gen: stream(),
|
|
744
|
+
timeoutMs: opts.timeoutMs,
|
|
650
745
|
onDone: async (result) => {
|
|
651
|
-
await self.emit("exec.completed", seq,
|
|
652
|
-
exitCode: result.exitCode,
|
|
653
|
-
seq
|
|
654
|
-
});
|
|
746
|
+
await self.emit("exec.completed", seq, execCompletedPayload(result, seq));
|
|
655
747
|
self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
|
|
656
|
-
if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId);
|
|
748
|
+
if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId, result);
|
|
657
749
|
}
|
|
658
750
|
});
|
|
659
751
|
}
|
|
@@ -729,7 +821,7 @@ var SandboxCore = class {
|
|
|
729
821
|
seq
|
|
730
822
|
});
|
|
731
823
|
self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
|
|
732
|
-
if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId);
|
|
824
|
+
if (opts.strict !== false && result.exitCode !== 0) throw new CommandError(result.exitCode, cmd, self.sandboxId, result);
|
|
733
825
|
}
|
|
734
826
|
}, {
|
|
735
827
|
write: (data) => {
|
|
@@ -873,7 +965,7 @@ var SandboxCore = class {
|
|
|
873
965
|
seq
|
|
874
966
|
});
|
|
875
967
|
self.deps.hooks?.onExecComplete?.(self.sandboxId, seq, result);
|
|
876
|
-
if (result.exitCode !== 0) throw new CommandError(result.exitCode, command, self.sandboxId);
|
|
968
|
+
if (result.exitCode !== 0) throw new CommandError(result.exitCode, command, self.sandboxId, result);
|
|
877
969
|
}
|
|
878
970
|
});
|
|
879
971
|
};
|
|
@@ -885,6 +977,22 @@ var SandboxCore = class {
|
|
|
885
977
|
return new BashSession(sessionId, execInSession, closeSession);
|
|
886
978
|
}
|
|
887
979
|
};
|
|
980
|
+
/**
|
|
981
|
+
* What `exec.completed` records. The optional fields appear only when they say something, so a
|
|
982
|
+
* row for an ordinary command is the same as it was before they existed.
|
|
983
|
+
*/
|
|
984
|
+
function execCompletedPayload(result, seq) {
|
|
985
|
+
return {
|
|
986
|
+
exitCode: result.exitCode,
|
|
987
|
+
seq,
|
|
988
|
+
...result.durationMs !== void 0 ? { durationMs: result.durationMs } : {},
|
|
989
|
+
...result.killed ? {
|
|
990
|
+
killed: true,
|
|
991
|
+
signal: result.signal
|
|
992
|
+
} : {},
|
|
993
|
+
...result.timedOut ? { timedOut: true } : {}
|
|
994
|
+
};
|
|
995
|
+
}
|
|
888
996
|
//#endregion
|
|
889
997
|
//#region src/sandbox/files.ts
|
|
890
998
|
/** Write a file into the sandbox. */
|
|
@@ -960,6 +1068,27 @@ async function replaceInFiles(sb, replacements) {
|
|
|
960
1068
|
await (await sb.getExecClient()).replaceInFiles(replacements);
|
|
961
1069
|
}
|
|
962
1070
|
//#endregion
|
|
1071
|
+
//#region src/sandbox/capabilities.ts
|
|
1072
|
+
/**
|
|
1073
|
+
* Throw `CAPABILITY_UNSUPPORTED`, naming the capability and the provider, when the provider
|
|
1074
|
+
* declares it cannot do something.
|
|
1075
|
+
*
|
|
1076
|
+
* Only an explicit `false` is a refusal. `"unverified"` (configured, not proven) goes ahead and
|
|
1077
|
+
* may still fail at the call, and a provider with no descriptor, which is what a test double
|
|
1078
|
+
* usually is, is not second-guessed.
|
|
1079
|
+
*
|
|
1080
|
+
* This is the early failure: a spec that needs egress, or a `checkpoint()` on a provider that
|
|
1081
|
+
* cannot snapshot, is refused before anything is created or sent, with a message that names the
|
|
1082
|
+
* missing capability instead of a failure three calls later that reads like a bad spec.
|
|
1083
|
+
*/
|
|
1084
|
+
function requireCapability(provider, capability, sandboxId) {
|
|
1085
|
+
if (provider.descriptor?.capabilities?.[capability] !== false) return;
|
|
1086
|
+
throw new SandboxError(`The ${provider.id} provider does not support ${capability}`, sandboxId, "CAPABILITY_UNSUPPORTED", { details: {
|
|
1087
|
+
capability,
|
|
1088
|
+
provider: provider.id
|
|
1089
|
+
} });
|
|
1090
|
+
}
|
|
1091
|
+
//#endregion
|
|
963
1092
|
//#region src/sandbox/lifecycle.ts
|
|
964
1093
|
/** Return all checkpoints for this sandbox in creation order. */
|
|
965
1094
|
function listCheckpoints(sb) {
|
|
@@ -973,7 +1102,8 @@ function listCheckpoints(sb) {
|
|
|
973
1102
|
* `close()` remains valid on a paused sandbox.
|
|
974
1103
|
*/
|
|
975
1104
|
async function pause(sb) {
|
|
976
|
-
|
|
1105
|
+
requireCapability(sb.deps.provider, "pause", sb.sandboxId);
|
|
1106
|
+
await sb.deps.provider.pauseSandbox(sb.sandboxId);
|
|
977
1107
|
sb.setPaused(true);
|
|
978
1108
|
sb.disposeExecClient();
|
|
979
1109
|
sb.clearExecClient();
|
|
@@ -990,7 +1120,8 @@ async function pause(sb) {
|
|
|
990
1120
|
* Polls until the sandbox reports Running before returning.
|
|
991
1121
|
*/
|
|
992
1122
|
async function resume(sb) {
|
|
993
|
-
|
|
1123
|
+
requireCapability(sb.deps.provider, "pause", sb.sandboxId);
|
|
1124
|
+
await sb.deps.provider.resumeSandbox(sb.sandboxId);
|
|
994
1125
|
sb.setPaused(false);
|
|
995
1126
|
await sb.waitForRunning();
|
|
996
1127
|
await sb.emit("sandbox.resumed", -1);
|
|
@@ -1004,7 +1135,8 @@ async function resume(sb) {
|
|
|
1004
1135
|
* the latest checkpoint, or pass the returned ID to `Sandbox.restoreSnapshot()`.
|
|
1005
1136
|
*/
|
|
1006
1137
|
async function checkpoint(sb, name) {
|
|
1007
|
-
|
|
1138
|
+
requireCapability(sb.deps.provider, "snapshot", sb.sandboxId);
|
|
1139
|
+
const snap = await sb.deps.provider.createSnapshot(sb.sandboxId);
|
|
1008
1140
|
await sb.waitForSnapshot(snap.id);
|
|
1009
1141
|
await sb.emit("sandbox.checkpoint_created", -1, {
|
|
1010
1142
|
snapshotId: snap.id,
|
|
@@ -1043,8 +1175,9 @@ async function checkpoint(sb, name) {
|
|
|
1043
1175
|
* of `opts.resourceId` — pass either, both, or neither.
|
|
1044
1176
|
*/
|
|
1045
1177
|
async function fork(sb, tag, runId, opts) {
|
|
1046
|
-
if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId);
|
|
1047
|
-
|
|
1178
|
+
if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId, "CAPABILITY_UNSUPPORTED", { details: { capability: "fork" } });
|
|
1179
|
+
requireCapability(sb.deps.provider, "snapshot", sb.sandboxId);
|
|
1180
|
+
const snap = await sb.deps.provider.createSnapshot(sb.sandboxId);
|
|
1048
1181
|
await sb.waitForSnapshot(snap.id);
|
|
1049
1182
|
await sb.emit("sandbox.checkpoint_created", -1, {
|
|
1050
1183
|
snapshotId: snap.id,
|
|
@@ -1082,7 +1215,7 @@ async function close(sb) {
|
|
|
1082
1215
|
sb.openSessionClosers.clear();
|
|
1083
1216
|
sb.disposeExecClient();
|
|
1084
1217
|
try {
|
|
1085
|
-
await sb.deps.
|
|
1218
|
+
await sb.deps.provider.deleteSandbox(sb.sandboxId);
|
|
1086
1219
|
} finally {
|
|
1087
1220
|
await sb.emit("sandbox.closed", -1);
|
|
1088
1221
|
sb.deps.hooks?.onSandboxClosed?.(sb.sandboxId);
|
|
@@ -1106,17 +1239,17 @@ async function* watchMetrics(sb) {
|
|
|
1106
1239
|
const ec = await sb.getExecClient();
|
|
1107
1240
|
for await (const ev of ec.watchMetrics()) if (isMetrics(ev)) yield ev;
|
|
1108
1241
|
}
|
|
1109
|
-
/** `
|
|
1242
|
+
/** `watchMetrics()` types every event payload as an `ExecEvent`; this checks it's actually metrics. */
|
|
1110
1243
|
function isMetrics(ev) {
|
|
1111
1244
|
return "cpu" in ev && typeof ev.cpu === "number" && "memory" in ev && typeof ev.memory === "number";
|
|
1112
1245
|
}
|
|
1113
1246
|
/** Return sandbox diagnostic logs (names, sizes, and optional inline content). */
|
|
1114
1247
|
async function diagnosticLogs(sb) {
|
|
1115
|
-
return sb.deps.
|
|
1248
|
+
return sb.deps.provider.getDiagnosticLogs(sb.sandboxId);
|
|
1116
1249
|
}
|
|
1117
1250
|
/** Return sandbox diagnostic events (timestamps, types, and messages). */
|
|
1118
1251
|
async function diagnosticEvents(sb) {
|
|
1119
|
-
return sb.deps.
|
|
1252
|
+
return sb.deps.provider.getDiagnosticEvents(sb.sandboxId);
|
|
1120
1253
|
}
|
|
1121
1254
|
/**
|
|
1122
1255
|
* Return a proxied URL and auth headers for a port inside the sandbox.
|
|
@@ -1124,7 +1257,7 @@ async function diagnosticEvents(sb) {
|
|
|
1124
1257
|
* Use this to send HTTP requests to a server running inside the sandbox.
|
|
1125
1258
|
*/
|
|
1126
1259
|
async function proxy(sb, port) {
|
|
1127
|
-
const ep = await sb.deps.
|
|
1260
|
+
const ep = await sb.deps.provider.getEndpoint(sb.sandboxId, port);
|
|
1128
1261
|
return {
|
|
1129
1262
|
url: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
|
|
1130
1263
|
headers: ep.headers ?? {}
|
|
@@ -1134,7 +1267,7 @@ async function proxy(sb, port) {
|
|
|
1134
1267
|
//#region src/sandbox/credentials.ts
|
|
1135
1268
|
function requireBroker(sb) {
|
|
1136
1269
|
const broker = sb.deps.credentialBroker;
|
|
1137
|
-
if (!broker) throw new SandboxError("No CredentialBroker configured — pass credentialProxy: true to client.sandbox() (and ensure the OpenSandbox server has egress.image configured) to use sb.credentials.*", sb.sandboxId);
|
|
1270
|
+
if (!broker) throw new SandboxError("No CredentialBroker configured — pass credentialProxy: true to client.sandbox() (and ensure the OpenSandbox server has egress.image configured) to use sb.credentials.*", sb.sandboxId, "CAPABILITY_UNSUPPORTED", { details: { capability: "credentials" } });
|
|
1138
1271
|
return broker;
|
|
1139
1272
|
}
|
|
1140
1273
|
/**
|
|
@@ -1186,8 +1319,15 @@ async function listBindings(sb) {
|
|
|
1186
1319
|
}
|
|
1187
1320
|
//#endregion
|
|
1188
1321
|
//#region src/sandbox/egress.ts
|
|
1322
|
+
/** The provider's egress control, or a typed error when it has none. */
|
|
1189
1323
|
function client(sb) {
|
|
1190
|
-
|
|
1324
|
+
requireCapability(sb.deps.provider, "egress", sb.sandboxId);
|
|
1325
|
+
const egress = sb.deps.provider.egress;
|
|
1326
|
+
if (!egress) throw new SandboxError(`The ${sb.deps.provider.id} provider cannot change a sandbox's egress rules at runtime`, sb.sandboxId, "CAPABILITY_UNSUPPORTED", { details: {
|
|
1327
|
+
capability: "egress",
|
|
1328
|
+
provider: sb.deps.provider.id
|
|
1329
|
+
} });
|
|
1330
|
+
return egress;
|
|
1191
1331
|
}
|
|
1192
1332
|
/**
|
|
1193
1333
|
* Merge allow/deny rules into this sandbox's live egress policy. An incoming rule replaces
|
|
@@ -1580,4 +1720,4 @@ function composeHooks(hooks, opts = {}) {
|
|
|
1580
1720
|
};
|
|
1581
1721
|
}
|
|
1582
1722
|
//#endregion
|
|
1583
|
-
export { BashSession, CommandError, ConsoleLogger, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, reconstructBoundCredentials, reconstructEgressRules, resolveBoundCredential,
|
|
1723
|
+
export { AlineoError, BashSession, CommandError, ConsoleLogger, DEFAULT_PROVIDER_ID, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, errorCodeOf, isRetryable, noopLogger, reconstructBoundCredentials, reconstructEgressRules, requireCapability, resolveBoundCredential, resolveExecChannel };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alineo-labs/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -29,9 +29,10 @@
|
|
|
29
29
|
"test:watch": "vitest"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
+
"@alineo-labs/errors": "0.1.0",
|
|
32
33
|
"@alineo-labs/logger": "0.1.0",
|
|
33
|
-
"@alineo-labs/
|
|
34
|
-
"@alineo-labs/schema": "0.
|
|
34
|
+
"@alineo-labs/provider": "0.1.0",
|
|
35
|
+
"@alineo-labs/schema": "0.3.0"
|
|
35
36
|
},
|
|
36
37
|
"devDependencies": {
|
|
37
38
|
"bun-types": "1.4.2",
|