@moondeck/station 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/agent.ts CHANGED
@@ -150,6 +150,9 @@ const TaskUpData = z.object({
150
150
  worktreePath: z.string(),
151
151
  codeServerPort: z.number().int().positive().optional(),
152
152
  previewPorts: PreviewPortRuntimesSchema.optional(),
153
+ /** F6: the task's machine had been terminated, and this start launched a
154
+ * fresh one; work only on the old machine is gone. A feed system note. */
155
+ environmentReplaced: z.literal(true).optional(),
153
156
  /** Degraded start: uai-init failed twice; surfaced as a feed system note. */
154
157
  initWarning: z.string().optional(),
155
158
  /** ADR-153: whether this start put the secrets proxy's CA, and its pins,
@@ -22,5 +22,7 @@ export function indexedPreamble(agent: RosterAgent): string {
22
22
  undefined,
23
23
  "/workspace",
24
24
  "task/x",
25
+ undefined, undefined, undefined, undefined, undefined, undefined,
26
+ { path: `/workspace/.moondeck/agents/${agent.id}/SKILL.md`, installedPackages: [] },
25
27
  );
26
28
  }
@@ -93,6 +93,8 @@ export interface LeasedEngineAccount {
93
93
  authKind: "env" | "config-dir" | "custom-connection";
94
94
  connection?: CustomConnectionLease;
95
95
  connectionMaterial?: CustomConnectionMaterial;
96
+ /** ADR-168: the models it may run; absent = every model. */
97
+ allowedModels?: readonly string[];
96
98
  /** The lease parameter's version this material was read at. */
97
99
  version: number;
98
100
  /** Env-token accounts: the variables the engine's spawn takes. */
@@ -115,6 +117,7 @@ export interface UnavailableEngineAccount {
115
117
  authKind: "env" | "config-dir" | "custom-connection";
116
118
  home: string | null;
117
119
  connection?: CustomConnectionLease;
120
+ allowedModels?: readonly string[];
118
121
  unavailable: true;
119
122
  }
120
123
 
@@ -209,6 +212,7 @@ function accountOf(credential: TaskEngineCredential): ServedEngineAccount {
209
212
  authKind: manifest.authKind,
210
213
  home,
211
214
  ...(manifest.connection ? { connection: manifest.connection } : {}),
215
+ ...(manifest.allowedModels ? { allowedModels: [...manifest.allowedModels] } : {}),
212
216
  };
213
217
  if (
214
218
  credential.availability !== "available" ||
@@ -23,6 +23,7 @@ import { ENGINE_ACCOUNT_PATHS } from "../src/engine-account-paths";
23
23
  * caps reset over time).
24
24
  */
25
25
 
26
+ import { accountAllowsModel } from "../src/model-limits";
26
27
  import {
27
28
  HOST_ACCOUNT_SCOPE,
28
29
  isEngineAccountScope,
@@ -184,6 +185,9 @@ export interface ResolvedEngineAccount {
184
185
  execEnv: Record<string, string>;
185
186
  /** config-dir accounts only: host dir to copy + container dir target. */
186
187
  configDir?: { hostDir: string; containerDir: string };
188
+ /** ADR-168: a leased account's allowed models (canonical roster ids);
189
+ * absent = every model. A runner's own accounts never carry one. */
190
+ allowedModels?: readonly string[];
187
191
  }
188
192
 
189
193
  // ---------------------------------------------------------------------------
@@ -554,19 +558,35 @@ export function noteEngineAccountUsed(id: string, now: number = Date.now()): voi
554
558
  state(id).lastUsedAt = now;
555
559
  }
556
560
 
561
+ /** ADR-168: the accounts that may run `model` for `kind` (all of them when
562
+ * `model` is undefined: the caller has no model to judge by). */
563
+ export function accountsAllowingModel<T extends Pick<ResolvedEngineAccount, "kind" | "allowedModels">>(
564
+ accounts: readonly T[],
565
+ model: string | null | undefined,
566
+ ): T[] {
567
+ if (model === undefined) return [...accounts];
568
+ return accounts.filter((a) => accountAllowsModel(a.allowedModels, a.kind, model));
569
+ }
570
+
557
571
  /**
558
572
  * Pure selection over a resolved list: least-recently-used account not in
559
573
  * `exclude` and not cooling. Falls back to the least-recently-used cooling
560
574
  * account if ALL are cooling (better to try a capped account than stall).
561
575
  * Returns null only when the list (minus exclusions) is empty.
576
+ *
577
+ * ADR-168: with `model`, only accounts allowing it are candidates — before
578
+ * the preferred pick, the try-order pick and the all-cooling fallback alike,
579
+ * so no path ever returns an account that does not allow the agent's model.
580
+ * `null` is an agent with no model set, which only an account without a
581
+ * limit allows.
562
582
  */
563
583
  export function selectAccount(
564
584
  accounts: ResolvedEngineAccount[],
565
- opts: { exclude?: Set<string>; now?: number; preferredId?: string } = {},
585
+ opts: { exclude?: Set<string>; now?: number; preferredId?: string; model?: string | null } = {},
566
586
  ): ResolvedEngineAccount | null {
567
587
  const now = opts.now ?? Date.now();
568
588
  const exclude = opts.exclude ?? new Set<string>();
569
- const candidates = accounts.filter((a) => !exclude.has(a.id));
589
+ const candidates = accountsAllowingModel(accounts, opts.model).filter((a) => !exclude.has(a.id));
570
590
  if (candidates.length === 0) return null;
571
591
  const lru = (a: ResolvedEngineAccount): number => state(a.id).lastUsedAt;
572
592
  const healthy = candidates.filter((a) => accountCooldownUntil(a.id) <= now);
@@ -597,6 +617,8 @@ export function pickEngineAccount(
597
617
  preferredId?: string;
598
618
  /** ADR-131 D3: the task's scope; default = the host's own accounts. */
599
619
  scope?: string;
620
+ /** ADR-168: only accounts allowing this model (undefined: any). */
621
+ model?: string | null;
600
622
  } = {},
601
623
  ): ResolvedEngineAccount | null {
602
624
  const accounts = resolveEngineAccounts(
@@ -608,6 +630,7 @@ export function pickEngineAccount(
608
630
  exclude: opts.exclude,
609
631
  now: opts.now,
610
632
  preferredId: opts.preferredId,
633
+ model: opts.model,
611
634
  });
612
635
  }
613
636
 
@@ -22,6 +22,10 @@ import { spawn } from "node:child_process";
22
22
  import type { DockerResult } from "./docker-exec";
23
23
 
24
24
  const DEFAULT_TIMEOUT_MS = 60_000;
25
+ /** ssh's ConnectTimeout for every machine exec: it bounds the TCP connect
26
+ * and the SSH handshake and key exchange (ssh_config(5)). Exec budgets that
27
+ * must leave room for a slow connect count it in (task-env-forwarder.ts). */
28
+ export const MACHINE_SSH_CONNECT_TIMEOUT_SECONDS = 10;
25
29
  const DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
26
30
  /** SIGKILLed ssh normally closes at once; an unreapable child must not hold
27
31
  * the promise open past the caller's own deadline. */
@@ -123,7 +127,7 @@ export function machineSshArgs(
123
127
  "-o",
124
128
  "StrictHostKeyChecking=accept-new",
125
129
  "-o",
126
- "ConnectTimeout=10",
130
+ `ConnectTimeout=${MACHINE_SSH_CONNECT_TIMEOUT_SECONDS}`,
127
131
  "-i",
128
132
  target.keyPath,
129
133
  "-p",
@@ -166,7 +170,7 @@ export function machineEnvironmentSshArgs(
166
170
  "-o",
167
171
  "StrictHostKeyChecking=accept-new",
168
172
  "-o",
169
- "ConnectTimeout=10",
173
+ `ConnectTimeout=${MACHINE_SSH_CONNECT_TIMEOUT_SECONDS}`,
170
174
  "-i",
171
175
  target.keyPath,
172
176
  "-p",
@@ -24,11 +24,14 @@ import { spawn } from "node:child_process";
24
24
  import type { DockerResult } from "./docker-exec";
25
25
  import { createHash } from "node:crypto";
26
26
 
27
- import type {
28
- MachineInfo,
29
- MachineProvider,
30
- MachineSpec,
31
- MachineState,
27
+ import {
28
+ MachineLaunchTokenSpentError,
29
+ type MachineInfo,
30
+ type MachineLaunchIntent,
31
+ type MachineLaunchIntentStore,
32
+ type MachineProvider,
33
+ type MachineSpec,
34
+ type MachineState,
32
35
  } from "./machine-provider";
33
36
  import {
34
37
  noApprovedImageMessage,
@@ -79,12 +82,12 @@ export interface AwsMachineConfig {
79
82
 
80
83
  const DEFAULT_DISK_GIB = 50;
81
84
 
82
- type Runner = (args: string[]) => Promise<DockerResult>;
85
+ type Runner = (args: string[], options?: { env?: Record<string, string> }) => Promise<DockerResult>;
83
86
 
84
87
  const DEFAULT_TIMEOUT_MS = 60_000;
85
88
 
86
89
  function defaultRunner(region: string): Runner {
87
- return (args) =>
90
+ return (args, options = {}) =>
88
91
  new Promise<DockerResult>((resolve) => {
89
92
  let stdout = "";
90
93
  let stderr = "";
@@ -92,7 +95,10 @@ function defaultRunner(region: string): Runner {
92
95
  const child = spawn(
93
96
  "aws",
94
97
  ["--region", region, "--output", "json", ...args],
95
- { stdio: ["ignore", "pipe", "pipe"] },
98
+ {
99
+ stdio: ["ignore", "pipe", "pipe"],
100
+ ...(options.env ? { env: { ...process.env, ...options.env } } : {}),
101
+ },
96
102
  );
97
103
  const settle = (status: number | null): void => {
98
104
  if (settled) return;
@@ -236,6 +242,81 @@ type LiveInstance = {
236
242
  payloadValidation: "pending" | "ok" | null;
237
243
  };
238
244
 
245
+ interface LaunchSubnet {
246
+ id: string;
247
+ /** Its availability zone, when describe-subnets named it. */
248
+ az: string | null;
249
+ /** UAI_AWS_SUBNET_ID: never replaced by another subnet. */
250
+ pinned: boolean;
251
+ }
252
+
253
+ function azLabel(subnet: LaunchSubnet): string {
254
+ return subnet.az ?? subnet.id;
255
+ }
256
+
257
+ /**
258
+ * EC2 error codes that reject a launch in THIS availability zone or subnet
259
+ * and provably launched nothing, so another AZ is safe to try (F3):
260
+ *
261
+ * - InsufficientInstanceCapacity: AWS has no On-Demand capacity for the type
262
+ * in the requested AZ; AWS's own advice is to try another AZ
263
+ * (docs.aws.amazon.com/AWSEC2/latest/UserGuide/troubleshooting-launch.html).
264
+ * - Unsupported, only in its instance-type/AZ form (AZ_UNSUPPORTED): the type
265
+ * is not offered in the requested AZ ("Please retry your request by ...
266
+ * choosing <other AZs>", same page). Any other Unsupported stops.
267
+ * - InsufficientFreeAddressesInSubnet: the subnet has no free private
268
+ * address (EC2 API error codes reference); another default subnet has its
269
+ * own range.
270
+ *
271
+ * Each launch asks for exactly one instance (--count 1, so MinCount 1), and
272
+ * RunInstances launches nothing when it cannot launch MinCount
273
+ * (RunInstances API reference). With AWS_MAX_ATTEMPTS=1 every answer is one
274
+ * request. So a definite rejection is no instance.
275
+ * Everything else (no exit status, RequestLimitExceeded, InternalError,
276
+ * Unavailable, an unrecognised code or message) is ambiguous and stops.
277
+ */
278
+ /** The AZ-specific `Unsupported` answer, as EC2 words it: "Your requested
279
+ * instance type (m7g.xlarge) is not supported in your requested
280
+ * Availability Zone (us-west-2d)." */
281
+ const AZ_UNSUPPORTED = /instance type \([^)]+\) is not supported in your requested Availability Zone \([^)]+\)/;
282
+
283
+ const AZ_REJECTION_CODES = new Set([
284
+ "InsufficientInstanceCapacity",
285
+ "Unsupported",
286
+ "InsufficientFreeAddressesInSubnet",
287
+ ]);
288
+
289
+ function definiteCapacityRejection(res: DockerResult): { code: string; message: string } | null {
290
+ if (res.status === null || res.status === 0) return null;
291
+ const match = /An error occurred \(([A-Za-z]+)\) when calling the RunInstances operation(?: \(reached max retries: (\d+)\))?: ([^\n]*)/.exec(res.stderr);
292
+ if (!match || !AZ_REJECTION_CODES.has(match[1]!)) return null;
293
+ // `Unsupported` covers many unsupported requests; only the instance-type
294
+ // and AZ one is about this AZ (review #mta79m).
295
+ if (match[1] === "Unsupported" && !AZ_UNSUPPORTED.test(match[3]!)) return null;
296
+ // Only a single answered request is a clean rejection. With
297
+ // AWS_MAX_ATTEMPTS=1, botocore's standard retry mode still marks a
298
+ // retryable error as max-attempts-reached on the first attempt
299
+ // (botocore/retries/standard.py, MaxAttemptsChecker sets
300
+ // MaxAttemptsReached), and ClientError then appends "(reached max
301
+ // retries: <RetryAttempts>)" (botocore/exceptions.py, _get_retry_info):
302
+ // 0 there is one attempt. A positive count means earlier attempts whose
303
+ // outcome is unknown: stop.
304
+ if (match[2] !== undefined && Number(match[2]) !== 0) return null;
305
+ return { code: match[1]!, message: match[3]!.trim() };
306
+ }
307
+
308
+ /** The one instance id a run-instances answer names; null otherwise. */
309
+ function runInstancesInstanceId(stdout: string): string | null {
310
+ try {
311
+ const instances = (JSON.parse(stdout) as { Instances?: unknown }).Instances;
312
+ if (!Array.isArray(instances) || instances.length !== 1) return null;
313
+ const id = (instances[0] as { InstanceId?: unknown } | null)?.InstanceId;
314
+ return typeof id === "string" && /^i-[0-9a-f]{8,32}$/.test(id) ? id : null;
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+
239
320
  /** Strict reservations parse. Any malformed instance voids the answer. */
240
321
  function parseReservations(stdout: string): LiveInstance[] | null {
241
322
  let parsed: unknown;
@@ -495,19 +576,23 @@ export function createAwsMachineProvider(
495
576
  return selected.id;
496
577
  }
497
578
 
498
- let resolvedSubnet: string | null = null;
499
- async function resolveSubnet(): Promise<string> {
500
- if (config.subnetId) return config.subnetId;
501
- if (resolvedSubnet) return resolvedSubnet;
579
+ let resolvedSubnets: LaunchSubnet[] | null = null;
580
+ /** Where a launch may go, in order. An explicit UAI_AWS_SUBNET_ID is the
581
+ * only candidate and is never overridden. Otherwise every default-VPC
582
+ * subnet (one per AZ, sorted by AZ), the public ones only when any is
583
+ * public: the Station dials the machine's public address. */
584
+ async function resolveSubnets(): Promise<LaunchSubnet[]> {
585
+ if (config.subnetId) return [{ id: config.subnetId, az: null, pinned: true }];
586
+ if (resolvedSubnets) return resolvedSubnets;
502
587
  const res = await runner([
503
588
  "ec2",
504
589
  "describe-subnets",
505
590
  "--filters",
506
591
  "Name=default-for-az,Values=true",
507
592
  "--query",
508
- "sort_by(Subnets, &AvailabilityZone)[].{id: SubnetId, public: MapPublicIpOnLaunch, vpc: VpcId}",
593
+ "sort_by(Subnets, &AvailabilityZone)[].{id: SubnetId, public: MapPublicIpOnLaunch, vpc: VpcId, az: AvailabilityZone}",
509
594
  ]);
510
- let subnets: Array<{ id?: unknown; public?: unknown }> = [];
595
+ let subnets: Array<{ id?: unknown; public?: unknown; az?: unknown }> = [];
511
596
  if (res.status === 0) {
512
597
  try {
513
598
  const parsed = JSON.parse(res.stdout);
@@ -516,19 +601,32 @@ export function createAwsMachineProvider(
516
601
  subnets = [];
517
602
  }
518
603
  }
519
- const chosen =
520
- subnets.find((s) => s.public === true && typeof s.id === "string") ??
521
- subnets.find((s) => typeof s.id === "string");
522
- if (!chosen || typeof chosen.id !== "string") {
604
+ const named = subnets.filter((s): s is { id: string; public?: unknown; az?: unknown } => typeof s.id === "string");
605
+ const publicOnes = named.filter((s) => s.public === true);
606
+ const eligible = publicOnes.length > 0 ? publicOnes : named;
607
+ if (eligible.length === 0) {
523
608
  throw new Error(
524
609
  `no default-VPC subnet found in ${config.region} — set ` +
525
610
  "UAI_AWS_SUBNET_ID to a public subnet",
526
611
  );
527
612
  }
528
- resolvedSubnet = chosen.id;
529
- return chosen.id;
613
+ resolvedSubnets = eligible.map((s) => ({
614
+ id: s.id,
615
+ az: typeof s.az === "string" ? s.az : null,
616
+ pinned: false,
617
+ }));
618
+ return resolvedSubnets;
530
619
  }
531
620
 
621
+ /** Launch intents for callers that bring no durable store (tests, the
622
+ * smoke scripts): per task, in-process only. */
623
+ const memoryIntents = new Map<string, MachineLaunchIntent>();
624
+ const intentStoreFor = (spec: MachineSpec): MachineLaunchIntentStore =>
625
+ spec.launchIntent ?? {
626
+ read: () => memoryIntents.get(spec.taskId) ?? null,
627
+ write: (intent) => void memoryIntents.set(spec.taskId, intent),
628
+ };
629
+
532
630
  let resolvedSecurityGroup: string | null = null;
533
631
  async function resolveSecurityGroup(subnetId: string): Promise<string> {
534
632
  if (config.securityGroupId) return config.securityGroupId;
@@ -743,78 +841,158 @@ export function createAwsMachineProvider(
743
841
  // Only an auto-selected image is subject to the payload-marker probe.
744
842
  const autoSelected = !spec.image.startsWith("ami-");
745
843
  const image = await resolveImage(spec.image);
746
- const subnetId = await resolveSubnet();
747
- const securityGroupId = await resolveSecurityGroup(subnetId);
844
+ const subnets = await resolveSubnets();
845
+ // Default-VPC subnets share the default VPC, so one group serves all.
846
+ const securityGroupId = await resolveSecurityGroup(subnets[0]!.id);
748
847
  const rootDevice = await rootDeviceName(image);
749
- // a live machine.
750
- const launchFingerprint = createHash("sha256")
751
- .update(
848
+ // F3 (review #mta79m): the persisted intent's subnet goes first, an
849
+ // attempt whose outcome is unknown included. Its token replays: a
850
+ // machine it made comes back (no second one in another AZ, whatever the
851
+ // tag query shows), and only a definite rejection there moves on. A
852
+ // launched intent also makes the AZ that worked the task's first choice.
853
+ const intents = intentStoreFor(spec);
854
+ const intent = intents.read();
855
+ const remembered: LaunchSubnet | null =
856
+ intent === null || subnets[0]!.pinned
857
+ ? null
858
+ : subnets.find((s) => s.id === intent.subnetId) ?? { id: intent.subnetId, az: null, pinned: false };
859
+ const order = remembered === null
860
+ ? subnets
861
+ : [remembered, ...subnets.filter((s) => s.id !== remembered.id)];
862
+ // F3: one attempt per subnet, moving on ONLY after a definite
863
+ // per-AZ rejection that launched nothing. Each subnet's token differs
864
+ // (the subnet is in the fingerprint), and is the same on every retry of
865
+ // that subnet, so a later attempt there replays rather than doubles.
866
+ const rejected: Array<{ subnet: LaunchSubnet; code: string; message: string }> = [];
867
+ let launchedIn: LaunchSubnet | null = null;
868
+ for (const subnet of order) {
869
+ const subnetId = subnet.id;
870
+ // a live machine.
871
+ const launchFingerprint = createHash("sha256")
872
+ .update(
873
+ JSON.stringify([
874
+ image,
875
+ type,
876
+ spec.authorizedPublicKey ?? null,
877
+ subnetId,
878
+ securityGroupId,
879
+ config.iamInstanceProfileArn ?? null,
880
+ diskGiB,
881
+ // The tag spec depends on the validation mode (an auto-selected
882
+ // image gets the `pending` tag, a pinned one none), so the mode
883
+ // is part of the token: the same AMI pinned and auto-selected
884
+ // must never share one (IdempotentParameterMismatch). The "v1"
885
+ // also keeps the tokens of 1.0.4 and earlier from meeting the new tag spec.
886
+ // describe-first above still prevents a double launch.
887
+ ["payload-validation-v1", autoSelected ? "pending" : null],
888
+ // F6: the task's Nth machine after N-1 proven terminations,
889
+ // appended only when N > 0, so generation 0 keeps exactly the
890
+ // 1.0.5 token (payload-validation-v1 included).
891
+ ...((spec.launchGeneration ?? 0) > 0
892
+ ? [["launch-generation", spec.launchGeneration]]
893
+ : []),
894
+ ]),
895
+ )
896
+ .digest("hex")
897
+ .slice(0, 16);
898
+ const args = [
899
+ "ec2",
900
+ "run-instances",
901
+ "--image-id",
902
+ image,
903
+ "--instance-type",
904
+ type,
905
+ "--count",
906
+ "1",
907
+ // Idempotency across crashed/retried provisions: the same token can
908
+ // never mint a second instance.
909
+ "--client-token",
910
+ `${machineId}-${launchFingerprint}`.slice(0, 64),
911
+ "--tag-specifications",
912
+ `ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}${
913
+ autoSelected ? `,{Key=${PAYLOAD_VALIDATION_TAG},Value=pending}` : ""
914
+ }]`,
915
+ "--block-device-mappings",
752
916
  JSON.stringify([
753
- image,
754
- type,
755
- spec.authorizedPublicKey ?? null,
756
- subnetId,
757
- securityGroupId,
758
- config.iamInstanceProfileArn ?? null,
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],
767
- ]),
768
- )
769
- .digest("hex")
770
- .slice(0, 16);
771
- const args = [
772
- "ec2",
773
- "run-instances",
774
- "--image-id",
775
- image,
776
- "--instance-type",
777
- type,
778
- "--count",
779
- "1",
780
- // Idempotency across crashed/retried provisions: the same token can
781
- // never mint a second instance.
782
- "--client-token",
783
- `${machineId}-${launchFingerprint}`.slice(0, 64),
784
- "--tag-specifications",
785
- `ResourceType=instance,Tags=[{Key=${AWS_MACHINE_TAG},Value=${spec.taskId}},{Key=Name,Value=${machineId}}${
786
- autoSelected ? `,{Key=${PAYLOAD_VALIDATION_TAG},Value=pending}` : ""
787
- }]`,
788
- "--block-device-mappings",
789
- JSON.stringify([
790
- {
791
- DeviceName: rootDevice,
792
- Ebs: {
793
- VolumeSize: diskGiB,
794
- VolumeType: "gp3",
795
- DeleteOnTermination: true,
917
+ {
918
+ DeviceName: rootDevice,
919
+ Ebs: {
920
+ VolumeSize: diskGiB,
921
+ VolumeType: "gp3",
922
+ DeleteOnTermination: true,
923
+ },
796
924
  },
797
- },
798
- ]),
799
- ...(spec.authorizedPublicKey
800
- ? ["--user-data", awsUserData(spec.authorizedPublicKey)]
801
- : []),
802
- "--subnet-id",
803
- subnetId,
804
- "--security-group-ids",
805
- securityGroupId,
806
- ...(config.iamInstanceProfileArn
807
- ? ["--iam-instance-profile", `Arn=${config.iamInstanceProfileArn}`]
808
- : []),
809
- ];
810
- const res = await runner(args);
811
- if (res.status !== 0) {
925
+ ]),
926
+ ...(spec.authorizedPublicKey
927
+ ? ["--user-data", awsUserData(spec.authorizedPublicKey)]
928
+ : []),
929
+ "--subnet-id",
930
+ subnetId,
931
+ "--security-group-ids",
932
+ securityGroupId,
933
+ ...(config.iamInstanceProfileArn
934
+ ? ["--iam-instance-profile", `Arn=${config.iamInstanceProfileArn}`]
935
+ : []),
936
+ ];
937
+ // Durable BEFORE the request: a crash or an unknown answer from here
938
+ // on leaves this subnet to be replayed first. A failed write launches
939
+ // nothing.
940
+ intents.write({ subnetId, state: "attempting" });
941
+ // One attempt per answer (review #mta79m): the CLI's own retries
942
+ // could hide an earlier attempt's unknown outcome behind a final
943
+ // capacity error. AWS_MAX_ATTEMPTS counts the initial call, so 1
944
+ // disables retries; the environment overrides the config file
945
+ // (AWS CLI "AWS CLI retries" and environment-variable docs).
946
+ const res = await runner(args, { env: { AWS_MAX_ATTEMPTS: "1" } });
947
+ if (res.status === 0) {
948
+ // F6 (test 6.3): a repeated client token is answered with the
949
+ // instance it first launched, even once that instance is terminated
950
+ // (its root volume deleted with it). The tag query below never lists
951
+ // a terminated instance, so look the answered instance up by id: only
952
+ // a definite terminated / shutting-down answer is proof the token is
953
+ // spent. A brand-new id that is not yet visible proves nothing.
954
+ const answeredId = runInstancesInstanceId(res.stdout);
955
+ if (answeredId !== null) {
956
+ const byId = await runner([
957
+ "ec2",
958
+ "describe-instances",
959
+ "--instance-ids",
960
+ answeredId,
961
+ ]);
962
+ const answered = byId.status === 0 ? parseReservations(byId.stdout) : null;
963
+ const gone = answered?.length === 1 &&
964
+ answered[0]!.instanceId === answeredId &&
965
+ (answered[0]!.state === "terminated" || answered[0]!.state === "shutting-down");
966
+ if (gone) {
967
+ throw new MachineLaunchTokenSpentError(machineId, answeredId, answered[0]!.state);
968
+ }
969
+ }
970
+ launchedIn = subnet;
971
+ break;
972
+ }
973
+ const rejection = subnet.pinned ? null : definiteCapacityRejection(res);
974
+ if (rejection === null) {
975
+ // Ambiguous (a timeout, throttling, a 5xx, anything unrecognised) or
976
+ // a pinned subnet: no other AZ, since this attempt may have launched.
977
+ throw new Error(
978
+ `machine launch failed for ${machineId}${
979
+ rejected.length > 0 ? ` (after no capacity in ${rejected.map((r) => azLabel(r.subnet)).join(", ")})` : ""
980
+ }: ${res.stderr.trim() || `exit ${res.status ?? "killed"}`}`,
981
+ );
982
+ }
983
+ rejected.push({ subnet, ...rejection });
984
+ console.warn(
985
+ `[machine-aws] ${machineId}: ${rejection.code} in ${azLabel(subnet)}; trying the next availability zone`,
986
+ );
987
+ }
988
+ if (launchedIn === null) {
812
989
  throw new Error(
813
- `machine launch failed for ${machineId}: ${
814
- res.stderr.trim() || `exit ${res.status ?? "killed"}`
815
- }`,
990
+ `machine launch failed for ${machineId}: no ${type} capacity in ${config.region} ` +
991
+ `(${rejected.map((r) => `${azLabel(r.subnet)}: ${r.code}`).join("; ")}). ` +
992
+ "Try again later, choose another instance type, or launch the host in another region.",
816
993
  );
817
994
  }
995
+ intents.write({ subnetId: launchedIn.id, state: "launched" });
818
996
  // DescribeInstances TAG FILTERS are eventually consistent: the query
819
997
  // can miss an instance RunInstances just created (live 2026-08-28 —
820
998
  // the machine was running the whole time while launch reported
@@ -43,6 +43,49 @@ export interface MachineSpec {
43
43
  * host-routable there, so SSH must ride a loopback-published port. The
44
44
  * Linux guinea pig and cloud backends dial the address directly. */
45
45
  publishSsh?: boolean;
46
+ /** F3: where the task's launch intent is kept (its control dir), so a
47
+ * retry after a restart replays the subnet an earlier attempt used before
48
+ * trying any other. Backends without placement choices ignore it. */
49
+ launchIntent?: MachineLaunchIntentStore;
50
+ /** Which launch of this task's machine this is (F6). A cloud backend's
51
+ * launch idempotency is keyed on it: 0 (or absent) is the task's first
52
+ * machine, with the token every earlier release used. The caller bumps it
53
+ * only after the backend proved the previous generation's machine
54
+ * terminated (MachineLaunchTokenSpentError), so a retry of a launch still
55
+ * in flight keeps its token and can never mint a second machine. */
56
+ launchGeneration?: number;
57
+ }
58
+
59
+ /** The subnet a launch is attempting or launched in; `attempting` means its
60
+ * outcome is not yet known. */
61
+ export interface MachineLaunchIntent {
62
+ subnetId: string;
63
+ state: "attempting" | "launched";
64
+ }
65
+
66
+ export interface MachineLaunchIntentStore {
67
+ read(): MachineLaunchIntent | null;
68
+ /** Atomic and durable before it returns; throws rather than pretend. */
69
+ write(intent: MachineLaunchIntent): void;
70
+ }
71
+
72
+ /**
73
+ * The backend's launch idempotency resolved to a machine that is already
74
+ * terminated (F6, test 6.3): EC2 remembers a client token for a while past
75
+ * termination and answers a repeat with the old, gone instance. Proof that
76
+ * this launch generation is spent; the caller may launch the next one.
77
+ */
78
+ export class MachineLaunchTokenSpentError extends Error {
79
+ override readonly name = "MachineLaunchTokenSpentError";
80
+ constructor(
81
+ readonly machineId: string,
82
+ readonly instanceId: string,
83
+ readonly instanceState: string,
84
+ ) {
85
+ super(
86
+ `machine ${machineId}: its launch token resolved to instance ${instanceId}, which is ${instanceState}`,
87
+ );
88
+ }
46
89
  }
47
90
 
48
91
  export interface MachineInfo {