@moondeck/station 1.0.4 → 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.
@@ -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
+ }
@@ -30,14 +30,27 @@ import type {
30
30
  MachineSpec,
31
31
  MachineState,
32
32
  } from "./machine-provider";
33
+ import {
34
+ noApprovedImageMessage,
35
+ PAYLOAD_AMI_OWNER,
36
+ payloadImageFilters,
37
+ PRODUCTION_PAYLOAD_SELECTOR,
38
+ selectStationPayloadImage,
39
+ STALE_MAX_MS,
40
+ type PayloadImageSelector,
41
+ } from "./machine-payload-image";
33
42
 
34
43
  export const AWS_MACHINE_TAG = "com.uai.machine";
44
+ /** Station payload validation state, carried ON the instance so it survives
45
+ * retries, Station restarts and moves with the machine. `pending` is set
46
+ * atomically in run-instances for an auto-selected image; `ok` once the
47
+ * payload marker was confirmed over ssh (task-environment/machine.ts). */
48
+ export const PAYLOAD_VALIDATION_TAG = "com.uai.payload-validation";
35
49
 
36
- /** ADR-125 BYO-AWS: the Uai account that publishes the public payload AMIs,
37
- * and the name prefix build-ami.sh stamps on them. A host with no
38
- * UAI_MACHINE_IMAGE resolves the newest published payload in its region. */
39
- export const PAYLOAD_AMI_OWNER = "277057415208";
40
- export const PAYLOAD_AMI_NAME_PREFIX = "uai-machine-payload";
50
+ /** ADR-125 BYO-AWS: a host with no UAI_MACHINE_IMAGE resolves the newest
51
+ * APPROVED Station payload in its region; the gate is
52
+ * PRODUCTION_PAYLOAD_SELECTOR (machine-payload-image.ts). */
53
+ export { PAYLOAD_AMI_OWNER };
41
54
  /** Regions the payload AMI is published to (build-ami.sh bakes in the first
42
55
  * and copies to the rest). A BYO-AWS runner elsewhere would find no image
43
56
  * and fail every launch, so setup refuses other regions up front (owner,
@@ -220,6 +233,7 @@ type LiveInstance = {
220
233
  state: string;
221
234
  privateIp: string | null;
222
235
  taskLabel: string | null;
236
+ payloadValidation: "pending" | "ok" | null;
223
237
  };
224
238
 
225
239
  /** Strict reservations parse. Any malformed instance voids the answer. */
@@ -249,6 +263,7 @@ function parseReservations(stdout: string): LiveInstance[] | null {
249
263
  const state = record.State?.Name;
250
264
  if (typeof state !== "string") return null;
251
265
  let taskLabel: string | null = null;
266
+ let payloadValidation: "pending" | "ok" | null = null;
252
267
  if (record.Tags !== undefined) {
253
268
  if (!Array.isArray(record.Tags)) return null;
254
269
  for (const tag of record.Tags) {
@@ -256,6 +271,11 @@ function parseReservations(stdout: string): LiveInstance[] | null {
256
271
  if (typeof tag.Value !== "string") return null;
257
272
  taskLabel = tag.Value;
258
273
  }
274
+ if (tag?.Key === PAYLOAD_VALIDATION_TAG) {
275
+ if (typeof tag.Value !== "string") return null;
276
+ // Anything but `ok` is still unvalidated: fail closed (probe).
277
+ payloadValidation = tag.Value === "ok" ? "ok" : "pending";
278
+ }
259
279
  }
260
280
  }
261
281
  instances.push({
@@ -272,6 +292,7 @@ function parseReservations(stdout: string): LiveInstance[] | null {
272
292
  ? record.PrivateIpAddress
273
293
  : null,
274
294
  taskLabel,
295
+ payloadValidation,
275
296
  });
276
297
  }
277
298
  }
@@ -323,19 +344,25 @@ async function hostEgressIp(): Promise<string> {
323
344
  );
324
345
  }
325
346
 
326
- /** How long a resolved payload AMI is trusted before the newest published
347
+ /** How long a resolved payload AMI is trusted before the newest approved
327
348
  * image is looked up again. Long enough that a burst of launches shares one
328
- * describe-images; short enough that a freshly published image reaches every
329
- * RUNNING host — shared and BYO — on its next task without a host restart
330
- * (before 0.9.106 the answer was kept for the process lifetime). */
349
+ * describe-images; short enough that a promotion or demotion reaches every
350
+ * RUNNING host on its next task without a restart. */
331
351
  export const PAYLOAD_AMI_TTL_MS = 5 * 60_000;
332
352
 
333
353
  export function createAwsMachineProvider(
334
354
  config: AwsMachineConfig,
335
355
  runner: Runner = defaultRunner(config.region),
336
- deps: { now?: () => number } = {},
356
+ deps: {
357
+ now?: () => number;
358
+ /** ONLY the non-packaged canary driver passes one. Production
359
+ * construction (task-environment/index.ts) never does, and no env var or
360
+ * config reads one. */
361
+ selector?: PayloadImageSelector;
362
+ } = {},
337
363
  ): MachineProvider {
338
364
  const now = deps.now ?? (() => Date.now());
365
+ const selector = deps.selector ?? PRODUCTION_PAYLOAD_SELECTOR;
339
366
  const taskIdOf = (machineId: string): string => {
340
367
  if (!machineId.startsWith("uai-machine-")) {
341
368
  throw new Error(`not a uai machine id: ${machineId}`);
@@ -385,51 +412,87 @@ export function createAwsMachineProvider(
385
412
  // orchestrator can never reach.
386
413
  // -------------------------------------------------------------------------
387
414
 
388
- let resolvedImage: { id: string; at: number } | null = null;
415
+ // The last SUCCESSFUL lookup's answer. Only a successful lookup sets
416
+ // lastOkAt; a failed one never advances it.
417
+ let payloadMemo: {
418
+ id: string;
419
+ name: string;
420
+ lastOkAt: number;
421
+ deprecationTime: number | null;
422
+ } | null = null;
423
+ /** Guards applied before EVERY cached return (the TTL fast path and the
424
+ * failed-lookup fallback alike): at most STALE_MAX_MS after the last
425
+ * successful lookup, and never at or past the image's deprecation time. */
426
+ const memoReturnable = (at: number): boolean =>
427
+ payloadMemo !== null &&
428
+ at < payloadMemo.lastOkAt + STALE_MAX_MS &&
429
+ (payloadMemo.deprecationTime === null || at < payloadMemo.deprecationTime);
430
+
389
431
  async function resolveImage(specImage: string): Promise<string> {
432
+ // An explicit AMI (UAI_MACHINE_IMAGE=ami-…) bypasses the lookup.
390
433
  if (specImage.startsWith("ami-")) return specImage;
391
- if (resolvedImage && now() - resolvedImage.at < PAYLOAD_AMI_TTL_MS) {
392
- return resolvedImage.id;
434
+ const started = now();
435
+ if (payloadMemo && started - payloadMemo.lastOkAt < PAYLOAD_AMI_TTL_MS && memoReturnable(started)) {
436
+ return payloadMemo.id;
393
437
  }
394
438
  const res = await runner([
395
439
  "ec2",
396
440
  "describe-images",
397
441
  "--owners",
398
- PAYLOAD_AMI_OWNER,
442
+ selector.owner,
399
443
  "--filters",
400
- `Name=name,Values=${PAYLOAD_AMI_NAME_PREFIX}-*`,
401
- "Name=state,Values=available",
444
+ ...payloadImageFilters(selector),
402
445
  "--query",
403
- "sort_by(Images, &CreationDate)[-1].ImageId",
446
+ "Images[].{ImageId: ImageId, Name: Name, CreationDate: CreationDate, OwnerId: OwnerId, " +
447
+ "Architecture: Architecture, State: State, Public: Public, DeprecationTime: DeprecationTime, Tags: Tags}",
404
448
  ]);
405
- let image: unknown = null;
449
+ let images: unknown = null;
406
450
  if (res.status === 0) {
407
451
  try {
408
- image = JSON.parse(res.stdout);
452
+ images = JSON.parse(res.stdout);
409
453
  } catch {
410
- image = null;
454
+ images = null;
411
455
  }
412
456
  }
413
- if (typeof image !== "string" || !image.startsWith("ami-")) {
414
- // A stale-but-known image beats a failed launch when the lookup itself
415
- // hiccups; only a host that never resolved one has nothing to offer.
416
- if (resolvedImage) return resolvedImage.id;
457
+ const at = now();
458
+ if (!Array.isArray(images)) {
459
+ // A failed lookup proves nothing: keep launching the last approved
460
+ // image only while its guards hold, otherwise fail closed.
461
+ if (payloadMemo && memoReturnable(at)) {
462
+ console.warn(
463
+ `[machine-aws] payload image lookup failed in ${config.region}; keeping ${payloadMemo.id} ` +
464
+ `(last confirmed ${Math.round((at - payloadMemo.lastOkAt) / 1000)}s ago)`,
465
+ );
466
+ return payloadMemo.id;
467
+ }
417
468
  throw new Error(
418
- `no uai machine payload AMI is published in ${config.region} — set ` +
419
- "UAI_MACHINE_IMAGE to an AMI id, or ask Moondeck to publish this region",
469
+ `could not look up the Moondeck Station machine image in ${config.region}: ${
470
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
471
+ } — set UAI_MACHINE_IMAGE to an AMI id to launch without the lookup`,
420
472
  );
421
473
  }
422
- if (resolvedImage?.id !== image) {
423
- // The journal line that tells an operator which payload a task got —
424
- // an exit 127 for a missing CLI is otherwise the only symptom of a
425
- // region that never received the latest publish.
474
+ const { selected, rejected } = selectStationPayloadImage(images, selector, at);
475
+ if (!selected) {
476
+ // A successful empty answer is authoritative: forget the cached image.
477
+ payloadMemo = null;
478
+ if (rejected.length > 0) {
479
+ console.warn(
480
+ `[machine-aws] payload images rejected in ${config.region}: ${rejected
481
+ .map((r) => `${r.id} (${r.reason})`)
482
+ .join(", ")}`,
483
+ );
484
+ }
485
+ throw new Error(noApprovedImageMessage(selector, config.region));
486
+ }
487
+ if (payloadMemo?.id !== selected.id) {
488
+ // The journal line that tells an operator which payload a task got.
426
489
  console.log(
427
- `[machine-aws] payload image for ${config.region}: ${image}` +
428
- (resolvedImage ? ` (was ${resolvedImage.id})` : ""),
490
+ `[machine-aws] payload image for ${config.region}: ${selected.id} (${selected.name})` +
491
+ (payloadMemo ? ` (was ${payloadMemo.id})` : ""),
429
492
  );
430
493
  }
431
- resolvedImage = { id: image, at: now() };
432
- return image;
494
+ payloadMemo = { ...selected, lastOkAt: at };
495
+ return selected.id;
433
496
  }
434
497
 
435
498
  let resolvedSubnet: string | null = null;
@@ -647,6 +710,8 @@ export function createAwsMachineProvider(
647
710
  return {
648
711
  id: machineId,
649
712
  taskLabel: instance.taskLabel,
713
+ payloadValidation: instance.payloadValidation,
714
+ instanceId: instance.instanceId,
650
715
  state,
651
716
  // Still stopping: its processes run until the instance is stopped.
652
717
  ...(instance.state === "stopping" ? { frozen: true as const } : {}),
@@ -674,7 +739,9 @@ export function createAwsMachineProvider(
674
739
  // volume while the root stays small — so resolve it per image.
675
740
  const diskGiB = config.diskGiB ?? DEFAULT_DISK_GIB;
676
741
  // ADR-125 BYO-AWS: explicit config wins; otherwise resolve the newest
677
- // published payload AMI and the default-VPC network per process.
742
+ // approved payload AMI and the default-VPC network per process.
743
+ // Only an auto-selected image is subject to the payload-marker probe.
744
+ const autoSelected = !spec.image.startsWith("ami-");
678
745
  const image = await resolveImage(spec.image);
679
746
  const subnetId = await resolveSubnet();
680
747
  const securityGroupId = await resolveSecurityGroup(subnetId);
@@ -690,6 +757,13 @@ export function createAwsMachineProvider(
690
757
  securityGroupId,
691
758
  config.iamInstanceProfileArn ?? null,
692
759
  diskGiB,
760
+ // The tag spec depends on the validation mode (an auto-selected
761
+ // image gets the `pending` tag, a pinned one none), so the mode
762
+ // is part of the token: the same AMI pinned and auto-selected
763
+ // must never share one (IdempotentParameterMismatch). The "v1"
764
+ // also keeps the tokens of 1.0.4 and earlier from meeting the new tag spec.
765
+ // describe-first above still prevents a double launch.
766
+ ["payload-validation-v1", autoSelected ? "pending" : null],
693
767
  ]),
694
768
  )
695
769
  .digest("hex")
@@ -708,7 +782,9 @@ export function createAwsMachineProvider(
708
782
  "--client-token",
709
783
  `${machineId}-${launchFingerprint}`.slice(0, 64),
710
784
  "--tag-specifications",
711
- `ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}]`,
785
+ `ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}${
786
+ autoSelected ? `,{Key=${PAYLOAD_VALIDATION_TAG},Value=pending}` : ""
787
+ }]`,
712
788
  "--block-device-mappings",
713
789
  JSON.stringify([
714
790
  {
@@ -760,7 +836,67 @@ export function createAwsMachineProvider(
760
836
  })`,
761
837
  );
762
838
  }
763
- return info;
839
+ // What was launched decides the probe, not a possibly stale describe.
840
+ return { ...info, payloadValidation: autoSelected ? "pending" : null };
841
+ },
842
+
843
+ async terminateInstance(machineId: string, instanceId: string): Promise<void> {
844
+ if (!/^i-[0-9a-f]+$/.test(instanceId)) {
845
+ throw new Error(`machine ${machineId}: refusing to terminate bad instance id ${instanceId}`);
846
+ }
847
+ const res = await runner(["ec2", "terminate-instances", "--instance-ids", instanceId]);
848
+ if (res.status !== 0) {
849
+ throw new Error(
850
+ `machine terminate failed for ${machineId} (${instanceId}): ${
851
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
852
+ }`,
853
+ );
854
+ }
855
+ // Proven by THIS instance id, never by the tag (which may now name a
856
+ // replacement): shutting-down/terminated, or EC2's exact not-found.
857
+ const deadline = Date.now() + 120_000;
858
+ for (;;) {
859
+ const raw = await runner([
860
+ "ec2",
861
+ "describe-instances",
862
+ "--instance-ids",
863
+ instanceId,
864
+ "--query",
865
+ "Reservations[].Instances[].State.Name",
866
+ "--output",
867
+ "text",
868
+ ]);
869
+ const state = raw.status === 0 ? raw.stdout.trim() : "";
870
+ if (state === "shutting-down" || state === "terminated") return;
871
+ if (raw.status !== 0 && /InvalidInstanceID\.NotFound/.test(raw.stderr)) return;
872
+ if (Date.now() >= deadline) {
873
+ throw new Error(`instance ${instanceId} of ${machineId} could not be proven terminated (${state || "unknown"})`);
874
+ }
875
+ await new Promise<void>((resolve) => setTimeout(resolve, 5_000));
876
+ }
877
+ },
878
+
879
+ async markPayloadValidated(machineId: string, instanceId: string): Promise<void> {
880
+ if (!/^i-[0-9a-f]+$/.test(instanceId)) {
881
+ throw new Error(`could not record payload validation on ${machineId}: bad instance id ${instanceId}`);
882
+ }
883
+ // The probed instance itself — never re-resolved by tag, so a
884
+ // replacement under the same logical id can never inherit `ok`.
885
+ const res = await runner([
886
+ "ec2",
887
+ "create-tags",
888
+ "--resources",
889
+ instanceId,
890
+ "--tags",
891
+ `Key=${PAYLOAD_VALIDATION_TAG},Value=ok`,
892
+ ]);
893
+ if (res.status !== 0) {
894
+ throw new Error(
895
+ `could not record payload validation on ${machineId}: ${
896
+ res.stderr.trim() || `exit ${res.status ?? "killed"}`
897
+ }`,
898
+ );
899
+ }
764
900
  },
765
901
 
766
902
  async stop(machineId: string): Promise<void> {
@@ -900,6 +1036,8 @@ export function createAwsMachineProvider(
900
1036
  ? awsMachineName(instance.taskLabel)
901
1037
  : instance.instanceId,
902
1038
  taskLabel: instance.taskLabel,
1039
+ payloadValidation: instance.payloadValidation,
1040
+ instanceId: instance.instanceId,
903
1041
  state,
904
1042
  ...(instance.state === "stopping" ? { frozen: true as const } : {}),
905
1043
  address: state === "running" ? instance.privateIp : null,
@@ -66,6 +66,17 @@ export interface MachineInfo {
66
66
  sshPort?: number;
67
67
  /** Present only alongside `unknown` — what the backend actually said. */
68
68
  detail?: string;
69
+ /** Station payload validation recorded ON the machine (aws: the
70
+ * `com.uai.payload-validation` tag, set to `pending` atomically at launch
71
+ * of an auto-selected image). `pending` = the payload marker has not been
72
+ * confirmed yet, so it is probed before any workspace prep; `ok` = it was;
73
+ * null/absent = never subject to the probe (pinned image, pre-1.0.5
74
+ * machine, or a backend without the concept). */
75
+ payloadValidation?: "pending" | "ok" | null;
76
+ /** The PHYSICAL instance behind the logical id (aws: the EC2 instance id).
77
+ * Payload validation is bound to it: a replacement under the same logical
78
+ * id is a different machine and is validated afresh. */
79
+ instanceId?: string;
69
80
  }
70
81
 
71
82
  export interface MachineProvider {
@@ -87,4 +98,15 @@ export interface MachineProvider {
87
98
  * rows reject the whole listing (they could hide exactly the labeled
88
99
  * machine a proof needs to see). */
89
100
  list(): Promise<MachineInfo[]>;
101
+ /** Record that the payload marker was confirmed ON exactly `instanceId`
102
+ * (the physical instance that was probed), never on whatever the logical
103
+ * id resolves to now. Backends without validation state omit it. Throws
104
+ * when the write fails; the instance then stays `pending`. */
105
+ markPayloadValidated?(id: string, instanceId: string): Promise<void>;
106
+ /** Terminate exactly ONE physical instance (the one a payload probe
107
+ * rejected), never re-resolving the logical id: a replacement under the
108
+ * same id is never touched. Resolves once that instance is proven
109
+ * shutting down or gone; throws otherwise. Ordinary teardown keeps using
110
+ * `terminate(id)`. */
111
+ terminateInstance?(id: string, instanceId: string): Promise<void>;
90
112
  }
@@ -37,6 +37,8 @@ import {
37
37
  BUNDLED_RUNTIME_ROOT,
38
38
  MANAGED_RUNTIME_CAPABILITY,
39
39
  MANAGED_RUNTIME_CREDENTIALS,
40
+ AGENT_FILES_SINCE_1_0_5,
41
+ agentFilesRequiredFor,
40
42
  MANAGED_RUNTIME_CREDENTIALS_VERSION,
41
43
  extractVerifiedRuntimeArchive,
42
44
  readVerifiedArtifactFile,
@@ -2165,6 +2167,29 @@ export async function validateInstalledRuntime(
2165
2167
  throw new Error(`managed runtime file escapes its version directory: ${relative}`);
2166
2168
  }
2167
2169
  }
2170
+ for (const [relative, executable] of AGENT_FILES_SINCE_1_0_5) {
2171
+ const absolute = path.join(root, ...relative.split("/"));
2172
+ const stat = await lstat(absolute).catch((error: NodeJS.ErrnoException) => {
2173
+ if (error.code === "ENOENT") return null;
2174
+ throw error;
2175
+ });
2176
+ // Absent in every generation before 1.0.5, a rollback target included;
2177
+ // required from 1.0.5 on.
2178
+ if (stat === null) {
2179
+ if (agentFilesRequiredFor(descriptor.hostVersion)) {
2180
+ throw new Error(`managed runtime is missing regular file ${relative}`);
2181
+ }
2182
+ continue;
2183
+ }
2184
+ if (!stat.isFile()) throw new Error(`managed runtime is missing regular file ${relative}`);
2185
+ if (executable && (stat.mode & 0o111) === 0) {
2186
+ throw new Error(`managed runtime file is not executable: ${relative}`);
2187
+ }
2188
+ const resolved = await realpath(absolute);
2189
+ if (!isInside(root, resolved)) {
2190
+ throw new Error(`managed runtime file escapes its version directory: ${relative}`);
2191
+ }
2192
+ }
2168
2193
  if (capabilities.capabilitySchemaVersion === 3) {
2169
2194
  await validateInstalledRuntimeAssets(root, capabilities);
2170
2195
  }
@@ -1665,6 +1665,14 @@ export class Orchestrator {
1665
1665
  ) {
1666
1666
  return false;
1667
1667
  }
1668
+ // A healthy initial start stays memoized, so binds and the start-loop tail
1669
+ // do not run on a re-attach ensure. Reassert the actual roster state to
1670
+ // heal a ready event lost by the cloud's former stage-write race. An ensure
1671
+ // acknowledgement alone is not readiness: every roster member must have
1672
+ // bound (including one-shot engines that have since exited).
1673
+ if (ready && this.rosterReady(channel)) {
1674
+ this.emitTaskStage(channel.taskId, "ready");
1675
+ }
1668
1676
  return ready;
1669
1677
  }
1670
1678
 
@@ -459,6 +459,41 @@ function validateEntryGraph(
459
459
  }
460
460
  }
461
461
 
462
+
463
+ /**
464
+ * Agent scripts added in Station 1.0.5: the dependency list _common.sh
465
+ * sources, and the Station's report of it. The build requires them
466
+ * (scripts/host-runtime/archive.mjs). Validation here and of an installed
467
+ * generation (managed-runtime.ts) requires them for a generation at or above
468
+ * 1.0.5, and for an older one checks them only if present: both validators
469
+ * also judge OLDER generations (a rollback target, a pinned earlier
470
+ * release), which never had them, and refusing those would block every way
471
+ * back. Main is still 1.0.4 while these land; #790's bump to 1.0.5 is what
472
+ * makes them required, with no further change here.
473
+ */
474
+ export const AGENT_FILES_SINCE_1_0_5: ReadonlyArray<readonly [string, boolean]> = Object.freeze([
475
+ Object.freeze(["agent/scripts/agent/_deps.sh", false] as const),
476
+ Object.freeze(["agent/scripts/agent/check-deps.sh", true] as const),
477
+ ]);
478
+ const AGENT_FILES_REQUIRED_FROM = Object.freeze([1, 0, 5] as const);
479
+
480
+ /**
481
+ * Whether a generation of `version` must carry AGENT_FILES_SINCE_1_0_5.
482
+ * Compares the numeric major.minor.patch core, so 1.0.5 and every later
483
+ * release (1.0.10, 1.1.0, 2.0.0) require them, and a prerelease of 1.0.5 is
484
+ * built from code that has them. A version that does not parse is held to
485
+ * the stricter rule.
486
+ */
487
+ export function agentFilesRequiredFor(version: string): boolean {
488
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(version);
489
+ if (!match) return true;
490
+ const core = [Number(match[1]), Number(match[2]), Number(match[3])];
491
+ for (let i = 0; i < 3; i++) {
492
+ if (core[i]! !== AGENT_FILES_REQUIRED_FROM[i]) return core[i]! > AGENT_FILES_REQUIRED_FROM[i]!;
493
+ }
494
+ return true;
495
+ }
496
+
462
497
  function validateEntryLayout(
463
498
  entries: readonly ArchiveEntry[],
464
499
  byPath: ReadonlyMap<string, ArchiveEntry>,
@@ -555,6 +590,18 @@ function validateEntryLayout(
555
590
  throw new Error(`runtime archive executable mode is invalid: ${executable}`);
556
591
  }
557
592
  }
593
+ const agentFilesRequired = agentFilesRequiredFor(descriptor.hostVersion);
594
+ for (const [file, executable] of AGENT_FILES_SINCE_1_0_5) {
595
+ const entry = byPath.get(file);
596
+ if (entry === undefined) {
597
+ if (agentFilesRequired) throw new Error(`runtime archive is missing regular file ${file}`);
598
+ continue;
599
+ }
600
+ if (entry.type !== "0") throw new Error(`runtime archive is missing regular file ${file}`);
601
+ if (executable && entry.mode !== 0o755) {
602
+ throw new Error(`runtime archive executable mode is invalid: ${file}`);
603
+ }
604
+ }
558
605
  return {
559
606
  ...platformCapabilities,
560
607
  runtimeCapabilityVersion,