@lunora/container 1.0.0-alpha.11 → 1.0.0-alpha.110

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.
Files changed (38) hide show
  1. package/LICENSE.md +201 -104
  2. package/README.md +32 -10
  3. package/dist/bridge.d.mts +58 -33
  4. package/dist/bridge.d.ts +58 -33
  5. package/dist/bridge.mjs +1 -79
  6. package/dist/do/index.d.mts +362 -78
  7. package/dist/do/index.d.ts +362 -78
  8. package/dist/do/index.mjs +1 -321
  9. package/dist/index.d.mts +590 -151
  10. package/dist/index.d.ts +590 -151
  11. package/dist/index.mjs +1 -2
  12. package/dist/otel.d.mts +146 -47
  13. package/dist/otel.d.ts +146 -47
  14. package/dist/otel.mjs +1 -220
  15. package/dist/packem_shared/CONTAINER_EXEC_PATH-7Hcd6-zs.mjs +1 -0
  16. package/dist/packem_shared/CUSTOM_INSTANCE_MIN_MEMORY_MIB_PER_VCPU-D8Hy9Rxv.mjs +1 -0
  17. package/dist/packem_shared/ContainerProxy-CfXjS6ZI.mjs +27 -0
  18. package/dist/packem_shared/DURABLE_OBJECT_POLICY_FORBIDDEN_KEYS-gYi8RBUO.mjs +1 -0
  19. package/dist/packem_shared/LunoraSandboxContainer-DPnhJUu1.mjs +1 -0
  20. package/dist/packem_shared/abort-deadline-jwbW9Ala.mjs +1 -0
  21. package/dist/packem_shared/createContainerContext-p6QxWjsm.mjs +1 -0
  22. package/dist/packem_shared/exec-BYLW70sR.mjs +1 -0
  23. package/dist/packem_shared/jurisdiction-DtE9s70w.mjs +1 -0
  24. package/dist/packem_shared/jurisdiction.d-BwpauCoI.d.mts +471 -0
  25. package/dist/packem_shared/jurisdiction.d-BwpauCoI.d.ts +471 -0
  26. package/dist/packem_shared/sampling-D21rpu_s.mjs +1 -0
  27. package/dist/packem_shared/sandbox-types.d-DXlHnsEg.d.mts +110 -0
  28. package/dist/packem_shared/sandbox-types.d-DXlHnsEg.d.ts +110 -0
  29. package/dist/sandbox/index.d.mts +66 -0
  30. package/dist/sandbox/index.d.ts +66 -0
  31. package/dist/sandbox/index.mjs +1 -0
  32. package/package.json +9 -3
  33. package/dist/packem_shared/ContainerProxy-DWqUX_re.mjs +0 -1474
  34. package/dist/packem_shared/containerBindingName-BiTrAF1J.mjs +0 -224
  35. package/dist/packem_shared/createContainerContext-Cg53QGdf.mjs +0 -223
  36. package/dist/packem_shared/jurisdiction-CuPNcLDt.mjs +0 -13
  37. package/dist/packem_shared/jurisdiction.d-TwTGkgTg.d.mts +0 -266
  38. package/dist/packem_shared/jurisdiction.d-TwTGkgTg.d.ts +0 -266
@@ -1,5 +1,13 @@
1
- import { DurableObject, WorkerEntrypoint } from 'cloudflare:workers';
2
- import { a as ContainerDefinition, D as DurableObjectJurisdiction } from "../packem_shared/jurisdiction.d-TwTGkgTg.js";
1
+ /**
2
+ * `@lunora/container/do` — the workerd-only half of the package.
3
+ *
4
+ * `@cloudflare/containers` imports `cloudflare:workers` at module scope, so
5
+ * anything touching it lives behind this subpath: the package root stays
6
+ * importable from Node tooling (codegen, config, app unit tests) while the
7
+ * generated `_generated/containers.ts` imports the base class from here.
8
+ */
9
+ import { d as ContainerRuntimeInstanceType, C as ContainerDefinition, D as DurableObjectJurisdiction, b as ContainerSnapshot, e as ContainerSpawnRequest } from "../packem_shared/jurisdiction.d-BwpauCoI.js";
10
+ import { DurableObject, WorkerEntrypoint, RpcTarget } from 'cloudflare:workers';
3
11
  /**
4
12
  * ContainerStartOptions as they come from worker types
5
13
  */
@@ -119,7 +127,7 @@ type OutboundHandler<E = Cloudflare.Env, P = unknown> = {
119
127
  type OutboundHandlerParams = Record<string, unknown>;
120
128
  type OutboundHandlerParamsOf<THandler> = THandler extends ((req: Request, env: unknown, ctx: OutboundHandlerContext<infer Params>) => Promise<Response> | Response) ? Params : never;
121
129
  declare function outboundParams<THandler extends OutboundHandler<unknown, unknown>>(_handler: THandler, params: OutboundHandlerParamsOf<THandler>): OutboundHandlerParamsOf<THandler>;
122
- type OutboundHandlers<ParamsByMethod extends OutboundHandlerParams, E = Cloudflare.Env> = { [Method in keyof ParamsByMethod]?: OutboundHandler<E, ParamsByMethod[Method]> };
130
+ type OutboundHandlers<ParamsByMethod extends OutboundHandlerParams, E = Cloudflare.Env> = { [Method in keyof ParamsByMethod]?: OutboundHandler<E, ParamsByMethod[Method]>; };
123
131
  type OutboundHandlerOverride<Params = unknown> = {
124
132
  method: string;
125
133
  } & ([Params] extends [undefined] ? {
@@ -345,7 +353,7 @@ declare class Container<Env = Cloudflare.Env> extends DurableObject<Env> {
345
353
  * When the counter transitions to 0, renew the activity timeout so the
346
354
  * inactivity window starts fresh from the moment the last request completes.
347
355
  */
348
- private decrementInflight;
356
+ protected decrementInflight(): void;
349
357
  /**
350
358
  * Schedule a task to be executed in the future.
351
359
  *
@@ -387,10 +395,17 @@ declare class Container<Env = Cloudflare.Env> extends DurableObject<Env> {
387
395
  private onStopCalled;
388
396
  private state;
389
397
  private monitor;
390
- private startInFlight;
398
+ protected startInFlight?: Promise<unknown>;
391
399
  private monitoredPromise;
392
400
  private sleepAfterMs;
393
- private inflightRequests;
401
+ protected inflightRequests: number;
402
+ /** Patched (Lunora): the `durable_object`-policy image reference and size `start()` forwards. */
403
+ protected image?: string;
404
+ protected instance?: string | {
405
+ vcpu: number;
406
+ memoryMib: number;
407
+ diskMb: number;
408
+ };
394
409
  private outboundByHostOverrides;
395
410
  private outboundHandlerOverride?;
396
411
  private allowedHostsOverride?;
@@ -483,115 +498,384 @@ declare class Container<Env = Cloudflare.Env> extends DurableObject<Env> {
483
498
  getSchedule<T = string>(id: string): Promise<Schedule<T> | undefined>;
484
499
  private isActivityExpired;
485
500
  }
501
+ /** The runtime's `ExecProcess`, structurally — only what a spawned process uses. */
502
+ interface NativeProcess {
503
+ exitCode: Promise<number>;
504
+ isPty?: boolean;
505
+ kill: (signal?: number) => void;
506
+ pid?: number;
507
+ resize?: (cols: number, rows: number) => void;
508
+ stderr?: ReadableStream | null;
509
+ stdin?: WritableStream | null;
510
+ stdout?: ReadableStream | null;
511
+ }
512
+ /**
513
+ * Control half of a spawned process, returned to the caller as an RPC stub.
514
+ * The streams travel next to it in {@link SpawnedProcess}: a stream can cross
515
+ * RPC only once, so it is handed over directly rather than exposed through a
516
+ * property that could be read twice.
517
+ */
518
+ declare class ContainerProcessControl extends RpcTarget {
519
+ #private;
520
+ constructor(process: NativeProcess, exit: Promise<number>);
521
+ /** Resolves with the exit code once the process ends. */
522
+ exitCode(): Promise<number>;
523
+ /** Send `signal` (default `SIGTERM`) to the process. A no-op once it has exited. */
524
+ kill(signal?: number): void;
525
+ /** Resize a PTY process's terminal. Throws for a process spawned without `pty`. */
526
+ resize(cols: number, rows: number): void;
527
+ }
528
+ /** What `lunoraSpawn` returns over RPC. */
529
+ interface SpawnedProcess {
530
+ control: ContainerProcessControl;
531
+ isPty: boolean;
532
+ pid: number;
533
+ /** `null` under `pty`, where stderr is merged into the terminal output. */
534
+ stderr: ReadableStream<Uint8Array> | null;
535
+ /** A writable stdin when the request asked for `stdin: true`, else `null`. */
536
+ stdin: WritableStream<Uint8Array> | null;
537
+ stdout: ReadableStream<Uint8Array> | null;
538
+ }
539
+ /** What an explicit `start()` chose that later restarts must reuse. */
540
+ interface StartOverride {
541
+ /** Replaces the declared env, `secrets` and `secretsStore` wholesale. */
542
+ envVars?: Record<string, string>;
543
+ /** A key of the definition's `images`, or a managed `cloudflare/…` image. */
544
+ image?: string;
545
+ instanceType?: ContainerRuntimeInstanceType;
546
+ }
486
547
  type DurableObjectContext = ConstructorParameters<typeof Container>[0];
548
+ /** The runtime's `ctx.container`, once known to be present. */
549
+ type ContainerRuntime = NonNullable<DurableObjectContext["container"]>;
550
+ /** A running container plus the release for the in-flight count taken on it. See `LunoraContainer.lunoraAcquire`. */
551
+ interface AcquiredContainer {
552
+ container: ContainerRuntime;
553
+ /** Drop the in-flight count. Idempotent. */
554
+ release: () => void;
555
+ }
556
+ /**
557
+ * The `start()` options `LunoraContainer` accepts on top of the base's: the
558
+ * `durable_object`-policy image, size and snapshot to restore.
559
+ */
560
+ type LunoraStartOptions = NonNullable<Parameters<Container["start"]>[0]> & Pick<StartOverride, "image" | "instanceType"> & {
561
+ snapshot?: ContainerSnapshot;
562
+ };
487
563
  /**
488
- * Base class for the generated Container DO classes. Applies a
489
- * `defineContainer` definition onto `@cloudflare/containers`' `Container`:
490
- * port, sleep timeout, internet access, and the container environment (static
491
- * `env` merged with the declared Worker secrets — a declared-but-unset secret
492
- * fails fast here rather than starting a container without its credential).
493
- *
494
- * Generated subclasses stay one line of behavior:
495
- *
496
- * ```ts
497
- * export class TranscoderContainer extends LunoraContainer {
498
- * constructor(ctx: DurableObjectState, env: Env) {
499
- * super(ctx, env, transcoder, "transcoder");
500
- * }
501
- * }
502
- * ```
503
- */
564
+ * Base class for the generated Container DO classes. Applies a
565
+ * `defineContainer` definition onto `@cloudflare/containers`' `Container`:
566
+ * port, sleep timeout, internet access, and the container environment (static
567
+ * `env` merged with the declared Worker secrets — a declared-but-unset secret
568
+ * fails fast here rather than starting a container without its credential).
569
+ *
570
+ * Generated subclasses stay one line of behavior:
571
+ *
572
+ * ```ts
573
+ * export class TranscoderContainer extends LunoraContainer {
574
+ * constructor(ctx: DurableObjectState, env: Env) {
575
+ * super(ctx, env, transcoder, "transcoder");
576
+ * }
577
+ * }
578
+ * ```
579
+ */
504
580
  declare class LunoraContainer<Env = unknown> extends Container<Env> {
581
+ /** The `lunora/containers.ts` export name, for lifecycle log correlation and error messages. */
582
+ protected readonly lunoraName: string;
505
583
  /**
506
- * Data-residency jurisdiction the app's DOs are pinned to (codegen passes the
507
- * schema's `.jurisdiction("…")`). Used to pin the best-effort lifecycle report
508
- * to the same region as the root shard. `undefined` ⇒ un-pinned.
509
- */
584
+ * Data-residency jurisdiction the app's DOs are pinned to (codegen passes the
585
+ * schema's `.jurisdiction("…")`). Used to pin the best-effort lifecycle report
586
+ * to the same region as the root shard. `undefined` ⇒ un-pinned.
587
+ */
510
588
  private readonly lunoraJurisdiction?;
511
- /** The `lunora/containers.ts` export name, for lifecycle log correlation. */
512
- private readonly lunoraName;
513
589
  /** Default port the readiness probes target when a check omits its own `port`. */
514
590
  private readonly lunoraDefaultPort?;
515
591
  /** Hard-cap lifetime in whole seconds (from the `hardTimeout` config), or `undefined`. */
516
592
  private readonly lunoraHardTimeoutSeconds?;
593
+ /** In-flight `readyOn` gate for the current start; cleared when it fails. See `awaitReadinessGate`. */
594
+ private lunoraReadiness?;
517
595
  /** Declarative readiness probes that gate request proxying (from the `readyOn` config). */
518
596
  private readonly lunoraReadyOn;
519
597
  /** Map of container env-var name → Worker Secrets Store binding name (from the `secretsStore` config). */
520
598
  private readonly lunoraSecretsStore?;
521
- /** Memoised Secrets Store resolution: run once, then merged into `envVars` before the first start. */
599
+ /** The definition's `env` + `secrets`, as resolved at construction — the env a start uses absent an override. */
600
+ private readonly lunoraDeclaredEnv;
601
+ /** The persisted start override, once loaded. See {@link START_OVERRIDE_KEY}. */
602
+ private lunoraOverride?;
603
+ /** Whether the override field reflects storage (read once per DO instance, then kept in step). */
604
+ private lunoraOverrideLoaded;
605
+ /** Memoised Secrets Store resolution: the resolved `name → value` map, fetched once. */
522
606
  private lunoraSecretsStoreResolved?;
607
+ /** Whether the definition uses the `durable_object` scheduling policy. */
608
+ private readonly lunoraDurableObjectScheduled;
609
+ /** The definition's default image name and instance size (`durable_object` policy only). */
610
+ private readonly lunoraDefaultSelection;
611
+ /**
612
+ * Count of runs observed to have ENDED, bumped by the `onStop` hook. Read
613
+ * across a start: a bump means the run that start snapshotted is over,
614
+ * whatever the `running` flag said at snapshot time. See `beginStart`.
615
+ */
616
+ private lunoraStops;
523
617
  constructor(context: DurableObjectContext, env: Env, definition: ContainerDefinition, exportName?: string, jurisdiction?: DurableObjectJurisdiction);
524
618
  /**
525
- * Proxy entry for every `ctx.containers.&lt;name>` fetch. Resolves the
526
- * `secretsStore` bindings into `envVars` before delegating, so the values
527
- * are present when the base implicitly starts the container for this
528
- * request — a no-op when `secretsStore` is unset.
529
- */
619
+ * Save the running container's filesystem (`durable_object` policy only).
620
+ * The handle is plain data: store it and pass it to `start({ snapshot })` to
621
+ * restore it here or in another instance. Memory and processes are not
622
+ * captured — a restored container runs its entrypoint again.
623
+ */
624
+ lunoraSnapshot(options?: {
625
+ name?: string;
626
+ }): Promise<ContainerSnapshot>;
627
+ /**
628
+ * HTTP entry for every request to this Durable Object. Refuses the reserved
629
+ * `/__lunora/*` namespace unconditionally: `exec` reaches it only through
630
+ * the {@link lunoraExec} RPC, so no header, path spelling, or inbound request
631
+ * an app forwards as-is (`env.CONTAINER_X.get(id).fetch(request)`) opens it.
632
+ * The client-side path guard is the first line; this is the second.
633
+ */
634
+ override fetch(request: Request): Promise<Response>;
635
+ /**
636
+ * Proxy entry for every `ctx.containers.<name>` fetch — and a public RPC on
637
+ * the stub in its own right, so it applies the same `/__lunora/*` refusal
638
+ * as {@link fetch} rather than trusting that every caller came through it.
639
+ * The base starts the container for this request through
640
+ * {@link startAndWaitForPorts}, which is where the `secretsStore` resolution
641
+ * lives — a request that finds the container already healthy needs no
642
+ * resolution at all.
643
+ */
530
644
  override containerFetch(...args: Parameters<Container<Env>["containerFetch"]>): Promise<Response>;
531
645
  /**
532
- * Explicit start (`ctx.containers.&lt;name>.get(id).start()`). Resolves the
533
- * `secretsStore` bindings into `envVars` first, mirroring
534
- * {@link containerFetch}. A per-instance `start({ envVars })` replaces the
535
- * env set wholesale (base behavior), so the injected values only apply to a
536
- * bare `start()` — same as the static `env`/`secrets`. When the caller
537
- * supplies its own `envVars` we skip resolution entirely: those values would
538
- * be discarded anyway, so a missing/unreadable binding shouldn't fail a start
539
- * that never uses them.
540
- */
541
- override start(...args: Parameters<Container<Env>["start"]>): Promise<void>;
646
+ * The exec entry: `handle.exec` delivers its `POST /__lunora/exec` here, as
647
+ * an RPC, never over {@link fetch}. An RPC can only be invoked by code that
648
+ * holds the Durable Object binding, which is what makes the exec route
649
+ * unreachable from request content. Accepts exactly the exec route and
650
+ * nothing else under the reserved namespace, and honours a `.port(n)`
651
+ * handle's target-port header the way the base `fetch` does.
652
+ */
653
+ lunoraExec(request: Request): Promise<Response>;
654
+ /**
655
+ * Start a process and stream it (`handle.spawn()`), through the runtime's
656
+ * native `ctx.container.exec()`. Starts the container first when it is not
657
+ * running, and counts the process in flight until it exits, so `sleepAfter`
658
+ * cannot stop the container under it. The process's streams and a control
659
+ * stub (`exitCode` / `kill` / `resize`) cross back over RPC.
660
+ */
661
+ lunoraSpawn(request: ContainerSpawnRequest): Promise<SpawnedProcess>;
662
+ /**
663
+ * The start path `containerFetch` takes (and the one an app can call itself).
664
+ * Resolves the `secretsStore` bindings into `envVars` first — `doStartContainer`
665
+ * reads `this.envVars`, so a container started this way would otherwise boot
666
+ * without its Secrets Store values.
667
+ *
668
+ * The base's last act is `blockConcurrencyWhile(… onStart())`, so this
669
+ * override resumes on the far side of that gate — which is where
670
+ * {@link afterContainerStart} has to run. See its docblock.
671
+ */
672
+ override startAndWaitForPorts(...args: Parameters<Container<Env>["startAndWaitForPorts"]>): Promise<void>;
673
+ /**
674
+ * Explicit start (`ctx.containers.<name>.get(id).start()`).
675
+ *
676
+ * A per-instance `start({ envVars })` REPLACES the declared env (`env`,
677
+ * `secrets`, `secretsStore` — the Secrets Store is not even read) and is
678
+ * PERSISTED: every later start of this instance, explicit or implicit (a
679
+ * `fetch`/`exec` after the container slept, crashed or hit `hardTimeout`),
680
+ * boots with the same variables until `destroy()`. That is what makes
681
+ * `start({ envVars: {} })` a credential-free sandbox rather than one that
682
+ * gets its credentials back on the next restart.
683
+ *
684
+ * A start with `envVars` that differ from what the instance is running (or
685
+ * starting) with is REJECTED rather than silently joined: the base would
686
+ * return early on a live container, reporting a start whose env never took
687
+ * effect. `stop()` it first, or `destroy()` it to drop the override.
688
+ */
689
+ override start(options?: LunoraStartOptions, waitOptions?: Parameters<Container<Env>["start"]>[1]): Promise<void>;
690
+ /**
691
+ * Stop the container and forget this instance's start override, so the next
692
+ * start uses the declared env, image and size again.
693
+ */
694
+ override destroy(): Promise<void>;
542
695
  override onActivityExpired(): Promise<void>;
543
696
  override onError(error: unknown): unknown;
544
697
  override onStart(): Promise<void>;
545
698
  /**
546
- * Hook run when the container's `hardTimeout` elapses (dispatched by the base
547
- * scheduler via the run-generation-stamped schedule armed in
548
- * {@link onStart}). Default: stop the instance. Override to drain/checkpoint
549
- * first. A stale schedule from a previous run, or an already-stopped
550
- * instance, is ignored (upstream cloudflare/containers#85).
551
- */
699
+ * Hook run when the container's `hardTimeout` elapses (dispatched by the base
700
+ * scheduler via the run-generation-stamped schedule armed in
701
+ * {@link onStart}). Default: stop the instance. Override to drain/checkpoint
702
+ * first. A stale schedule from a previous run, or an already-stopped
703
+ * instance, is ignored (upstream cloudflare/containers#85).
704
+ *
705
+ * `stop()` sends SIGTERM and returns; nothing escalates to `destroy()`. The
706
+ * cap is therefore a signal, not a bound — a container that traps or ignores
707
+ * SIGTERM keeps running, and the schedule is ONE-SHOT (the base deletes the
708
+ * row once it fires), so nothing signals it a second time either: an ignored
709
+ * SIGTERM means the cap is spent, not retried. Override this hook and follow
710
+ * the stop with a `destroy()` after a grace period if your workload needs a
711
+ * real ceiling.
712
+ */
552
713
  onHardTimeoutExpired(payload?: {
553
714
  generation?: number;
554
715
  }): Promise<void>;
555
716
  override onStop(parameters: StopParams): Promise<void>;
556
717
  /**
557
- * Arm the hard-timeout kill via the base scheduler (so it integrates with
558
- * the container's own alarm machinery instead of fighting it). Bumps the run
559
- * generation and stamps the schedule with it, so {@link onHardTimeoutExpired}
560
- * can tell a fresh schedule from a stale one. No-op without a `hardTimeout`.
561
- */
718
+ * Get the container running for an operation that talks to it through
719
+ * `ctx.container` rather than over HTTP (`spawn`, and the sandbox helpers),
720
+ * and count the operation in flight so `sleepAfter` cannot stop the
721
+ * container underneath it. Goes through the same readiness gate a proxied
722
+ * request does, and through {@link start} when the container is stopped —
723
+ * `start()` returns once the container runs, so a container that serves no
724
+ * port starts here too. The caller must call `release` when the operation
725
+ * ends, including when the result is a stream that outlives this call.
726
+ */
727
+ protected lunoraAcquire(operation: string): Promise<AcquiredContainer>;
728
+ /**
729
+ * Runs on every start path after the env and image are settled and before
730
+ * the base starts the container — which is also before the base installs
731
+ * its outbound interception. A subclass that has to register an outbound
732
+ * intercept ahead of the base's catch-all does it here. No-op by default.
733
+ */
734
+ protected beforeContainerStart(): Promise<void>;
735
+ /** A 403 for a path under the reserved namespace, else `undefined`. */
736
+ private refuseReserved;
737
+ /**
738
+ * Arm the hard timeout and block on the `readyOn` probes — the work that has
739
+ * to happen once per real start, **outside** the base's start gate.
740
+ *
741
+ * It cannot live in `onStart`, which is the obvious home for it: the base
742
+ * invokes that hook as `blockConcurrencyWhile(async () => { … onStart() })`
743
+ * (`@cloudflare/containers`, both `start()` and `startAndWaitForPorts()`),
744
+ * and workerd treats a *rejecting* `blockConcurrencyWhile` closure as
745
+ * unrecoverable — it aborts the Durable Object, discards its in-memory state
746
+ * and every hibernating socket on it, and flattens the error to a plain
747
+ * `Error`. A readiness timeout is an ordinary, diagnosable failure: it must
748
+ * surface as the `LunoraError` naming the check, the port and the budget,
749
+ * not cost the object its life and arrive as an opaque message. (The same
750
+ * reasoning, and the same settle-outside-the-gate remedy, is written up on
751
+ * `ShardHost.runSerialized` in `@lunora/platform-cloudflare`.) A 30-second
752
+ * wait also has no business inside a gate that blocks every other dispatch
753
+ * to the object.
754
+ *
755
+ * Both start entry points call this immediately after `super`, so it runs
756
+ * once per start. It does NOT gate proxying on its own: the base commits the
757
+ * healthy state inside the start gate, before this runs, so a concurrent
758
+ * request would sail past `containerFetch`'s status check. That is what
759
+ * `awaitReadinessGate` is for, and it is the seam the move cost us —
760
+ * the in-gate placement got this for free from `blockConcurrencyWhile`.
761
+ */
762
+ private afterContainerStart;
763
+ /**
764
+ * Decide — synchronously, before anything is started — whether this start
765
+ * begins a NEW container run, and drop the previous run's readiness gate when
766
+ * it does. Returns whether the container was already running.
767
+ *
768
+ * The gate has to be keyed on the run, and `onStop` alone cannot key it:
769
+ * `@cloudflare/containers` reaches `onStop` only through
770
+ * `syncPendingStoppedEvents`, which `start()` never calls (only
771
+ * `startAndWaitForPorts`, `stop()` and the alarm loop do), while the monitor
772
+ * callback that observes a container exit merely records the state. So a
773
+ * `start()` in the up-to-three-minute window before the next alarm found the
774
+ * finished run's settled gate and skipped BOTH `armHardTimeout` and the
775
+ * `readyOn` probes — run 2 ran uncapped and was proxied to before it reported
776
+ * ready. A `hardTimeout` firing its own SIGTERM lands in exactly that window.
777
+ *
778
+ * The mirror case is why the answer is not "always re-arm": a start that finds
779
+ * the container already up begins no run, and re-arming there moves the cap
780
+ * (see {@link afterContainerStart}).
781
+ *
782
+ * Read with no `await` between it and `super`, so two concurrent starts of a
783
+ * stopped container both observe `false` and the second joins the first's
784
+ * gate instead of arming a second schedule — and so the flag is as fresh as
785
+ * it can be. It is a snapshot either way, and the run can end after it: the
786
+ * base's own pre-start work (`getPortsToCheck`, `syncPendingStoppedEvents`)
787
+ * still runs on the far side of it, and a start that came in on a live
788
+ * container would then arm nothing for the run the base goes on to start.
789
+ * Hence the second half of the answer, in the callers: an `onStop` observed
790
+ * ACROSS the base call ({@link lunoraStops}) demotes the snapshot, because
791
+ * the run it described is over. What that does not cover is an exit inside
792
+ * `start()`'s own base call — that path never syncs pending stop events, so
793
+ * nothing reports the exit until the next alarm or `startAndWaitForPorts`,
794
+ * and the cap for such a run is armed only when one of those arrives.
795
+ */
796
+ private beginStart;
797
+ /**
798
+ * Block until the `readyOn` probes for the current start have passed.
799
+ *
800
+ * Necessary because the base marks the container healthy *inside* the start
801
+ * gate — `startAndWaitForPorts` runs `setHealthy()` immediately before
802
+ * `onStart()` — while our probes run after it returns. `containerFetch`
803
+ * skips the start path entirely once it observes
804
+ * `container.running && status === "healthy"`, so without this a request
805
+ * arriving mid-probe would proxy to a container that never reported ready,
806
+ * and a request arriving after a *failed* probe would do so permanently.
807
+ * Holding `setHealthy` and the probes together the way the base does would
808
+ * mean putting the probes back inside the gate, which is the defect this
809
+ * whole path exists to avoid.
810
+ */
811
+ private awaitReadinessGate;
812
+ /**
813
+ * Arm the hard-timeout kill via the base scheduler (so it integrates with
814
+ * the container's own alarm machinery instead of fighting it). Bumps the run
815
+ * generation and stamps the schedule with it, so {@link onHardTimeoutExpired}
816
+ * can tell a fresh schedule from a stale one. No-op without a `hardTimeout`.
817
+ */
562
818
  private armHardTimeout;
563
819
  /**
564
- * Resolve the `secretsStore` bindings (async `.get()`) once and merge the
565
- * values into `envVars`, so they're present when the base starts the
566
- * container. Memoised on the first call — every later start reuses the
567
- * resolved promise. A missing binding or a non-string value fails fast (the
568
- * start surfaces the error), the same fail-closed stance the static
569
- * `secrets` resolution takes for a missing Worker secret. No-op without
570
- * `secretsStore`.
571
- */
820
+ * Resolve the `secretsStore` bindings (async `.get()`) once and merge the
821
+ * values into `envVars`, so they're present when the base starts the
822
+ * container. Memoised on the first call — every later start reuses the
823
+ * resolved promise. A missing binding or a non-string value fails fast (the
824
+ * start surfaces the error), the same fail-closed stance the static
825
+ * `secrets` resolution takes for a missing Worker secret. No-op without
826
+ * `secretsStore`.
827
+ */
572
828
  private resolveSecretsStoreEnv;
829
+ /** The persisted start override, read from storage once per instance lifetime. */
830
+ private readOverride;
831
+ /**
832
+ * Validate an explicit start's choices and persist them — merged over the
833
+ * stored override, so `start({ instanceType })` alone keeps a chosen image.
834
+ * Everything is checked before the one write, so a rejected start stores
835
+ * nothing. A start whose choices differ from what a running (or starting)
836
+ * container has is REJECTED rather than silently joined: the base would
837
+ * return early on a live container, reporting a start that never took
838
+ * effect. A snapshot restore only applies to a fresh start, so it is refused
839
+ * on a busy one.
840
+ */
841
+ private recordStartOverride;
842
+ /**
843
+ * Set `envVars` for the start about to happen: the persisted override when
844
+ * there is one (the Secrets Store is not read), else the declared env plus
845
+ * the resolved Secrets Store values.
846
+ */
847
+ private applyStartEnv;
573
848
  /**
574
- * Block until every `readyOn` probe responds with its expected status, or
575
- * throw once the readiness budget is spent. Probes run in parallel and hit
576
- * the container's TCP port directly (NOT `containerFetch`, which would
577
- * recurse back into the start path). No-op without `readyOn`.
578
- */
849
+ * Resolve the image reference and instance size for the start about to
850
+ * happen (`durable_object` policy only): the persisted explicit choice, else
851
+ * the definition default. A fresh boot with neither an image nor a snapshot
852
+ * would be rejected by the runtime, so it fails here with the fix instead.
853
+ */
854
+ private applyStartSelection;
855
+ /** Map an image name to the reference `ctx.container.start()` takes, via `ctx.container.images`. */
856
+ private resolveImage;
857
+ /**
858
+ * Block until every `readyOn` probe responds with its expected status, or
859
+ * throw once the readiness budget is spent. Probes run in parallel and hit
860
+ * the container's TCP port directly (NOT `containerFetch`, which would
861
+ * recurse back into the start path). No-op without `readyOn`.
862
+ */
579
863
  private awaitContainerReadiness;
580
864
  /** Poll one readiness probe until it returns its expected status or the shared deadline passes. */
581
865
  private awaitReadinessCheck;
582
866
  /**
583
- * Best-effort push of `envelope` into the root ShardDO's log buffer so it
584
- * also appears in the Studio Logs panel (the terminal already has it via
585
- * `emitContainerLifecycle`). Fire-and-forget and fully swallowed: a missing
586
- * `SHARD` binding, a missing admin token, or a fetch failure NEVER throws
587
- * out of a lifecycle hook — the `console` path stays the source of truth.
588
- */
867
+ * Best-effort push of `envelope` into the root ShardDO's log buffer so it
868
+ * also appears in the Studio Logs panel (the terminal already has it via
869
+ * `emitContainerLifecycle`). Fire-and-forget and fully swallowed: a missing
870
+ * `SHARD` binding, a missing admin token, or a fetch failure NEVER throws
871
+ * out of a lifecycle hook — the `console` path stays the source of truth.
872
+ */
589
873
  private surfaceInStudioLogs;
590
874
  /**
591
- * Per-instance correlation id: the Durable Object id, which Cloudflare also
592
- * injects into the container as `CLOUDFLARE_DURABLE_OBJECT_ID`. Read
593
- * defensively — the id shape varies and isn't worth crashing a hook over.
594
- */
875
+ * Per-instance correlation id: the Durable Object id, which Cloudflare also
876
+ * injects into the container as `CLOUDFLARE_DURABLE_OBJECT_ID`. Read
877
+ * defensively — the id shape varies and isn't worth crashing a hook over.
878
+ */
595
879
  private instanceId;
596
880
  }
597
881
  export { ContainerProxy, LunoraContainer, type OutboundHandler, type OutboundHandlerContext, type OutboundHandlerParams, type OutboundHandlerParamsOf, type OutboundHandlers, outboundParams };