@alineo-labs/core 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { ConsoleLogger, ILogger, LogLevel, noopLogger } from "@alineo-labs/logger";
2
2
  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
+ import { LedgerEnvelope } from "@alineo-labs/schema/types";
3
4
  //#region src/ledger.d.ts
4
5
  /** Status of a sandbox session derived from its ledger events. */
5
6
  export declare enum SandboxStatus {
@@ -23,7 +24,7 @@ interface SandboxDetails {
23
24
  * `crypto.randomUUID()` if the caller didn't supply one via `SandboxOptions.runId`.
24
25
  * A resumed, forked, or restored-from-snapshot sandbox always inherits its origin's
25
26
  * `runId` rather than getting a new one, so every sandbox descended from the same
26
- * root call (directly or via `sb.fork()`/`Alineo.spawn()`/`alineo fork`) shares it —
27
+ * root call (directly or via `sb.fork()`/`Alineo.spawn()`/`alineo spawn`) shares it —
27
28
  * the mechanism `client.sandboxes.list({ runId })` correlates on.
28
29
  */
29
30
  runId: string;
@@ -71,67 +72,62 @@ interface ListSandboxOptions {
71
72
  /** Events emitted during execution and stored in the ledger. */
72
73
  export declare enum LedgerEvent {
73
74
  /** Emitted when a sandbox is created and reaches Running state. */
74
- SandboxCreated = "sandbox_created",
75
+ SandboxCreated = "sandbox.created",
75
76
  /** Emitted at the start of each exec() or execCode() call. */
76
- ExecStart = "exec_start",
77
+ ExecStart = "exec.started",
77
78
  /** Streaming output chunk from exec() or execCode(). */
78
- ExecEvent = "exec_event",
79
+ ExecEvent = "exec.output",
79
80
  /** Emitted when an exec() or execCode() call completes. */
80
- ExecComplete = "exec_complete",
81
+ ExecComplete = "exec.completed",
81
82
  /** Emitted when checkpoint() captures a snapshot. */
82
- CheckpointCreated = "checkpoint_created",
83
+ CheckpointCreated = "sandbox.checkpoint_created",
83
84
  /** Emitted when a sandbox is closed. */
84
- SandboxClosed = "sandbox_closed",
85
+ SandboxClosed = "sandbox.closed",
85
86
  /** Emitted when pause() freezes the container. */
86
- SandboxPaused = "sandbox_paused",
87
+ SandboxPaused = "sandbox.paused",
87
88
  /** Emitted when resume() restores the container to Running. */
88
- SandboxResumed = "sandbox_resumed",
89
+ SandboxResumed = "sandbox.resumed",
89
90
  /**
90
91
  * Emitted by `sb.credentials.set()`/`.patch()`. Payload is binding metadata only
91
92
  * (name, host, injection type) — the credential value is never written to the ledger.
92
93
  */
93
- CredentialBound = "credential_bound",
94
+ CredentialBound = "credential.bound",
94
95
  /** Emitted by `sb.credentials.remove()`. */
95
- CredentialRevoked = "credential_revoked",
96
+ CredentialRevoked = "credential.revoked",
96
97
  /**
97
98
  * Emitted by `sb.egress.patch()`. Payload is `{ rules: NetworkRule[] }` — the exact rules
98
99
  * passed to the sidecar, so `Sandbox.resume()` can fold a still-wanted allowance back into
99
100
  * the resumed sandbox's boot policy (egress policy is sidecar-local and does not survive a
100
101
  * resume). `sb.fork()` does not carry these.
101
102
  */
102
- EgressRuleAdded = "egress_rule_added",
103
+ EgressRuleAdded = "egress.rule_added",
103
104
  /** Emitted by `sb.egress.delete()`. Payload is `{ targets: string[] }`. */
104
- EgressRuleRemoved = "egress_rule_removed",
105
+ EgressRuleRemoved = "egress.rule_removed",
105
106
  /**
106
107
  * Emitted when the permission gate pauses a tool call for human approval. Payload is
107
108
  * `{ requestId, tool, target }` — metadata only; the raw tool arguments (which can carry
108
109
  * secrets in a bash command or a file write) are never written to the ledger.
109
110
  */
110
- PermissionRequested = "permission_requested",
111
+ PermissionRequested = "permission.requested",
111
112
  /**
112
- * Emitted when a `PermissionRequested` is answered — by a caller, a batched
113
- * always/reject decision, a timeout, or a session resume dropping it. Payload is
114
- * `{ requestId, decision }`.
113
+ * Emitted when a `PermissionRequested` reaches a final state — answered by a caller, a
114
+ * batched always/reject decision, a timeout, or a session resume dropping it. Payload is
115
+ * `{ requestId, decision }`. `decision.kind` is one of `PermissionDecision`'s real answers
116
+ * (`once`/`always`/`reject`) for every case except the dropped one, which is `"dropped"` —
117
+ * deliberately not a `PermissionDecision`, because nobody answered it.
115
118
  */
116
- PermissionResolved = "permission_resolved",
117
- /** Emitted once when a workflow run starts, before any steps execute. */
118
- RunStarted = "run_started",
119
- /** Emitted at the beginning of each step. */
120
- StepStart = "step_start",
121
- /** Emitted when a step finishes successfully. */
122
- StepComplete = "step_complete",
123
- /** Emitted when a step throws an unrecoverable error. */
124
- StepFailed = "step_failed",
125
- /** Emitted when a step's rollback handler completes during saga compensation. */
126
- StepRolledBack = "step_rolled_back",
127
- /** Emitted after all steps finish without error. */
128
- WorkflowComplete = "workflow_complete",
129
- /** Emitted after rollback completes following a step failure. */
130
- WorkflowFailed = "workflow_failed",
131
- /** Durable resumption point written after each successful step. */
132
- Checkpoint = "checkpoint",
133
- /** Emitted when a sandbox snapshot is captured mid-run. */
134
- Snapshot = "snapshot"
119
+ PermissionResolved = "permission.resolved",
120
+ /**
121
+ * durability-roadmap M3, 3.2: emitted by the agent SDK after a turn-level checkpoint
122
+ * (workspace + session-file tarball, NOT `sb.checkpoint()`'s OpenSandbox snapshot — see
123
+ * `CheckpointCreated` above and `packages/agent/src/checkpoint.ts`'s doc comment for why the
124
+ * two are deliberately separate mechanisms) is captured and durably stored. Payload is
125
+ * `{ turn, snapshotRef }` — written only once the tarball is confirmed stored, since a
126
+ * snapshot without this event pointing at it is unreachable garbage. Shares the same
127
+ * `IStorageAdapter`-backed ledger `PermissionRequested`/`PermissionResolved` already use, so
128
+ * a standalone SDK caller and alineod both read it back the same way (`adapter.readAll`).
129
+ */
130
+ AgentCheckpointed = "agent.checkpointed"
135
131
  }
136
132
  /** A single event record written to the storage adapter during a session. */
137
133
  interface LedgerEntry {
@@ -147,7 +143,7 @@ interface LedgerEntry {
147
143
  event: LedgerEvent;
148
144
  /** Event-specific data (step output, snapshot ID, exec text, etc.). */
149
145
  payload?: unknown;
150
- /** Error message when `event` is `StepFailed` or `WorkflowFailed`. */
146
+ /** Error message, when the event records a failure. */
151
147
  error?: string;
152
148
  }
153
149
  /** A recorded checkpoint for a sandbox session. */
@@ -173,6 +169,49 @@ interface EnvironmentRecord {
173
169
  /** Unix timestamp (ms) when the environment was last built. */
174
170
  builtAt: number;
175
171
  }
172
+ /**
173
+ * One entry in a generic, two-level-partition append-only ledger — the shared primitive
174
+ * durability-roadmap.md's M3 (3.1b) introduces so a second consumer (alineod's swarm ledger,
175
+ * `apps/alineod/src/state/db.ts`) can depend on the same package the sandbox SDK's own ledger
176
+ * already does, instead of each hand-rolling `bun:sqlite`. Deliberately narrower than
177
+ * `IStorageAdapter`/`LedgerEntry` above: no derived-aggregation methods (`listSandboxDetails`
178
+ * and friends stay specific to the sandbox SDK's own shape), and ordering is always by `seq`
179
+ * (true write order) — never by `ts`, which stays a per-consumer concern. `scope` and `subScope`
180
+ * are deliberately generic names: the sandbox SDK's shape is `(name, sandboxId)`; alineod's is
181
+ * `(runId, agentId)`. Only the access patterns alineod's existing `ledger` table actually uses
182
+ * are supported (filter by `scope` alone, filter by `subScope` alone plus an event filter, or a
183
+ * full unfiltered replay) — not the sandbox SDK's combined `(scope, subScope)` filter, which
184
+ * stays on `IStorageAdapter.readAll()` as it is today.
185
+ */
186
+ interface EngineLedgerEntry {
187
+ /** Primary partition key — e.g. a run id. Required on every entry. */
188
+ scope: string;
189
+ /** Secondary partition key — e.g. an agent id. Omitted/null for a scope-level event. */
190
+ subScope?: string | null;
191
+ ts: number;
192
+ event: string;
193
+ payload?: unknown;
194
+ }
195
+ /** A stored `EngineLedgerEntry`, with the monotonic sequence number assigned on append. */
196
+ interface EngineLedgerRow extends EngineLedgerEntry {
197
+ seq: number;
198
+ }
199
+ interface IEngineLedger {
200
+ /** Run migrations / open connections. Must be called before first use. */
201
+ connect?(): Promise<void>;
202
+ /** Release connections and resources. Call on graceful shutdown. */
203
+ close?(): Promise<void>;
204
+ /** Append one entry and return it with its assigned `seq`. */
205
+ append(entry: EngineLedgerEntry): Promise<EngineLedgerRow>;
206
+ /** Every entry for one `scope`, in `seq` order, optionally only those after a given `seq`. */
207
+ readByScope(scope: string, opts?: {
208
+ afterSeq?: number;
209
+ }): Promise<EngineLedgerRow[]>;
210
+ /** Every entry for one `subScope`, in `seq` order, optionally filtered to one `event` type. */
211
+ readBySubScope(subScope: string, event?: string): Promise<EngineLedgerRow[]>;
212
+ /** Every entry across every scope, in `seq` order — for a full replay at boot. */
213
+ readAll(): Promise<EngineLedgerRow[]>;
214
+ }
176
215
  /**
177
216
  * Persistence interface for session event storage.
178
217
  *
@@ -526,6 +565,17 @@ interface SandboxHooks {
526
565
  interface SandboxDeps {
527
566
  control: ControlClient;
528
567
  adapter: IStorageAdapter;
568
+ /**
569
+ * Receives a `LedgerEnvelope` for every event this sandbox emits, beside the ledger write.
570
+ *
571
+ * Synchronous and must not throw — it runs on the write path of a sandbox operation, so an
572
+ * async sink would become backpressure and a throwing one would fail the very operation
573
+ * being recorded. Deliberately NOT joined to `_ledgerQueue` for the same reason.
574
+ *
575
+ * @internal Sinks are an export path and the ledger is the system of record; the public
576
+ * shape of this belongs with the work that owns export.
577
+ */
578
+ sink?: (envelope: LedgerEnvelope) => void;
529
579
  hooks?: SandboxHooks;
530
580
  /** Broker for `sb.credentials.*` — undefined unless the sandbox was created with `credentialProxy: true`. */
531
581
  credentialBroker?: CredentialBroker;
@@ -767,8 +817,14 @@ declare class SandboxCore implements SandboxInternal {
767
817
  export declare class SandboxHandle extends SandboxCore {
768
818
  /** Write a file into the sandbox. */
769
819
  writeFile(path: string, content: string): Promise<void>;
820
+ /** Write raw bytes into the sandbox — for binary content `writeFile`'s string-typed
821
+ * signature isn't safe for (a gzip tarball, an image). */
822
+ writeFileBytes(path: string, bytes: Uint8Array): Promise<void>;
770
823
  /** Read a file from the sandbox as a UTF-8 string. */
771
824
  readFile(path: string): Promise<string>;
825
+ /** Read a file from the sandbox as raw bytes — for binary content `readFile`'s UTF-8
826
+ * decode would corrupt (a gzip tarball, an image). */
827
+ readFileBytes(path: string): Promise<Uint8Array>;
772
828
  /** Delete a file from the sandbox. */
773
829
  deleteFile(path: string): Promise<void>;
774
830
  /** Move or rename a file inside the sandbox. */
@@ -978,7 +1034,7 @@ export declare class SandboxHandle extends SandboxCore {
978
1034
  * execd is ready to accept connections.
979
1035
  *
980
1036
  * Defaults give ~80s of total patience (retries=45, capped at 2s/attempt), not the ~11s this
981
- * had before (retries=15, capped at 1s/attempt). Bumped after a live `alineo fork` failure
1037
+ * had before (retries=15, capped at 1s/attempt). Bumped after a live `alineo spawn` failure
982
1038
  * (issue #32): a child forked while its parent sandbox was busy running a real Chrome session
983
1039
  * took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
984
1040
  * budget before the exec daemon inside it had actually started accepting connections. An
@@ -1074,4 +1130,4 @@ export declare class StepTimeoutError extends WorkflowError {
1074
1130
  constructor(stepId: string, timeoutMs: number);
1075
1131
  }
1076
1132
  //#endregion
1077
- 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 EnvironmentRecord, type ExecCodeOptions, type ExecOptions, type ExecResult, type FileInfo, type ILogger, type IStorageAdapter, type LedgerEntry, type ListSandboxOptions, LogLevel, type Metrics, type PendingInteractiveExec, type PtyControls, type ReconstructedEgress, type SandboxDeps, type SandboxDetails, type SandboxHooks, noopLogger };
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 };
package/dist/index.mjs CHANGED
@@ -10,67 +10,62 @@ let SandboxStatus = /* @__PURE__ */ function(SandboxStatus) {
10
10
  /** Events emitted during execution and stored in the ledger. */
11
11
  let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
12
12
  /** Emitted when a sandbox is created and reaches Running state. */
13
- LedgerEvent["SandboxCreated"] = "sandbox_created";
13
+ LedgerEvent["SandboxCreated"] = "sandbox.created";
14
14
  /** Emitted at the start of each exec() or execCode() call. */
15
- LedgerEvent["ExecStart"] = "exec_start";
15
+ LedgerEvent["ExecStart"] = "exec.started";
16
16
  /** Streaming output chunk from exec() or execCode(). */
17
- LedgerEvent["ExecEvent"] = "exec_event";
17
+ LedgerEvent["ExecEvent"] = "exec.output";
18
18
  /** Emitted when an exec() or execCode() call completes. */
19
- LedgerEvent["ExecComplete"] = "exec_complete";
19
+ LedgerEvent["ExecComplete"] = "exec.completed";
20
20
  /** Emitted when checkpoint() captures a snapshot. */
21
- LedgerEvent["CheckpointCreated"] = "checkpoint_created";
21
+ LedgerEvent["CheckpointCreated"] = "sandbox.checkpoint_created";
22
22
  /** Emitted when a sandbox is closed. */
23
- LedgerEvent["SandboxClosed"] = "sandbox_closed";
23
+ LedgerEvent["SandboxClosed"] = "sandbox.closed";
24
24
  /** Emitted when pause() freezes the container. */
25
- LedgerEvent["SandboxPaused"] = "sandbox_paused";
25
+ LedgerEvent["SandboxPaused"] = "sandbox.paused";
26
26
  /** Emitted when resume() restores the container to Running. */
27
- LedgerEvent["SandboxResumed"] = "sandbox_resumed";
27
+ LedgerEvent["SandboxResumed"] = "sandbox.resumed";
28
28
  /**
29
29
  * Emitted by `sb.credentials.set()`/`.patch()`. Payload is binding metadata only
30
30
  * (name, host, injection type) — the credential value is never written to the ledger.
31
31
  */
32
- LedgerEvent["CredentialBound"] = "credential_bound";
32
+ LedgerEvent["CredentialBound"] = "credential.bound";
33
33
  /** Emitted by `sb.credentials.remove()`. */
34
- LedgerEvent["CredentialRevoked"] = "credential_revoked";
34
+ LedgerEvent["CredentialRevoked"] = "credential.revoked";
35
35
  /**
36
36
  * Emitted by `sb.egress.patch()`. Payload is `{ rules: NetworkRule[] }` — the exact rules
37
37
  * passed to the sidecar, so `Sandbox.resume()` can fold a still-wanted allowance back into
38
38
  * the resumed sandbox's boot policy (egress policy is sidecar-local and does not survive a
39
39
  * resume). `sb.fork()` does not carry these.
40
40
  */
41
- LedgerEvent["EgressRuleAdded"] = "egress_rule_added";
41
+ LedgerEvent["EgressRuleAdded"] = "egress.rule_added";
42
42
  /** Emitted by `sb.egress.delete()`. Payload is `{ targets: string[] }`. */
43
- LedgerEvent["EgressRuleRemoved"] = "egress_rule_removed";
43
+ LedgerEvent["EgressRuleRemoved"] = "egress.rule_removed";
44
44
  /**
45
45
  * Emitted when the permission gate pauses a tool call for human approval. Payload is
46
46
  * `{ requestId, tool, target }` — metadata only; the raw tool arguments (which can carry
47
47
  * secrets in a bash command or a file write) are never written to the ledger.
48
48
  */
49
- LedgerEvent["PermissionRequested"] = "permission_requested";
49
+ LedgerEvent["PermissionRequested"] = "permission.requested";
50
50
  /**
51
- * Emitted when a `PermissionRequested` is answered — by a caller, a batched
52
- * always/reject decision, a timeout, or a session resume dropping it. Payload is
53
- * `{ requestId, decision }`.
51
+ * Emitted when a `PermissionRequested` reaches a final state — answered by a caller, a
52
+ * batched always/reject decision, a timeout, or a session resume dropping it. Payload is
53
+ * `{ requestId, decision }`. `decision.kind` is one of `PermissionDecision`'s real answers
54
+ * (`once`/`always`/`reject`) for every case except the dropped one, which is `"dropped"` —
55
+ * deliberately not a `PermissionDecision`, because nobody answered it.
54
56
  */
55
- LedgerEvent["PermissionResolved"] = "permission_resolved";
56
- /** Emitted once when a workflow run starts, before any steps execute. */
57
- LedgerEvent["RunStarted"] = "run_started";
58
- /** Emitted at the beginning of each step. */
59
- LedgerEvent["StepStart"] = "step_start";
60
- /** Emitted when a step finishes successfully. */
61
- LedgerEvent["StepComplete"] = "step_complete";
62
- /** Emitted when a step throws an unrecoverable error. */
63
- LedgerEvent["StepFailed"] = "step_failed";
64
- /** Emitted when a step's rollback handler completes during saga compensation. */
65
- LedgerEvent["StepRolledBack"] = "step_rolled_back";
66
- /** Emitted after all steps finish without error. */
67
- LedgerEvent["WorkflowComplete"] = "workflow_complete";
68
- /** Emitted after rollback completes following a step failure. */
69
- LedgerEvent["WorkflowFailed"] = "workflow_failed";
70
- /** Durable resumption point written after each successful step. */
71
- LedgerEvent["Checkpoint"] = "checkpoint";
72
- /** Emitted when a sandbox snapshot is captured mid-run. */
73
- LedgerEvent["Snapshot"] = "snapshot";
57
+ LedgerEvent["PermissionResolved"] = "permission.resolved";
58
+ /**
59
+ * durability-roadmap M3, 3.2: emitted by the agent SDK after a turn-level checkpoint
60
+ * (workspace + session-file tarball, NOT `sb.checkpoint()`'s OpenSandbox snapshot — see
61
+ * `CheckpointCreated` above and `packages/agent/src/checkpoint.ts`'s doc comment for why the
62
+ * two are deliberately separate mechanisms) is captured and durably stored. Payload is
63
+ * `{ turn, snapshotRef }` — written only once the tarball is confirmed stored, since a
64
+ * snapshot without this event pointing at it is unreachable garbage. Shares the same
65
+ * `IStorageAdapter`-backed ledger `PermissionRequested`/`PermissionResolved` already use, so
66
+ * a standalone SDK caller and alineod both read it back the same way (`adapter.readAll`).
67
+ */
68
+ LedgerEvent["AgentCheckpointed"] = "agent.checkpointed";
74
69
  return LedgerEvent;
75
70
  }({});
76
71
  //#endregion
@@ -169,13 +164,13 @@ async function resolveBoundCredential(name, source, resolver, sandboxId) {
169
164
  */
170
165
  function reconstructBoundCredentials(entries) {
171
166
  const result = /* @__PURE__ */ new Map();
172
- for (const entry of entries) if (entry.event === "credential_bound") {
167
+ for (const entry of entries) if (entry.event === "credential.bound") {
173
168
  const { name, binding, source } = entry.payload;
174
169
  result.set(name, {
175
170
  binding,
176
171
  source
177
172
  });
178
- } else if (entry.event === "credential_revoked") {
173
+ } else if (entry.event === "credential.revoked") {
179
174
  const { name } = entry.payload;
180
175
  result.delete(name);
181
176
  }
@@ -198,13 +193,13 @@ function reconstructBoundCredentials(entries) {
198
193
  function reconstructEgressRules(entries) {
199
194
  const byTarget = /* @__PURE__ */ new Map();
200
195
  const removed = /* @__PURE__ */ new Set();
201
- for (const entry of entries) if (entry.event === "egress_rule_added") {
196
+ for (const entry of entries) if (entry.event === "egress.rule_added") {
202
197
  const { rules } = entry.payload;
203
198
  for (const rule of rules) {
204
199
  byTarget.set(rule.target, rule);
205
200
  removed.delete(rule.target);
206
201
  }
207
- } else if (entry.event === "egress_rule_removed") {
202
+ } else if (entry.event === "egress.rule_removed") {
208
203
  const { targets } = entry.payload;
209
204
  for (const target of targets) {
210
205
  byTarget.delete(target);
@@ -418,7 +413,7 @@ var InteractiveExecHandle = class extends ExecHandle {
418
413
  * execd is ready to accept connections.
419
414
  *
420
415
  * Defaults give ~80s of total patience (retries=45, capped at 2s/attempt), not the ~11s this
421
- * had before (retries=15, capped at 1s/attempt). Bumped after a live `alineo fork` failure
416
+ * had before (retries=15, capped at 1s/attempt). Bumped after a live `alineo spawn` failure
422
417
  * (issue #32): a child forked while its parent sandbox was busy running a real Chrome session
423
418
  * took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
424
419
  * budget before the exec daemon inside it had actually started accepting connections. An
@@ -592,14 +587,28 @@ var SandboxCore = class {
592
587
  throw new SandboxError(`Snapshot ${snapshotId} did not become ready within ${timeoutMs}ms`, this.sandboxId);
593
588
  }
594
589
  emit(event, stepIndex, payload) {
590
+ const ts = Date.now();
595
591
  const entry = {
596
- ts: Date.now(),
592
+ ts,
597
593
  name: this.name,
598
594
  sandboxId: this.sandboxId,
599
595
  stepIndex,
600
596
  event,
601
597
  payload
602
598
  };
599
+ if (this.deps.sink) try {
600
+ this.deps.sink({
601
+ v: 1,
602
+ ts,
603
+ type: event,
604
+ data: {
605
+ sandboxId: this.sandboxId,
606
+ name: this.name,
607
+ stepIndex,
608
+ payload
609
+ }
610
+ });
611
+ } catch {}
603
612
  const result = this._ledgerQueue.then(() => this.deps.adapter.append(entry));
604
613
  this._ledgerQueue = result.catch(() => {});
605
614
  return result;
@@ -615,7 +624,7 @@ var SandboxCore = class {
615
624
  const self = this;
616
625
  async function* stream() {
617
626
  const execClient = await self.getExecClient();
618
- await self.emit("exec_start", seq, {
627
+ await self.emit("exec.started", seq, {
619
628
  cmd,
620
629
  seq
621
630
  });
@@ -628,7 +637,7 @@ var SandboxCore = class {
628
637
  envs: opts.env,
629
638
  timeout: opts.timeoutMs
630
639
  })) {
631
- await self.emit("exec_event", seq, {
640
+ await self.emit("exec.output", seq, {
632
641
  seq,
633
642
  ...ev
634
643
  });
@@ -639,7 +648,7 @@ var SandboxCore = class {
639
648
  type: "stream",
640
649
  gen: stream(),
641
650
  onDone: async (result) => {
642
- await self.emit("exec_complete", seq, {
651
+ await self.emit("exec.completed", seq, {
643
652
  exitCode: result.exitCode,
644
653
  seq
645
654
  });
@@ -659,7 +668,7 @@ var SandboxCore = class {
659
668
  const pending = this.pendingInteractive.get(seq);
660
669
  const self = this;
661
670
  let closer;
662
- const execStartLogged = self.emit("exec_start", seq, {
671
+ const execStartLogged = self.emit("exec.started", seq, {
663
672
  cmd,
664
673
  seq,
665
674
  interactive: true,
@@ -681,7 +690,7 @@ var SandboxCore = class {
681
690
  await pty.connect(sessionId, (chunk) => {
682
691
  onFirstOutput?.();
683
692
  onFirstOutput = void 0;
684
- self.emit("exec_event", seq, {
693
+ self.emit("exec.output", seq, {
685
694
  seq,
686
695
  type: "stdout",
687
696
  text: chunk
@@ -715,7 +724,7 @@ var SandboxCore = class {
715
724
  },
716
725
  onDone: async (result) => {
717
726
  if (closer) self.openSessionClosers.delete(closer);
718
- await self.emit("exec_complete", seq, {
727
+ await self.emit("exec.completed", seq, {
719
728
  exitCode: result.exitCode,
720
729
  seq
721
730
  });
@@ -724,7 +733,7 @@ var SandboxCore = class {
724
733
  }
725
734
  }, {
726
735
  write: (data) => {
727
- execStartLogged.then(() => self.emit("exec_event", seq, {
736
+ execStartLogged.then(() => self.emit("exec.output", seq, {
728
737
  seq,
729
738
  type: "stdin",
730
739
  text: data
@@ -785,7 +794,7 @@ var SandboxCore = class {
785
794
  const self = this;
786
795
  async function* stream() {
787
796
  const execClient = await self.getExecClient();
788
- await self.emit("exec_start", seq, {
797
+ await self.emit("exec.started", seq, {
789
798
  code,
790
799
  seq
791
800
  });
@@ -793,7 +802,7 @@ var SandboxCore = class {
793
802
  code,
794
803
  context: opts.context
795
804
  })) {
796
- await self.emit("exec_event", seq, {
805
+ await self.emit("exec.output", seq, {
797
806
  seq,
798
807
  ...ev
799
808
  });
@@ -804,7 +813,7 @@ var SandboxCore = class {
804
813
  type: "stream",
805
814
  gen: stream(),
806
815
  onDone: async (result) => {
807
- await self.emit("exec_complete", seq, {
816
+ await self.emit("exec.completed", seq, {
808
817
  exitCode: result.exitCode,
809
818
  seq
810
819
  });
@@ -837,7 +846,7 @@ var SandboxCore = class {
837
846
  const execInSession = (command, cmdOpts) => {
838
847
  const seq = ++self._seq;
839
848
  async function* stream() {
840
- await self.emit("exec_start", seq, {
849
+ await self.emit("exec.started", seq, {
841
850
  cmd: command,
842
851
  seq,
843
852
  sessionId
@@ -848,7 +857,7 @@ var SandboxCore = class {
848
857
  cwd: cmdOpts?.cwd,
849
858
  timeout: cmdOpts?.timeoutMs
850
859
  })) {
851
- await self.emit("exec_event", seq, {
860
+ await self.emit("exec.output", seq, {
852
861
  seq,
853
862
  ...ev
854
863
  });
@@ -859,7 +868,7 @@ var SandboxCore = class {
859
868
  type: "stream",
860
869
  gen: stream(),
861
870
  onDone: async (result) => {
862
- await self.emit("exec_complete", seq, {
871
+ await self.emit("exec.completed", seq, {
863
872
  exitCode: result.exitCode,
864
873
  seq
865
874
  });
@@ -882,8 +891,18 @@ var SandboxCore = class {
882
891
  async function writeFile(sb, path, content) {
883
892
  await (await sb.getExecClient()).uploadFile(path, content);
884
893
  }
885
- /** Read a file from the sandbox as a UTF-8 string. */
886
- async function readFile(sb, path) {
894
+ /** Write raw bytes into the sandbox — for binary content (a gzip tarball, an image) that
895
+ * `writeFile`'s string-typed signature would push a caller toward corrupting via a lossy
896
+ * decode/re-encode round trip before it ever reaches this function. */
897
+ async function writeFileBytes(sb, path, bytes) {
898
+ await (await sb.getExecClient()).uploadFile(path, new Uint8Array(bytes));
899
+ }
900
+ /**
901
+ * Read a file from the sandbox as raw bytes — no `TextDecoder`, so binary content (a gzip
902
+ * tarball, an image) round-trips intact. `readFile()` below is this plus a UTF-8 decode; a
903
+ * caller that needs the decode uses that instead, not this one re-encoded.
904
+ */
905
+ async function readFileBytes(sb, path) {
887
906
  const reader = (await (await sb.getExecClient()).downloadFile(path)).getReader();
888
907
  const chunks = [];
889
908
  while (true) {
@@ -898,7 +917,11 @@ async function readFile(sb, path) {
898
917
  merged.set(chunk, offset);
899
918
  offset += chunk.length;
900
919
  }
901
- return new TextDecoder().decode(merged);
920
+ return merged;
921
+ }
922
+ /** Read a file from the sandbox as a UTF-8 string. */
923
+ async function readFile(sb, path) {
924
+ return new TextDecoder().decode(await readFileBytes(sb, path));
902
925
  }
903
926
  /** Delete a file from the sandbox. */
904
927
  async function deleteFile(sb, path) {
@@ -954,7 +977,7 @@ async function pause(sb) {
954
977
  sb.setPaused(true);
955
978
  sb.disposeExecClient();
956
979
  sb.clearExecClient();
957
- await sb.emit("sandbox_paused", -1);
980
+ await sb.emit("sandbox.paused", -1);
958
981
  sb.deps.hooks?.onSandboxPaused?.(sb.sandboxId);
959
982
  }
960
983
  /**
@@ -970,7 +993,7 @@ async function resume(sb) {
970
993
  await sb.deps.control.resumeSandbox(sb.sandboxId);
971
994
  sb.setPaused(false);
972
995
  await sb.waitForRunning();
973
- await sb.emit("sandbox_resumed", -1);
996
+ await sb.emit("sandbox.resumed", -1);
974
997
  sb.deps.hooks?.onSandboxResumed?.(sb.sandboxId);
975
998
  }
976
999
  /**
@@ -983,7 +1006,7 @@ async function resume(sb) {
983
1006
  async function checkpoint(sb, name) {
984
1007
  const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
985
1008
  await sb.waitForSnapshot(snap.id);
986
- await sb.emit("checkpoint_created", -1, {
1009
+ await sb.emit("sandbox.checkpoint_created", -1, {
987
1010
  snapshotId: snap.id,
988
1011
  name
989
1012
  });
@@ -999,7 +1022,7 @@ async function checkpoint(sb, name) {
999
1022
  *
1000
1023
  * @param runId Override the forked sandbox's run correlation ID instead of inheriting
1001
1024
  * whatever this sandbox's own creation closed over. Needed when forking across a process
1002
- * boundary (e.g. `alineo fork`, which re-`Alineo.attach()`es in a brand-new CLI process with
1025
+ * boundary (e.g. `alineo spawn`, which re-`Alineo.attach()`es in a brand-new CLI process with
1003
1026
  * no access to the original in-memory closure) — the caller reads the correct value from
1004
1027
  * `process.env.ALINEO_RUN_ID` and passes it explicitly rather than relying on this sandbox's
1005
1028
  * own (possibly unknown) default.
@@ -1023,7 +1046,7 @@ async function fork(sb, tag, runId, opts) {
1023
1046
  if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId);
1024
1047
  const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
1025
1048
  await sb.waitForSnapshot(snap.id);
1026
- await sb.emit("checkpoint_created", -1, {
1049
+ await sb.emit("sandbox.checkpoint_created", -1, {
1027
1050
  snapshotId: snap.id,
1028
1051
  name: tag
1029
1052
  });
@@ -1061,7 +1084,7 @@ async function close(sb) {
1061
1084
  try {
1062
1085
  await sb.deps.control.deleteSandbox(sb.sandboxId);
1063
1086
  } finally {
1064
- await sb.emit("sandbox_closed", -1);
1087
+ await sb.emit("sandbox.closed", -1);
1065
1088
  sb.deps.hooks?.onSandboxClosed?.(sb.sandboxId);
1066
1089
  sb.deps.onClose?.();
1067
1090
  }
@@ -1124,7 +1147,7 @@ function requireBroker(sb) {
1124
1147
  */
1125
1148
  async function set(sb, name, value, binding, source) {
1126
1149
  await requireBroker(sb).set(sb.sandboxId, name, value, binding);
1127
- await sb.emit("credential_bound", -1, {
1150
+ await sb.emit("credential.bound", -1, {
1128
1151
  name,
1129
1152
  binding,
1130
1153
  source
@@ -1144,7 +1167,7 @@ async function patch$1(sb, name, changes) {
1144
1167
  binding: changes.binding
1145
1168
  });
1146
1169
  if (changes.binding) {
1147
- await sb.emit("credential_bound", -1, {
1170
+ await sb.emit("credential.bound", -1, {
1148
1171
  name,
1149
1172
  binding: changes.binding,
1150
1173
  source: changes.source
@@ -1155,7 +1178,7 @@ async function patch$1(sb, name, changes) {
1155
1178
  /** Revoke a credential — subsequent matching requests are no longer injected. */
1156
1179
  async function remove$1(sb, name) {
1157
1180
  await requireBroker(sb).remove(sb.sandboxId, name);
1158
- await sb.emit("credential_revoked", -1, { name });
1181
+ await sb.emit("credential.revoked", -1, { name });
1159
1182
  }
1160
1183
  /** List binding metadata (host/injection shape) for this sandbox — never returns values. */
1161
1184
  async function listBindings(sb) {
@@ -1178,12 +1201,12 @@ function client(sb) {
1178
1201
  */
1179
1202
  async function patch(sb, rules) {
1180
1203
  await client(sb).patchRules(sb.sandboxId, rules);
1181
- await sb.emit("egress_rule_added", -1, { rules });
1204
+ await sb.emit("egress.rule_added", -1, { rules });
1182
1205
  }
1183
1206
  /** Remove egress rules from this sandbox's live policy, by `target`. Unknown targets are ignored. */
1184
1207
  async function remove(sb, targets) {
1185
1208
  await client(sb).deleteRules(sb.sandboxId, targets);
1186
- await sb.emit("egress_rule_removed", -1, { targets });
1209
+ await sb.emit("egress.rule_removed", -1, { targets });
1187
1210
  }
1188
1211
  /** This sandbox's current egress policy, as the sidecar reports it. */
1189
1212
  async function get(sb) {
@@ -1212,10 +1235,20 @@ var SandboxHandle = class extends SandboxCore {
1212
1235
  async writeFile(path, content) {
1213
1236
  return writeFile(this, path, content);
1214
1237
  }
1238
+ /** Write raw bytes into the sandbox — for binary content `writeFile`'s string-typed
1239
+ * signature isn't safe for (a gzip tarball, an image). */
1240
+ async writeFileBytes(path, bytes) {
1241
+ return writeFileBytes(this, path, bytes);
1242
+ }
1215
1243
  /** Read a file from the sandbox as a UTF-8 string. */
1216
1244
  async readFile(path) {
1217
1245
  return readFile(this, path);
1218
1246
  }
1247
+ /** Read a file from the sandbox as raw bytes — for binary content `readFile`'s UTF-8
1248
+ * decode would corrupt (a gzip tarball, an image). */
1249
+ async readFileBytes(path) {
1250
+ return readFileBytes(this, path);
1251
+ }
1219
1252
  /** Delete a file from the sandbox. */
1220
1253
  async deleteFile(path) {
1221
1254
  return deleteFile(this, path);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alineo-labs/core",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -30,7 +30,8 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@alineo-labs/logger": "0.1.0",
33
- "@alineo-labs/opensandbox": "0.3.1"
33
+ "@alineo-labs/opensandbox": "0.3.2",
34
+ "@alineo-labs/schema": "0.2.0"
34
35
  },
35
36
  "devDependencies": {
36
37
  "bun-types": "1.4.2",