@moondeck/station 1.0.6 → 1.0.8

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.
@@ -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
 
@@ -0,0 +1,22 @@
1
+ import { parseInitialAttachmentInput } from "../src/initial-attachments";
2
+ import { abortInitialAttachment, receiveInitialAttachment, type InitialAttachmentEnvironment } from "./initial-attachments";
3
+
4
+ /** The production command gate, shared with its boundary tests. */
5
+ export async function handleInitialAttachmentCommand(
6
+ value: unknown,
7
+ dependencies: {
8
+ runTaskLifecycle<T>(taskId: string, work: () => Promise<T>): Promise<T>;
9
+ getTask(taskId: string): { runEpoch?: number; statusMirror: string | null } | null | undefined;
10
+ environment(taskId: string): Promise<InitialAttachmentEnvironment | null>;
11
+ },
12
+ ): Promise<{ exists: boolean } | undefined> {
13
+ const input = parseInitialAttachmentInput(value);
14
+ return dependencies.runTaskLifecycle(input.taskId, async () => {
15
+ if (input.operation === "abort") { await abortInitialAttachment(input); return; }
16
+ const task = dependencies.getTask(input.taskId);
17
+ if (!task || task.runEpoch !== input.runEpoch || task.statusMirror !== "running") throw new Error("Initial attachment runtime changed; retry startup");
18
+ const environment = await dependencies.environment(input.taskId);
19
+ if (!environment) throw new Error("Initial attachments require an available task environment");
20
+ return receiveInitialAttachment(input, environment);
21
+ });
22
+ }
@@ -0,0 +1,71 @@
1
+ /** Chunked cloud bytes, staged outside the workspace, published before launch. */
2
+ import { mkdtemp, open, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { parseInitialAttachmentInput, initialAttachmentParts, type InitialAttachmentWriteInput } from "../src/initial-attachments";
6
+ import type { TaskEnvironmentHandle } from "./task-environment/types";
7
+ import { writeContainedRuntimeFile } from "./task-environment/workspace-files";
8
+
9
+
10
+ interface Transfer { runEpoch: number; taskId: string; path: string; size: number; offset: number; directory: string; timer: NodeJS.Timeout; busy: boolean; preserveExisting: boolean }
11
+ const transfers = new Map<string, Transfer>();
12
+ const receiving = new Set<string>();
13
+ async function discard(id: string, transfer: Transfer): Promise<void> {
14
+ clearTimeout(transfer.timer);
15
+ transfers.delete(id);
16
+ await rm(transfer.directory, { recursive: true, force: true });
17
+ }
18
+
19
+ /** Cleanup is safe even after teardown/epoch change: it touches only the
20
+ * staging transfer bound to this exact task and run, never the workspace. */
21
+ export async function abortInitialAttachment(input: InitialAttachmentWriteInput): Promise<void> {
22
+ parseInitialAttachmentInput(input);
23
+ const current = transfers.get(input.transferId);
24
+ if (current && current.taskId === input.taskId && current.runEpoch === input.runEpoch && !current.busy) await discard(input.transferId, current);
25
+ }
26
+
27
+ export type InitialAttachmentEnvironment = Pick<TaskEnvironmentHandle, "exec" | "descriptor">;
28
+
29
+ export async function receiveInitialAttachment(input: InitialAttachmentWriteInput, environment: InitialAttachmentEnvironment): Promise<{ exists: boolean } | undefined> {
30
+ parseInitialAttachmentInput(input);
31
+ const parts = initialAttachmentParts(input.path);
32
+ if (input.operation === "probe") return { exists: await writeContainedRuntimeFile(environment, parts, new Uint8Array(), "probe") };
33
+ if (input.operation === "abort") { await abortInitialAttachment(input); return; }
34
+ const bytes = Buffer.from(input.dataBase64, "base64");
35
+ if (bytes.toString("base64") !== input.dataBase64 || input.offset + bytes.length > input.size || (bytes.length === 0 && input.size !== 0)) throw new Error("Invalid initial attachment chunk");
36
+ if (receiving.has(input.transferId)) throw new Error("Initial attachment transfer is busy");
37
+ receiving.add(input.transferId);
38
+ try {
39
+ let transfer = transfers.get(input.transferId);
40
+ if (!transfer) {
41
+ if (input.offset !== 0 || transfers.size >= 8) throw new Error("Initial attachment transfer unavailable; retry startup");
42
+ const directory = await mkdtemp(join(tmpdir(), "moondeck-initial-"));
43
+ const timer = setTimeout(() => { const current = transfers.get(input.transferId); if (current && !current.busy) void discard(input.transferId, current).catch((error) => console.error("Initial attachment staging cleanup failed", error)); }, 10 * 60_000);
44
+ timer.unref();
45
+ transfer = { runEpoch: input.runEpoch, taskId: input.taskId, path: input.path, size: input.size, offset: 0, directory, timer, busy: false, preserveExisting: input.preserveExisting === true };
46
+ transfers.set(input.transferId, transfer);
47
+ }
48
+ if (transfer.runEpoch !== input.runEpoch || transfer.busy || transfer.taskId !== input.taskId || transfer.path !== input.path || transfer.size !== input.size || transfer.offset !== input.offset || transfer.preserveExisting !== (input.preserveExisting === true)) {
49
+ // A foreign task/run must not cancel another transfer. A bad repeat from
50
+ // the same owner is terminal and should release the staging slot now.
51
+ if (transfer.taskId === input.taskId && transfer.runEpoch === input.runEpoch && !transfer.busy) await discard(input.transferId, transfer);
52
+ throw new Error("Initial attachment transfer does not match");
53
+ }
54
+ transfer.busy = true;
55
+ try {
56
+ const staged = join(transfer.directory, "bytes");
57
+ const file = await open(staged, input.offset === 0 ? "wx" : "a", 0o600);
58
+ try { await file.writeFile(bytes); } finally { await file.close(); }
59
+ transfer.offset += bytes.length;
60
+ if (transfer.offset === transfer.size) {
61
+ const content = await readFile(staged);
62
+ if (content.length !== transfer.size) throw new Error("Incomplete initial attachment");
63
+ await writeContainedRuntimeFile(environment, parts, content, transfer.preserveExisting ? "preserve" : "replace");
64
+ await discard(input.transferId, transfer);
65
+ }
66
+ } catch (error) {
67
+ await discard(input.transferId, transfer);
68
+ throw error;
69
+ } finally { transfer.busy = false; if (transfers.has(input.transferId)) transfer.timer.refresh(); }
70
+ } finally { receiving.delete(input.transferId); }
71
+ }