@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.
@@ -15,15 +15,20 @@
15
15
  */
16
16
 
17
17
  import { execFile, spawn as nodeSpawn } from "node:child_process";
18
- import { readFileSync, statSync, writeFileSync } from "node:fs";
18
+ import { readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
19
+ import { join } from "node:path";
19
20
  import { promisify } from "node:util";
20
21
 
21
- import type {
22
- MachineInfo,
23
- MachineProvider,
22
+ import {
23
+ MachineLaunchTokenSpentError,
24
+ type MachineInfo,
25
+ type MachineLaunchIntent,
26
+ type MachineLaunchIntentStore,
27
+ type MachineProvider,
24
28
  } from "../machine-provider";
25
29
  import { machineEnvironmentSshArgs } from "../machine-exec";
26
30
  import { STATION_MACHINE_PAYLOAD_MARKER } from "../machine-payload-image";
31
+ import type { EnvironmentLossNotice } from "./types";
27
32
  import { applyProjectEnvProfile } from "../runtime-authority";
28
33
  import { rootAnchoredRequest } from "./anchor";
29
34
  import {
@@ -121,6 +126,283 @@ export interface MachineTaskEnvironmentDeps {
121
126
  readyTimeoutMs?: number;
122
127
  }
123
128
 
129
+ /**
130
+ * F6: which launch of a task's machine is current, kept beside its SSH
131
+ * identity in the task control dir so it survives a Station restart. The
132
+ * generation feeds the backend's launch idempotency (MachineSpec), and is
133
+ * bumped only after the backend proves the current generation's machine
134
+ * terminated. `launched` records that this generation's launch succeeded, and
135
+ * `instanceId` which instance it made: a later launch answered by a DIFFERENT
136
+ * instance means the old one, and its disk, went away. The same instance
137
+ * means a retry found it again (a lagging describe), and nothing was lost.
138
+ *
139
+ * `pendingLossNotices` holds those proofs, one per lost machine, until the
140
+ * user has been told (reviews #w3qdsr, #4ndq0w): each is added when its loss
141
+ * is proven, carried across a crash before the relaunch and across failed
142
+ * starts after it, and removed (by its id) only once the cloud has its note.
143
+ * A queue, not one slot: every lost machine is its own fact with its own id,
144
+ * so a second loss can never be folded into, or hidden behind, the first.
145
+ */
146
+ export interface MachineLaunchRecord {
147
+ generation: number;
148
+ launched: boolean;
149
+ instanceId?: string;
150
+ pendingLossNotices?: PendingLossNotice[];
151
+ /** F3: the subnet the latest launch attempt used, written BEFORE its
152
+ * run-instances; `attempting` means its outcome is not yet known. The
153
+ * next launch replays this subnet first (fileLaunchIntentStore). One
154
+ * record, so the generation and the subnet always move together; every
155
+ * write re-reads the file and keeps the fields it does not own. */
156
+ launchIntent?: MachineLaunchIntent;
157
+ }
158
+
159
+ export interface PendingLossNotice {
160
+ lostInstanceId: string | null;
161
+ /** The generation that replaced it: with the instance, the loss's id. */
162
+ generation: number;
163
+ /** Handed to a publisher at least once (review #2cp6r4). Set before the
164
+ * first publish and never cleared: the cloud may hold this id already, so
165
+ * the entry is immutable (never folded, grown or dropped) until its id is
166
+ * acknowledged, and every retry resends the identical id and text. */
167
+ attempted?: true;
168
+ /** A summary of several losses folded together when the queue overflowed
169
+ * (review #d0p42f). `lostInstanceId` and `generation` are the FIRST folded
170
+ * loss's, so the summary's id never changes as more fold in. */
171
+ folded?: { count: number; instanceIds: string[] };
172
+ }
173
+
174
+ /**
175
+ * The most entries the queue keeps (review #d0p42f). Each one needs a real
176
+ * EC2 machine of this task proven terminated, whose note the cloud has not
177
+ * yet confirmed. Even a handful between two successful starts is far beyond
178
+ * what happens, so 16 never folds in practice and still bounds a broken
179
+ * delivery path. With at most MAX_FOLDED_INSTANCE_IDS ids in a summary, the
180
+ * whole record stays under 4 KiB.
181
+ *
182
+ * It is never exceeded (review #2cp6r4): the Station delivers one entry per
183
+ * task at a time, oldest first, and attempts the next only once the current
184
+ * one is acknowledged, so at most one entry is attempted at any time and at
185
+ * least 15 of 16 are always foldable.
186
+ */
187
+ export const MAX_PENDING_LOSS_NOTICES = 16;
188
+ export const MAX_FOLDED_INSTANCE_IDS = 8;
189
+
190
+ function isPendingLossNotice(value: unknown): value is PendingLossNotice {
191
+ if (typeof value !== "object" || value === null) return false;
192
+ const notice = value as { lostInstanceId?: unknown; generation?: unknown; attempted?: unknown; folded?: unknown };
193
+ const folded = notice.folded as { count?: unknown; instanceIds?: unknown } | undefined;
194
+ return (
195
+ (notice.lostInstanceId === null || typeof notice.lostInstanceId === "string") &&
196
+ typeof notice.generation === "number" &&
197
+ Number.isSafeInteger(notice.generation) &&
198
+ (notice.attempted === undefined || notice.attempted === true) &&
199
+ (folded === undefined ||
200
+ (typeof folded === "object" &&
201
+ folded !== null &&
202
+ typeof folded.count === "number" &&
203
+ Number.isSafeInteger(folded.count) &&
204
+ folded.count >= 1 &&
205
+ Array.isArray(folded.instanceIds) &&
206
+ folded.instanceIds.length <= MAX_FOLDED_INSTANCE_IDS &&
207
+ folded.instanceIds.every((id) => typeof id === "string" && id.length <= 64)))
208
+ );
209
+ }
210
+
211
+ /** `into` (a summary, or a single loss that becomes one) with `next` folded in. */
212
+ function foldLossNotices(into: PendingLossNotice, next: PendingLossNotice): PendingLossNotice {
213
+ const idsOf = (notice: PendingLossNotice): string[] =>
214
+ notice.folded?.instanceIds ?? (notice.lostInstanceId === null ? [] : [notice.lostInstanceId]);
215
+ const countOf = (notice: PendingLossNotice): number => notice.folded?.count ?? 1;
216
+ return {
217
+ lostInstanceId: into.lostInstanceId,
218
+ generation: into.generation,
219
+ folded: {
220
+ count: countOf(into) + countOf(next),
221
+ instanceIds: [...idsOf(into), ...idsOf(next)].slice(0, MAX_FOLDED_INSTANCE_IDS),
222
+ },
223
+ };
224
+ }
225
+
226
+ /** The record's queue with `notice` added, unless one with its id is there. */
227
+ export function withLossNotice(current: MachineLaunchRecord, notice: PendingLossNotice): PendingLossNotice[] {
228
+ const existing = current.pendingLossNotices ?? [];
229
+ if (existing.some((pending) => lossNoticeId(pending) === lossNoticeId(notice))) return existing;
230
+ const queue = [...existing, notice];
231
+ // Reviews #d0p42f, #2cp6r4: at most MAX_PENDING_LOSS_NOTICES entries.
232
+ while (queue.length > MAX_PENDING_LOSS_NOTICES) {
233
+ // The two oldest entries never attempted fold into one. An attempted
234
+ // entry is never touched: the cloud may already hold its id. A summary
235
+ // never attempted may grow (the cloud never saw its id) and keeps it;
236
+ // two singles make a new summary, whose id is its own first loss's.
237
+ const first = queue.findIndex((pending) => pending.attempted !== true);
238
+ const second = first === -1 ? -1 : queue.findIndex((pending, index) => index > first && pending.attempted !== true);
239
+ if (second === -1) {
240
+ // Only reachable with two or more attempted entries, which one-at-a-time
241
+ // delivery never leaves: refuse rather than drop a proof or grow past
242
+ // the bound.
243
+ throw new Error(
244
+ `machine-loss notice queue invariant broken: ${String(queue.filter((pending) => pending.attempted === true).length)} attempted entries`,
245
+ );
246
+ }
247
+ const folded = foldLossNotices(queue[first]!, queue[second]!);
248
+ queue.splice(second, 1);
249
+ queue.splice(first, 1, folded);
250
+ }
251
+ return queue;
252
+ }
253
+
254
+ export function lossNoticeId(notice: PendingLossNotice): string {
255
+ const single = `${notice.lostInstanceId ?? "unknown-instance"}@generation-${notice.generation}`;
256
+ return notice.folded ? `folded:${single}` : single;
257
+ }
258
+
259
+ export const MACHINE_LAUNCH_RECORD = "machine-launch.json";
260
+
261
+ /** The task's launch record; a task from before F6 has none (generation 0,
262
+ * never recorded as launched). A record that does not parse is refused, not
263
+ * guessed at: a wrong generation could reuse a spent token or double-launch. */
264
+ export function readMachineLaunchRecord(controlDir: string): MachineLaunchRecord {
265
+ let raw: string;
266
+ try {
267
+ raw = readFileSync(join(controlDir, MACHINE_LAUNCH_RECORD), "utf8");
268
+ } catch (error) {
269
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { generation: 0, launched: false };
270
+ throw error;
271
+ }
272
+ const parsed = JSON.parse(raw) as {
273
+ schemaVersion?: unknown;
274
+ generation?: unknown;
275
+ launched?: unknown;
276
+ instanceId?: unknown;
277
+ pendingLossNotices?: unknown;
278
+ launchIntent?: { subnetId?: unknown; state?: unknown } | null;
279
+ };
280
+ if (
281
+ parsed?.schemaVersion !== 1 ||
282
+ typeof parsed.generation !== "number" ||
283
+ !Number.isSafeInteger(parsed.generation) ||
284
+ parsed.generation < 0 ||
285
+ typeof parsed.launched !== "boolean" ||
286
+ (parsed.instanceId !== undefined && typeof parsed.instanceId !== "string") ||
287
+ (parsed.pendingLossNotices !== undefined &&
288
+ (!Array.isArray(parsed.pendingLossNotices) || !parsed.pendingLossNotices.every(isPendingLossNotice))) ||
289
+ (parsed.launchIntent !== undefined &&
290
+ (typeof parsed.launchIntent !== "object" ||
291
+ parsed.launchIntent === null ||
292
+ typeof parsed.launchIntent.subnetId !== "string" ||
293
+ // Refused, not guessed at: a wrong subnet could launch a second machine.
294
+ !/^subnet-[0-9a-f]{8,32}$/.test(parsed.launchIntent.subnetId) ||
295
+ (parsed.launchIntent.state !== "attempting" && parsed.launchIntent.state !== "launched")))
296
+ ) {
297
+ throw new Error(`machine launch record in ${controlDir} is invalid`);
298
+ }
299
+ return {
300
+ generation: parsed.generation,
301
+ launched: parsed.launched,
302
+ ...(typeof parsed.instanceId === "string" ? { instanceId: parsed.instanceId } : {}),
303
+ ...(Array.isArray(parsed.pendingLossNotices) && parsed.pendingLossNotices.length > 0
304
+ ? {
305
+ pendingLossNotices: (parsed.pendingLossNotices as PendingLossNotice[]).map((notice) => ({
306
+ lostInstanceId: notice.lostInstanceId,
307
+ generation: notice.generation,
308
+ ...(notice.attempted === true ? { attempted: true as const } : {}),
309
+ ...(notice.folded
310
+ ? { folded: { count: notice.folded.count, instanceIds: [...notice.folded.instanceIds] } }
311
+ : {}),
312
+ })),
313
+ }
314
+ : {}),
315
+ ...(parsed.launchIntent !== undefined
316
+ ? {
317
+ launchIntent: {
318
+ subnetId: parsed.launchIntent.subnetId as string,
319
+ state: parsed.launchIntent.state as MachineLaunchIntent["state"],
320
+ },
321
+ }
322
+ : {}),
323
+ };
324
+ }
325
+
326
+ /** Read the record afresh, change it, write it: a writer never drops a field
327
+ * another one owns (the launch intent, the loss notice). */
328
+ export function updateMachineLaunchRecord(
329
+ controlDir: string,
330
+ change: (current: MachineLaunchRecord) => MachineLaunchRecord,
331
+ ): void {
332
+ writeMachineLaunchRecord(controlDir, change(readMachineLaunchRecord(controlDir)));
333
+ }
334
+
335
+ /** F3's launch-intent store over the task's machine-launch.json. */
336
+ export function fileLaunchIntentStore(controlDir: string): MachineLaunchIntentStore {
337
+ return {
338
+ read: () => readMachineLaunchRecord(controlDir).launchIntent ?? null,
339
+ write: (intent) => updateMachineLaunchRecord(controlDir, (current) => ({ ...current, launchIntent: { ...intent } })),
340
+ };
341
+ }
342
+
343
+ /** The pending notice as the Station delivers it. Both steps touch only the
344
+ * notice they were handed (by id) and throw on a failed write. */
345
+ export function machineLossNotice(controlDir: string, pending: PendingLossNotice): EnvironmentLossNotice {
346
+ const id = lossNoticeId(pending);
347
+ // Each step re-reads the record and touches only this notice, by id.
348
+ const update = (change: (notice: PendingLossNotice) => PendingLossNotice | null): void =>
349
+ updateMachineLaunchRecord(controlDir, (current) => {
350
+ const queue: PendingLossNotice[] = [];
351
+ for (const notice of current.pendingLossNotices ?? []) {
352
+ if (lossNoticeId(notice) !== id) {
353
+ queue.push(notice);
354
+ continue;
355
+ }
356
+ const next = change(notice);
357
+ if (next !== null) queue.push(next);
358
+ }
359
+ const { pendingLossNotices: _old, ...rest } = current;
360
+ return queue.length > 0 ? { ...rest, pendingLossNotices: queue } : rest;
361
+ });
362
+ return {
363
+ id,
364
+ attempted: pending.attempted === true,
365
+ lostEnvironments: pending.folded?.count ?? 1,
366
+ markAttempted: () => {
367
+ // Persist the mark first and read what the entry carries from that same
368
+ // write: from here on it never changes, so the text sent now is the
369
+ // text every retry sends.
370
+ let count: number | null = null;
371
+ update((notice) => {
372
+ count = notice.folded?.count ?? 1;
373
+ return { ...notice, attempted: true };
374
+ });
375
+ return count;
376
+ },
377
+ acknowledge: () => update(() => null),
378
+ };
379
+ }
380
+
381
+ export function writeMachineLaunchRecord(controlDir: string, record: MachineLaunchRecord): void {
382
+ const path = join(controlDir, MACHINE_LAUNCH_RECORD);
383
+ const temporary = `${path}.${process.pid}.tmp`;
384
+ writeFileSync(temporary, `${JSON.stringify({ schemaVersion: 1, ...record })}\n`, { mode: 0o600 });
385
+ renameSync(temporary, path);
386
+ }
387
+
388
+ /** Best-effort: never blocks resuming a machine that exists. */
389
+ function noteMachineSeen(controlDir: string, taskId: string, instanceId: string | undefined): void {
390
+ try {
391
+ const record = readMachineLaunchRecord(controlDir);
392
+ if (!record.launched || (instanceId !== undefined && record.instanceId !== instanceId)) {
393
+ writeMachineLaunchRecord(controlDir, {
394
+ ...record,
395
+ launched: true,
396
+ ...(instanceId !== undefined ? { instanceId } : {}),
397
+ });
398
+ }
399
+ } catch (error) {
400
+ console.warn(
401
+ `[machine] task ${taskId}: could not update its launch record: ${error instanceof Error ? error.message : String(error)}`,
402
+ );
403
+ }
404
+ }
405
+
124
406
  export function machineTaskEnvironmentLocator(
125
407
  value: MachineTaskEnvironmentLocatorValue,
126
408
  ): TaskEnvironmentLocator {
@@ -1050,14 +1332,70 @@ export function createMachineTaskEnvironmentProvider(
1050
1332
  // or a restarted Station sees the same answer: an unconfirmed machine
1051
1333
  // is probed whether it is fresh or reused.
1052
1334
  let payloadValidation = existing.payloadValidation ?? null;
1335
+ const controlDir = deps.taskControlDir(taskId);
1053
1336
  if (existing.state === "absent") {
1054
- const launched = await deps.machines.launch({
1337
+ // Read once for what this start knows of the task's last machine.
1338
+ // Every write below re-reads the record (updateMachineLaunchRecord)
1339
+ // and changes only its own fields: a delivery may acknowledge a
1340
+ // notice while this start awaits a launch, and a snapshot taken
1341
+ // before that await must never be written back (review #4ndq0w).
1342
+ const record = readMachineLaunchRecord(controlDir);
1343
+ let generation = record.generation;
1344
+ const launchSpec = {
1055
1345
  taskId,
1056
1346
  image: input.image,
1057
1347
  cpus: input.cpus,
1058
1348
  memoryMiB: input.memoryMiB,
1059
1349
  authorizedPublicKey: keys.publicKey,
1060
1350
  ...(input.publishSsh ? { publishSsh: true } : {}),
1351
+ launchIntent: fileLaunchIntentStore(deps.taskControlDir(taskId)),
1352
+ };
1353
+ let launched: MachineInfo;
1354
+ try {
1355
+ launched = await deps.machines.launch({ ...launchSpec, launchGeneration: generation });
1356
+ } catch (error) {
1357
+ if (!(error instanceof MachineLaunchTokenSpentError)) throw error;
1358
+ // F6: the backend proved this generation's machine terminated, so
1359
+ // its token can only ever answer with that machine. Persist the
1360
+ // next generation BEFORE launching it: a crash mid-launch retries
1361
+ // with the new token, never the spent one, and never mints twice.
1362
+ generation += 1;
1363
+ const loss: PendingLossNotice = { lostInstanceId: error.instanceId, generation };
1364
+ const nextGeneration = generation;
1365
+ updateMachineLaunchRecord(controlDir, (current) => {
1366
+ // The lost instance is no longer the task's: drop its id, so a
1367
+ // retry after a crash cannot prove the same loss again.
1368
+ const { instanceId: _lost, ...rest } = current;
1369
+ return { ...rest, generation: nextGeneration, launched: false, pendingLossNotices: withLossNotice(current, loss) };
1370
+ });
1371
+ console.warn(
1372
+ `[machine] task ${taskId}: ${error.message}; launching generation ${generation} with a new launch token`,
1373
+ );
1374
+ launched = await deps.machines.launch({ ...launchSpec, launchGeneration: generation });
1375
+ }
1376
+ // Lost only on proof: the token was spent on a terminated instance
1377
+ // (above), or a launch this record knows answered with a different
1378
+ // instance than before.
1379
+ const replacedInstance =
1380
+ record.instanceId !== undefined &&
1381
+ launched.instanceId !== undefined &&
1382
+ launched.instanceId !== record.instanceId
1383
+ ? record.instanceId
1384
+ : null;
1385
+ const launchedGeneration = generation;
1386
+ updateMachineLaunchRecord(controlDir, (current) => {
1387
+ const { instanceId: _previous, ...rest } = current;
1388
+ return {
1389
+ // The current record: the launch intent the launch just wrote,
1390
+ // and the notice queue as deliveries left it.
1391
+ ...rest,
1392
+ generation: launchedGeneration,
1393
+ launched: true,
1394
+ ...(launched.instanceId !== undefined ? { instanceId: launched.instanceId } : {}),
1395
+ ...(replacedInstance !== null
1396
+ ? { pendingLossNotices: withLossNotice(current, { lostInstanceId: replacedInstance, generation: launchedGeneration }) }
1397
+ : {}),
1398
+ };
1061
1399
  });
1062
1400
  if (launched.id !== machineId) {
1063
1401
  // The backend named the machine something other than what the
@@ -1069,8 +1407,11 @@ export function createMachineTaskEnvironmentProvider(
1069
1407
  );
1070
1408
  }
1071
1409
  payloadValidation = launched.payloadValidation ?? null;
1072
- } else if (existing.state === "stopped") {
1073
- await deps.machines.start(machineId);
1410
+ } else {
1411
+ // A machine seen for this task (one a pre-F6 Station launched has no
1412
+ // record yet): once it is gone, a later Resume must say so.
1413
+ noteMachineSeen(controlDir, taskId, existing.instanceId);
1414
+ if (existing.state === "stopped") await deps.machines.start(machineId);
1074
1415
  }
1075
1416
  // running/pending: fall through to the ssh-readiness proof below.
1076
1417
 
@@ -1131,7 +1472,23 @@ export function createMachineTaskEnvironmentProvider(
1131
1472
  );
1132
1473
  }
1133
1474
  }
1134
- return { handle, result: handle.descriptor, reused };
1475
+ // Reported by every start until one succeeds, a retry that found the
1476
+ // replacement already running included.
1477
+ let pending: PendingLossNotice[] = [];
1478
+ try {
1479
+ pending = readMachineLaunchRecord(controlDir).pendingLossNotices ?? [];
1480
+ } catch {
1481
+ // An unreadable record was refused above for a launch; for a reused
1482
+ // machine it only costs the notice.
1483
+ }
1484
+ return {
1485
+ handle,
1486
+ result: handle.descriptor,
1487
+ reused,
1488
+ ...(pending.length > 0
1489
+ ? { replacedLostEnvironment: true, lossNotices: pending.map((notice) => machineLossNotice(controlDir, notice)) }
1490
+ : {}),
1491
+ };
1135
1492
  },
1136
1493
 
1137
1494
  async reconstruct(
@@ -378,6 +378,34 @@ export interface TaskEnvironmentProvisioned<TResult, TTeardownResult = void> {
378
378
  * stopped machine, whose disk holds the task's work — rather than creating
379
379
  * it. A failed start stops such an environment; it never destroys it. */
380
380
  reused?: boolean;
381
+ /** F6: the task had an environment before, it is gone (a terminated
382
+ * machine and its disk), and this provision created a fresh one. Work
383
+ * that lived only on the old one is lost; the start says so. */
384
+ replacedLostEnvironment?: boolean;
385
+ /** The proof behind replacedLostEnvironment, until the user is told. */
386
+ /** One per lost environment not yet told, oldest first (review #4ndq0w). */
387
+ lossNotices?: EnvironmentLossNotice[];
388
+ }
389
+
390
+ /**
391
+ * A lost environment the user has not yet been told about (F6, reviews
392
+ * #tgxadc, #2cp6r4). The Station delivers a task's notices one at a time,
393
+ * oldest first: markAttempted (persisted, never undone) before the first
394
+ * publish, the same id and text on every retry, and acknowledge only once the
395
+ * cloud has the note. The next notice is attempted only after that.
396
+ */
397
+ export interface EnvironmentLossNotice {
398
+ readonly id: string;
399
+ /** Handed to a publisher before: resend exactly this. */
400
+ readonly attempted: boolean;
401
+ /** How many lost environments this notice speaks for: 1, or more for a
402
+ * summary folded from an overflowing queue (review #d0p42f). */
403
+ readonly lostEnvironments?: number;
404
+ /** Before publishing: mark the notice attempted (persisted; from then on it
405
+ * is immutable) and return how many lost environments it carries, or
406
+ * null when it is already gone. */
407
+ markAttempted(): number | null;
408
+ acknowledge(): void;
381
409
  }
382
410
 
383
411
  export interface TaskEnvironmentProvider<
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "Moondeck Station: runs Moondeck tasks in containers on a machine you control.",
5
5
  "license": "MIT",
6
6
  "author": "Moondeck <team@moondeck.io>",
@@ -77,6 +77,10 @@
77
77
  "types": "./src/engine-models.ts",
78
78
  "default": "./src/engine-models.ts"
79
79
  },
80
+ "./model-limits": {
81
+ "types": "./src/model-limits.ts",
82
+ "default": "./src/model-limits.ts"
83
+ },
80
84
  "./engine-usage": {
81
85
  "types": "./src/engine-usage.ts",
82
86
  "default": "./src/engine-usage.ts"
@@ -1,5 +1,6 @@
1
1
  import { LEASE_PARAMETER_ROOT, BROKER_PARAMETER_ROOT, MAX_CREDENTIAL_ID_CHARS, MAX_PARAMETER_NAME_CHARS, leaseParameterName, brokerParameterName, idPathSegment, parseIdPathSegment, isEngineKind, parseLeaseParameterName, parseBrokerParameterName, sameLocation, isIdValue, isTagValue, type CredentialClass, type CredentialScope, type CredentialLocation } from "./credential-location";
2
2
  export * from "./credential-location";
3
+ import { isAllowedModelsWire } from "./model-limits";
3
4
  import { parseCaptureFlowWire, parseCaptureResultWire, type CaptureFlowWire, type CaptureResultWire } from "./capture-wire";
4
5
  export * from "./capture-wire";
5
6
  import { exactObject, isPositiveInteger, isEpochMs } from "./credential-wire-validation";
@@ -406,6 +407,11 @@ export interface LeaseManifestEngine {
406
407
  connection?: CustomConnectionLease;
407
408
  /** Position within its scope; the list itself is already in try order. */
408
409
  position: number;
410
+ /** ADR-168: the models this account may run (canonical roster ids,
411
+ * `@runuai/host/model-limits`); absent = every model. Sent only to a
412
+ * runner advertising `accountModelLimits`: this parser is exact, so an
413
+ * older one would refuse the whole grant over an unknown key. */
414
+ allowedModels?: string[];
409
415
  }
410
416
 
411
417
  export interface LeaseManifestMcp {
@@ -711,7 +717,7 @@ function parseEngine(
711
717
  "label",
712
718
  "authKind",
713
719
  "position",
714
- ], ["connection"]);
720
+ ], ["connection", "allowedModels"]);
715
721
  if (
716
722
  !o ||
717
723
  !isIdValue(o.credentialId) ||
@@ -725,7 +731,8 @@ function parseEngine(
725
731
  !isScope(o.scope) ||
726
732
  !isBoundedString(o.label, MAX_MANIFEST_LABEL_CHARS) ||
727
733
  (o.authKind !== "env" && o.authKind !== "config-dir" && o.authKind !== "custom-connection") ||
728
- !isNonNegativeInteger(o.position)
734
+ !isNonNegativeInteger(o.position) ||
735
+ (o.allowedModels !== undefined && (!isAllowedModelsWire(o.allowedModels) || o.authKind === "custom-connection"))
729
736
  ) {
730
737
  return null;
731
738
  }
@@ -756,6 +763,7 @@ function parseEngine(
756
763
  authKind: o.authKind,
757
764
  position: o.position,
758
765
  ...(connection ? { connection } : {}),
766
+ ...(o.allowedModels !== undefined ? { allowedModels: [...(o.allowedModels as string[])] } : {}),
759
767
  };
760
768
  }
761
769
 
@@ -53,6 +53,49 @@ export class EventOutbox {
53
53
  private sentUpTo = 0;
54
54
  /** Entries dropped by overflow since the last drain — for one loud log. */
55
55
  private droppedSinceDrain = 0;
56
+ /** Highest seq the cloud has acknowledged. */
57
+ private ackedUpTo = 0;
58
+ /** Seqs dropped before transmission, as merged [from, to] ranges (drops
59
+ * are oldest-first runs, so this stays small). A later cumulative ack
60
+ * never makes a dropped entry delivered (review #mta79m). */
61
+ private droppedRanges: Array<[number, number]> = [];
62
+ /** Callers waiting to learn whether one entry reached the cloud. */
63
+ private ackWaiters = new Map<number, Array<(delivered: boolean) => void>>();
64
+
65
+ /**
66
+ * Whether the entry `seq` reached the cloud: true once a cumulative ack
67
+ * covers it, false if it is dropped (oversized, or overflow) first. Pending
68
+ * while neither has happened, e.g. across a disconnect; a process exit
69
+ * settles nothing, which callers treat as not delivered.
70
+ */
71
+ whenAcked(seq: number): Promise<boolean> {
72
+ if (this.wasDropped(seq)) return Promise.resolve(false);
73
+ if (seq <= this.ackedUpTo) return Promise.resolve(true);
74
+ if (!this.entries.some((entry) => entry.seq === seq)) return Promise.resolve(false);
75
+ return new Promise((resolve) => {
76
+ const waiting = this.ackWaiters.get(seq) ?? [];
77
+ waiting.push(resolve);
78
+ this.ackWaiters.set(seq, waiting);
79
+ });
80
+ }
81
+
82
+ private wasDropped(seq: number): boolean {
83
+ return this.droppedRanges.some(([from, to]) => seq >= from && seq <= to);
84
+ }
85
+
86
+ private noteDropped(seq: number): void {
87
+ const last = this.droppedRanges[this.droppedRanges.length - 1];
88
+ if (last && seq === last[1] + 1) last[1] = seq;
89
+ else this.droppedRanges.push([seq, seq]);
90
+ this.settle(seq, false);
91
+ }
92
+
93
+ private settle(seq: number, delivered: boolean): void {
94
+ const waiting = this.ackWaiters.get(seq);
95
+ if (!waiting) return;
96
+ this.ackWaiters.delete(seq);
97
+ for (const resolve of waiting) resolve(delivered);
98
+ }
56
99
 
57
100
  /** Serialize + append. Returns the entry's seq. */
58
101
  enqueue(event: HostEvent): number {
@@ -61,6 +104,7 @@ export class EventOutbox {
61
104
  const bytes = Buffer.byteLength(raw, "utf8");
62
105
  if (bytes > MAX_EVENT_FRAME_BYTES) {
63
106
  this.droppedSinceDrain += 1;
107
+ this.noteDropped(seq);
64
108
  return seq;
65
109
  }
66
110
  this.entries.push({ seq, raw, bytes });
@@ -72,6 +116,7 @@ export class EventOutbox {
72
116
  const dropped = this.entries.shift();
73
117
  if (!dropped) break;
74
118
  this.totalBytes -= dropped.bytes;
119
+ this.noteDropped(dropped.seq);
75
120
  // Only a NEVER-SENT entry is a real loss; an unacked-but-sent one most
76
121
  // likely landed and just lost its ack.
77
122
  if (dropped.seq > this.sentUpTo) this.droppedSinceDrain += 1;
@@ -87,8 +132,12 @@ export class EventOutbox {
87
132
  this.totalBytes -= entry.bytes;
88
133
  i += 1;
89
134
  }
90
- if (i > 0) this.entries.splice(0, i);
135
+ if (i > 0) {
136
+ for (const entry of this.entries.slice(0, i)) this.settle(entry.seq, true);
137
+ this.entries.splice(0, i);
138
+ }
91
139
  if (seq > this.sentUpTo) this.sentUpTo = seq;
140
+ if (seq > this.ackedUpTo) this.ackedUpTo = seq;
92
141
  }
93
142
 
94
143
  /**