@alineo-labs/core 0.2.0 → 0.3.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,4 +1,4 @@
1
- import { ControlClient, DiagnosticEvent, DiagnosticEvent as DiagnosticEvent$1, DiagnosticLog, DiagnosticLog as DiagnosticLog$1, ExecClient, FileInfo, FileInfo as FileInfo$1, Metrics, Metrics as Metrics$1, PtyClient, SSEEvent } from "@alineo-labs/opensandbox";
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
2
 
3
3
  //#region src/ledger.d.ts
4
4
  /** Status of a sandbox session derived from its ledger events. */
@@ -27,6 +27,32 @@ interface SandboxDetails {
27
27
  * the mechanism `client.sandboxes.list({ runId })` correlates on.
28
28
  */
29
29
  runId: string;
30
+ /**
31
+ * Durable resource identity this session's memory should be scoped by — see
32
+ * `@alineo-labs/memory`'s `ResourceRef.resourceId`. Unlike `runId` (present on every
33
+ * session), this is `undefined` unless the caller explicitly set `SandboxOptions.resourceId`.
34
+ * Threaded through the ledger the same way `runId` is (recorded in the `sandbox_created`
35
+ * event's payload, not a dedicated column), and inherited by `resume()`/`fork()`/
36
+ * `restoreSnapshot()` the same way `runId` is.
37
+ */
38
+ resourceId?: string;
39
+ /**
40
+ * Durable team identity this session's memory should be scoped by — see
41
+ * `@alineo-labs/memory`'s `ResourceRef.teamId`. Threaded through the ledger the same way
42
+ * `resourceId` is (recorded in the `sandbox_created` event's payload, not a dedicated
43
+ * column), and inherited by `resume()`/`fork()`/`restoreSnapshot()` the same way. Exists so
44
+ * `episodicRecall()`/`episodicTree()` can be team-scoped — without this, two different
45
+ * teams' sessions sharing a `resourceId` (plausible: `Alineo.resourceRef` defaults
46
+ * `resourceId` to the agent's own name) would have their ledger histories silently merged,
47
+ * since the ledger otherwise has no team concept at all to filter on.
48
+ */
49
+ teamId?: string;
50
+ /**
51
+ * `sandboxId` of the session this one was created from via `sb.fork()`, if any — absent
52
+ * for a top-level `client.sandbox()` session. Lets episodic memory (`@alineo-labs/memory`'s
53
+ * `episodicRecall`) walk a fork lineage rather than only seeing one flat session.
54
+ */
55
+ parentSandboxId?: string;
30
56
  }
31
57
  /** Options for filtering session listings. */
32
58
  interface ListSandboxOptions {
@@ -37,6 +63,10 @@ interface ListSandboxOptions {
37
63
  before?: number;
38
64
  /** Return only sessions belonging to this run — see `SandboxDetails.runId`. */
39
65
  runId?: string;
66
+ /** Return only sessions scoped to this resource — see `SandboxDetails.resourceId`. */
67
+ resourceId?: string;
68
+ /** Return only sessions scoped to this team — see `SandboxDetails.teamId`. */
69
+ teamId?: string;
40
70
  }
41
71
  /** Events emitted during execution and stored in the ledger. */
42
72
  declare enum LedgerEvent {
@@ -56,6 +86,13 @@ declare enum LedgerEvent {
56
86
  SandboxPaused = "sandbox_paused",
57
87
  /** Emitted when resume() restores the container to Running. */
58
88
  SandboxResumed = "sandbox_resumed",
89
+ /**
90
+ * Emitted by `sb.credentials.set()`/`.patch()`. Payload is binding metadata only
91
+ * (name, host, injection type) — the credential value is never written to the ledger.
92
+ */
93
+ CredentialBound = "credential_bound",
94
+ /** Emitted by `sb.credentials.remove()`. */
95
+ CredentialRevoked = "credential_revoked",
59
96
  /** Emitted once when a workflow run starts, before any steps execute. */
60
97
  RunStarted = "run_started",
61
98
  /** Emitted at the beginning of each step. */
@@ -184,6 +221,98 @@ declare class ConsoleLogger implements ILogger {
184
221
  }
185
222
  declare const noopLogger: ILogger;
186
223
  //#endregion
224
+ //#region src/credentials.d.ts
225
+ /**
226
+ * Where and how a credential is injected into outbound requests. Matched by `host` (an FQDN
227
+ * or wildcard domain, e.g. `"api.github.com"` or `"*.openai.com"`) and, optionally, a
228
+ * `pathPrefix` to further scope the binding within that host.
229
+ */
230
+ interface CredentialBinding {
231
+ /** FQDN or wildcard domain this credential applies to. */
232
+ host: string;
233
+ /** Narrows the binding to requests whose path starts with this prefix. */
234
+ pathPrefix?: string;
235
+ /** 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
+ };
246
+ }
247
+ /**
248
+ * Where a credential's *value* comes from — orthogonal to `CredentialBinding` (which only
249
+ * describes where it gets injected). Persisted in the ledger alongside the binding (metadata
250
+ * only, never the value itself) so `resume()`/`fork()` know how to re-supply it later.
251
+ *
252
+ * `"env"` resolves automatically from `process.env` — no caller code needed. `"external"`
253
+ * means the value isn't re-derivable from anything alineo can see on its own (a one-time
254
+ * minted token, a value generated at call time, ...) — resolving one requires an explicit
255
+ * `CredentialResolver` at resume/fork time, and `resolveBoundCredential()` throws rather than
256
+ * silently proceeding if one isn't supplied.
257
+ */
258
+ type CredentialSource = {
259
+ type: "env";
260
+ varName: string;
261
+ } | {
262
+ type: "external";
263
+ ref?: string;
264
+ };
265
+ /**
266
+ * Persistence-agnostic contract for registering credentials that get injected into a sandbox's
267
+ * outbound requests without the sandbox process ever holding the real value — mirrors
268
+ * `IStorageAdapter`'s shape. `alineo` ships `OpenSandboxCredentialBroker` (from
269
+ * `@alineo-labs/vault`) as the default/only implementation today.
270
+ *
271
+ * Implementations must never surface the raw `value` passed to `set()`/`patch()` back out of
272
+ * any other method — `listBindings()` in particular returns binding *shape* only, so callers
273
+ * (e.g. `Sandbox.resume()`) can know what to re-register without alineo itself ever needing to
274
+ * persist a secret.
275
+ */
276
+ interface CredentialBroker {
277
+ /** Register (or replace) a named credential's value and where it gets injected. */
278
+ set(sandboxId: string, name: string, value: string, binding: CredentialBinding): Promise<void>;
279
+ /** Update a binding's injection rule and/or value without needing to resupply both. */
280
+ patch(sandboxId: string, name: string, changes: Partial<{
281
+ value: string;
282
+ binding: CredentialBinding;
283
+ }>): Promise<void>;
284
+ /** Revoke a credential — subsequent matching requests are no longer injected. */
285
+ remove(sandboxId: string, name: string): Promise<void>;
286
+ /** List binding metadata (host/injection shape) for a sandbox — never returns values. */
287
+ listBindings(sandboxId: string): Promise<Array<{
288
+ name: string;
289
+ binding: CredentialBinding;
290
+ }>>;
291
+ }
292
+ /** Resolves a bound credential's real value, given its name and `CredentialSource`, at resume/fork time. */
293
+ type CredentialResolver = (name: string, source: CredentialSource) => string | undefined | Promise<string | undefined>;
294
+ /**
295
+ * Resolves a bound credential's value: `type: "env"` sources resolve automatically from
296
+ * `process.env`; anything else — or an env var that's since become unset — falls back to the
297
+ * caller-supplied `resolver`. Throws `SandboxError` if neither yields a value, rather than
298
+ * silently dropping the credential (the previous behavior when no resolver was supplied at
299
+ * all — see plans/credential-injection.md).
300
+ */
301
+ declare function resolveBoundCredential(name: string, source: CredentialSource | undefined, resolver: CredentialResolver | undefined, sandboxId: string): Promise<string>;
302
+ /** One credential's reconstructed state, as recovered from ledger history by `reconstructBoundCredentials()`. */
303
+ interface BoundCredential {
304
+ binding: CredentialBinding;
305
+ source?: CredentialSource;
306
+ }
307
+ /**
308
+ * Reconstructs the latest bound/revoked state per credential name from a session's ledger
309
+ * history — used by both `Sandbox.resume()` and `sb.fork()` to know what to re-register on a
310
+ * new sandbox, since the vault itself (sidecar-runtime-only state) never survives either
311
+ * operation. Scans the *whole* history, not just some replay window — credential bindings
312
+ * aren't tied to specific execs the way exec replay is.
313
+ */
314
+ declare function reconstructBoundCredentials(entries: LedgerEntry[]): Map<string, BoundCredential>;
315
+ //#endregion
187
316
  //#region src/exec-handle.d.ts
188
317
  interface ExecResult {
189
318
  stdout: string;
@@ -341,7 +470,7 @@ interface ExecCodeOptions {
341
470
  /** Execution context (stateful interpreter session). */
342
471
  context?: {
343
472
  id: string;
344
- language: import("@alineo-labs/opensandbox").CodeLanguage;
473
+ language: CodeLanguage;
345
474
  };
346
475
  }
347
476
  /** Lifecycle hooks for observability. Pass via `SandboxDeps.hooks`. */
@@ -354,12 +483,16 @@ interface SandboxHooks {
354
483
  onSandboxFailed?(sandboxId: string, error: Error): void;
355
484
  onSandboxPaused?(sandboxId: string): void;
356
485
  onSandboxResumed?(sandboxId: string): void;
486
+ /** Fires on `sb.credentials.set()`/`.patch()` — never carries the credential value. */
487
+ onCredentialInjected?(sandboxId: string, name: string, binding: CredentialBinding): void;
357
488
  }
358
489
  /** Internal dependencies injected by `Sandbox`. */
359
490
  interface SandboxDeps {
360
491
  control: ControlClient;
361
492
  adapter: IStorageAdapter;
362
493
  hooks?: SandboxHooks;
494
+ /** Broker for `sb.credentials.*` — undefined unless the sandbox was created with `credentialProxy: true`. */
495
+ credentialBroker?: CredentialBroker;
363
496
  /** Called when `close()` completes — used by `Sandbox` for concurrency accounting. */
364
497
  onClose?: () => void;
365
498
  /** Default shell for all `exec()` calls on this sandbox. Defaults to `"/bin/sh"`. */
@@ -368,9 +501,19 @@ interface SandboxDeps {
368
501
  * Called by `fork()` to create a new SandboxHandle from a snapshot — injected by `Sandbox`.
369
502
  * `runId`, if passed, overrides whatever run-correlation ID this closure would otherwise
370
503
  * default to (see `fork()`'s own docs in `lifecycle.ts` for why an explicit override is
371
- * needed across a process boundary).
504
+ * needed across a process boundary). `opts.resourceId`/`opts.teamId` work the same way —
505
+ * absent, the closure falls back to whatever this sandbox's own creation captured (a
506
+ * continuation of the same resource's memory); passed explicitly, the forked child gets a
507
+ * *different* resource/team identity instead of inheriting this sandbox's one. Needed for
508
+ * `Alineo.spawn()`, where the child is a semantically different agent, not a branch of the
509
+ * same one.
372
510
  */
373
- fork?: (snapshotId: string, tag?: string, runId?: string) => Promise<SandboxHandle>;
511
+ fork?: (snapshotId: string, tag?: string, runId?: string, opts?: {
512
+ networkPolicy?: NetworkPolicy;
513
+ credentialProxy?: boolean;
514
+ resourceId?: string;
515
+ teamId?: string;
516
+ }) => Promise<SandboxHandle>;
374
517
  /** Route execd and proxy calls through the OpenSandbox server. Required when the server runs in Docker. */
375
518
  useServerProxy?: boolean;
376
519
  }
@@ -535,7 +678,7 @@ declare class SandboxCore implements SandboxInternal {
535
678
  * await sb.execCode('print(x)', { context: ctx }); // prints 42
536
679
  * ```
537
680
  */
538
- createCodeContext(language: import("@alineo-labs/opensandbox").CodeLanguage): Promise<import("@alineo-labs/opensandbox").CodeContext>;
681
+ createCodeContext(language: CodeLanguage): Promise<CodeContext>;
539
682
  /**
540
683
  * Execute code via the sandbox's code interpreter (Python, JS, etc.).
541
684
  *
@@ -651,6 +794,34 @@ declare class SandboxHandle extends SandboxCore {
651
794
  }>;
652
795
  /** Return current CPU and memory usage for this sandbox. */
653
796
  metrics(): Promise<Metrics$1>;
797
+ /**
798
+ * Register, update, revoke, and list credentials injected into this sandbox's outbound
799
+ * requests without the sandbox process ever holding the real value. Requires the sandbox to
800
+ * have been created with `credentialProxy: true` — every method throws `SandboxError`
801
+ * otherwise.
802
+ *
803
+ * @example
804
+ * ```ts
805
+ * await sb.credentials.set("github", process.env.GH_TOKEN!, {
806
+ * host: "api.github.com",
807
+ * injection: { type: "header", name: "Authorization" },
808
+ * });
809
+ * await sb.credentials.remove("github");
810
+ * ```
811
+ */
812
+ readonly credentials: {
813
+ set: (name: string, value: string, binding: CredentialBinding, source?: CredentialSource) => Promise<void>;
814
+ patch: (name: string, changes: Partial<{
815
+ value: string;
816
+ binding: CredentialBinding;
817
+ source: CredentialSource;
818
+ }>) => Promise<void>;
819
+ remove: (name: string) => Promise<void>;
820
+ listBindings: () => Promise<Array<{
821
+ name: string;
822
+ binding: CredentialBinding;
823
+ }>>;
824
+ };
654
825
  /**
655
826
  * Stream real-time CPU and memory metrics from execd via SSE.
656
827
  *
@@ -709,8 +880,23 @@ declare class SandboxHandle extends SandboxCore {
709
880
  *
710
881
  * @param runId Override the forked sandbox's run-correlation ID (see `SandboxDetails.runId`)
711
882
  * instead of inheriting this sandbox's own default.
883
+ * @param opts.resolveCredential Resolves values for any credentials this sandbox has bound
884
+ * via `sb.credentials.set()` whose source can't be resolved automatically — see
885
+ * `CredentialResolver`. No-op if this sandbox never bound any.
886
+ * @param opts.credentialProxy Force-enables the child's credential proxy even if this
887
+ * sandbox has nothing bound to carry over — for registering brand-new credentials on the
888
+ * child right after `fork()` returns.
889
+ * @param opts.resourceId Override the forked sandbox's resource scope instead of inheriting
890
+ * this sandbox's own — for a fork that's a *different* resource, not a continuation of
891
+ * this one's memory (see `SandboxOptions.resourceId`).
892
+ * @param opts.teamId Same override, for team scope (see `SandboxOptions.teamId`).
712
893
  */
713
- fork(tag?: string, runId?: string): Promise<SandboxHandle>;
894
+ fork(tag?: string, runId?: string, opts?: {
895
+ resolveCredential?: CredentialResolver;
896
+ credentialProxy?: boolean;
897
+ resourceId?: string;
898
+ teamId?: string;
899
+ }): Promise<SandboxHandle>;
714
900
  /**
715
901
  * Capture a snapshot of the sandbox's current filesystem state.
716
902
  *
@@ -831,4 +1017,4 @@ declare class StepTimeoutError extends WorkflowError {
831
1017
  constructor(stepId: string, timeoutMs: number);
832
1018
  }
833
1019
  //#endregion
834
- export { type AttachableSource, BashSession, type CheckpointInfo, CommandError, type ComposeHooksOptions, ConsoleLogger, 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, resolveExecClient };
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 };
package/dist/index.mjs CHANGED
@@ -24,6 +24,13 @@ let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
24
24
  LedgerEvent["SandboxPaused"] = "sandbox_paused";
25
25
  /** Emitted when resume() restores the container to Running. */
26
26
  LedgerEvent["SandboxResumed"] = "sandbox_resumed";
27
+ /**
28
+ * Emitted by `sb.credentials.set()`/`.patch()`. Payload is binding metadata only
29
+ * (name, host, injection type) — the credential value is never written to the ledger.
30
+ */
31
+ LedgerEvent["CredentialBound"] = "credential_bound";
32
+ /** Emitted by `sb.credentials.remove()`. */
33
+ LedgerEvent["CredentialRevoked"] = "credential_revoked";
27
34
  /** Emitted once when a workflow run starts, before any steps execute. */
28
35
  LedgerEvent["RunStarted"] = "run_started";
29
36
  /** Emitted at the beginning of each step. */
@@ -154,6 +161,45 @@ var StepTimeoutError = class extends WorkflowError {
154
161
  }
155
162
  };
156
163
  //#endregion
164
+ //#region src/credentials.ts
165
+ /**
166
+ * Resolves a bound credential's value: `type: "env"` sources resolve automatically from
167
+ * `process.env`; anything else — or an env var that's since become unset — falls back to the
168
+ * caller-supplied `resolver`. Throws `SandboxError` if neither yields a value, rather than
169
+ * silently dropping the credential (the previous behavior when no resolver was supplied at
170
+ * all — see plans/credential-injection.md).
171
+ */
172
+ async function resolveBoundCredential(name, source, resolver, sandboxId) {
173
+ if (source?.type === "env") {
174
+ const fromEnv = process.env[source.varName];
175
+ if (fromEnv !== void 0) return fromEnv;
176
+ }
177
+ const fromResolver = await resolver?.(name, source ?? { type: "external" });
178
+ if (fromResolver !== void 0) return fromResolver;
179
+ 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);
180
+ }
181
+ /**
182
+ * Reconstructs the latest bound/revoked state per credential name from a session's ledger
183
+ * history — used by both `Sandbox.resume()` and `sb.fork()` to know what to re-register on a
184
+ * new sandbox, since the vault itself (sidecar-runtime-only state) never survives either
185
+ * operation. Scans the *whole* history, not just some replay window — credential bindings
186
+ * aren't tied to specific execs the way exec replay is.
187
+ */
188
+ function reconstructBoundCredentials(entries) {
189
+ const result = /* @__PURE__ */ new Map();
190
+ for (const entry of entries) if (entry.event === "credential_bound") {
191
+ const { name, binding, source } = entry.payload;
192
+ result.set(name, {
193
+ binding,
194
+ source
195
+ });
196
+ } else if (entry.event === "credential_revoked") {
197
+ const { name } = entry.payload;
198
+ result.delete(name);
199
+ }
200
+ return result;
201
+ }
202
+ //#endregion
157
203
  //#region src/exec-handle.ts
158
204
  /**
159
205
  * Returned by `SandboxHandle.exec()` and `SandboxHandle.execCode()`.
@@ -207,7 +253,9 @@ var ExecHandle = class {
207
253
  exitCode
208
254
  };
209
255
  this._notify();
210
- driver.onDone(result).then(() => resolve(result), (err) => {
256
+ driver.onDone(result).then(() => {
257
+ resolve(result);
258
+ }, (err) => {
211
259
  this._err = err;
212
260
  this._hasErr = true;
213
261
  reject(err);
@@ -334,7 +382,9 @@ var InteractiveExecHandle = class extends ExecHandle {
334
382
  * the live remote shell. Resolves when the session ends.
335
383
  */
336
384
  async attach(readable, writable) {
337
- const onData = (chunk) => this.write(chunk.toString());
385
+ const onData = (chunk) => {
386
+ this.write(chunk.toString());
387
+ };
338
388
  readable.on("data", onData);
339
389
  try {
340
390
  await this.pipe(writable);
@@ -483,7 +533,7 @@ var SandboxCore = class {
483
533
  }
484
534
  async getExecClient() {
485
535
  if (this._paused) throw new SandboxError("sandbox is paused — call resume() first", this.sandboxId);
486
- if (!this._execClient) this._execClient = await resolveExecClient(this.deps.control, this.sandboxId, this.deps.useServerProxy);
536
+ this._execClient ??= await resolveExecClient(this.deps.control, this.sandboxId, this.deps.useServerProxy);
487
537
  return this._execClient;
488
538
  }
489
539
  /** Resolve a fresh `PtyClient` for a new interactive session. Reuses `getExecClient()`'s readiness wait. */
@@ -536,9 +586,10 @@ var SandboxCore = class {
536
586
  exec(cmd, opts = {}) {
537
587
  if (opts.interactive) return this._execInteractive(cmd, opts);
538
588
  const seq = ++this._seq;
539
- if (this.replayCache.has(seq)) return new ExecHandle({
589
+ const cachedResult = this.replayCache.get(seq);
590
+ if (cachedResult) return new ExecHandle({
540
591
  type: "replay",
541
- result: this.replayCache.get(seq)
592
+ result: cachedResult
542
593
  });
543
594
  const self = this;
544
595
  async function* stream() {
@@ -579,9 +630,10 @@ var SandboxCore = class {
579
630
  /** Backs `exec(cmd, { interactive: true })` — see that method's docs. */
580
631
  _execInteractive(cmd, opts) {
581
632
  const seq = ++this._seq;
582
- if (this.replayCache.has(seq)) return new InteractiveExecHandle({
633
+ const cachedResult = this.replayCache.get(seq);
634
+ if (cachedResult) return new InteractiveExecHandle({
583
635
  type: "replay",
584
- result: this.replayCache.get(seq)
636
+ result: cachedResult
585
637
  });
586
638
  const pending = this.pendingInteractive.get(seq);
587
639
  const self = this;
@@ -614,7 +666,9 @@ var SandboxCore = class {
614
666
  text: chunk
615
667
  });
616
668
  push(chunk);
617
- }, (exitCode) => finish(exitCode));
669
+ }, (exitCode) => {
670
+ finish(exitCode);
671
+ });
618
672
  closer = async () => {
619
673
  if (closer) self.openSessionClosers.delete(closer);
620
674
  pty.close();
@@ -654,16 +708,24 @@ var SandboxCore = class {
654
708
  type: "stdin",
655
709
  text: data
656
710
  }));
657
- ptyPromise.then((pty) => pty.write(data));
711
+ ptyPromise.then((pty) => {
712
+ pty.write(data);
713
+ });
658
714
  },
659
715
  resize: (cols, rows) => {
660
- ptyPromise.then((pty) => pty.resize(cols, rows));
716
+ ptyPromise.then((pty) => {
717
+ pty.resize(cols, rows);
718
+ });
661
719
  },
662
720
  signal: (name) => {
663
- ptyPromise.then((pty) => pty.signal(name));
721
+ ptyPromise.then((pty) => {
722
+ pty.signal(name);
723
+ });
664
724
  },
665
725
  close: () => {
666
- ptyPromise.then((pty) => pty.close());
726
+ ptyPromise.then((pty) => {
727
+ pty.close();
728
+ });
667
729
  }
668
730
  });
669
731
  }
@@ -694,9 +756,10 @@ var SandboxCore = class {
694
756
  */
695
757
  execCode(code, opts = {}) {
696
758
  const seq = ++this._seq;
697
- if (this.replayCache.has(seq)) return new ExecHandle({
759
+ const cachedResult = this.replayCache.get(seq);
760
+ if (cachedResult) return new ExecHandle({
698
761
  type: "replay",
699
- result: this.replayCache.get(seq)
762
+ result: cachedResult
700
763
  });
701
764
  const self = this;
702
765
  async function* stream() {
@@ -805,7 +868,7 @@ async function readFile(sb, path) {
805
868
  while (true) {
806
869
  const { done, value } = await reader.read();
807
870
  if (done) break;
808
- if (value) chunks.push(value);
871
+ chunks.push(value);
809
872
  }
810
873
  const total = chunks.reduce((n, c) => n + c.length, 0);
811
874
  const merged = new Uint8Array(total);
@@ -919,8 +982,23 @@ async function checkpoint(sb, name) {
919
982
  * no access to the original in-memory closure) — the caller reads the correct value from
920
983
  * `process.env.ALINEO_RUN_ID` and passes it explicitly rather than relying on this sandbox's
921
984
  * own (possibly unknown) default.
985
+ * @param opts.resolveCredential Resolves values for credentials this sandbox has bound whose
986
+ * `CredentialSource` isn't `"env"` (or whose env var has since become unset) — the vault is
987
+ * sidecar-runtime-only, so it never survives the fork on its own. Only relevant if this
988
+ * sandbox has ever called `sb.credentials.set()`; a no-op otherwise. Throws `SandboxError`
989
+ * if a bound credential can't be resolved rather than silently omitting it from the child.
990
+ * @param opts.credentialProxy Force-enables the child's credential proxy even if this sandbox
991
+ * has no bound credentials of its own to carry over — for a caller that plans to register
992
+ * brand-new credentials on the child right after `fork()` returns (this sandbox's own bound
993
+ * credentials, if any, always enable it regardless of this flag).
994
+ * @param opts.resourceId Override the forked sandbox's resource scope (see
995
+ * `SandboxOptions.resourceId`) instead of inheriting this sandbox's own default — for a fork
996
+ * that's a *different* resource, not a continuation of this one's memory (e.g.
997
+ * `alineo`'s `Alineo.spawn()`, where the child is a semantically different agent).
998
+ * @param opts.teamId Same override, for team scope (see `SandboxOptions.teamId`). Independent
999
+ * of `opts.resourceId` — pass either, both, or neither.
922
1000
  */
923
- async function fork(sb, tag, runId) {
1001
+ async function fork(sb, tag, runId, opts) {
924
1002
  if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId);
925
1003
  const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
926
1004
  await sb.waitForSnapshot(snap.id);
@@ -929,7 +1007,23 @@ async function fork(sb, tag, runId) {
929
1007
  name: tag
930
1008
  });
931
1009
  sb.deps.hooks?.onCheckpoint?.(sb.sandboxId, snap.id, tag);
932
- return sb.deps.fork(snap.id, tag, runId);
1010
+ const boundCredentials = reconstructBoundCredentials(await sb.deps.adapter.readAll(sb.name, sb.sandboxId));
1011
+ const needsCredentialProxy = boundCredentials.size > 0 || opts?.credentialProxy === true;
1012
+ const networkPolicy = needsCredentialProxy ? {
1013
+ defaultAction: "allow",
1014
+ egress: []
1015
+ } : void 0;
1016
+ const child = await sb.deps.fork(snap.id, tag, runId, {
1017
+ networkPolicy,
1018
+ credentialProxy: needsCredentialProxy,
1019
+ resourceId: opts?.resourceId,
1020
+ teamId: opts?.teamId
1021
+ });
1022
+ for (const [name, { binding, source }] of boundCredentials) {
1023
+ const value = await resolveBoundCredential(name, source, opts?.resolveCredential, sb.sandboxId);
1024
+ await child.credentials.set(name, value, binding, source);
1025
+ }
1026
+ return child;
933
1027
  }
934
1028
  /**
935
1029
  * Delete the sandbox container and release its resources.
@@ -992,6 +1086,60 @@ async function proxy(sb, port) {
992
1086
  };
993
1087
  }
994
1088
  //#endregion
1089
+ //#region src/sandbox/credentials.ts
1090
+ function requireBroker(sb) {
1091
+ const broker = sb.deps.credentialBroker;
1092
+ 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);
1093
+ return broker;
1094
+ }
1095
+ /**
1096
+ * Register (or replace) a named credential's value and where it gets injected.
1097
+ *
1098
+ * @param source Where `value` came from — `{ type: "env", varName }` resolves automatically
1099
+ * on `resume()`/`fork()`; anything else (including omitting this) requires an explicit
1100
+ * `resolveCredential` callback there, and `resume()`/`fork()` throw rather than silently
1101
+ * dropping the credential if one isn't supplied. Persisted as metadata only — never `value`.
1102
+ */
1103
+ async function set(sb, name, value, binding, source) {
1104
+ await requireBroker(sb).set(sb.sandboxId, name, value, binding);
1105
+ await sb.emit("credential_bound", -1, {
1106
+ name,
1107
+ binding,
1108
+ source
1109
+ });
1110
+ sb.deps.hooks?.onCredentialInjected?.(sb.sandboxId, name, binding);
1111
+ }
1112
+ /**
1113
+ * Update a binding's injection rule, source, and/or value without needing to resupply all
1114
+ * three. Note: a ledger entry (needed for `resume()`/`fork()` reconstruction) is only written
1115
+ * when `changes.binding` is provided — this module doesn't track prior state to merge a
1116
+ * source-only change against, so changing `source` alone requires re-passing the (possibly
1117
+ * unchanged) `binding` too.
1118
+ */
1119
+ async function patch(sb, name, changes) {
1120
+ await requireBroker(sb).patch(sb.sandboxId, name, {
1121
+ value: changes.value,
1122
+ binding: changes.binding
1123
+ });
1124
+ if (changes.binding) {
1125
+ await sb.emit("credential_bound", -1, {
1126
+ name,
1127
+ binding: changes.binding,
1128
+ source: changes.source
1129
+ });
1130
+ sb.deps.hooks?.onCredentialInjected?.(sb.sandboxId, name, changes.binding);
1131
+ }
1132
+ }
1133
+ /** Revoke a credential — subsequent matching requests are no longer injected. */
1134
+ async function remove(sb, name) {
1135
+ await requireBroker(sb).remove(sb.sandboxId, name);
1136
+ await sb.emit("credential_revoked", -1, { name });
1137
+ }
1138
+ /** List binding metadata (host/injection shape) for this sandbox — never returns values. */
1139
+ async function listBindings(sb) {
1140
+ return requireBroker(sb).listBindings(sb.sandboxId);
1141
+ }
1142
+ //#endregion
995
1143
  //#region src/sandbox/sandbox.ts
996
1144
  /**
997
1145
  * A live sandbox container. Returned by `Sandbox.sandbox()` and `Sandbox.resume()`.
@@ -1094,6 +1242,27 @@ var SandboxHandle = class extends SandboxCore {
1094
1242
  return metrics(this);
1095
1243
  }
1096
1244
  /**
1245
+ * Register, update, revoke, and list credentials injected into this sandbox's outbound
1246
+ * requests without the sandbox process ever holding the real value. Requires the sandbox to
1247
+ * have been created with `credentialProxy: true` — every method throws `SandboxError`
1248
+ * otherwise.
1249
+ *
1250
+ * @example
1251
+ * ```ts
1252
+ * await sb.credentials.set("github", process.env.GH_TOKEN!, {
1253
+ * host: "api.github.com",
1254
+ * injection: { type: "header", name: "Authorization" },
1255
+ * });
1256
+ * await sb.credentials.remove("github");
1257
+ * ```
1258
+ */
1259
+ credentials = {
1260
+ 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),
1263
+ listBindings: () => listBindings(this)
1264
+ };
1265
+ /**
1097
1266
  * Stream real-time CPU and memory metrics from execd via SSE.
1098
1267
  *
1099
1268
  * Holds a long-lived connection — break out of the loop when done to avoid
@@ -1163,9 +1332,19 @@ var SandboxHandle = class extends SandboxCore {
1163
1332
  *
1164
1333
  * @param runId Override the forked sandbox's run-correlation ID (see `SandboxDetails.runId`)
1165
1334
  * instead of inheriting this sandbox's own default.
1335
+ * @param opts.resolveCredential Resolves values for any credentials this sandbox has bound
1336
+ * via `sb.credentials.set()` whose source can't be resolved automatically — see
1337
+ * `CredentialResolver`. No-op if this sandbox never bound any.
1338
+ * @param opts.credentialProxy Force-enables the child's credential proxy even if this
1339
+ * sandbox has nothing bound to carry over — for registering brand-new credentials on the
1340
+ * child right after `fork()` returns.
1341
+ * @param opts.resourceId Override the forked sandbox's resource scope instead of inheriting
1342
+ * this sandbox's own — for a fork that's a *different* resource, not a continuation of
1343
+ * this one's memory (see `SandboxOptions.resourceId`).
1344
+ * @param opts.teamId Same override, for team scope (see `SandboxOptions.teamId`).
1166
1345
  */
1167
- async fork(tag, runId) {
1168
- return fork(this, tag, runId);
1346
+ async fork(tag, runId, opts) {
1347
+ return fork(this, tag, runId, opts);
1169
1348
  }
1170
1349
  /**
1171
1350
  * Capture a snapshot of the sandbox's current filesystem state.
@@ -1223,30 +1402,78 @@ function composeHooks(hooks, opts = {}) {
1223
1402
  }
1224
1403
  return {
1225
1404
  onSandboxCreated(sandboxId, name) {
1226
- active.forEach((h, i) => h.onSandboxCreated && call("onSandboxCreated", i, () => h.onSandboxCreated(sandboxId, name)));
1405
+ active.forEach((h, i) => {
1406
+ const fn = h.onSandboxCreated?.bind(h);
1407
+ if (fn) call("onSandboxCreated", i, () => {
1408
+ fn(sandboxId, name);
1409
+ });
1410
+ });
1227
1411
  },
1228
1412
  onExecStart(sandboxId, seq, cmd) {
1229
- active.forEach((h, i) => h.onExecStart && call("onExecStart", i, () => h.onExecStart(sandboxId, seq, cmd)));
1413
+ active.forEach((h, i) => {
1414
+ const fn = h.onExecStart?.bind(h);
1415
+ if (fn) call("onExecStart", i, () => {
1416
+ fn(sandboxId, seq, cmd);
1417
+ });
1418
+ });
1230
1419
  },
1231
1420
  onExecComplete(sandboxId, seq, result) {
1232
- active.forEach((h, i) => h.onExecComplete && call("onExecComplete", i, () => h.onExecComplete(sandboxId, seq, result)));
1421
+ active.forEach((h, i) => {
1422
+ const fn = h.onExecComplete?.bind(h);
1423
+ if (fn) call("onExecComplete", i, () => {
1424
+ fn(sandboxId, seq, result);
1425
+ });
1426
+ });
1233
1427
  },
1234
1428
  onCheckpoint(sandboxId, snapshotId, name) {
1235
- active.forEach((h, i) => h.onCheckpoint && call("onCheckpoint", i, () => h.onCheckpoint(sandboxId, snapshotId, name)));
1429
+ active.forEach((h, i) => {
1430
+ const fn = h.onCheckpoint?.bind(h);
1431
+ if (fn) call("onCheckpoint", i, () => {
1432
+ fn(sandboxId, snapshotId, name);
1433
+ });
1434
+ });
1236
1435
  },
1237
1436
  onSandboxClosed(sandboxId) {
1238
- active.forEach((h, i) => h.onSandboxClosed && call("onSandboxClosed", i, () => h.onSandboxClosed(sandboxId)));
1437
+ active.forEach((h, i) => {
1438
+ const fn = h.onSandboxClosed?.bind(h);
1439
+ if (fn) call("onSandboxClosed", i, () => {
1440
+ fn(sandboxId);
1441
+ });
1442
+ });
1239
1443
  },
1240
1444
  onSandboxFailed(sandboxId, error) {
1241
- active.forEach((h, i) => h.onSandboxFailed && call("onSandboxFailed", i, () => h.onSandboxFailed(sandboxId, error)));
1445
+ active.forEach((h, i) => {
1446
+ const fn = h.onSandboxFailed?.bind(h);
1447
+ if (fn) call("onSandboxFailed", i, () => {
1448
+ fn(sandboxId, error);
1449
+ });
1450
+ });
1242
1451
  },
1243
1452
  onSandboxPaused(sandboxId) {
1244
- active.forEach((h, i) => h.onSandboxPaused && call("onSandboxPaused", i, () => h.onSandboxPaused(sandboxId)));
1453
+ active.forEach((h, i) => {
1454
+ const fn = h.onSandboxPaused?.bind(h);
1455
+ if (fn) call("onSandboxPaused", i, () => {
1456
+ fn(sandboxId);
1457
+ });
1458
+ });
1245
1459
  },
1246
1460
  onSandboxResumed(sandboxId) {
1247
- active.forEach((h, i) => h.onSandboxResumed && call("onSandboxResumed", i, () => h.onSandboxResumed(sandboxId)));
1461
+ active.forEach((h, i) => {
1462
+ const fn = h.onSandboxResumed?.bind(h);
1463
+ if (fn) call("onSandboxResumed", i, () => {
1464
+ fn(sandboxId);
1465
+ });
1466
+ });
1467
+ },
1468
+ onCredentialInjected(sandboxId, name, binding) {
1469
+ active.forEach((h, i) => {
1470
+ const fn = h.onCredentialInjected?.bind(h);
1471
+ if (fn) call("onCredentialInjected", i, () => {
1472
+ fn(sandboxId, name, binding);
1473
+ });
1474
+ });
1248
1475
  }
1249
1476
  };
1250
1477
  }
1251
1478
  //#endregion
1252
- export { BashSession, CommandError, ConsoleLogger, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, resolveExecClient };
1479
+ export { BashSession, CommandError, ConsoleLogger, ExecConnectionError, ExecHandle, InteractiveExecHandle, LedgerEvent, LogLevel, SandboxError, SandboxHandle, SandboxStatus, StepTimeoutError, WorkflowError, composeHooks, noopLogger, reconstructBoundCredentials, resolveBoundCredential, resolveExecClient };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alineo-labs/core",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,7 @@
29
29
  "test:watch": "vitest"
30
30
  },
31
31
  "dependencies": {
32
- "@alineo-labs/opensandbox": "0.1.0"
32
+ "@alineo-labs/opensandbox": "0.2.0"
33
33
  },
34
34
  "devDependencies": {
35
35
  "bun-types": "1.3.14",