@alineo-labs/core 0.4.1 → 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,4 +1,6 @@
1
+ import { ConsoleLogger, ILogger, LogLevel, noopLogger } from "@alineo-labs/logger";
1
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";
2
4
  //#region src/ledger.d.ts
3
5
  /** Status of a sandbox session derived from its ledger events. */
4
6
  export declare enum SandboxStatus {
@@ -22,7 +24,7 @@ interface SandboxDetails {
22
24
  * `crypto.randomUUID()` if the caller didn't supply one via `SandboxOptions.runId`.
23
25
  * A resumed, forked, or restored-from-snapshot sandbox always inherits its origin's
24
26
  * `runId` rather than getting a new one, so every sandbox descended from the same
25
- * 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 —
26
28
  * the mechanism `client.sandboxes.list({ runId })` correlates on.
27
29
  */
28
30
  runId: string;
@@ -70,67 +72,62 @@ interface ListSandboxOptions {
70
72
  /** Events emitted during execution and stored in the ledger. */
71
73
  export declare enum LedgerEvent {
72
74
  /** Emitted when a sandbox is created and reaches Running state. */
73
- SandboxCreated = "sandbox_created",
75
+ SandboxCreated = "sandbox.created",
74
76
  /** Emitted at the start of each exec() or execCode() call. */
75
- ExecStart = "exec_start",
77
+ ExecStart = "exec.started",
76
78
  /** Streaming output chunk from exec() or execCode(). */
77
- ExecEvent = "exec_event",
79
+ ExecEvent = "exec.output",
78
80
  /** Emitted when an exec() or execCode() call completes. */
79
- ExecComplete = "exec_complete",
81
+ ExecComplete = "exec.completed",
80
82
  /** Emitted when checkpoint() captures a snapshot. */
81
- CheckpointCreated = "checkpoint_created",
83
+ CheckpointCreated = "sandbox.checkpoint_created",
82
84
  /** Emitted when a sandbox is closed. */
83
- SandboxClosed = "sandbox_closed",
85
+ SandboxClosed = "sandbox.closed",
84
86
  /** Emitted when pause() freezes the container. */
85
- SandboxPaused = "sandbox_paused",
87
+ SandboxPaused = "sandbox.paused",
86
88
  /** Emitted when resume() restores the container to Running. */
87
- SandboxResumed = "sandbox_resumed",
89
+ SandboxResumed = "sandbox.resumed",
88
90
  /**
89
91
  * Emitted by `sb.credentials.set()`/`.patch()`. Payload is binding metadata only
90
92
  * (name, host, injection type) — the credential value is never written to the ledger.
91
93
  */
92
- CredentialBound = "credential_bound",
94
+ CredentialBound = "credential.bound",
93
95
  /** Emitted by `sb.credentials.remove()`. */
94
- CredentialRevoked = "credential_revoked",
96
+ CredentialRevoked = "credential.revoked",
95
97
  /**
96
98
  * Emitted by `sb.egress.patch()`. Payload is `{ rules: NetworkRule[] }` — the exact rules
97
99
  * passed to the sidecar, so `Sandbox.resume()` can fold a still-wanted allowance back into
98
100
  * the resumed sandbox's boot policy (egress policy is sidecar-local and does not survive a
99
101
  * resume). `sb.fork()` does not carry these.
100
102
  */
101
- EgressRuleAdded = "egress_rule_added",
103
+ EgressRuleAdded = "egress.rule_added",
102
104
  /** Emitted by `sb.egress.delete()`. Payload is `{ targets: string[] }`. */
103
- EgressRuleRemoved = "egress_rule_removed",
105
+ EgressRuleRemoved = "egress.rule_removed",
104
106
  /**
105
107
  * Emitted when the permission gate pauses a tool call for human approval. Payload is
106
108
  * `{ requestId, tool, target }` — metadata only; the raw tool arguments (which can carry
107
109
  * secrets in a bash command or a file write) are never written to the ledger.
108
110
  */
109
- PermissionRequested = "permission_requested",
111
+ PermissionRequested = "permission.requested",
110
112
  /**
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 }`.
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.
114
118
  */
115
- PermissionResolved = "permission_resolved",
116
- /** Emitted once when a workflow run starts, before any steps execute. */
117
- RunStarted = "run_started",
118
- /** Emitted at the beginning of each step. */
119
- StepStart = "step_start",
120
- /** Emitted when a step finishes successfully. */
121
- StepComplete = "step_complete",
122
- /** Emitted when a step throws an unrecoverable error. */
123
- StepFailed = "step_failed",
124
- /** Emitted when a step's rollback handler completes during saga compensation. */
125
- StepRolledBack = "step_rolled_back",
126
- /** Emitted after all steps finish without error. */
127
- WorkflowComplete = "workflow_complete",
128
- /** Emitted after rollback completes following a step failure. */
129
- WorkflowFailed = "workflow_failed",
130
- /** Durable resumption point written after each successful step. */
131
- Checkpoint = "checkpoint",
132
- /** Emitted when a sandbox snapshot is captured mid-run. */
133
- 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"
134
131
  }
135
132
  /** A single event record written to the storage adapter during a session. */
136
133
  interface LedgerEntry {
@@ -146,7 +143,7 @@ interface LedgerEntry {
146
143
  event: LedgerEvent;
147
144
  /** Event-specific data (step output, snapshot ID, exec text, etc.). */
148
145
  payload?: unknown;
149
- /** Error message when `event` is `StepFailed` or `WorkflowFailed`. */
146
+ /** Error message, when the event records a failure. */
150
147
  error?: string;
151
148
  }
152
149
  /** A recorded checkpoint for a sandbox session. */
@@ -172,6 +169,49 @@ interface EnvironmentRecord {
172
169
  /** Unix timestamp (ms) when the environment was last built. */
173
170
  builtAt: number;
174
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
+ }
175
215
  /**
176
216
  * Persistence interface for session event storage.
177
217
  *
@@ -216,31 +256,6 @@ interface IStorageAdapter {
216
256
  listEnvironments(): Promise<EnvironmentRecord[]>;
217
257
  }
218
258
  //#endregion
219
- //#region src/logger.d.ts
220
- export declare enum LogLevel {
221
- Debug = 0,
222
- Info = 1,
223
- Warn = 2,
224
- Error = 3,
225
- Silent = 4
226
- }
227
- interface ILogger {
228
- debug(msg: string, meta?: Record<string, unknown>): void;
229
- info(msg: string, meta?: Record<string, unknown>): void;
230
- warn(msg: string, meta?: Record<string, unknown>): void;
231
- error(msg: string, meta?: Record<string, unknown>): void;
232
- }
233
- export declare class ConsoleLogger implements ILogger {
234
- private readonly minLevel;
235
- constructor(minLevel?: LogLevel);
236
- private log;
237
- debug(msg: string, meta?: Record<string, unknown>): void;
238
- info(msg: string, meta?: Record<string, unknown>): void;
239
- warn(msg: string, meta?: Record<string, unknown>): void;
240
- error(msg: string, meta?: Record<string, unknown>): void;
241
- }
242
- export declare const noopLogger: ILogger;
243
- //#endregion
244
259
  //#region src/credentials.d.ts
245
260
  /**
246
261
  * How a credential reaches an outbound request.
@@ -550,6 +565,17 @@ interface SandboxHooks {
550
565
  interface SandboxDeps {
551
566
  control: ControlClient;
552
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;
553
579
  hooks?: SandboxHooks;
554
580
  /** Broker for `sb.credentials.*` — undefined unless the sandbox was created with `credentialProxy: true`. */
555
581
  credentialBroker?: CredentialBroker;
@@ -791,8 +817,14 @@ declare class SandboxCore implements SandboxInternal {
791
817
  export declare class SandboxHandle extends SandboxCore {
792
818
  /** Write a file into the sandbox. */
793
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>;
794
823
  /** Read a file from the sandbox as a UTF-8 string. */
795
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>;
796
828
  /** Delete a file from the sandbox. */
797
829
  deleteFile(path: string): Promise<void>;
798
830
  /** Move or rename a file inside the sandbox. */
@@ -1002,7 +1034,7 @@ export declare class SandboxHandle extends SandboxCore {
1002
1034
  * execd is ready to accept connections.
1003
1035
  *
1004
1036
  * Defaults give ~80s of total patience (retries=45, capped at 2s/attempt), not the ~11s this
1005
- * 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
1006
1038
  * (issue #32): a child forked while its parent sandbox was busy running a real Chrome session
1007
1039
  * took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
1008
1040
  * budget before the exec daemon inside it had actually started accepting connections. An
@@ -1098,4 +1130,4 @@ export declare class StepTimeoutError extends WorkflowError {
1098
1130
  constructor(stepId: string, timeoutMs: number);
1099
1131
  }
1100
1132
  //#endregion
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 };
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
@@ -1,3 +1,4 @@
1
+ import { ConsoleLogger, LogLevel, noopLogger } from "@alineo-labs/logger";
1
2
  import { EgressClient, ExecClient, PtyClient, SSEEventType, SandboxState, SnapshotState } from "@alineo-labs/opensandbox";
2
3
  //#region src/ledger.ts
3
4
  /** Status of a sandbox session derived from its ledger events. */
@@ -9,110 +10,65 @@ let SandboxStatus = /* @__PURE__ */ function(SandboxStatus) {
9
10
  /** Events emitted during execution and stored in the ledger. */
10
11
  let LedgerEvent = /* @__PURE__ */ function(LedgerEvent) {
11
12
  /** Emitted when a sandbox is created and reaches Running state. */
12
- LedgerEvent["SandboxCreated"] = "sandbox_created";
13
+ LedgerEvent["SandboxCreated"] = "sandbox.created";
13
14
  /** Emitted at the start of each exec() or execCode() call. */
14
- LedgerEvent["ExecStart"] = "exec_start";
15
+ LedgerEvent["ExecStart"] = "exec.started";
15
16
  /** Streaming output chunk from exec() or execCode(). */
16
- LedgerEvent["ExecEvent"] = "exec_event";
17
+ LedgerEvent["ExecEvent"] = "exec.output";
17
18
  /** Emitted when an exec() or execCode() call completes. */
18
- LedgerEvent["ExecComplete"] = "exec_complete";
19
+ LedgerEvent["ExecComplete"] = "exec.completed";
19
20
  /** Emitted when checkpoint() captures a snapshot. */
20
- LedgerEvent["CheckpointCreated"] = "checkpoint_created";
21
+ LedgerEvent["CheckpointCreated"] = "sandbox.checkpoint_created";
21
22
  /** Emitted when a sandbox is closed. */
22
- LedgerEvent["SandboxClosed"] = "sandbox_closed";
23
+ LedgerEvent["SandboxClosed"] = "sandbox.closed";
23
24
  /** Emitted when pause() freezes the container. */
24
- LedgerEvent["SandboxPaused"] = "sandbox_paused";
25
+ LedgerEvent["SandboxPaused"] = "sandbox.paused";
25
26
  /** Emitted when resume() restores the container to Running. */
26
- LedgerEvent["SandboxResumed"] = "sandbox_resumed";
27
+ LedgerEvent["SandboxResumed"] = "sandbox.resumed";
27
28
  /**
28
29
  * Emitted by `sb.credentials.set()`/`.patch()`. Payload is binding metadata only
29
30
  * (name, host, injection type) — the credential value is never written to the ledger.
30
31
  */
31
- LedgerEvent["CredentialBound"] = "credential_bound";
32
+ LedgerEvent["CredentialBound"] = "credential.bound";
32
33
  /** Emitted by `sb.credentials.remove()`. */
33
- LedgerEvent["CredentialRevoked"] = "credential_revoked";
34
+ LedgerEvent["CredentialRevoked"] = "credential.revoked";
34
35
  /**
35
36
  * Emitted by `sb.egress.patch()`. Payload is `{ rules: NetworkRule[] }` — the exact rules
36
37
  * passed to the sidecar, so `Sandbox.resume()` can fold a still-wanted allowance back into
37
38
  * the resumed sandbox's boot policy (egress policy is sidecar-local and does not survive a
38
39
  * resume). `sb.fork()` does not carry these.
39
40
  */
40
- LedgerEvent["EgressRuleAdded"] = "egress_rule_added";
41
+ LedgerEvent["EgressRuleAdded"] = "egress.rule_added";
41
42
  /** Emitted by `sb.egress.delete()`. Payload is `{ targets: string[] }`. */
42
- LedgerEvent["EgressRuleRemoved"] = "egress_rule_removed";
43
+ LedgerEvent["EgressRuleRemoved"] = "egress.rule_removed";
43
44
  /**
44
45
  * Emitted when the permission gate pauses a tool call for human approval. Payload is
45
46
  * `{ requestId, tool, target }` — metadata only; the raw tool arguments (which can carry
46
47
  * secrets in a bash command or a file write) are never written to the ledger.
47
48
  */
48
- LedgerEvent["PermissionRequested"] = "permission_requested";
49
+ LedgerEvent["PermissionRequested"] = "permission.requested";
49
50
  /**
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 }`.
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.
53
56
  */
54
- LedgerEvent["PermissionResolved"] = "permission_resolved";
55
- /** Emitted once when a workflow run starts, before any steps execute. */
56
- LedgerEvent["RunStarted"] = "run_started";
57
- /** Emitted at the beginning of each step. */
58
- LedgerEvent["StepStart"] = "step_start";
59
- /** Emitted when a step finishes successfully. */
60
- LedgerEvent["StepComplete"] = "step_complete";
61
- /** Emitted when a step throws an unrecoverable error. */
62
- LedgerEvent["StepFailed"] = "step_failed";
63
- /** Emitted when a step's rollback handler completes during saga compensation. */
64
- LedgerEvent["StepRolledBack"] = "step_rolled_back";
65
- /** Emitted after all steps finish without error. */
66
- LedgerEvent["WorkflowComplete"] = "workflow_complete";
67
- /** Emitted after rollback completes following a step failure. */
68
- LedgerEvent["WorkflowFailed"] = "workflow_failed";
69
- /** Durable resumption point written after each successful step. */
70
- LedgerEvent["Checkpoint"] = "checkpoint";
71
- /** Emitted when a sandbox snapshot is captured mid-run. */
72
- 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";
73
69
  return LedgerEvent;
74
70
  }({});
75
71
  //#endregion
76
- //#region src/logger.ts
77
- let LogLevel = /* @__PURE__ */ function(LogLevel) {
78
- LogLevel[LogLevel["Debug"] = 0] = "Debug";
79
- LogLevel[LogLevel["Info"] = 1] = "Info";
80
- LogLevel[LogLevel["Warn"] = 2] = "Warn";
81
- LogLevel[LogLevel["Error"] = 3] = "Error";
82
- LogLevel[LogLevel["Silent"] = 4] = "Silent";
83
- return LogLevel;
84
- }({});
85
- var ConsoleLogger = class {
86
- minLevel;
87
- constructor(minLevel = 1) {
88
- this.minLevel = minLevel;
89
- }
90
- log(level, prefix, msg, meta) {
91
- if (level < this.minLevel) return;
92
- const out = meta ? `${prefix} ${msg} ${JSON.stringify(meta)}` : `${prefix} ${msg}`;
93
- if (level >= 3) console.error(out);
94
- else console.log(out);
95
- }
96
- debug(msg, meta) {
97
- this.log(0, "[DEBUG]", msg, meta);
98
- }
99
- info(msg, meta) {
100
- this.log(1, "[INFO]", msg, meta);
101
- }
102
- warn(msg, meta) {
103
- this.log(2, "[WARN]", msg, meta);
104
- }
105
- error(msg, meta) {
106
- this.log(3, "[ERROR]", msg, meta);
107
- }
108
- };
109
- const noopLogger = {
110
- debug: () => {},
111
- info: () => {},
112
- warn: () => {},
113
- error: () => {}
114
- };
115
- //#endregion
116
72
  //#region src/errors.ts
117
73
  /** Base class for all alineo workflow runtime errors. */
118
74
  var WorkflowError = class extends Error {
@@ -208,13 +164,13 @@ async function resolveBoundCredential(name, source, resolver, sandboxId) {
208
164
  */
209
165
  function reconstructBoundCredentials(entries) {
210
166
  const result = /* @__PURE__ */ new Map();
211
- for (const entry of entries) if (entry.event === "credential_bound") {
167
+ for (const entry of entries) if (entry.event === "credential.bound") {
212
168
  const { name, binding, source } = entry.payload;
213
169
  result.set(name, {
214
170
  binding,
215
171
  source
216
172
  });
217
- } else if (entry.event === "credential_revoked") {
173
+ } else if (entry.event === "credential.revoked") {
218
174
  const { name } = entry.payload;
219
175
  result.delete(name);
220
176
  }
@@ -237,13 +193,13 @@ function reconstructBoundCredentials(entries) {
237
193
  function reconstructEgressRules(entries) {
238
194
  const byTarget = /* @__PURE__ */ new Map();
239
195
  const removed = /* @__PURE__ */ new Set();
240
- for (const entry of entries) if (entry.event === "egress_rule_added") {
196
+ for (const entry of entries) if (entry.event === "egress.rule_added") {
241
197
  const { rules } = entry.payload;
242
198
  for (const rule of rules) {
243
199
  byTarget.set(rule.target, rule);
244
200
  removed.delete(rule.target);
245
201
  }
246
- } else if (entry.event === "egress_rule_removed") {
202
+ } else if (entry.event === "egress.rule_removed") {
247
203
  const { targets } = entry.payload;
248
204
  for (const target of targets) {
249
205
  byTarget.delete(target);
@@ -457,7 +413,7 @@ var InteractiveExecHandle = class extends ExecHandle {
457
413
  * execd is ready to accept connections.
458
414
  *
459
415
  * Defaults give ~80s of total patience (retries=45, capped at 2s/attempt), not the ~11s this
460
- * 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
461
417
  * (issue #32): a child forked while its parent sandbox was busy running a real Chrome session
462
418
  * took ~35s just to reach `Running`, then immediately exhausted the old ~11s execd-readiness
463
419
  * budget before the exec daemon inside it had actually started accepting connections. An
@@ -631,14 +587,28 @@ var SandboxCore = class {
631
587
  throw new SandboxError(`Snapshot ${snapshotId} did not become ready within ${timeoutMs}ms`, this.sandboxId);
632
588
  }
633
589
  emit(event, stepIndex, payload) {
590
+ const ts = Date.now();
634
591
  const entry = {
635
- ts: Date.now(),
592
+ ts,
636
593
  name: this.name,
637
594
  sandboxId: this.sandboxId,
638
595
  stepIndex,
639
596
  event,
640
597
  payload
641
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 {}
642
612
  const result = this._ledgerQueue.then(() => this.deps.adapter.append(entry));
643
613
  this._ledgerQueue = result.catch(() => {});
644
614
  return result;
@@ -654,7 +624,7 @@ var SandboxCore = class {
654
624
  const self = this;
655
625
  async function* stream() {
656
626
  const execClient = await self.getExecClient();
657
- await self.emit("exec_start", seq, {
627
+ await self.emit("exec.started", seq, {
658
628
  cmd,
659
629
  seq
660
630
  });
@@ -667,7 +637,7 @@ var SandboxCore = class {
667
637
  envs: opts.env,
668
638
  timeout: opts.timeoutMs
669
639
  })) {
670
- await self.emit("exec_event", seq, {
640
+ await self.emit("exec.output", seq, {
671
641
  seq,
672
642
  ...ev
673
643
  });
@@ -678,7 +648,7 @@ var SandboxCore = class {
678
648
  type: "stream",
679
649
  gen: stream(),
680
650
  onDone: async (result) => {
681
- await self.emit("exec_complete", seq, {
651
+ await self.emit("exec.completed", seq, {
682
652
  exitCode: result.exitCode,
683
653
  seq
684
654
  });
@@ -698,7 +668,7 @@ var SandboxCore = class {
698
668
  const pending = this.pendingInteractive.get(seq);
699
669
  const self = this;
700
670
  let closer;
701
- const execStartLogged = self.emit("exec_start", seq, {
671
+ const execStartLogged = self.emit("exec.started", seq, {
702
672
  cmd,
703
673
  seq,
704
674
  interactive: true,
@@ -720,7 +690,7 @@ var SandboxCore = class {
720
690
  await pty.connect(sessionId, (chunk) => {
721
691
  onFirstOutput?.();
722
692
  onFirstOutput = void 0;
723
- self.emit("exec_event", seq, {
693
+ self.emit("exec.output", seq, {
724
694
  seq,
725
695
  type: "stdout",
726
696
  text: chunk
@@ -754,7 +724,7 @@ var SandboxCore = class {
754
724
  },
755
725
  onDone: async (result) => {
756
726
  if (closer) self.openSessionClosers.delete(closer);
757
- await self.emit("exec_complete", seq, {
727
+ await self.emit("exec.completed", seq, {
758
728
  exitCode: result.exitCode,
759
729
  seq
760
730
  });
@@ -763,7 +733,7 @@ var SandboxCore = class {
763
733
  }
764
734
  }, {
765
735
  write: (data) => {
766
- execStartLogged.then(() => self.emit("exec_event", seq, {
736
+ execStartLogged.then(() => self.emit("exec.output", seq, {
767
737
  seq,
768
738
  type: "stdin",
769
739
  text: data
@@ -824,7 +794,7 @@ var SandboxCore = class {
824
794
  const self = this;
825
795
  async function* stream() {
826
796
  const execClient = await self.getExecClient();
827
- await self.emit("exec_start", seq, {
797
+ await self.emit("exec.started", seq, {
828
798
  code,
829
799
  seq
830
800
  });
@@ -832,7 +802,7 @@ var SandboxCore = class {
832
802
  code,
833
803
  context: opts.context
834
804
  })) {
835
- await self.emit("exec_event", seq, {
805
+ await self.emit("exec.output", seq, {
836
806
  seq,
837
807
  ...ev
838
808
  });
@@ -843,7 +813,7 @@ var SandboxCore = class {
843
813
  type: "stream",
844
814
  gen: stream(),
845
815
  onDone: async (result) => {
846
- await self.emit("exec_complete", seq, {
816
+ await self.emit("exec.completed", seq, {
847
817
  exitCode: result.exitCode,
848
818
  seq
849
819
  });
@@ -876,7 +846,7 @@ var SandboxCore = class {
876
846
  const execInSession = (command, cmdOpts) => {
877
847
  const seq = ++self._seq;
878
848
  async function* stream() {
879
- await self.emit("exec_start", seq, {
849
+ await self.emit("exec.started", seq, {
880
850
  cmd: command,
881
851
  seq,
882
852
  sessionId
@@ -887,7 +857,7 @@ var SandboxCore = class {
887
857
  cwd: cmdOpts?.cwd,
888
858
  timeout: cmdOpts?.timeoutMs
889
859
  })) {
890
- await self.emit("exec_event", seq, {
860
+ await self.emit("exec.output", seq, {
891
861
  seq,
892
862
  ...ev
893
863
  });
@@ -898,7 +868,7 @@ var SandboxCore = class {
898
868
  type: "stream",
899
869
  gen: stream(),
900
870
  onDone: async (result) => {
901
- await self.emit("exec_complete", seq, {
871
+ await self.emit("exec.completed", seq, {
902
872
  exitCode: result.exitCode,
903
873
  seq
904
874
  });
@@ -921,8 +891,18 @@ var SandboxCore = class {
921
891
  async function writeFile(sb, path, content) {
922
892
  await (await sb.getExecClient()).uploadFile(path, content);
923
893
  }
924
- /** Read a file from the sandbox as a UTF-8 string. */
925
- 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) {
926
906
  const reader = (await (await sb.getExecClient()).downloadFile(path)).getReader();
927
907
  const chunks = [];
928
908
  while (true) {
@@ -937,7 +917,11 @@ async function readFile(sb, path) {
937
917
  merged.set(chunk, offset);
938
918
  offset += chunk.length;
939
919
  }
940
- 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));
941
925
  }
942
926
  /** Delete a file from the sandbox. */
943
927
  async function deleteFile(sb, path) {
@@ -993,7 +977,7 @@ async function pause(sb) {
993
977
  sb.setPaused(true);
994
978
  sb.disposeExecClient();
995
979
  sb.clearExecClient();
996
- await sb.emit("sandbox_paused", -1);
980
+ await sb.emit("sandbox.paused", -1);
997
981
  sb.deps.hooks?.onSandboxPaused?.(sb.sandboxId);
998
982
  }
999
983
  /**
@@ -1009,7 +993,7 @@ async function resume(sb) {
1009
993
  await sb.deps.control.resumeSandbox(sb.sandboxId);
1010
994
  sb.setPaused(false);
1011
995
  await sb.waitForRunning();
1012
- await sb.emit("sandbox_resumed", -1);
996
+ await sb.emit("sandbox.resumed", -1);
1013
997
  sb.deps.hooks?.onSandboxResumed?.(sb.sandboxId);
1014
998
  }
1015
999
  /**
@@ -1022,7 +1006,7 @@ async function resume(sb) {
1022
1006
  async function checkpoint(sb, name) {
1023
1007
  const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
1024
1008
  await sb.waitForSnapshot(snap.id);
1025
- await sb.emit("checkpoint_created", -1, {
1009
+ await sb.emit("sandbox.checkpoint_created", -1, {
1026
1010
  snapshotId: snap.id,
1027
1011
  name
1028
1012
  });
@@ -1038,7 +1022,7 @@ async function checkpoint(sb, name) {
1038
1022
  *
1039
1023
  * @param runId Override the forked sandbox's run correlation ID instead of inheriting
1040
1024
  * whatever this sandbox's own creation closed over. Needed when forking across a process
1041
- * 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
1042
1026
  * no access to the original in-memory closure) — the caller reads the correct value from
1043
1027
  * `process.env.ALINEO_RUN_ID` and passes it explicitly rather than relying on this sandbox's
1044
1028
  * own (possibly unknown) default.
@@ -1062,7 +1046,7 @@ async function fork(sb, tag, runId, opts) {
1062
1046
  if (!sb.deps.fork) throw new SandboxError("fork() is not supported on this sandbox", sb.sandboxId);
1063
1047
  const snap = await sb.deps.control.createSnapshot(sb.sandboxId);
1064
1048
  await sb.waitForSnapshot(snap.id);
1065
- await sb.emit("checkpoint_created", -1, {
1049
+ await sb.emit("sandbox.checkpoint_created", -1, {
1066
1050
  snapshotId: snap.id,
1067
1051
  name: tag
1068
1052
  });
@@ -1100,7 +1084,7 @@ async function close(sb) {
1100
1084
  try {
1101
1085
  await sb.deps.control.deleteSandbox(sb.sandboxId);
1102
1086
  } finally {
1103
- await sb.emit("sandbox_closed", -1);
1087
+ await sb.emit("sandbox.closed", -1);
1104
1088
  sb.deps.hooks?.onSandboxClosed?.(sb.sandboxId);
1105
1089
  sb.deps.onClose?.();
1106
1090
  }
@@ -1163,7 +1147,7 @@ function requireBroker(sb) {
1163
1147
  */
1164
1148
  async function set(sb, name, value, binding, source) {
1165
1149
  await requireBroker(sb).set(sb.sandboxId, name, value, binding);
1166
- await sb.emit("credential_bound", -1, {
1150
+ await sb.emit("credential.bound", -1, {
1167
1151
  name,
1168
1152
  binding,
1169
1153
  source
@@ -1183,7 +1167,7 @@ async function patch$1(sb, name, changes) {
1183
1167
  binding: changes.binding
1184
1168
  });
1185
1169
  if (changes.binding) {
1186
- await sb.emit("credential_bound", -1, {
1170
+ await sb.emit("credential.bound", -1, {
1187
1171
  name,
1188
1172
  binding: changes.binding,
1189
1173
  source: changes.source
@@ -1194,7 +1178,7 @@ async function patch$1(sb, name, changes) {
1194
1178
  /** Revoke a credential — subsequent matching requests are no longer injected. */
1195
1179
  async function remove$1(sb, name) {
1196
1180
  await requireBroker(sb).remove(sb.sandboxId, name);
1197
- await sb.emit("credential_revoked", -1, { name });
1181
+ await sb.emit("credential.revoked", -1, { name });
1198
1182
  }
1199
1183
  /** List binding metadata (host/injection shape) for this sandbox — never returns values. */
1200
1184
  async function listBindings(sb) {
@@ -1217,12 +1201,12 @@ function client(sb) {
1217
1201
  */
1218
1202
  async function patch(sb, rules) {
1219
1203
  await client(sb).patchRules(sb.sandboxId, rules);
1220
- await sb.emit("egress_rule_added", -1, { rules });
1204
+ await sb.emit("egress.rule_added", -1, { rules });
1221
1205
  }
1222
1206
  /** Remove egress rules from this sandbox's live policy, by `target`. Unknown targets are ignored. */
1223
1207
  async function remove(sb, targets) {
1224
1208
  await client(sb).deleteRules(sb.sandboxId, targets);
1225
- await sb.emit("egress_rule_removed", -1, { targets });
1209
+ await sb.emit("egress.rule_removed", -1, { targets });
1226
1210
  }
1227
1211
  /** This sandbox's current egress policy, as the sidecar reports it. */
1228
1212
  async function get(sb) {
@@ -1251,10 +1235,20 @@ var SandboxHandle = class extends SandboxCore {
1251
1235
  async writeFile(path, content) {
1252
1236
  return writeFile(this, path, content);
1253
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
+ }
1254
1243
  /** Read a file from the sandbox as a UTF-8 string. */
1255
1244
  async readFile(path) {
1256
1245
  return readFile(this, path);
1257
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
+ }
1258
1252
  /** Delete a file from the sandbox. */
1259
1253
  async deleteFile(path) {
1260
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.1",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -29,7 +29,9 @@
29
29
  "test:watch": "vitest"
30
30
  },
31
31
  "dependencies": {
32
- "@alineo-labs/opensandbox": "0.3.0"
32
+ "@alineo-labs/logger": "0.1.0",
33
+ "@alineo-labs/opensandbox": "0.3.2",
34
+ "@alineo-labs/schema": "0.2.0"
33
35
  },
34
36
  "devDependencies": {
35
37
  "bun-types": "1.4.2",