@moinulmoin/eden-runtime-cloudflare 0.6.0 → 0.7.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.
@@ -23810,8 +23810,30 @@ var EVE_HOST_DEFAULTS = {
23810
23810
  healthPath: "/eve/v1/health",
23811
23811
  internalPort: 8080,
23812
23812
  instance: "standard-1",
23813
- sleepAfter: "24h"
23813
+ sleepAfter: "1h"
23814
23814
  };
23815
+ var EVE_HOST_SLEEP_SNAPSHOT_MARGIN_MS = 15 * 6e4;
23816
+ var EVE_HOST_MAX_SLEEP_AFTER_MS = 6 * 36e5 - EVE_HOST_SLEEP_SNAPSHOT_MARGIN_MS;
23817
+ function parseEveSleepAfterMs(value) {
23818
+ const match = /^([0-9]+)(ms|s|m|h|d)?$/u.exec(value.trim());
23819
+ if (match === null) {
23820
+ throw new EveHostError(
23821
+ "HOST_READINESS_UNPROVEN",
23822
+ "The Container sleepAfter override is not a parseable duration."
23823
+ );
23824
+ }
23825
+ const amount = Number.parseInt(match[1] ?? "", 10);
23826
+ const unit = match[2] ?? "s";
23827
+ const factor = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
23828
+ const ms2 = amount * factor;
23829
+ if (ms2 > EVE_HOST_MAX_SLEEP_AFTER_MS) {
23830
+ throw new EveHostError(
23831
+ "HOST_READINESS_UNPROVEN",
23832
+ "The Container sleepAfter override exceeds 345m (5 h 45 min); Cloudflare stops a container within 6 hours of its Durable Object going idle, so Eden must snapshot before then."
23833
+ );
23834
+ }
23835
+ return ms2;
23836
+ }
23815
23837
  var EVE_SCHEDULE_WAKE_LEAD_MS = 24e4;
23816
23838
  var EVE_SCHEDULE_WAKE_GRACE_MS = 6e4;
23817
23839
  var MINUTE_MS = 6e4;
@@ -23944,15 +23966,7 @@ function isEveWorkflowInternalRoute(pathname) {
23944
23966
  }
23945
23967
  var EVE_HOST_OWNED_HEADERS = [
23946
23968
  "forwarded",
23947
- "x-forwarded-for",
23948
- "x-forwarded-host",
23949
- "x-forwarded-port",
23950
- "x-forwarded-proto",
23951
- "x-forwarded-server",
23952
- "x-forwarded-scheme",
23953
23969
  "x-real-ip",
23954
- "cf-connecting-ip",
23955
- "cf-visitor",
23956
23970
  "true-client-ip",
23957
23971
  "x-original-host",
23958
23972
  "x-original-proto",
@@ -23961,23 +23975,11 @@ var EVE_HOST_OWNED_HEADERS = [
23961
23975
  "x-proxy-host",
23962
23976
  "x-host",
23963
23977
  "x-eve-public-origin",
23964
- "x-workflow-local-base-url",
23965
- "x-eden-eve-callback-base",
23966
- "x-eden-eve-deployment-id",
23967
- "x-eden-eve-generation-id",
23968
- "x-eden-eve-started-deployment",
23969
- "x-eden-eve-public-origin",
23970
- "x-eden-eve-correlation-id",
23971
- "x-eden-eve-container-name",
23972
- "x-eden-eve-container-id",
23973
- "x-eden-eve-runtime-revision",
23974
- "x-eden-container-name",
23975
- "x-eden-container-id",
23976
- "cf-container-target-port"
23978
+ "x-workflow-local-base-url"
23977
23979
  ];
23978
23980
  var EVE_HOST_OWNED_HEADER_SET = new Set(EVE_HOST_OWNED_HEADERS);
23979
23981
  var WORKER_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
23980
- var SUBDOMAIN_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
23982
+ var SUBDOMAIN_PATTERN = WORKER_NAME_PATTERN;
23981
23983
  var IDENTIFIER_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
23982
23984
  var EveHostError = class extends Error {
23983
23985
  code;
@@ -24090,21 +24092,6 @@ function throwIfAborted(signal) {
24090
24092
  );
24091
24093
  }
24092
24094
  }
24093
- function createEveHostLifecycleObserver(now = Date.now) {
24094
- const events = [];
24095
- return {
24096
- events,
24097
- record(type, safeStatus) {
24098
- const event = {
24099
- type,
24100
- at: now(),
24101
- ...safeStatus === void 0 ? {} : { safeStatus }
24102
- };
24103
- events.push(event);
24104
- return event;
24105
- }
24106
- };
24107
- }
24108
24095
  function responseBodyIsReady(value) {
24109
24096
  if (typeof value !== "object" || value === null) return false;
24110
24097
  const record2 = value;
@@ -24336,18 +24323,23 @@ function createEveReadinessGate(options) {
24336
24323
 
24337
24324
  // src/eve-host-runtime.ts
24338
24325
  var EVE_CLOUDFLARE_CONTAINERS_CA_PATH = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";
24326
+ var EVE_HOST_ENTRYPOINT = Object.freeze([
24327
+ "/bin/sh",
24328
+ "-c",
24329
+ "rm -f /dev/kvm; cd /workspace && exec ./node_modules/.bin/eve start --host 0.0.0.0 --port 8080"
24330
+ ]);
24339
24331
  var EVE_HOST_CONTAINER_ACTIVITY_KEY = "eden.eve.host.last-activity-at";
24340
24332
  var EVE_HOST_CONTAINER_SNAPSHOT_KEY = "eden.eve.host.workspace-snapshot";
24341
24333
  var EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY = "eden.eve.host.snapshot-attempts";
24334
+ var EVE_HOST_CONTAINER_STARTED_IMAGE_KEY = "eden.eve.host.started-image";
24335
+ var EVE_HOST_SANDBOX_CARRY_KEY = "eden.eve.host.sandbox-carry";
24336
+ var EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX = "eden.eve.host.sandbox-carry";
24337
+ var EVE_HOST_SANDBOX_CARRY_SOURCE = "/workspace/.eve/sandbox-cache/just-bash";
24338
+ var EVE_HOST_CARRY_LIMITS = {
24339
+ chunkBytes: 1024 * 1024,
24340
+ maxBytes: 1024 * 1024 * 1024
24341
+ };
24342
24342
  var EVE_HOST_SNAPSHOT_MAX_ATTEMPTS = 3;
24343
- function sleepAfterDurationMs(value) {
24344
- const match = /^([0-9]+)(ms|s|m|h|d)?$/u.exec(value.trim());
24345
- if (match === null) return void 0;
24346
- const amount = Number.parseInt(match[1] ?? "", 10);
24347
- const unit = match[2] ?? "s";
24348
- const factor = unit === "ms" ? 1 : unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
24349
- return amount * factor;
24350
- }
24351
24343
  var EdenWorldDurableObject = class {
24352
24344
  core;
24353
24345
  constructor(ctx, env) {
@@ -24363,12 +24355,11 @@ var EdenWorldDurableObject = class {
24363
24355
  delivery: {
24364
24356
  deliver: async (message) => {
24365
24357
  const origin = env.EVE_PUBLIC_ORIGIN;
24366
- const binding = env.EVE_CONTAINER_BINDING_NAME;
24367
24358
  const instance = env.EVE_CONTAINER_INSTANCE_NAME;
24368
- if (typeof origin !== "string" || typeof binding !== "string" || typeof instance !== "string") {
24359
+ if (typeof origin !== "string" || typeof instance !== "string") {
24369
24360
  throw new Error("The World queue Container identity is unavailable.");
24370
24361
  }
24371
- const namespace = env[binding];
24362
+ const namespace = env.EVE_CONTAINER;
24372
24363
  const response = await namespace.getByName(instance).loopbackFetch(
24373
24364
  new Request(new URL(`/.well-known/workflow/v1/${message.path}`, origin), {
24374
24365
  method: "POST",
@@ -24411,16 +24402,14 @@ var EdenWorldDurableObject = class {
24411
24402
  };
24412
24403
  async function routeEveOutboundRequest(request, env) {
24413
24404
  const publicOrigin = env.EVE_PUBLIC_ORIGIN;
24414
- const bindingName = env.EVE_CONTAINER_BINDING_NAME;
24415
24405
  const instanceName = env.EVE_CONTAINER_INSTANCE_NAME;
24416
- if (typeof publicOrigin !== "string" || typeof bindingName !== "string" || typeof instanceName !== "string") {
24406
+ if (typeof publicOrigin !== "string" || typeof instanceName !== "string") {
24417
24407
  throw new EveHostError(
24418
24408
  "HOST_ORIGIN_UNAVAILABLE",
24419
24409
  "The container loopback identity is unavailable to the outbound handler."
24420
24410
  );
24421
24411
  }
24422
24412
  assertStableOrigin(publicOrigin);
24423
- assertNonEmpty(bindingName, "Container binding name");
24424
24413
  assertNonEmpty(instanceName, "Container instance name");
24425
24414
  const hostname3 = new URL(request.url).hostname;
24426
24415
  if (hostname3 !== new URL(publicOrigin).hostname) {
@@ -24431,7 +24420,7 @@ async function routeEveOutboundRequest(request, env) {
24431
24420
  if (world === void 0) return new Response(null, { status: 404 });
24432
24421
  return world.get(world.idFromName("world")).fetch(request);
24433
24422
  }
24434
- const namespace = env[bindingName];
24423
+ const namespace = env.EVE_CONTAINER;
24435
24424
  if (namespace === void 0) {
24436
24425
  throw new EveHostError(
24437
24426
  "HOST_READINESS_UNPROVEN",
@@ -24446,8 +24435,6 @@ var EveHostLoopback = class extends WorkerEntrypoint {
24446
24435
  }
24447
24436
  };
24448
24437
  var EveHostDurableContainer = class extends DurableObject {
24449
- lifecycle = createEveHostLifecycleObserver();
24450
- readinessStarted = false;
24451
24438
  /** Evidence is cached only while the container it was proven on keeps running. */
24452
24439
  readinessEvidence;
24453
24440
  /** True once the running container's image was proven to equal `images.eve`. */
@@ -24459,6 +24446,12 @@ var EveHostDurableContainer = class extends DurableObject {
24459
24446
  */
24460
24447
  readinessEpoch = 0;
24461
24448
  monitorAttached = false;
24449
+ /** Serializes sandbox-session carry-outs on this Durable Object instance. */
24450
+ carryOutQueue = Promise.resolve();
24451
+ /** True only while the last start was fresh from `images.eve`, not a snapshot. */
24452
+ pendingCarryRestore = false;
24453
+ /** Shared single-flight carry restore for the current container generation. */
24454
+ carryRestorePromise;
24462
24455
  envVars;
24463
24456
  sleepAfterMs;
24464
24457
  readiness;
@@ -24495,13 +24488,9 @@ var EveHostDurableContainer = class extends DurableObject {
24495
24488
  NODE_EXTRA_CA_CERTS: EVE_CLOUDFLARE_CONTAINERS_CA_PATH,
24496
24489
  ...env.EDEN_EVE_RUNTIME_REVISION === void 0 ? {} : { EDEN_EVE_RUNTIME_REVISION: env.EDEN_EVE_RUNTIME_REVISION }
24497
24490
  };
24498
- const sleepAfterOverride = env.EDEN_EVE_CONTAINER_SLEEP_AFTER;
24499
- this.sleepAfterMs = sleepAfterOverride === void 0 ? sleepAfterDurationMs(EVE_HOST_DEFAULTS.sleepAfter) ?? 864e5 : sleepAfterDurationMs(sleepAfterOverride) ?? (() => {
24500
- throw new EveHostError(
24501
- "HOST_READINESS_UNPROVEN",
24502
- "The Container sleepAfter override is not a parseable duration."
24503
- );
24504
- })();
24491
+ this.sleepAfterMs = parseEveSleepAfterMs(
24492
+ env.EDEN_EVE_CONTAINER_SLEEP_AFTER ?? EVE_HOST_DEFAULTS.sleepAfter
24493
+ );
24505
24494
  this.readiness = createEveReadinessGate({
24506
24495
  start: async () => {
24507
24496
  await this.ensureContainerStarted();
@@ -24531,9 +24520,10 @@ var EveHostDurableContainer = class extends DurableObject {
24531
24520
  containerRuntime() {
24532
24521
  return this.ctx.container;
24533
24522
  }
24534
- /** Container lifetime the platform keeps after the DO goes inactive. */
24523
+ /** Container lifetime the platform keeps after the DO goes inactive: long
24524
+ * enough for the idle alarm to snapshot first, within Cloudflare's 6 h cap. */
24535
24525
  get inactivityTimeoutMs() {
24536
- return this.sleepAfterMs + 15 * 6e4;
24526
+ return this.sleepAfterMs + EVE_HOST_SLEEP_SNAPSHOT_MARGIN_MS;
24537
24527
  }
24538
24528
  attachMonitor(runtime) {
24539
24529
  if (this.monitorAttached) return;
@@ -24541,23 +24531,21 @@ var EveHostDurableContainer = class extends DurableObject {
24541
24531
  runtime.monitor().then(
24542
24532
  () => {
24543
24533
  this.monitorAttached = false;
24544
- this.recordContainerStopped("exit");
24534
+ this.recordContainerStopped();
24545
24535
  },
24546
- (error61) => {
24536
+ () => {
24547
24537
  this.monitorAttached = false;
24548
- this.recordContainerStopped(
24549
- error61 instanceof Error ? error61.name : "runtime_signal"
24550
- );
24538
+ this.recordContainerStopped();
24551
24539
  }
24552
24540
  );
24553
24541
  }
24554
- recordContainerStopped(reason) {
24542
+ recordContainerStopped() {
24555
24543
  this.readinessEpoch += 1;
24556
- this.readinessStarted = false;
24557
24544
  this.readinessEvidence = void 0;
24558
24545
  this.imageVerified = false;
24546
+ this.pendingCarryRestore = false;
24547
+ this.carryRestorePromise = void 0;
24559
24548
  this.readiness.reset();
24560
- this.lifecycle.record("stopped", reason);
24561
24549
  }
24562
24550
  /** Routes the container's own requests to its public origin back inside. */
24563
24551
  async registerLoopbackIntercept(runtime) {
@@ -24585,7 +24573,7 @@ var EveHostDurableContainer = class extends DurableObject {
24585
24573
  * is restored only when it was captured from the exact image this Worker
24586
24574
  * version configures — restoring an older snapshot silently runs the
24587
24575
  * previous image — so after an image update the container starts fresh and
24588
- * workspace files intentionally do not carry across.
24576
+ * the readiness path restores the carried sandbox sessions instead.
24589
24577
  */
24590
24578
  async ensureContainerStarted() {
24591
24579
  const runtime = this.containerRuntime();
@@ -24606,24 +24594,26 @@ var EveHostDurableContainer = class extends DurableObject {
24606
24594
  const storedSnapshot = await this.ctx.storage.get(
24607
24595
  EVE_HOST_CONTAINER_SNAPSHOT_KEY
24608
24596
  );
24609
- if (this.lifecycle.events.some((event) => event.type === "started")) {
24610
- this.lifecycle.record("replaced");
24611
- }
24597
+ const snapshotId = storedSnapshot !== void 0 && storedSnapshot.image === expectedImage ? storedSnapshot.id : void 0;
24612
24598
  runtime.start({
24613
- ...storedSnapshot !== void 0 && storedSnapshot.image === expectedImage ? { containerSnapshot: { id: storedSnapshot.id } } : { image: expectedImage },
24599
+ ...snapshotId === void 0 ? { image: expectedImage } : { containerSnapshot: { id: snapshotId } },
24614
24600
  instance: EVE_HOST_DEFAULTS.instance,
24615
24601
  enableInternet: true,
24616
- env: this.envVars
24602
+ env: this.envVars,
24603
+ entrypoint: EVE_HOST_ENTRYPOINT
24617
24604
  });
24605
+ this.pendingCarryRestore = snapshotId === void 0;
24606
+ await this.ctx.storage.put(EVE_HOST_CONTAINER_STARTED_IMAGE_KEY, expectedImage);
24618
24607
  await this.registerLoopbackIntercept(runtime);
24619
24608
  this.attachMonitor(runtime);
24620
24609
  await runtime.setInactivityTimeout(this.inactivityTimeoutMs);
24621
- this.lifecycle.record("started");
24622
24610
  }
24623
24611
  /**
24624
- * Replaces the running container when `inspect()` proves it still serves a
24625
- * pre-update image: this Worker version's `images.eve` is selected at
24626
- * `start()`, so an in-place update must stop the stale instance itself.
24612
+ * Replaces the running container when it still serves a pre-update image:
24613
+ * this Worker version's `images.eve` is selected at `start()`, so an
24614
+ * in-place update must stop the stale instance itself. `inspect()` reports
24615
+ * an empty image for a snapshot-restored container, so the image recorded
24616
+ * at start stands in for it.
24627
24617
  */
24628
24618
  async reconcileRunningImage() {
24629
24619
  if (this.imageVerified) return;
@@ -24636,51 +24626,247 @@ var EveHostDurableContainer = class extends DurableObject {
24636
24626
  } catch {
24637
24627
  info = null;
24638
24628
  }
24639
- if (info?.image === expectedImage) {
24629
+ const runningImage = info?.image !== void 0 && info.image !== "" ? info.image : await this.ctx.storage.get(EVE_HOST_CONTAINER_STARTED_IMAGE_KEY);
24630
+ if (runningImage === expectedImage) {
24640
24631
  this.imageVerified = true;
24641
24632
  return;
24642
24633
  }
24643
- this.lifecycle.record("image_mismatch");
24644
- this.recordContainerStopped("replaced");
24634
+ this.recordContainerStopped();
24635
+ try {
24636
+ await this.carrySandboxSessionsOut(runtime);
24637
+ } catch (error61) {
24638
+ console.error(
24639
+ "The Eve sandbox session carry failed before the image update:",
24640
+ error61 instanceof Error ? error61.message : "unknown"
24641
+ );
24642
+ }
24645
24643
  await runtime.destroy();
24646
24644
  const stoppedAt = Date.now();
24647
24645
  while (runtime.running && Date.now() - stoppedAt < 1e4) {
24648
24646
  await new Promise((resolve) => setTimeout(resolve, 25));
24649
24647
  }
24650
24648
  }
24649
+ /**
24650
+ * Streams `/workspace/.eve/sandbox-cache/just-bash/sessions` — every
24651
+ * conversation's sandbox files and metadata — into Durable Object storage,
24652
+ * so a fresh container started by an image update can restore them. Not
24653
+ * carried: templates and the rest of `/workspace`, which come from the new
24654
+ * image. One carry runs at a time on this Durable Object; a failure never
24655
+ * blocks the destroy that follows and leaves the previous carry intact.
24656
+ */
24657
+ carrySandboxSessionsOut(runtime) {
24658
+ const run = this.carryOutQueue.then(
24659
+ () => this.carrySandboxSessionsOutNow(runtime)
24660
+ );
24661
+ this.carryOutQueue = run.then(
24662
+ () => void 0,
24663
+ () => void 0
24664
+ );
24665
+ return run;
24666
+ }
24667
+ async carrySandboxSessionsOutNow(runtime) {
24668
+ const previous = await this.ctx.storage.get(
24669
+ EVE_HOST_SANDBOX_CARRY_KEY
24670
+ );
24671
+ const carryId = globalThis.crypto.randomUUID();
24672
+ const chunkPrefix = `${EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX}.${carryId}.`;
24673
+ const writtenChunkKeys = [];
24674
+ const discardWrittenChunks = async () => {
24675
+ for (const key of writtenChunkKeys) await this.ctx.storage.delete(key);
24676
+ };
24677
+ const exec = await runtime.exec(
24678
+ [
24679
+ "sh",
24680
+ "-c",
24681
+ `cd ${EVE_HOST_SANDBOX_CARRY_SOURCE} && [ -d sessions ] && tar -czf - sessions || true`
24682
+ ],
24683
+ { stdout: "pipe", stderr: "pipe" }
24684
+ );
24685
+ const buffered = [];
24686
+ let bufferedBytes = 0;
24687
+ let chunks = 0;
24688
+ let bytes2 = 0;
24689
+ const flushOnce = async () => {
24690
+ if (bufferedBytes === 0) return;
24691
+ const size = Math.min(bufferedBytes, EVE_HOST_CARRY_LIMITS.chunkBytes);
24692
+ const value = new Uint8Array(size);
24693
+ let offset = 0;
24694
+ while (offset < size) {
24695
+ const part = buffered[0];
24696
+ if (part === void 0) break;
24697
+ const take = Math.min(part.byteLength, size - offset);
24698
+ value.set(
24699
+ take === part.byteLength ? part : part.subarray(0, take),
24700
+ offset
24701
+ );
24702
+ offset += take;
24703
+ if (take === part.byteLength) buffered.shift();
24704
+ else buffered[0] = part.subarray(take);
24705
+ }
24706
+ bufferedBytes -= size;
24707
+ const key = `${chunkPrefix}${chunks}`;
24708
+ writtenChunkKeys.push(key);
24709
+ await this.ctx.storage.put(key, value);
24710
+ chunks += 1;
24711
+ bytes2 += value.byteLength;
24712
+ };
24713
+ const flushBufferedChunks = async () => {
24714
+ while (bufferedBytes >= EVE_HOST_CARRY_LIMITS.chunkBytes) {
24715
+ await flushOnce();
24716
+ }
24717
+ };
24718
+ try {
24719
+ const stdout = exec.stdout;
24720
+ if (stdout === null) throw new Error("the exec stdout was not piped");
24721
+ const reader = stdout.getReader();
24722
+ let overflowed = false;
24723
+ for (; ; ) {
24724
+ const { done, value } = await reader.read();
24725
+ if (done) break;
24726
+ if (value === void 0) continue;
24727
+ buffered.push(value);
24728
+ bufferedBytes += value.byteLength;
24729
+ if (bytes2 + bufferedBytes > EVE_HOST_CARRY_LIMITS.maxBytes) {
24730
+ overflowed = true;
24731
+ break;
24732
+ }
24733
+ await flushBufferedChunks();
24734
+ }
24735
+ await reader.cancel().catch(() => void 0);
24736
+ if (overflowed) {
24737
+ await discardWrittenChunks();
24738
+ console.error(
24739
+ `The Eve sandbox session carry exceeded ${EVE_HOST_CARRY_LIMITS.maxBytes} compressed bytes; keeping the previous carry.`
24740
+ );
24741
+ return;
24742
+ }
24743
+ await flushOnce();
24744
+ } catch (error61) {
24745
+ await discardWrittenChunks();
24746
+ throw error61;
24747
+ }
24748
+ let exitCode = -1;
24749
+ try {
24750
+ exitCode = await exec.exitCode;
24751
+ } catch {
24752
+ exitCode = -1;
24753
+ }
24754
+ if (exitCode !== 0) {
24755
+ await discardWrittenChunks();
24756
+ console.error(
24757
+ `The Eve sandbox session carry failed with exit code ${exitCode}; keeping the previous carry.`
24758
+ );
24759
+ return;
24760
+ }
24761
+ if (bytes2 === 0) {
24762
+ return;
24763
+ }
24764
+ await this.ctx.storage.put(EVE_HOST_SANDBOX_CARRY_KEY, {
24765
+ id: carryId,
24766
+ chunks,
24767
+ bytes: bytes2,
24768
+ at: Date.now()
24769
+ });
24770
+ if (previous !== void 0) {
24771
+ for (let index = 0; index < previous.chunks; index += 1) {
24772
+ await this.ctx.storage.delete(
24773
+ `${EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX}.${previous.id}.${index}`
24774
+ );
24775
+ }
24776
+ }
24777
+ }
24778
+ /**
24779
+ * Single restore per fresh container generation, shared by every
24780
+ * concurrent readiness caller: the first caller starts it, everyone awaits
24781
+ * the same promise, and no request is forwarded before it settles.
24782
+ */
24783
+ async restoreCarriedSandboxSessions() {
24784
+ if (!this.pendingCarryRestore) return;
24785
+ this.carryRestorePromise ??= this.carrySandboxSessionsIn();
24786
+ await this.carryRestorePromise;
24787
+ this.pendingCarryRestore = false;
24788
+ }
24789
+ /**
24790
+ * Extracts the carried sandbox sessions into a container that started
24791
+ * fresh from `images.eve`. The archive streams chunk by chunk from Durable
24792
+ * Object storage through exec stdin, so it never sits in isolate memory. A
24793
+ * failure is logged and swallowed: the agent still serves, only the
24794
+ * carried files are missing.
24795
+ */
24796
+ async carrySandboxSessionsIn() {
24797
+ try {
24798
+ const carry = await this.ctx.storage.get(
24799
+ EVE_HOST_SANDBOX_CARRY_KEY
24800
+ );
24801
+ if (carry === void 0) return;
24802
+ let nextChunk = 0;
24803
+ const archive = new ReadableStream({
24804
+ pull: async (controller) => {
24805
+ if (nextChunk >= carry.chunks) {
24806
+ controller.close();
24807
+ return;
24808
+ }
24809
+ const chunk = await this.ctx.storage.get(
24810
+ `${EVE_HOST_SANDBOX_CARRY_CHUNK_PREFIX}.${carry.id}.${nextChunk}`
24811
+ );
24812
+ const index = nextChunk;
24813
+ nextChunk += 1;
24814
+ if (chunk === void 0) {
24815
+ controller.error(
24816
+ new Error(`The sandbox carry chunk ${index} is missing.`)
24817
+ );
24818
+ return;
24819
+ }
24820
+ controller.enqueue(chunk);
24821
+ }
24822
+ });
24823
+ const runtime = this.containerRuntime();
24824
+ if (runtime === void 0) {
24825
+ throw new Error("the Container runtime is unavailable");
24826
+ }
24827
+ const exec = await runtime.exec(
24828
+ [
24829
+ "sh",
24830
+ "-c",
24831
+ `mkdir -p ${EVE_HOST_SANDBOX_CARRY_SOURCE} && tar -xzf - -C ${EVE_HOST_SANDBOX_CARRY_SOURCE}`
24832
+ ],
24833
+ { stdin: archive, stderr: "pipe" }
24834
+ );
24835
+ let exitCode = -1;
24836
+ try {
24837
+ exitCode = await exec.exitCode;
24838
+ } catch {
24839
+ exitCode = -1;
24840
+ }
24841
+ if (exitCode !== 0) {
24842
+ console.error(
24843
+ `The Eve sandbox session restore failed with exit code ${exitCode}; the agent serves without the carried files.`
24844
+ );
24845
+ }
24846
+ } catch (error61) {
24847
+ console.error(
24848
+ "The Eve sandbox session restore failed; the agent serves without the carried files:",
24849
+ error61 instanceof Error ? error61.message : "unknown"
24850
+ );
24851
+ }
24852
+ }
24651
24853
  async ensureEveReady(signal = new AbortController().signal) {
24652
24854
  await this.reconcileRunningImage();
24653
24855
  if (this.readinessEvidence !== void 0) {
24654
24856
  return this.readinessEvidence;
24655
24857
  }
24656
- if (!this.readinessStarted) {
24657
- this.readinessStarted = true;
24658
- this.lifecycle.record("start_requested");
24659
- }
24660
24858
  const epoch = this.readinessEpoch;
24661
24859
  const evidence = await this.readiness(signal);
24662
24860
  if (epoch === this.readinessEpoch) {
24861
+ await this.restoreCarriedSandboxSessions();
24663
24862
  this.readinessEvidence = evidence;
24664
24863
  this.imageVerified = true;
24665
24864
  }
24666
- this.lifecycle.record("health_ready", evidence.healthStatus);
24667
24865
  return evidence;
24668
24866
  }
24669
24867
  async fetch(request) {
24670
24868
  const requestDeploymentId = request.headers.get("x-eden-eve-deployment-id") ?? void 0;
24671
- await this.ensureEveReady(request.signal);
24672
- await this.touchActivity();
24673
- const runtime = this.containerRuntime();
24674
- if (runtime === void 0) {
24675
- throw new EveHostError(
24676
- "HOST_READINESS_UNPROVEN",
24677
- "The Container runtime is unavailable on this Durable Object."
24678
- );
24679
- }
24680
- const url2 = new URL(request.url);
24681
- const response = await runtime.getTcpPort(EVE_HOST_DEFAULTS.internalPort).fetch(
24682
- new Request(`http://container${url2.pathname}${url2.search}`, request)
24683
- );
24869
+ const response = await this.forwardToEve(request);
24684
24870
  if (requestDeploymentId !== void 0 && requestDeploymentId === this.env.EDEN_EVE_DEPLOYMENT_ID && this.readinessEvidence !== void 0 && this.imageVerified) {
24685
24871
  const headers = new Headers(response.headers);
24686
24872
  headers.set("x-eden-eve-started-deployment", requestDeploymentId);
@@ -24698,6 +24884,9 @@ var EveHostDurableContainer = class extends DurableObject {
24698
24884
  * loopback path is not a deployment-health signal).
24699
24885
  */
24700
24886
  async loopbackFetch(request) {
24887
+ return this.forwardToEve(request);
24888
+ }
24889
+ async forwardToEve(request) {
24701
24890
  await this.ensureEveReady(request.signal);
24702
24891
  await this.touchActivity();
24703
24892
  const runtime = this.containerRuntime();
@@ -24728,6 +24917,14 @@ var EveHostDurableContainer = class extends DurableObject {
24728
24917
  return;
24729
24918
  }
24730
24919
  if (runtime === void 0 || !runtime.running) return;
24920
+ try {
24921
+ await this.carrySandboxSessionsOut(runtime);
24922
+ } catch (error61) {
24923
+ console.error(
24924
+ "The Eve sandbox session carry failed during idle sleep:",
24925
+ error61 instanceof Error ? error61.message : "unknown"
24926
+ );
24927
+ }
24731
24928
  const attempts = await this.ctx.storage.get(
24732
24929
  EVE_HOST_CONTAINER_SNAPSHOT_ATTEMPTS_KEY
24733
24930
  ) ?? 0;
@@ -24749,7 +24946,7 @@ var EveHostDurableContainer = class extends DurableObject {
24749
24946
  return;
24750
24947
  }
24751
24948
  await runtime.destroy(new Error("idle-snapshot-done"));
24752
- this.recordContainerStopped("snapshot:idle");
24949
+ this.recordContainerStopped();
24753
24950
  } catch (error61) {
24754
24951
  const message = error61 instanceof Error ? error61.message : "unknown";
24755
24952
  if (attempts + 1 >= EVE_HOST_SNAPSHOT_MAX_ATTEMPTS) {
@@ -24763,7 +24960,7 @@ var EveHostDurableContainer = class extends DurableObject {
24763
24960
  await runtime.destroy(
24764
24961
  new Error("idle-snapshot-abandoned")
24765
24962
  );
24766
- this.recordContainerStopped("snapshot:abandoned");
24963
+ this.recordContainerStopped();
24767
24964
  return;
24768
24965
  }
24769
24966
  console.error(
@@ -24786,15 +24983,9 @@ function createEveHostWorker(options) {
24786
24983
  }
24787
24984
  assertStableOrigin(options.publicOrigin, options.workerName);
24788
24985
  assertNonEmpty(options.stableContainerInstanceName, "Container instance name");
24789
- if (!IDENTIFIER_PATTERN.test(options.containerBindingName)) {
24790
- throw new EveHostError(
24791
- "HOST_READINESS_UNPROVEN",
24792
- "The Container binding name is not valid."
24793
- );
24794
- }
24795
24986
  const schedules = options.schedules ?? [];
24796
24987
  const resolveContainer = (env) => {
24797
- const namespace = env[options.containerBindingName];
24988
+ const namespace = env.EVE_CONTAINER;
24798
24989
  if (namespace === void 0) {
24799
24990
  throw new EveHostError(
24800
24991
  "HOST_READINESS_UNPROVEN",
@@ -24848,14 +25039,7 @@ function createEveHostWorker(options) {
24848
25039
  if (!due) return;
24849
25040
  ctx.waitUntil(
24850
25041
  resolveContainer(env).fetch(new Request(
24851
- new URL(EVE_HOST_DEFAULTS.healthPath, options.publicOrigin),
24852
- {
24853
- headers: {
24854
- // Stamp the Worker's own deployment so a stale Durable
24855
- // Object never falls back to its own environment.
24856
- "x-eden-eve-deployment-id": options.deploymentId
24857
- }
24858
- }
25042
+ new URL(EVE_HOST_DEFAULTS.healthPath, options.publicOrigin)
24859
25043
  )).catch((error61) => {
24860
25044
  console.error(
24861
25045
  "The scheduled wake request failed:",
@@ -24868,6 +25052,7 @@ function createEveHostWorker(options) {
24868
25052
  };
24869
25053
  }
24870
25054
  export {
25055
+ EVE_HOST_CARRY_LIMITS,
24871
25056
  EdenWorldDurableObject,
24872
25057
  EveHostDurableContainer,
24873
25058
  EveHostLoopback,