@moondeck/station 1.0.3 → 1.0.5

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.
@@ -25,7 +25,8 @@
25
25
  */
26
26
 
27
27
  import type { CloudCredentialRuntime } from "./cloud-credential-runtime";
28
- import { readTaskRunEpochState, runningTaskRuns } from "./runtime-state";
28
+ import { getHostTask, readTaskRunEpochState, runningTaskRuns } from "./runtime-state";
29
+ import { isTerminal } from "./task-status";
29
30
 
30
31
  export type CredentialsMode = "legacy" | "pending" | "active";
31
32
 
@@ -281,14 +282,40 @@ let markRecovered!: () => void;
281
282
  let recoveredSignal = new Promise<void>((resolve) => (markRecovered = resolve));
282
283
  let recovered = false;
283
284
 
285
+ /**
286
+ * A task with no run left on this runner, whose failed boot cleanup is its
287
+ * own (`recoverAll`):
288
+ * - its row terminal (`finished`, `canceled`, `killed`, `shipped`): the
289
+ * cloud moves no terminal task back to `starting` (Resume takes only
290
+ * `stopped`/`error`, Start only `draft`, a wake only `stopped`);
291
+ * - or no row (orphan GC purges it even while credentials are pending) and
292
+ * no open assignment.
293
+ * Neither is reattached (recovery walks active rows only) or resumed
294
+ * (`runningTaskRuns`), and any later start of it is fenced: the registry
295
+ * runs its full cleanup before its gate may open (`owesCleanup`). Anything
296
+ * else, an unreadable or unknown status included, may still run and is
297
+ * not: its surviving agents would be reattached before its paths were
298
+ * proven gone.
299
+ */
300
+ export function taskHasNoRunLeft(taskId: string): boolean {
301
+ const task = getHostTask(taskId);
302
+ if (task !== null) {
303
+ return typeof task.statusMirror === "string" && isTerminal(task.statusMirror);
304
+ }
305
+ return readTaskRunEpochState(taskId)?.assignmentOpen !== true;
306
+ }
307
+
284
308
  /**
285
309
  * ADR-154 boot recovery (§5, §6): the composer's sweep of every task with
286
310
  * cleanup left from the last process, before any surviving agent is
287
311
  * reattached or any grant asked for. Once per process: after it succeeds,
288
312
  * a call does nothing, so a later runtime re-activation never sweeps the
289
313
  * credentials of tasks running now; concurrent calls share one sweep.
290
- * Rejects, every task attempted, when any could not be cleaned up: the
291
- * runner stays `pending`, and a later call tries again.
314
+ * Rejects, every task attempted, when a task that may still run could not
315
+ * be cleaned up: the runner stays `pending`, and a later call tries again.
316
+ * One with no run left (`taskHasNoRunLeft`) fails alone, kept for the next
317
+ * process's sweep and for any later start's fence (2026-11-09: a finished
318
+ * task's rows held the runner in `checking` for good).
292
319
  */
293
320
  export function recoverCloudCredentials(): Promise<void> {
294
321
  if (recovered) return Promise.resolve();
@@ -296,7 +323,7 @@ export function recoverCloudCredentials(): Promise<void> {
296
323
  const composer = runtime;
297
324
  if (composer === null) return Promise.reject(new Error("the station has no cloud credentials composer"));
298
325
  const sweep = composer
299
- .recover((taskId) => readTaskRunEpochState(taskId)?.highestRunEpoch ?? 0)
326
+ .recover((taskId) => readTaskRunEpochState(taskId)?.highestRunEpoch ?? 0, taskHasNoRunLeft)
300
327
  .then(() => {
301
328
  recovered = true;
302
329
  markRecovered();
@@ -240,6 +240,14 @@ export type CredentialSessionReaderFactory = (args: {
240
240
 
241
241
  export interface TaskCredentialLeaseRegistryOptions {
242
242
  runnerKind: "owned" | "task-machine";
243
+ /**
244
+ * The startup fence: whether the boot sweep isolated the task's failed
245
+ * cleanup and it still has durable cleanup left. A start of it with no
246
+ * predecessor here then runs the full cleanup first, as a recovered start
247
+ * does, and its gate stays closed unless that cleanup succeeds. A throw
248
+ * counts as owed. Absent: nothing is owed.
249
+ */
250
+ owesCleanup?(taskId: string): boolean;
243
251
  send(frame: LeaseRequestV1Frame | CredentialRefreshFrame): boolean;
244
252
  /**
245
253
  * Must synchronously stop new consumers/spawns for this assignment.
@@ -862,20 +870,32 @@ export class TaskCredentialLeaseRegistry {
862
870
  this.#endSynchronously(current, "superseded");
863
871
  }
864
872
 
865
- const needsStartupCleanup = Boolean(current || options.recovery);
873
+ // A predecessor's own startup and full cleanup cover every run through
874
+ // its epoch. With none here, a boot sweep's isolated failure (2026-11-09
875
+ // review) fences the start like a recovery: no gate opens over its
876
+ // credential paths not yet proven gone.
877
+ let recovery = options.recovery === true;
878
+ if (!current && !recovery && this.#opts.owesCleanup) {
879
+ try {
880
+ recovery = this.#opts.owesCleanup(assignment.taskId);
881
+ } catch {
882
+ recovery = true;
883
+ }
884
+ }
885
+ const needsStartupCleanup = Boolean(current || recovery);
866
886
  const state = this.#newState(
867
887
  assignment,
868
888
  needsStartupCleanup ? "recovering" : "waiting",
869
889
  );
870
890
  state.startup = current
871
891
  ? { kind: "predecessor", state: current }
872
- : options.recovery
892
+ : recovery
873
893
  ? { kind: "recovery" }
874
894
  : null;
875
895
  this.#tasks.set(assignment.taskId, state);
876
896
  const gateClosed = this.#closeGate(
877
897
  state,
878
- options.recovery ? "recovery" : "starting",
898
+ recovery ? "recovery" : "starting",
879
899
  );
880
900
 
881
901
  if (needsStartupCleanup) {
@@ -2385,7 +2405,18 @@ export class TaskCredentialLeaseRegistry {
2385
2405
  state: TaskState,
2386
2406
  reason: LeaseGateCloseReason,
2387
2407
  ): Promise<void> {
2388
- if (state.startup) await this.#finishStartup(state);
2408
+ if (state.startup) {
2409
+ try {
2410
+ await this.#finishStartup(state);
2411
+ } catch (error) {
2412
+ // A startup cleanup that failed (a fenced or recovered start whose
2413
+ // runtime could not be reached, a predecessor's) never blocks the
2414
+ // cloud's taskDown: its own full cleanup below covers every run
2415
+ // through this one, and only it may destroy the runtime and prove
2416
+ // it absent (2026-11-09 review). Anything else waits for it.
2417
+ if (reason !== "teardown") throw error;
2418
+ }
2419
+ }
2389
2420
  if (state.gateCloseFailed && this.#closeGate(state, reason)) {
2390
2421
  state.gateCloseFailed = false;
2391
2422
  }
@@ -421,6 +421,9 @@ export class CloudCredentialRuntime {
421
421
  this.registry = new TaskCredentialLeaseRegistry({
422
422
  ...deps.registry,
423
423
  runnerKind: deps.runnerKind,
424
+ // The startup fence: a start of a task whose boot cleanup was isolated
425
+ // runs that cleanup before its gate may open.
426
+ owesCleanup: (taskId) => this.coordinator.isolatedCleanupOwed(taskId),
424
427
  send: (frame) => deps.send(frame),
425
428
  closeTaskGate: (assignment) => this.#close(assignment),
426
429
  openTaskGate: (assignment, view) => this.#openGate(assignment, view),
@@ -764,11 +767,15 @@ export class CloudCredentialRuntime {
764
767
  * Boot recovery (ADR-154 §5, §6): every task with cleanup left from the
765
768
  * last process (a crash, a cleanup that failed) cleaned up, at the newer
766
769
  * of its recorded and its admitted run, before any grant is asked for.
767
- * Every task is attempted; then any failure fails the sweep.
770
+ * Every task is attempted; then any failure of a task `isolatable` does
771
+ * not name fails the sweep (TaskCredentialCleanupCoordinator.recoverAll).
768
772
  */
769
- recover(runEpochForTask: (taskId: string) => number): Promise<void> {
773
+ recover(
774
+ runEpochForTask: (taskId: string) => number,
775
+ isolatable?: (taskId: string) => boolean,
776
+ ): Promise<void> {
770
777
  if (this.#shutDown) return Promise.reject(new StartInterruptedError("shutdown"));
771
- return this.#track(this.coordinator.recoverAll(runEpochForTask));
778
+ return this.#track(this.coordinator.recoverAll(runEpochForTask, isolatable));
772
779
  }
773
780
 
774
781
  /**
@@ -164,13 +164,25 @@ export interface RuntimeDetectionDeps {
164
164
  }
165
165
 
166
166
  interface RuntimeAutoRecheckOptions extends RuntimeDetectionDeps {
167
- /** Fast first retry covers Docker Desktop / OrbStack boot ordering. */
167
+ /** First background probe: fast, for Docker Desktop / OrbStack starting
168
+ * late at login. */
168
169
  firstDelayMs?: number;
169
- /** Later retries stay cheap while a daemon or desktop app starts. */
170
- intervalMs?: number;
171
- /** Bound background probing; an explicit recheck remains available later. */
172
- maxAttempts?: number;
173
- }
170
+ /** Second probe; each later one doubles it, up to maxIntervalMs. */
171
+ backoffStartMs?: number;
172
+ /** Backoff ceiling: a runtime that comes back is noticed within this. */
173
+ maxIntervalMs?: number;
174
+ /** How long one background probe may hold the loop. A slower probe keeps
175
+ * running as the shared in-flight detection; the next tick joins it. */
176
+ probeDeadlineMs?: number;
177
+ log?: (line: string) => void;
178
+ }
179
+
180
+ /** Background recheck cadence while a recheckable runtime is unavailable:
181
+ * 5 s, then 60 s doubling to 300 s (5 s, 60, 120, 240, 300, 300, …). */
182
+ export const RUNTIME_AUTO_RECHECK_FIRST_DELAY_MS = 5_000;
183
+ export const RUNTIME_AUTO_RECHECK_BACKOFF_START_MS = 60_000;
184
+ export const RUNTIME_AUTO_RECHECK_MAX_INTERVAL_MS = 5 * 60_000;
185
+ export const RUNTIME_AUTO_RECHECK_PROBE_DEADLINE_MS = 10_000;
174
186
 
175
187
  /** Parse an operator override without letting a typo silently pick a backend. */
176
188
  export function runtimePreference(value: string | undefined): RuntimePreference {
@@ -649,45 +661,169 @@ export async function ensureContainerRuntimeForTask(
649
661
  return initializeContainerRuntime(deps);
650
662
  }
651
663
 
664
+ /** Only an unavailable runtime whose remedy IS a recheck is probed in the
665
+ * background. Restart-only verdicts (a replaced engine, a rejected
666
+ * selection, a remote endpoint, a bad UAI_RUNTIME) cannot heal by probing. */
667
+ function runtimeAutoRecheckApplies(): boolean {
668
+ return state.status === "no-runtime" && state.action === RUNTIME_RECHECK_COMMAND;
669
+ }
670
+
671
+ let activeAutoRecheck: {
672
+ nudge: (reason: string) => void;
673
+ stop: () => void;
674
+ } | null = null;
675
+
676
+ /**
677
+ * While the runtime is unavailable but recheckable, re-probe it with backoff
678
+ * until it answers, then stop: a fast first probe at 5 s (a daemon starting
679
+ * late at login), then 60 s doubling to a 5 min ceiling. A wake nudge probes
680
+ * at once and restarts that schedule from its 5 s step. Live
681
+ * 2026-11-06: a 1.0.4 station restarted while OrbStack was hung in dark-wake
682
+ * showed unavailable for 14 h because its probing gave up. The loop never
683
+ * runs while ready, keeps at most one probe in flight (initializeContainer-
684
+ * Runtime joins the shared detection, which the operator's `runtime recheck`
685
+ * also waits on), and at most one loop runs per process.
686
+ */
652
687
  export function startContainerRuntimeAutoRecheck(
653
688
  options: RuntimeAutoRecheckOptions = {},
654
689
  ): () => void {
655
- if (
656
- state.status !== "no-runtime" ||
657
- state.action === RUNTIME_RESTART_COMMAND ||
658
- (options.maxAttempts ?? 45) <= 0
659
- ) {
660
- return () => {};
661
- }
662
-
663
- const firstDelayMs = options.firstDelayMs ?? 5_000;
664
- const intervalMs = options.intervalMs ?? 20_000;
665
- const maxAttempts = options.maxAttempts ?? 45;
666
- let attempts = 0;
690
+ activeAutoRecheck?.stop();
691
+ if (!runtimeAutoRecheckApplies()) return () => {};
692
+
693
+ const firstDelayMs = options.firstDelayMs ?? RUNTIME_AUTO_RECHECK_FIRST_DELAY_MS;
694
+ const backoffStartMs =
695
+ options.backoffStartMs ?? RUNTIME_AUTO_RECHECK_BACKOFF_START_MS;
696
+ const maxIntervalMs = options.maxIntervalMs ?? RUNTIME_AUTO_RECHECK_MAX_INTERVAL_MS;
697
+ const probeDeadlineMs =
698
+ options.probeDeadlineMs ?? RUNTIME_AUTO_RECHECK_PROBE_DEADLINE_MS;
699
+ const log = options.log ?? ((line: string) => console.warn(line));
700
+ // Index into the schedule: 0 → firstDelayMs, n ≥ 1 → backoffStartMs·2^(n-1),
701
+ // capped at maxIntervalMs.
702
+ let step = 0;
703
+ const nextDelayMs = (): number => {
704
+ const ms =
705
+ step === 0
706
+ ? firstDelayMs
707
+ : Math.min(backoffStartMs * 2 ** Math.min(step - 1, 30), maxIntervalMs);
708
+ step += 1;
709
+ return ms;
710
+ };
667
711
  let stopped = false;
712
+ let probing = false;
713
+ let nudgedDuringProbe = false;
668
714
  let timer: NodeJS.Timeout | null = null;
669
715
 
670
- const schedule = (delayMs: number): void => {
716
+ const stop = (): void => {
717
+ stopped = true;
718
+ if (timer) clearTimeout(timer);
719
+ timer = null;
720
+ if (activeAutoRecheck === handle) activeAutoRecheck = null;
721
+ };
722
+
723
+ const schedule = (ms: number): void => {
671
724
  timer = setTimeout(() => {
672
725
  timer = null;
673
- if (stopped || state.status === "ready") return;
674
- attempts += 1;
675
- void initializeContainerRuntime(options).then((next) => {
676
- if (stopped || next.status === "ready" || attempts >= maxAttempts) {
677
- return;
678
- }
679
- schedule(intervalMs);
680
- });
681
- }, delayMs);
726
+ void probe();
727
+ }, ms);
682
728
  timer.unref?.();
683
729
  };
684
730
 
685
- schedule(firstDelayMs);
686
- return () => {
687
- stopped = true;
731
+ const probe = async (): Promise<void> => {
732
+ if (stopped) return;
733
+ if (!runtimeAutoRecheckApplies()) {
734
+ stop();
735
+ return;
736
+ }
737
+ probing = true;
738
+ nudgedDuringProbe = false;
739
+ let deadline: NodeJS.Timeout | null = null;
740
+ try {
741
+ await Promise.race([
742
+ initializeContainerRuntime(options),
743
+ new Promise<void>((resolve) => {
744
+ deadline = setTimeout(resolve, probeDeadlineMs);
745
+ deadline.unref?.();
746
+ }),
747
+ ]);
748
+ } catch {
749
+ // initializeContainerRuntime never rejects; keep the loop alive anyway.
750
+ } finally {
751
+ if (deadline) clearTimeout(deadline);
752
+ probing = false;
753
+ }
754
+ if (stopped) return;
755
+ if (!runtimeAutoRecheckApplies()) {
756
+ stop();
757
+ return;
758
+ }
759
+ if (nudgedDuringProbe) {
760
+ // A wake landed while a probe begun before it was in flight: that
761
+ // probe may have dialed a still-asleep daemon, so look once more now.
762
+ nudgedDuringProbe = false;
763
+ step = 0;
764
+ void probe();
765
+ return;
766
+ }
767
+ schedule(nextDelayMs());
768
+ };
769
+
770
+ const nudge = (reason: string): void => {
771
+ if (stopped) return;
772
+ log(`[host-agent] ${reason}: rechecking the unavailable container runtime now`);
773
+ step = 0;
774
+ if (probing) {
775
+ nudgedDuringProbe = true;
776
+ return;
777
+ }
688
778
  if (timer) clearTimeout(timer);
689
779
  timer = null;
780
+ void probe();
690
781
  };
782
+
783
+ const handle = { nudge, stop };
784
+ activeAutoRecheck = handle;
785
+ log(
786
+ `[host-agent] container runtime unavailable; rechecking automatically in ` +
787
+ `${Math.round(firstDelayMs / 1000)}s, then every ${Math.round(backoffStartMs / 1000)}s ` +
788
+ `backing off to ${Math.round(maxIntervalMs / 1000)}s`,
789
+ );
790
+ schedule(nextDelayMs());
791
+ return stop;
792
+ }
793
+
794
+ /**
795
+ * Converge the background recheck on the current state; main calls this on
796
+ * every runtime change. Ready stops it. Any other state keeps a running loop
797
+ * as it is (its backoff is not reset by an unrelated change; a restart-only
798
+ * verdict ends it at its next tick) or, when none runs, starts one if the
799
+ * state is recheckable — whatever the previous state was. Codex review,
800
+ * 2026-11-06: quarantine (restart-only) → a failed operator recheck
801
+ * (recheckable) left no loop running, since only a ready → unavailable edge
802
+ * started one, and wake nudges had nothing to nudge.
803
+ */
804
+ export function syncContainerRuntimeAutoRecheck(
805
+ options: RuntimeAutoRecheckOptions = {},
806
+ ): () => void {
807
+ if (state.status === "ready") {
808
+ activeAutoRecheck?.stop();
809
+ return () => {};
810
+ }
811
+ if (activeAutoRecheck) return activeAutoRecheck.stop;
812
+ return startContainerRuntimeAutoRecheck(options);
813
+ }
814
+
815
+ /** Whether a background recheck loop is running (status and tests). */
816
+ export function containerRuntimeAutoRecheckActive(): boolean {
817
+ return activeAutoRecheck !== null;
818
+ }
819
+
820
+ /** A detected wake (the process-level suspend detector): probe the unavailable
821
+ * runtime now instead of at the next backoff step. A no-op while ready or
822
+ * with no background recheck running. Returns whether a loop was nudged. */
823
+ export function nudgeContainerRuntimeAutoRecheck(reason: string): boolean {
824
+ if (!activeAutoRecheck) return false;
825
+ activeAutoRecheck.nudge(reason);
826
+ return true;
691
827
  }
692
828
 
693
829
  /** Pure detection seam kept injectable for deterministic startup tests. */
@@ -1427,6 +1563,7 @@ export function resetContainerRuntimeSelectionForTests(): void {
1427
1563
  if (process.env.NODE_ENV !== "test") {
1428
1564
  throw new Error("runtime selection reset is test-only");
1429
1565
  }
1566
+ activeAutoRecheck?.stop();
1430
1567
  pinnedDockerHost = null;
1431
1568
  pinnedRuntimeProvider = null;
1432
1569
  pinnedDockerEngineId = null;
@@ -0,0 +1,192 @@
1
+ /**
2
+ * The Moondeck Station machine payload image: its identity, and the ONE place
3
+ * the AWS-host lookup's eligibility gate is defined (plan "AWS hosts on
4
+ * Moondeck Station" rev 3, §1).
5
+ *
6
+ * Gate: decision D1, branch T (the shared-tag channel). An image is eligible
7
+ * only when it is owned by the Moondeck account, named
8
+ * `moondeck-station-machine-payload-v1-YYYYMMDD-HHMM`, arm64, available,
9
+ * PUBLIC, carries the shared tags `ec2:SharedTag/io.moondeck.payload=station-v1`
10
+ * and `ec2:SharedTag/io.moondeck.channel=stable` (visible to every account
11
+ * that can see the image; only the owner can set them), is not deprecated,
12
+ * and its name sorts at or above the floor. Publishing alone selects nothing;
13
+ * `promote` (the channel tag) does.
14
+ *
15
+ * Every requirement is a compile-time constant of the frozen
16
+ * PRODUCTION_PAYLOAD_SELECTOR. No env var, config field or runtime fallback
17
+ * can drop or relax one; a requirement that cannot be read fails closed. The
18
+ * only other selector is the non-packaged canary driver's
19
+ * (scripts/machine-canary-aws.mjs), passed explicitly to
20
+ * createAwsMachineProvider; production construction (task-environment/
21
+ * index.ts) passes none, and a test asserts it.
22
+ *
23
+ * Imported by the cloud too (lib/machines/runtime.ts, lib/machines/aws.ts),
24
+ * so it must stay dependency-free.
25
+ */
26
+
27
+ /** The Moondeck account that bakes and publishes the payload images. */
28
+ export const PAYLOAD_AMI_OWNER = "277057415208";
29
+
30
+ export const STATION_MACHINE_AMI_PREFIX = "moondeck-station-machine-payload-v1";
31
+ /** Ordinary (owner-only) tag the cloud's pinned check reads. */
32
+ export const STATION_MACHINE_AMI_TAG = "io.moondeck.payload";
33
+ export const STATION_MACHINE_AMI_TAG_VALUE = "station-v1";
34
+ /** Written by payload-bootstrap.sh for the Station cohort only; probed on
35
+ * every auto-selected machine before any workspace prep (task-environment/
36
+ * machine.ts). */
37
+ export const STATION_MACHINE_PAYLOAD_MARKER = "/var/lib/moondeck/station-payload-v1";
38
+
39
+ /** Shared tags (`ec2:SharedTag/` prefix): visible to every account that can
40
+ * see the image, public included, and writable only by its owner. */
41
+ export const SHARED_PAYLOAD_TAG = "ec2:SharedTag/io.moondeck.payload";
42
+ export const SHARED_CHANNEL_TAG = "ec2:SharedTag/io.moondeck.channel";
43
+ export const STABLE_CHANNEL = "stable";
44
+
45
+ /**
46
+ * The floor: the oldest image name a Station release will still select.
47
+ * Names are fixed-width (`…-YYYYMMDD-HHMM`), so string order is time order.
48
+ *
49
+ * N1, the first Station payload image (us-west-2 ami-019703ad02ec97b40, its
50
+ * us-east-1 copy ami-012d87cec8aacd5dd). Recorded by the owner on 2026-11-06
51
+ * with D1 = T, after test 6.1. It moves only in a Station release, and never
52
+ * above N-1 (plan §4: rollback needs N-1 to stay eligible).
53
+ */
54
+ export const STATION_PAYLOAD_MIN_NAME = "moondeck-station-machine-payload-v1-20261106-0051";
55
+
56
+ /** How long a successful lookup's image may still be launched while later
57
+ * lookups keep FAILING. Not a bound from a demotion: a successful but stale
58
+ * DescribeImages answer refreshes it (AWS gives no propagation SLA). */
59
+ export const STALE_MAX_MS = 30 * 60_000;
60
+
61
+ export interface PayloadImageSelector {
62
+ readonly owner: string;
63
+ /** Names must match `^<namePrefix>-\d{8}-\d{4}$`. */
64
+ readonly namePrefix: string;
65
+ /** Lowest eligible name (inclusive); a well-formed name of this prefix. */
66
+ readonly minName: string;
67
+ /** Applied to BOTH the server-side `is-public` filter and the client-side
68
+ * `Public` check. */
69
+ readonly requirePublic: boolean;
70
+ /** Exact key=value tags, filtered server-side and re-checked client-side. */
71
+ readonly requiredTags: readonly { readonly key: string; readonly value: string }[];
72
+ /** For the error text: what "approved" means under this gate. */
73
+ readonly gateDescription: string;
74
+ }
75
+
76
+ export const PRODUCTION_PAYLOAD_SELECTOR: PayloadImageSelector = Object.freeze({
77
+ owner: PAYLOAD_AMI_OWNER,
78
+ namePrefix: STATION_MACHINE_AMI_PREFIX,
79
+ minName: STATION_PAYLOAD_MIN_NAME,
80
+ requirePublic: true,
81
+ requiredTags: Object.freeze([
82
+ Object.freeze({ key: SHARED_PAYLOAD_TAG, value: STATION_MACHINE_AMI_TAG_VALUE }),
83
+ Object.freeze({ key: SHARED_CHANNEL_TAG, value: STABLE_CHANNEL }),
84
+ ]),
85
+ gateDescription: "public, stable channel",
86
+ });
87
+
88
+ /** One image as DescribeImages reports it (the fields the gate reads). */
89
+ export interface DescribedImage {
90
+ ImageId?: unknown;
91
+ Name?: unknown;
92
+ OwnerId?: unknown;
93
+ Architecture?: unknown;
94
+ State?: unknown;
95
+ Public?: unknown;
96
+ DeprecationTime?: unknown;
97
+ Tags?: unknown;
98
+ }
99
+
100
+ export interface SelectedPayloadImage {
101
+ id: string;
102
+ name: string;
103
+ /** Epoch ms, or null when the image has no deprecation time. */
104
+ deprecationTime: number | null;
105
+ }
106
+
107
+ export interface PayloadImageSelection {
108
+ selected: SelectedPayloadImage | null;
109
+ rejected: { id: string; reason: string }[];
110
+ }
111
+
112
+ const NAME_SUFFIX = /^-\d{8}-\d{4}$/;
113
+
114
+ export function nameMatches(selector: PayloadImageSelector, name: string): boolean {
115
+ return (
116
+ name.startsWith(selector.namePrefix) &&
117
+ NAME_SUFFIX.test(name.slice(selector.namePrefix.length))
118
+ );
119
+ }
120
+
121
+ /** The `describe-images` filters for this selector. The client re-checks
122
+ * every one of them; the filters only keep the answer small. */
123
+ export function payloadImageFilters(selector: PayloadImageSelector): string[] {
124
+ return [
125
+ `Name=name,Values=${selector.namePrefix}-*`,
126
+ "Name=state,Values=available",
127
+ "Name=architecture,Values=arm64",
128
+ ...(selector.requirePublic ? ["Name=is-public,Values=true"] : []),
129
+ ...selector.requiredTags.map((tag) => `Name=tag:${tag.key},Values=${tag.value}`),
130
+ ];
131
+ }
132
+
133
+ export function noApprovedImageMessage(selector: PayloadImageSelector, region: string): string {
134
+ return (
135
+ `no approved Moondeck Station machine image (${selector.namePrefix}-*, ` +
136
+ `${selector.gateDescription}, ≥ ${selector.minName}) in ${region} — set ` +
137
+ "UAI_MACHINE_IMAGE to an AMI id, or ask Moondeck to publish this region"
138
+ );
139
+ }
140
+
141
+ function rejection(image: DescribedImage, selector: PayloadImageSelector, nowMs: number): string | null {
142
+ if (typeof image.ImageId !== "string" || !image.ImageId.startsWith("ami-")) return "no image id";
143
+ if (image.OwnerId !== selector.owner) return `owner ${String(image.OwnerId)}`;
144
+ if (typeof image.Name !== "string" || !nameMatches(selector, image.Name)) return `name ${String(image.Name)}`;
145
+ if (image.Architecture !== "arm64") return `architecture ${String(image.Architecture)}`;
146
+ if (image.State !== "available") return `state ${String(image.State)}`;
147
+ if (selector.requirePublic && image.Public !== true) return "not public";
148
+ if (selector.requiredTags.length > 0) {
149
+ if (!Array.isArray(image.Tags)) return "tags unreadable";
150
+ for (const required of selector.requiredTags) {
151
+ const found = image.Tags.some(
152
+ (tag: unknown) =>
153
+ typeof tag === "object" && tag !== null &&
154
+ (tag as { Key?: unknown }).Key === required.key &&
155
+ (tag as { Value?: unknown }).Value === required.value,
156
+ );
157
+ if (!found) return `missing ${required.key}=${required.value}`;
158
+ }
159
+ }
160
+ if (image.DeprecationTime !== undefined && image.DeprecationTime !== null) {
161
+ if (typeof image.DeprecationTime !== "string") return "deprecation time unreadable";
162
+ const at = Date.parse(image.DeprecationTime);
163
+ if (!Number.isFinite(at)) return "deprecation time unreadable";
164
+ if (!(nowMs < at)) return "deprecated";
165
+ }
166
+ if (image.Name < selector.minName) return `below the floor ${selector.minName}`;
167
+ return null;
168
+ }
169
+
170
+ /** Pure: the newest (by name) image meeting every requirement, plus why each
171
+ * other image was rejected. */
172
+ export function selectStationPayloadImage(
173
+ images: readonly DescribedImage[],
174
+ selector: PayloadImageSelector,
175
+ nowMs: number,
176
+ ): PayloadImageSelection {
177
+ const rejected: { id: string; reason: string }[] = [];
178
+ let best: SelectedPayloadImage | null = null;
179
+ for (const image of images) {
180
+ const reason = rejection(image, selector, nowMs);
181
+ if (reason !== null) {
182
+ rejected.push({ id: typeof image.ImageId === "string" ? image.ImageId : "?", reason });
183
+ continue;
184
+ }
185
+ const name = image.Name as string;
186
+ if (best === null || name > best.name) {
187
+ const deprecation = typeof image.DeprecationTime === "string" ? Date.parse(image.DeprecationTime) : null;
188
+ best = { id: image.ImageId as string, name, deprecationTime: deprecation };
189
+ }
190
+ }
191
+ return { selected: best, rejected };
192
+ }