@alineo-labs/core 0.3.0 → 0.4.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,8 +1,7 @@
1
- import { CodeContext, CodeLanguage, ControlClient, DiagnosticEvent, DiagnosticEvent as DiagnosticEvent$1, DiagnosticLog, DiagnosticLog as DiagnosticLog$1, ExecClient, FileInfo, FileInfo as FileInfo$1, Metrics, Metrics as Metrics$1, NetworkPolicy, PtyClient, SSEEvent } from "@alineo-labs/opensandbox";
2
-
1
+ import { CodeContext, CodeLanguage, ControlClient, DiagnosticEvent, DiagnosticEvent as DiagnosticEvent$1, DiagnosticLog, DiagnosticLog as DiagnosticLog$1, EgressPolicyStatus, ExecClient, FileInfo, FileInfo as FileInfo$1, Metrics, Metrics as Metrics$1, NetworkPolicy, NetworkRule, PtyClient, SSEEvent } from "@alineo-labs/opensandbox";
3
2
  //#region src/ledger.d.ts
4
3
  /** Status of a sandbox session derived from its ledger events. */
5
- declare enum SandboxStatus {
4
+ export declare enum SandboxStatus {
6
5
  Running = "running",
7
6
  Completed = "completed"
8
7
  }
@@ -69,7 +68,7 @@ interface ListSandboxOptions {
69
68
  teamId?: string;
70
69
  }
71
70
  /** Events emitted during execution and stored in the ledger. */
72
- declare enum LedgerEvent {
71
+ export declare enum LedgerEvent {
73
72
  /** Emitted when a sandbox is created and reaches Running state. */
74
73
  SandboxCreated = "sandbox_created",
75
74
  /** Emitted at the start of each exec() or execCode() call. */
@@ -93,6 +92,27 @@ declare enum LedgerEvent {
93
92
  CredentialBound = "credential_bound",
94
93
  /** Emitted by `sb.credentials.remove()`. */
95
94
  CredentialRevoked = "credential_revoked",
95
+ /**
96
+ * Emitted by `sb.egress.patch()`. Payload is `{ rules: NetworkRule[] }` — the exact rules
97
+ * passed to the sidecar, so `Sandbox.resume()` can fold a still-wanted allowance back into
98
+ * the resumed sandbox's boot policy (egress policy is sidecar-local and does not survive a
99
+ * resume). `sb.fork()` does not carry these.
100
+ */
101
+ EgressRuleAdded = "egress_rule_added",
102
+ /** Emitted by `sb.egress.delete()`. Payload is `{ targets: string[] }`. */
103
+ EgressRuleRemoved = "egress_rule_removed",
104
+ /**
105
+ * Emitted when the permission gate pauses a tool call for human approval. Payload is
106
+ * `{ requestId, tool, target }` — metadata only; the raw tool arguments (which can carry
107
+ * secrets in a bash command or a file write) are never written to the ledger.
108
+ */
109
+ PermissionRequested = "permission_requested",
110
+ /**
111
+ * Emitted when a `PermissionRequested` is answered — by a caller, a batched
112
+ * always/reject decision, a timeout, or a session resume dropping it. Payload is
113
+ * `{ requestId, decision }`.
114
+ */
115
+ PermissionResolved = "permission_resolved",
96
116
  /** Emitted once when a workflow run starts, before any steps execute. */
97
117
  RunStarted = "run_started",
98
118
  /** Emitted at the beginning of each step. */
@@ -197,7 +217,7 @@ interface IStorageAdapter {
197
217
  }
198
218
  //#endregion
199
219
  //#region src/logger.d.ts
200
- declare enum LogLevel {
220
+ export declare enum LogLevel {
201
221
  Debug = 0,
202
222
  Info = 1,
203
223
  Warn = 2,
@@ -210,7 +230,7 @@ interface ILogger {
210
230
  warn(msg: string, meta?: Record<string, unknown>): void;
211
231
  error(msg: string, meta?: Record<string, unknown>): void;
212
232
  }
213
- declare class ConsoleLogger implements ILogger {
233
+ export declare class ConsoleLogger implements ILogger {
214
234
  private readonly minLevel;
215
235
  constructor(minLevel?: LogLevel);
216
236
  private log;
@@ -219,9 +239,29 @@ declare class ConsoleLogger implements ILogger {
219
239
  warn(msg: string, meta?: Record<string, unknown>): void;
220
240
  error(msg: string, meta?: Record<string, unknown>): void;
221
241
  }
222
- declare const noopLogger: ILogger;
242
+ export declare const noopLogger: ILogger;
223
243
  //#endregion
224
244
  //#region src/credentials.d.ts
245
+ /**
246
+ * How a credential reaches an outbound request.
247
+ *
248
+ * - `header` — the sidecar adds the header `name: <value>` (value unprefixed; use it for
249
+ * `Authorization`, `X-API-Key`, etc.). The common case.
250
+ * - `substitution` — the sidecar replaces every literal occurrence of `placeholder` in the
251
+ * listed request surfaces with the value. **The request must already contain `placeholder`
252
+ * verbatim** — the agent or its config puts it there (e.g. a base URL of
253
+ * `https://api.example.com/v1?key=__API_KEY__`). This is the escape hatch for APIs that
254
+ * only take a key in the URL; `path`/`query` values are URL-encoded, `body` is encoded per
255
+ * content-type.
256
+ */
257
+ type CredentialInjection = {
258
+ type: "header";
259
+ name: string;
260
+ } | {
261
+ type: "substitution";
262
+ placeholder: string;
263
+ in: Array<"path" | "query" | "header" | "body">;
264
+ };
225
265
  /**
226
266
  * Where and how a credential is injected into outbound requests. Matched by `host` (an FQDN
227
267
  * or wildcard domain, e.g. `"api.github.com"` or `"*.openai.com"`) and, optionally, a
@@ -233,16 +273,7 @@ interface CredentialBinding {
233
273
  /** Narrows the binding to requests whose path starts with this prefix. */
234
274
  pathPrefix?: string;
235
275
  /** How the credential reaches the request. */
236
- injection: {
237
- type: "header";
238
- name: string;
239
- } | {
240
- type: "query";
241
- param: string;
242
- } | {
243
- type: "path";
244
- segment: string;
245
- };
276
+ injection: CredentialInjection;
246
277
  }
247
278
  /**
248
279
  * Where a credential's *value* comes from — orthogonal to `CredentialBinding` (which only
@@ -298,7 +329,7 @@ type CredentialResolver = (name: string, source: CredentialSource) => string | u
298
329
  * silently dropping the credential (the previous behavior when no resolver was supplied at
299
330
  * all — see plans/credential-injection.md).
300
331
  */
301
- declare function resolveBoundCredential(name: string, source: CredentialSource | undefined, resolver: CredentialResolver | undefined, sandboxId: string): Promise<string>;
332
+ export declare function resolveBoundCredential(name: string, source: CredentialSource | undefined, resolver: CredentialResolver | undefined, sandboxId: string): Promise<string>;
302
333
  /** One credential's reconstructed state, as recovered from ledger history by `reconstructBoundCredentials()`. */
303
334
  interface BoundCredential {
304
335
  binding: CredentialBinding;
@@ -311,7 +342,34 @@ interface BoundCredential {
311
342
  * operation. Scans the *whole* history, not just some replay window — credential bindings
312
343
  * aren't tied to specific execs the way exec replay is.
313
344
  */
314
- declare function reconstructBoundCredentials(entries: LedgerEntry[]): Map<string, BoundCredential>;
345
+ export declare function reconstructBoundCredentials(entries: LedgerEntry[]): Map<string, BoundCredential>;
346
+ //#endregion
347
+ //#region src/egress.d.ts
348
+ /** The still-live outcome of a session's runtime `sb.egress.*` calls. */
349
+ interface ReconstructedEgress {
350
+ /** Rules to (re-)apply — a later add for the same target supersedes an earlier one. */
351
+ apply: NetworkRule[];
352
+ /**
353
+ * Targets a `sb.egress.delete()` removed and no later `patch()` re-added — these must be
354
+ * dropped from the resumed sandbox's boot policy too, not just from the runtime deltas
355
+ * (a `delete()` of a rule that came from the *original* `networkPolicy` would otherwise be
356
+ * silently undone on resume).
357
+ */
358
+ remove: string[];
359
+ }
360
+ /**
361
+ * Reconstruct, from a session's ledger history, what its runtime `sb.egress.patch()` /
362
+ * `sb.egress.delete()` calls still amount to. Egress policy is sidecar-local runtime state —
363
+ * it does not survive the sidecar restarting and is not restored by OpenSandbox's
364
+ * snapshot/checkpoint — so `Sandbox.resume()` folds this back into the resumed sandbox's boot
365
+ * `networkPolicy`.
366
+ *
367
+ * Keyed by `target` (the sidecar's own merge key): a later add for a target wins; a later
368
+ * delete removes it (and is reported in `remove` so a boot-policy rule can be dropped too);
369
+ * a re-add after a delete brings it back. Scans the whole history, like
370
+ * `reconstructBoundCredentials`.
371
+ */
372
+ export declare function reconstructEgressRules(entries: LedgerEntry[]): ReconstructedEgress;
315
373
  //#endregion
316
374
  //#region src/exec-handle.d.ts
317
375
  interface ExecResult {
@@ -327,8 +385,10 @@ type ExecDriver = {
327
385
  type: "replay";
328
386
  result: ExecResult;
329
387
  } | {
330
- type: "pty"; /** Output already recorded before this handle was created (e.g. resumed from ledger) — shown as scrollback before live output resumes. */
331
- seedStdout?: string; /** Wire up push-based output/exit/failure callbacks. Called once, synchronously. */
388
+ type: "pty";
389
+ /** Output already recorded before this handle was created (e.g. resumed from ledger) — shown as scrollback before live output resumes. */
390
+ seedStdout?: string;
391
+ /** Wire up push-based output/exit/failure callbacks. Called once, synchronously. */
332
392
  attach: (push: (chunk: string) => void, finish: (exitCode: number) => void, fail: (err: unknown) => void) => void;
333
393
  onDone: (r: ExecResult) => Promise<void>;
334
394
  };
@@ -357,7 +417,7 @@ interface PtyControls {
357
417
  * for await (const chunk of sb.exec("npm test").stdout()) process.stdout.write(chunk);
358
418
  * ```
359
419
  */
360
- declare class ExecHandle implements PromiseLike<ExecResult> {
420
+ export declare class ExecHandle implements PromiseLike<ExecResult> {
361
421
  private readonly _promise;
362
422
  private readonly _chunks;
363
423
  private _wakeup;
@@ -407,7 +467,7 @@ interface AttachableSource {
407
467
  * await sb.exec("bash", { interactive: true }).attach(process.stdin, process.stdout);
408
468
  * ```
409
469
  */
410
- declare class InteractiveExecHandle extends ExecHandle {
470
+ export declare class InteractiveExecHandle extends ExecHandle {
411
471
  private readonly _controls?;
412
472
  constructor(driver: ExecDriver, controls?: PtyControls);
413
473
  /** Send input to the running process. No-op if the session already ended. */
@@ -551,7 +611,7 @@ interface SandboxInternal {
551
611
  *
552
612
  * Create with `sandbox.createSession()`. Always call `close()` when done.
553
613
  */
554
- declare class BashSession {
614
+ export declare class BashSession {
555
615
  /** execd session ID. */
556
616
  readonly sessionId: string;
557
617
  private readonly _execFn;
@@ -728,7 +788,7 @@ declare class SandboxCore implements SandboxInternal {
728
788
  * await sb.close();
729
789
  * ```
730
790
  */
731
- declare class SandboxHandle extends SandboxCore {
791
+ export declare class SandboxHandle extends SandboxCore {
732
792
  /** Write a file into the sandbox. */
733
793
  writeFile(path: string, content: string): Promise<void>;
734
794
  /** Read a file from the sandbox as a UTF-8 string. */
@@ -822,6 +882,27 @@ declare class SandboxHandle extends SandboxCore {
822
882
  binding: CredentialBinding;
823
883
  }>>;
824
884
  };
885
+ /**
886
+ * Adjust this sandbox's outbound network policy at runtime, via its egress sidecar. Only
887
+ * meaningful when the sandbox was created with a `networkPolicy` (otherwise no sidecar is
888
+ * attached and these calls error).
889
+ *
890
+ * `patch` merges rules in (an incoming rule replaces any rule with the same `target`);
891
+ * `delete` removes rules by `target`. Both take effect on the running sidecar immediately
892
+ * and are recorded to the ledger so `resume()`/`fork()` can re-apply a still-wanted change.
893
+ *
894
+ * @example
895
+ * ```ts
896
+ * await sb.egress.patch([{ action: "allow", target: "api.github.com" }]);
897
+ * // …later
898
+ * await sb.egress.delete(["api.github.com"]);
899
+ * ```
900
+ */
901
+ readonly egress: {
902
+ patch: (rules: NetworkRule[]) => Promise<void>;
903
+ delete: (targets: string[]) => Promise<void>;
904
+ get: () => Promise<EgressPolicyStatus>;
905
+ };
825
906
  /**
826
907
  * Stream real-time CPU and memory metrics from execd via SSE.
827
908
  *
@@ -931,7 +1012,7 @@ declare class SandboxHandle extends SandboxCore {
931
1012
  * fixed by scheduling around it from here, so it's addressed by simply affording much more
932
1013
  * patience before giving up.
933
1014
  */
934
- declare function resolveExecClient(control: ControlClient, sandboxId: string, useServerProxy?: boolean, retries?: number, delayMs?: number): Promise<ExecClient>;
1015
+ export declare function resolveExecClient(control: ControlClient, sandboxId: string, useServerProxy?: boolean, retries?: number, delayMs?: number): Promise<ExecClient>;
935
1016
  //#endregion
936
1017
  //#region src/sandbox/hooks.d.ts
937
1018
  interface ComposeHooksOptions {
@@ -965,11 +1046,11 @@ interface ComposeHooksOptions {
965
1046
  * });
966
1047
  * ```
967
1048
  */
968
- declare function composeHooks(hooks: (SandboxHooks | undefined)[], opts?: ComposeHooksOptions): SandboxHooks;
1049
+ export declare function composeHooks(hooks: (SandboxHooks | undefined)[], opts?: ComposeHooksOptions): SandboxHooks;
969
1050
  //#endregion
970
1051
  //#region src/errors.d.ts
971
1052
  /** Base class for all alineo workflow runtime errors. */
972
- declare class WorkflowError extends Error {
1053
+ export declare class WorkflowError extends Error {
973
1054
  constructor(message: string);
974
1055
  }
975
1056
  /**
@@ -977,11 +1058,11 @@ declare class WorkflowError extends Error {
977
1058
  * `Running` state; being paused when an operation requires a live sandbox;
978
1059
  * `fork()` being unsupported on this sandbox; or a snapshot operation failing.
979
1060
  */
980
- declare class SandboxError extends WorkflowError {
1061
+ export declare class SandboxError extends WorkflowError {
981
1062
  /** The sandbox ID, if one was assigned before the failure. */
982
1063
  readonly sandboxId?: string | undefined;
983
- constructor(message: string, /** The sandbox ID, if one was assigned before the failure. */
984
-
1064
+ constructor(message: string,
1065
+ /** The sandbox ID, if one was assigned before the failure. */
985
1066
  sandboxId?: string | undefined);
986
1067
  }
987
1068
  /**
@@ -989,7 +1070,7 @@ declare class SandboxError extends WorkflowError {
989
1070
  * The sandbox is `Running` from the control plane's perspective, but the exec
990
1071
  * daemon is not accepting connections.
991
1072
  */
992
- declare class ExecConnectionError extends WorkflowError {
1073
+ export declare class ExecConnectionError extends WorkflowError {
993
1074
  readonly sandboxId: string;
994
1075
  constructor(sandboxId: string);
995
1076
  }
@@ -1000,7 +1081,7 @@ declare class ExecConnectionError extends WorkflowError {
1000
1081
  * `BashSession.exec()` (a persistent session from `createSession()`), always
1001
1082
  * thrown on non-zero exit; there is no `strict` option for session execs.
1002
1083
  */
1003
- declare class CommandError extends WorkflowError {
1084
+ export declare class CommandError extends WorkflowError {
1004
1085
  readonly exitCode: number;
1005
1086
  readonly command: string;
1006
1087
  readonly sandboxId: string;
@@ -1011,10 +1092,10 @@ declare class CommandError extends WorkflowError {
1011
1092
  * in this codebase. `SandboxOptions.timeout`/`step.timeout` in `@alineo-labs/workflow`
1012
1093
  * bound sandbox container lifetime, which is a related but distinct concept.
1013
1094
  */
1014
- declare class StepTimeoutError extends WorkflowError {
1095
+ export declare class StepTimeoutError extends WorkflowError {
1015
1096
  readonly stepId: string;
1016
1097
  readonly timeoutMs: number;
1017
1098
  constructor(stepId: string, timeoutMs: number);
1018
1099
  }
1019
1100
  //#endregion
1020
- export { type AttachableSource, BashSession, type BoundCredential, type CheckpointInfo, CommandError, type ComposeHooksOptions, ConsoleLogger, type CredentialBinding, type CredentialBroker, type CredentialResolver, type CredentialSource, type DiagnosticEvent, type DiagnosticLog, type EnvironmentRecord, type ExecCodeOptions, ExecConnectionError, ExecHandle, type ExecOptions, type ExecResult, type FileInfo, type ILogger, type IStorageAdapter, InteractiveExecHandle, type LedgerEntry, LedgerEvent, type ListSandboxOptions, LogLevel, type Metrics, type PendingInteractiveExec, type PtyControls, type SandboxDeps, type SandboxDetails, SandboxError, SandboxHandle, type SandboxHooks, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, reconstructBoundCredentials, resolveBoundCredential, resolveExecClient };
1101
+ export type { AttachableSource, BoundCredential, CheckpointInfo, ComposeHooksOptions, CredentialBinding, CredentialBroker, CredentialInjection, CredentialResolver, CredentialSource, DiagnosticEvent, DiagnosticLog, EnvironmentRecord, ExecCodeOptions, ExecOptions, ExecResult, FileInfo, ILogger, IStorageAdapter, LedgerEntry, ListSandboxOptions, Metrics, PendingInteractiveExec, PtyControls, ReconstructedEgress, SandboxDeps, SandboxDetails, SandboxHooks };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { ExecClient, PtyClient, SSEEventType, SandboxState, SnapshotState } from "@alineo-labs/opensandbox";
1
+ import { EgressClient, ExecClient, PtyClient, SSEEventType, SandboxState, SnapshotState } from "@alineo-labs/opensandbox";
2
2
  //#region src/ledger.ts
3
3
  /** Status of a sandbox session derived from its ledger events. */
4
4
  let SandboxStatus = /* @__PURE__ */ function(SandboxStatus) {
@@ -31,6 +31,27 @@ let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
31
31
  LedgerEvent["CredentialBound"] = "credential_bound";
32
32
  /** Emitted by `sb.credentials.remove()`. */
33
33
  LedgerEvent["CredentialRevoked"] = "credential_revoked";
34
+ /**
35
+ * Emitted by `sb.egress.patch()`. Payload is `{ rules: NetworkRule[] }` — the exact rules
36
+ * passed to the sidecar, so `Sandbox.resume()` can fold a still-wanted allowance back into
37
+ * the resumed sandbox's boot policy (egress policy is sidecar-local and does not survive a
38
+ * resume). `sb.fork()` does not carry these.
39
+ */
40
+ LedgerEvent["EgressRuleAdded"] = "egress_rule_added";
41
+ /** Emitted by `sb.egress.delete()`. Payload is `{ targets: string[] }`. */
42
+ LedgerEvent["EgressRuleRemoved"] = "egress_rule_removed";
43
+ /**
44
+ * Emitted when the permission gate pauses a tool call for human approval. Payload is
45
+ * `{ requestId, tool, target }` — metadata only; the raw tool arguments (which can carry
46
+ * secrets in a bash command or a file write) are never written to the ledger.
47
+ */
48
+ LedgerEvent["PermissionRequested"] = "permission_requested";
49
+ /**
50
+ * Emitted when a `PermissionRequested` is answered — by a caller, a batched
51
+ * always/reject decision, a timeout, or a session resume dropping it. Payload is
52
+ * `{ requestId, decision }`.
53
+ */
54
+ LedgerEvent["PermissionResolved"] = "permission_resolved";
34
55
  /** Emitted once when a workflow run starts, before any steps execute. */
35
56
  LedgerEvent["RunStarted"] = "run_started";
36
57
  /** Emitted at the beginning of each step. */
@@ -200,6 +221,41 @@ function reconstructBoundCredentials(entries) {
200
221
  return result;
201
222
  }
202
223
  //#endregion
224
+ //#region src/egress.ts
225
+ /**
226
+ * Reconstruct, from a session's ledger history, what its runtime `sb.egress.patch()` /
227
+ * `sb.egress.delete()` calls still amount to. Egress policy is sidecar-local runtime state —
228
+ * it does not survive the sidecar restarting and is not restored by OpenSandbox's
229
+ * snapshot/checkpoint — so `Sandbox.resume()` folds this back into the resumed sandbox's boot
230
+ * `networkPolicy`.
231
+ *
232
+ * Keyed by `target` (the sidecar's own merge key): a later add for a target wins; a later
233
+ * delete removes it (and is reported in `remove` so a boot-policy rule can be dropped too);
234
+ * a re-add after a delete brings it back. Scans the whole history, like
235
+ * `reconstructBoundCredentials`.
236
+ */
237
+ function reconstructEgressRules(entries) {
238
+ const byTarget = /* @__PURE__ */ new Map();
239
+ const removed = /* @__PURE__ */ new Set();
240
+ for (const entry of entries) if (entry.event === "egress_rule_added") {
241
+ const { rules } = entry.payload;
242
+ for (const rule of rules) {
243
+ byTarget.set(rule.target, rule);
244
+ removed.delete(rule.target);
245
+ }
246
+ } else if (entry.event === "egress_rule_removed") {
247
+ const { targets } = entry.payload;
248
+ for (const target of targets) {
249
+ byTarget.delete(target);
250
+ removed.add(target);
251
+ }
252
+ }
253
+ return {
254
+ apply: [...byTarget.values()],
255
+ remove: [...removed]
256
+ };
257
+ }
258
+ //#endregion
203
259
  //#region src/exec-handle.ts
204
260
  /**
205
261
  * Returned by `SandboxHandle.exec()` and `SandboxHandle.execCode()`.
@@ -413,9 +469,11 @@ var InteractiveExecHandle = class extends ExecHandle {
413
469
  */
414
470
  async function resolveExecClient(control, sandboxId, useServerProxy, retries = 45, delayMs = 2e3) {
415
471
  const ep = await control.getEndpoint(sandboxId, 44772, useServerProxy);
472
+ const baseUrl = ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`;
473
+ const token = ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? "";
416
474
  const client = new ExecClient({
417
- baseUrl: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
418
- accessToken: ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? ""
475
+ baseUrl,
476
+ accessToken: token
419
477
  });
420
478
  let delay = Math.min(100, delayMs);
421
479
  for (let attempt = 0; attempt <= retries; attempt++) try {
@@ -541,9 +599,11 @@ var SandboxCore = class {
541
599
  if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId);
542
600
  await this.getExecClient();
543
601
  const ep = await this.deps.control.getEndpoint(this.sandboxId, 44772, this.deps.useServerProxy);
602
+ const baseUrl = ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`;
603
+ const token = ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? "";
544
604
  return new PtyClient({
545
- baseUrl: ep.endpoint.startsWith("http") ? ep.endpoint : `http://${ep.endpoint}`,
546
- accessToken: ep.headers?.["X-EXECD-ACCESS-TOKEN"] ?? ""
605
+ baseUrl,
606
+ accessToken: token
547
607
  });
548
608
  }
549
609
  async waitForRunning(timeoutMs = 12e4) {
@@ -1060,10 +1120,11 @@ async function metrics(sb) {
1060
1120
  */
1061
1121
  async function* watchMetrics(sb) {
1062
1122
  const ec = await sb.getExecClient();
1063
- for await (const ev of ec.watchMetrics()) {
1064
- const m = ev;
1065
- if (typeof m.cpu === "number" && typeof m.memory === "number") yield m;
1066
- }
1123
+ for await (const ev of ec.watchMetrics()) if (isMetrics(ev)) yield ev;
1124
+ }
1125
+ /** `ExecClient.watchMetrics()` types every SSE payload as `SSEEvent`; this checks it's actually metrics. */
1126
+ function isMetrics(ev) {
1127
+ return "cpu" in ev && typeof ev.cpu === "number" && "memory" in ev && typeof ev.memory === "number";
1067
1128
  }
1068
1129
  /** Return sandbox diagnostic logs (names, sizes, and optional inline content). */
1069
1130
  async function diagnosticLogs(sb) {
@@ -1116,7 +1177,7 @@ async function set(sb, name, value, binding, source) {
1116
1177
  * source-only change against, so changing `source` alone requires re-passing the (possibly
1117
1178
  * unchanged) `binding` too.
1118
1179
  */
1119
- async function patch(sb, name, changes) {
1180
+ async function patch$1(sb, name, changes) {
1120
1181
  await requireBroker(sb).patch(sb.sandboxId, name, {
1121
1182
  value: changes.value,
1122
1183
  binding: changes.binding
@@ -1131,7 +1192,7 @@ async function patch(sb, name, changes) {
1131
1192
  }
1132
1193
  }
1133
1194
  /** Revoke a credential — subsequent matching requests are no longer injected. */
1134
- async function remove(sb, name) {
1195
+ async function remove$1(sb, name) {
1135
1196
  await requireBroker(sb).remove(sb.sandboxId, name);
1136
1197
  await sb.emit("credential_revoked", -1, { name });
1137
1198
  }
@@ -1140,6 +1201,34 @@ async function listBindings(sb) {
1140
1201
  return requireBroker(sb).listBindings(sb.sandboxId);
1141
1202
  }
1142
1203
  //#endregion
1204
+ //#region src/sandbox/egress.ts
1205
+ function client(sb) {
1206
+ return new EgressClient(sb.deps.control, sb.deps.useServerProxy);
1207
+ }
1208
+ /**
1209
+ * Merge allow/deny rules into this sandbox's live egress policy. An incoming rule replaces
1210
+ * any existing rule with the same `target`; every other rule and the `defaultAction` are
1211
+ * untouched. The change is applied to the running sidecar immediately.
1212
+ *
1213
+ * Recorded to the ledger (the rules only, no secrets) so `Sandbox.resume()` can fold a
1214
+ * still-wanted change back into the resumed sandbox's boot policy — egress policy is
1215
+ * sidecar-local and does not survive a resume. (`sb.fork()` does not carry runtime egress
1216
+ * rules: a fork is a fresh branch and gets a wide-open `defaultAction: "allow"` policy.)
1217
+ */
1218
+ async function patch(sb, rules) {
1219
+ await client(sb).patchRules(sb.sandboxId, rules);
1220
+ await sb.emit("egress_rule_added", -1, { rules });
1221
+ }
1222
+ /** Remove egress rules from this sandbox's live policy, by `target`. Unknown targets are ignored. */
1223
+ async function remove(sb, targets) {
1224
+ await client(sb).deleteRules(sb.sandboxId, targets);
1225
+ await sb.emit("egress_rule_removed", -1, { targets });
1226
+ }
1227
+ /** This sandbox's current egress policy, as the sidecar reports it. */
1228
+ async function get(sb) {
1229
+ return client(sb).getPolicy(sb.sandboxId);
1230
+ }
1231
+ //#endregion
1143
1232
  //#region src/sandbox/sandbox.ts
1144
1233
  /**
1145
1234
  * A live sandbox container. Returned by `Sandbox.sandbox()` and `Sandbox.resume()`.
@@ -1258,11 +1347,32 @@ var SandboxHandle = class extends SandboxCore {
1258
1347
  */
1259
1348
  credentials = {
1260
1349
  set: (name, value, binding, source) => set(this, name, value, binding, source),
1261
- patch: (name, changes) => patch(this, name, changes),
1262
- remove: (name) => remove(this, name),
1350
+ patch: (name, changes) => patch$1(this, name, changes),
1351
+ remove: (name) => remove$1(this, name),
1263
1352
  listBindings: () => listBindings(this)
1264
1353
  };
1265
1354
  /**
1355
+ * Adjust this sandbox's outbound network policy at runtime, via its egress sidecar. Only
1356
+ * meaningful when the sandbox was created with a `networkPolicy` (otherwise no sidecar is
1357
+ * attached and these calls error).
1358
+ *
1359
+ * `patch` merges rules in (an incoming rule replaces any rule with the same `target`);
1360
+ * `delete` removes rules by `target`. Both take effect on the running sidecar immediately
1361
+ * and are recorded to the ledger so `resume()`/`fork()` can re-apply a still-wanted change.
1362
+ *
1363
+ * @example
1364
+ * ```ts
1365
+ * await sb.egress.patch([{ action: "allow", target: "api.github.com" }]);
1366
+ * // …later
1367
+ * await sb.egress.delete(["api.github.com"]);
1368
+ * ```
1369
+ */
1370
+ egress = {
1371
+ patch: (rules) => patch(this, rules),
1372
+ delete: (targets) => remove(this, targets),
1373
+ get: () => get(this)
1374
+ };
1375
+ /**
1266
1376
  * Stream real-time CPU and memory metrics from execd via SSE.
1267
1377
  *
1268
1378
  * Holds a long-lived connection — break out of the loop when done to avoid
@@ -1476,4 +1586,4 @@ function composeHooks(hooks, opts = {}) {
1476
1586
  };
1477
1587
  }
1478
1588
  //#endregion
1479
- export { BashSession, CommandError, ConsoleLogger, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, reconstructBoundCredentials, resolveBoundCredential, resolveExecClient };
1589
+ export { BashSession, CommandError, ConsoleLogger, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, reconstructBoundCredentials, reconstructEgressRules, resolveBoundCredential, resolveExecClient };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alineo-labs/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,12 +29,12 @@
29
29
  "test:watch": "vitest"
30
30
  },
31
31
  "dependencies": {
32
- "@alineo-labs/opensandbox": "0.2.0"
32
+ "@alineo-labs/opensandbox": "0.3.0"
33
33
  },
34
34
  "devDependencies": {
35
- "bun-types": "1.3.14",
36
- "tsdown": "0.22.3",
35
+ "bun-types": "1.4.2",
36
+ "tsdown": "0.23.0",
37
37
  "typescript": "6.0.3",
38
- "vitest": "4.1.9"
38
+ "vitest": "5.0.0"
39
39
  }
40
40
  }