@moondeck/station 1.0.6 → 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.
@@ -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
 
@@ -1,4 +1,5 @@
1
1
  import { isOwnedInternalConnectionRuntime } from "./internal-connections";
2
+ import { accountAllowsModel } from "../src/model-limits";
2
3
  import { prepareNodeData } from "./node-state";
3
4
  import { registerConnectionSecret } from "./connection-secret-redaction";
4
5
  import { buildCustomConnectionLaunch, tomlString, connectionNativeBlanks, connectionHomePreparation, newConnectionHome, connectionDnsLookupArgv, validateConnectionAddresses, connectionConnectArgv, CustomConnectionLaunchError, launchRefusal, CONNECTION_CONNECT_TIMEOUT_MS } from "./custom-connection-launch";
@@ -68,7 +69,7 @@ import {
68
69
  import { ACTIVE_STATUSES, isActive, isOnDashboard } from "./task-status";
69
70
  import { isSafeHostTaskId } from "./task-identity";
70
71
  import { projectEnvForTask } from "./host-env";
71
- import { shadowRoute } from "./routing/shadow";
72
+ import { CLASSIFIER_MODEL, shadowRoute } from "./routing/shadow";
72
73
  import {
73
74
  closeCurrentTaskRunAssignmentForStoppedRuntime,
74
75
  getHostTask,
@@ -132,11 +133,12 @@ import type {
132
133
  } from "./task-environment/types";
133
134
  import { renderSkillLayout } from "./skill-layout";
134
135
  import {
135
- containerSkillFile,
136
136
  installedSkillPath,
137
137
  installPackageSkills,
138
138
  type SkillExec,
139
139
  writeAgentSkills,
140
+ renderSkillMd,
141
+ type SkillDelivery,
140
142
  } from "./skills";
141
143
  import {
142
144
  ensureMachineGatewayTunnel,
@@ -325,6 +327,7 @@ interface Channel {
325
327
  agentHandle: TaskEnvironmentHandle<unknown> | null;
326
328
  /** Per-agent system preamble (channel briefing + assembled persona). */
327
329
  preambles: Map<string, string>;
330
+ skillDeliveries: Map<string, SkillDelivery>;
328
331
  /** Per-agent first-turn message — only agents whose `initialPrompt` is
329
332
  * non-empty have an entry. Delivered once at container-ready. */
330
333
  firstTurns: Map<string, string>;
@@ -1095,10 +1098,10 @@ export class Orchestrator {
1095
1098
  // array exactly also makes absence authoritative for live removal.
1096
1099
  channel.roster = [...spec.agents];
1097
1100
  this.cancelStaleConnectionRetries(channel);
1098
- for (const agent of added) {
1099
- // Per-agent link/document skills, like getOrCreateChannel does at
1100
- // channel birth. Best-effort.
1101
- writeAgentSkills(channel.taskId, agent, () => this.workspaceRuntime(channel.taskId));
1101
+ for (const agent of channel.roster) {
1102
+ if (JSON.stringify(previousById.get(agent.id)?.skills) !== JSON.stringify(agent.skills)) {
1103
+ channel.skillDeliveries.delete(agent.id);
1104
+ }
1102
1105
  }
1103
1106
  for (const { agent, reason } of changed) {
1104
1107
  const recoveryAbortPublished = this.supersedeRecovery(
@@ -1200,6 +1203,7 @@ export class Orchestrator {
1200
1203
  spec.mode,
1201
1204
  spec.secretaryAgentId,
1202
1205
  taskProxiedKeys(channel.taskId),
1206
+ channel.skillDeliveries.get(agent.id),
1203
1207
  ),
1204
1208
  );
1205
1209
  }
@@ -1262,6 +1266,7 @@ export class Orchestrator {
1262
1266
  }
1263
1267
  this.retireRunnerGeneration(channel, agentId);
1264
1268
  channel.preambles.delete(agentId);
1269
+ channel.skillDeliveries.delete(agentId);
1265
1270
  channel.firstTurns.delete(agentId);
1266
1271
  channel.browserStaleSessions.delete(agentId);
1267
1272
  channel.rosterSessionChanges.delete(agentId);
@@ -1465,6 +1470,7 @@ export class Orchestrator {
1465
1470
  agentEnvironment: null,
1466
1471
  agentHandle: null,
1467
1472
  preambles,
1473
+ skillDeliveries: new Map(),
1468
1474
  firstTurns,
1469
1475
  sessionsReady: null,
1470
1476
  browserReady: false,
@@ -1526,13 +1532,6 @@ export class Orchestrator {
1526
1532
  leasedLaunches: new Map(),
1527
1533
  };
1528
1534
  this.channels.set(taskId, channel);
1529
- // ADR-046: materialise each agent's skills to its per-agent SKILL.md in
1530
- // the workspace (bind-mounted into the container), best-effort, once the
1531
- // channel can give the task's runtime: where only it can make the
1532
- // agent's directory (macOS, #cb3j0z), it is asked for then.
1533
- for (const agent of roster) {
1534
- writeAgentSkills(taskId, agent, () => this.workspaceRuntime(taskId));
1535
- }
1536
1535
  return channel;
1537
1536
  }
1538
1537
 
@@ -1816,6 +1815,7 @@ export class Orchestrator {
1816
1815
  scope: account.scope,
1817
1816
  authKind: account.authKind as "env" | "config-dir",
1818
1817
  execEnv: {},
1818
+ ...(account.allowedModels ? { allowedModels: account.allowedModels } : {}),
1819
1819
  }));
1820
1820
  }
1821
1821
 
@@ -1826,17 +1826,21 @@ export class Orchestrator {
1826
1826
  kind: string,
1827
1827
  exclude?: Set<string>,
1828
1828
  preferredId?: string,
1829
+ /** ADR-168: the agent's model; only accounts allowing it are picked. */
1830
+ model?: string | null,
1829
1831
  ): ResolvedEngineAccount | null {
1830
1832
  if (!this.isLeasedChannel(channel)) {
1831
1833
  return pickEngineAccount(kind, {
1832
1834
  scope: channel.engineAccountScope,
1833
1835
  exclude,
1834
1836
  preferredId,
1837
+ model,
1835
1838
  });
1836
1839
  }
1837
1840
  return selectAccount(this.engineAccounts(channel, kind), {
1838
1841
  exclude,
1839
1842
  preferredId,
1843
+ model,
1840
1844
  });
1841
1845
  }
1842
1846
 
@@ -2669,12 +2673,7 @@ export class Orchestrator {
2669
2673
  // Same per-agent materialisation the initial start does. Browser setup
2670
2674
  // is awaited before EVERY missing-session spawn: that reasserts configs
2671
2675
  // clobbered by resume/auth injection and covers roster generation.
2672
- const skillExec = this.providerSkillExec(channel);
2673
- if (skillExec) {
2674
- await installPackageSkills(channel.taskId, missing, skillExec);
2675
- } else {
2676
- await installPackageSkills(channel.taskId, missing);
2677
- }
2676
+ await this.prepareSkills(channel, missing);
2678
2677
  if (!this.isActiveChannel(channel)) return;
2679
2678
 
2680
2679
  // One materialization gate owns provisioning and (when enabled)
@@ -2878,6 +2877,7 @@ export class Orchestrator {
2878
2877
  const account = pickEngineAccount(agent.kind, {
2879
2878
  scope: channel.engineAccountScope,
2880
2879
  preferredId: agent.accountId,
2880
+ model: agent.model ?? null,
2881
2881
  });
2882
2882
  if (!account) {
2883
2883
  channel.accountByAgent.delete(agent.id);
@@ -3120,7 +3120,9 @@ export class Orchestrator {
3120
3120
  if (!account) {
3121
3121
  reason = args.agent.accountBinding === "required"
3122
3122
  ? args.agent.accountId && open.connectionsUnsupported?.includes(args.agent.accountId) ? "unsupported" : "connection removed"
3123
- : `no ${kind} account this task can use`;
3123
+ : leasedModelExcluded(open, kind, args.agent.model)
3124
+ ? `no ${kind} account this task can use allows model "${args.agent.model || "(default)"}" — pick an allowed model, or ask an admin to change the accounts' allowed models or roles`
3125
+ : `no ${kind} account this task can use`;
3124
3126
  break;
3125
3127
  }
3126
3128
  if (account.authKind === "env") {
@@ -3349,12 +3351,16 @@ export class Orchestrator {
3349
3351
  owner: { agentId: string; slot: LeasedLaunchSlot } | null,
3350
3352
  identity: LeasedIdentity,
3351
3353
  environment: TaskEnvironmentHandle<unknown>,
3354
+ /** ADR-168: a one-shot's own model (the shadow classifier's): admitted
3355
+ * only while the account still allows it. */
3356
+ oneShotModel?: { kind: string; model: string | null },
3352
3357
  ): TaskEnvironmentHandle<unknown> {
3353
3358
  const agentId = owner?.agentId ?? null;
3354
3359
  const held = (): boolean =>
3355
3360
  this.isActiveChannel(channel) &&
3356
3361
  (owner === null
3357
- ? this.leasedMaterialServed(channel, identity)
3362
+ ? this.leasedMaterialServed(channel, identity) &&
3363
+ (oneShotModel === undefined || this.leasedIdentityAllowsModel(channel, identity, oneShotModel.kind, oneShotModel.model))
3358
3364
  : channel.leasedLaunches.get(owner.agentId) === owner.slot &&
3359
3365
  (owner.slot.session === null
3360
3366
  ? !owner.slot.created
@@ -3567,6 +3573,23 @@ export class Orchestrator {
3567
3573
  });
3568
3574
  }
3569
3575
 
3576
+ /** ADR-168: whether the leased account `identity` names allows `model`
3577
+ * right now (a connection or the task token: always). */
3578
+ private leasedIdentityAllowsModel(channel: Channel, identity: LeasedIdentity, kind: string, model: string | null): boolean {
3579
+ if (identity.subject !== "account" || identity.connection) return true;
3580
+ const lease = leasedEnginesFor(channel.taskId);
3581
+ const account = lease?.open ? lease.accounts.find((candidate) => candidate.credentialId === identity.credentialId) : undefined;
3582
+ return account !== undefined && accountAllowsModel(account.allowedModels, kind, model);
3583
+ }
3584
+
3585
+ /** ADR-168: whether the account an agent is bound to still allows its
3586
+ * model (a connection or the task token: always). */
3587
+ private leasedAccountAllowsAgent(lease: TaskEngineLease, identity: LeasedIdentity, agent: RosterAgent): boolean {
3588
+ if (identity.subject !== "account" || identity.connection) return true;
3589
+ const account = lease.accounts.find((candidate) => candidate.credentialId === identity.credentialId);
3590
+ return !account || accountAllowsModel(account.allowedModels, agent.kind, agent.model ?? null);
3591
+ }
3592
+
3570
3593
  /** Whether the task's open gate still serves `identity`'s account at its
3571
3594
  * revision and version, for its run, and that version is not being held
3572
3595
  * back for a newer one: what a one-shot may start on. An agent's task
@@ -3599,11 +3622,18 @@ export class Orchestrator {
3599
3622
  }
3600
3623
 
3601
3624
  /** Whether the agent may start on `identity` right now: still bound to it,
3602
- * and the task's open gate still serves that account at that revision and
3603
- * version, for that run. */
3625
+ * the task's open gate still serves that account at that revision and
3626
+ * version, for that run, and (ADR-168) the account still allows the
3627
+ * agent's current model. The last can change with no new revision: an
3628
+ * admin narrowing `allowedModels`, or the agent's model changing, while
3629
+ * its session is still being created. Launch admission and the
3630
+ * post-creation checks all read this. */
3604
3631
  private leasedIdentityHeld(channel: Channel, agentId: string, identity: LeasedIdentity): boolean {
3605
3632
  const bound = channel.leasedIdentityByAgent.get(agentId);
3606
- return bound !== undefined && sameLeasedIdentity(bound, identity) && this.leasedMaterialServed(channel, identity);
3633
+ if (bound === undefined || !sameLeasedIdentity(bound, identity) || !this.leasedMaterialServed(channel, identity)) return false;
3634
+ const agent = channel.roster.find((candidate) => candidate.id === agentId);
3635
+ const lease = leasedEnginesFor(channel.taskId);
3636
+ return !agent || !lease?.open || this.leasedAccountAllowsAgent(lease, identity, agent);
3607
3637
  }
3608
3638
 
3609
3639
  /** The leased account an agent runs on: the one it is bound to while that
@@ -3613,15 +3643,25 @@ export class Orchestrator {
3613
3643
  agentId: string,
3614
3644
  kind: string,
3615
3645
  lease: TaskEngineLease,
3646
+ /** ADR-168: the model the launch will run, when it isn't the agent's own
3647
+ * (the shadow classifier's); null = unknown, so only an unlimited
3648
+ * account qualifies. */
3649
+ model?: string | null,
3616
3650
  ): LeasedEngineAccount | undefined {
3617
3651
  const agent = channel.roster.find(candidate => candidate.id === agentId);
3618
3652
  if (agent?.accountBinding === "required") {
3619
3653
  return lease.accounts.find((account): account is LeasedEngineAccount => account.credentialId === agent.accountId && account.engineKind === kind && account.authKind === "custom-connection" && isLeasedEngineAccount(account));
3620
3654
  }
3621
3655
  if (lease.accounts.some(account => account.credentialId === agent?.accountId && account.authKind === "custom-connection")) return undefined;
3656
+ // ADR-168: only accounts allowing the agent's current model — so a model
3657
+ // changed mid-task, or an account an admin narrowed, moves the agent off
3658
+ // a binding that no longer allows it.
3622
3659
  const accounts = lease.accounts.filter(
3623
3660
  (account): account is LeasedEngineAccount =>
3624
- account.engineKind === kind && account.authKind !== "custom-connection" && isLeasedEngineAccount(account),
3661
+ account.engineKind === kind &&
3662
+ account.authKind !== "custom-connection" &&
3663
+ isLeasedEngineAccount(account) &&
3664
+ accountAllowsModel(account.allowedModels, kind, model !== undefined ? model : (agent?.model ?? null)),
3625
3665
  );
3626
3666
  const bound = channel.accountByAgent.get(agentId);
3627
3667
  const preferredId = channel.roster.find(
@@ -3809,7 +3849,9 @@ export class Orchestrator {
3809
3849
  let stale = false;
3810
3850
  for (const agent of channel.roster) {
3811
3851
  const identity = channel.leasedIdentityByAgent.get(agent.id);
3812
- if (!identity || this.leasedMaterialServed(channel, identity)) continue;
3852
+ // ADR-168: an account narrowed so it no longer allows the agent's model
3853
+ // is left too: the agent restarts on one that does, or stops saying so.
3854
+ if (!identity || (this.leasedMaterialServed(channel, identity) && this.leasedAccountAllowsAgent(lease, identity, agent))) continue;
3813
3855
  if (!channel.sessions.has(agent.id)) continue;
3814
3856
  channel.browserStaleSessions.add(agent.id);
3815
3857
  stale = true;
@@ -4393,9 +4435,14 @@ export class Orchestrator {
4393
4435
  maxOutputBytes: 64 * 1024,
4394
4436
  admit,
4395
4437
  });
4438
+ // ADR-168 (review #5): the account is chosen and admitted for the model
4439
+ // the classifier actually runs, never the agent's own. Grok's is the
4440
+ // CLI's default, unknown here, so only an account without a limit
4441
+ // qualifies. No compatible account: null, and the pass routes by rules.
4442
+ const classifierModel = CLASSIFIER_MODEL[kind] ?? null;
4396
4443
  if (!this.isLeasedChannel(channel)) {
4397
4444
  const running = whileOnOwnCredentials(async () => {
4398
- const env = { ...(pickEngineAccount(kind, { scope: channel.engineAccountScope })?.execEnv ?? {}) };
4445
+ const env = { ...(pickEngineAccount(kind, { scope: channel.engineAccountScope, model: classifierModel })?.execEnv ?? {}) };
4399
4446
  const r = await handle.exec(
4400
4447
  request(env, () => {
4401
4448
  if (!this.isActiveChannel(channel) || !onOwnCredentials()) throw new LeftOwnCredentialsError();
@@ -4409,7 +4456,7 @@ export class Orchestrator {
4409
4456
  }
4410
4457
  const lease = leasedEnginesFor(channel.taskId);
4411
4458
  if (!lease?.open) return null;
4412
- const account = this.leasedAccountFor(channel, agentId, kind, lease);
4459
+ const account = this.leasedAccountFor(channel, agentId, kind, lease, classifierModel);
4413
4460
  if (!account || account.authKind === "custom-connection") return null;
4414
4461
  const identity: LeasedIdentity = {
4415
4462
  subject: "account",
@@ -4430,10 +4477,13 @@ export class Orchestrator {
4430
4477
  this.trackEventOperation(channel, entry.settled);
4431
4478
  try {
4432
4479
  const env = await this.leasedOneShotEnv(channel, lease, account, handle);
4433
- if (!env || !this.leasedMaterialServed(channel, identity)) return null;
4434
- const r = await this.leasedLaunchEnvironment(channel, null, identity, handle).exec(
4480
+ const servedForClassifier = (): boolean =>
4481
+ this.leasedMaterialServed(channel, identity) &&
4482
+ this.leasedIdentityAllowsModel(channel, identity, kind, classifierModel);
4483
+ if (!env || !servedForClassifier()) return null;
4484
+ const r = await this.leasedLaunchEnvironment(channel, null, identity, handle, { kind, model: classifierModel }).exec(
4435
4485
  request(env, () => {
4436
- if (!this.isActiveChannel(channel) || !this.leasedMaterialServed(channel, identity)) {
4486
+ if (!this.isActiveChannel(channel) || !servedForClassifier()) {
4437
4487
  throw new CredentialLeaseUnavailableError("the shadow classifier's account moved");
4438
4488
  }
4439
4489
  }),
@@ -4514,12 +4564,10 @@ export class Orchestrator {
4514
4564
  return tracked;
4515
4565
  }
4516
4566
 
4517
- /** Provider-neutral skill installation for a settled task environment. The
4518
- * legacy path remains the default until the first environment handle has
4519
- * actually been reconstructed, avoiding a new await during cold admission.
4567
+ /** Adapt a settled environment for package installation. Only local container
4568
+ * callers may use the default Docker executor when no handle is available.
4520
4569
  */
4521
- private providerSkillExec(channel: Channel): SkillExec | undefined {
4522
- const environment = channel.agentHandle;
4570
+ private providerSkillExec(environment: TaskEnvironmentHandle<unknown> | null | undefined): SkillExec | undefined {
4523
4571
  if (!environment) return undefined;
4524
4572
  return async (_container, cmd, cwd) => {
4525
4573
  const argv = cmd as [string, ...string[]];
@@ -4539,6 +4587,45 @@ export class Orchestrator {
4539
4587
  };
4540
4588
  }
4541
4589
 
4590
+ /** Skills are launch material: await delivery, then rebuild the brief from its result. */
4591
+ private async prepareSkills(channel: Channel, agents: RosterAgent[]): Promise<void> {
4592
+ const remote = isEnvironmentTransportProvider(getHostTask(channel.taskId)?.environmentProvider);
4593
+ let environment: TaskEnvironmentHandle<unknown> | undefined;
4594
+ if (remote) {
4595
+ try {
4596
+ environment = await this.agentEnvironment(channel);
4597
+ } catch (error) {
4598
+ console.warn(`[skills] ${channel.taskId}: task environment unavailable: ${String(error)}`);
4599
+ }
4600
+ }
4601
+ if (!this.isActiveChannel(channel)) return;
4602
+ // Use the reconstructed handle directly, not the channel cache: a channel
4603
+ // invalidated during reconstruction never publishes agentHandle.
4604
+ const skillExec = this.providerSkillExec(remote ? environment : channel.agentHandle);
4605
+ // Remote packages must never select installPackageSkills' default Docker executor.
4606
+ const installedPackages = remote && !skillExec ? [] : await installPackageSkills(
4607
+ channel.taskId, agents, skillExec,
4608
+ );
4609
+ for (const agent of agents) {
4610
+ if (!this.isActiveChannel(channel)) return;
4611
+ const path = remote && !environment ? null : await writeAgentSkills(
4612
+ channel.taskId, agent, () => this.workspaceRuntime(channel.taskId), environment,
4613
+ );
4614
+ if (!this.isActiveChannel(channel) || !this.hasDesiredLaunchSettings(channel, agent.id, agent)) continue;
4615
+ const desired = channel.roster.find((entry) => entry.id === agent.id);
4616
+ if (JSON.stringify(desired?.skills) !== JSON.stringify(agent.skills)) continue;
4617
+ const delivery = { path, installedPackages };
4618
+ channel.skillDeliveries.set(agent.id, delivery);
4619
+ const spec = this.channelSpecs.get(channel.taskId);
4620
+ if (!spec) continue;
4621
+ channel.preambles.set(agent.id, buildSystemPreamble(
4622
+ channel.roster, agent, spec.projects, spec.globalContext, spec.workspacePath,
4623
+ spec.branch, channel.humans, channel.browserTesting, channel.sharedFiles,
4624
+ spec.mode, spec.secretaryAgentId, taskProxiedKeys(channel.taskId), delivery,
4625
+ ));
4626
+ }
4627
+ }
4628
+
4542
4629
  private async startSessions(channel: Channel): Promise<boolean> {
4543
4630
  const task = getHostTask(channel.taskId);
4544
4631
  if (
@@ -4612,12 +4699,7 @@ export class Orchestrator {
4612
4699
  // turn. Idempotent + best-effort (returns fast when there are none); a slow
4613
4700
  // clone/install briefly delays start, which is acceptable for skill-bearing
4614
4701
  // tasks. Never throws.
4615
- const skillExec = this.providerSkillExec(channel);
4616
- if (skillExec) {
4617
- await installPackageSkills(channel.taskId, initialRoster, skillExec);
4618
- } else {
4619
- await installPackageSkills(channel.taskId, initialRoster);
4620
- }
4702
+ await this.prepareSkills(channel, initialRoster);
4621
4703
  if (!this.isActiveChannel(channel)) return false;
4622
4704
 
4623
4705
  // ADR-053: wire the Playwright MCP browser before agents spawn — configs
@@ -6144,7 +6226,10 @@ export class Orchestrator {
6144
6226
  // handled by the path that owns this spawn slot.
6145
6227
  if (channel.spawning.has(agentId)) return true;
6146
6228
  if (agent.accountBinding === "required") return false;
6147
- if (this.engineAccounts(channel, agent.kind).length < 2) {
6229
+ // ADR-168: only accounts allowing the agent's model count. With one (or
6230
+ // none) left, the normal error path benches the agent until it resets;
6231
+ // the model rule is never broken to keep it running.
6232
+ if (accountsAllowingModel(this.engineAccounts(channel, agent.kind), agent.model ?? null).length < 2) {
6148
6233
  return false;
6149
6234
  }
6150
6235
 
@@ -6162,6 +6247,7 @@ export class Orchestrator {
6162
6247
  agent.kind,
6163
6248
  current ? new Set([current]) : undefined,
6164
6249
  agent.accountId,
6250
+ agent.model ?? null,
6165
6251
  );
6166
6252
  if (!next) return false;
6167
6253
 
@@ -6709,7 +6795,8 @@ export class Orchestrator {
6709
6795
  return;
6710
6796
  }
6711
6797
 
6712
- const accounts = this.engineAccounts(channel, agent.kind);
6798
+ // ADR-168: never restart it on an account that doesn't allow its model.
6799
+ const accounts = accountsAllowingModel(this.engineAccounts(channel, agent.kind), agent.model ?? null);
6713
6800
  const account =
6714
6801
  accounts.find((a) => a.id === channel.accountByAgent.get(agentId)) ??
6715
6802
  accounts[0];
@@ -7445,6 +7532,7 @@ export function buildSystemPreamble(
7445
7532
  mode?: "open" | "secretary",
7446
7533
  secretaryAgentId?: string,
7447
7534
  proxiedKeys?: readonly { readonly key: string; readonly domains: readonly string[] }[],
7535
+ skillDelivery?: SkillDelivery,
7448
7536
  ): string {
7449
7537
  const channelList = roster
7450
7538
  .map((a) =>
@@ -7925,16 +8013,18 @@ export function buildSystemPreamble(
7925
8013
  ? [
7926
8014
  "## Your skills",
7927
8015
  "",
7928
- ...(skillIndex.length > 0
8016
+ ...(!skillDelivery?.path
8017
+ ? ["Skill files are unavailable. The complete guide follows inline:", "", renderSkillMd(agent)]
8018
+ : skillIndex.length > 0
7929
8019
  ? [
7930
- `Your skills are indexed at \`${containerSkillFile(agent.id)}\`:`,
8020
+ `Your skills are indexed at \`${skillDelivery?.path}\`:`,
7931
8021
  `${skillNameList(skillIndex)}. Read the index at the start. Before work a skill`,
7932
8022
  "covers, or an action the index names, read that file in full with `cat`; the",
7933
8023
  "paths are beside the index. They're yours — other agents have their own.",
7934
8024
  ]
7935
8025
  : [
7936
8026
  "Reference material (links + documents) has been prepared for you at",
7937
- `\`${containerSkillFile(agent.id)}\`. Read it when a task touches what`,
8027
+ `\`${skillDelivery?.path}\`. Read it when a task touches what`,
7938
8028
  "it covers. It's yours — other agents have their own.",
7939
8029
  ]),
7940
8030
  "",
@@ -7946,13 +8036,14 @@ export function buildSystemPreamble(
7946
8036
  ...(agent.kind === "claude" &&
7947
8037
  (agent.skills ?? []).some((s) => s.type === "package")
7948
8038
  ? [
7949
- "## Installed skills",
8039
+ "## Package skills",
7950
8040
  "",
7951
- "These Claude Agent Skills are installed for this task — invoke them",
7952
- "when a task touches what they cover:",
8041
+ "Installation status for this task:",
7953
8042
  ...(agent.skills ?? [])
7954
8043
  .filter((s) => s.type === "package")
7955
- .map((s) => `- **${s.name}** (\`${installedSkillPath(s)}\`)`),
8044
+ .map((s) => skillDelivery?.installedPackages.includes(installedSkillPath(s))
8045
+ ? `- **${s.name}** (\`${installedSkillPath(s)}\`) — installed`
8046
+ : `- **${s.name}** — unavailable; installation did not succeed.`),
7956
8047
  "",
7957
8048
  ]
7958
8049
  : []),
@@ -11468,3 +11559,22 @@ function db_setRuntime(
11468
11559
  ): void {
11469
11560
  upsertHostTask(taskId, extras);
11470
11561
  }
11562
+
11563
+ /** ADR-168: the lease names native accounts of `kind`, but none allows
11564
+ * `model` — the words an agent stops with when an admin narrowed them. */
11565
+ function leasedModelExcluded(lease: TaskEngineLease, kind: string, model: string | undefined): boolean {
11566
+ const native = lease.accounts.filter(
11567
+ (account): account is LeasedEngineAccount =>
11568
+ account.engineKind === kind && account.authKind !== "custom-connection" && isLeasedEngineAccount(account),
11569
+ );
11570
+ return native.length > 0 && !native.some((account) => accountAllowsModel(account.allowedModels, kind, model ?? null));
11571
+ }
11572
+
11573
+ /** ADR-168: the accounts allowing `model` (pure; kept here so a test that
11574
+ * mocks the engine-accounts module wholesale still filters). */
11575
+ function accountsAllowingModel<T extends { kind: string; allowedModels?: readonly string[] }>(
11576
+ accounts: readonly T[],
11577
+ model: string | null,
11578
+ ): T[] {
11579
+ return accounts.filter((account) => accountAllowsModel(account.allowedModels, account.kind, model));
11580
+ }
package/lib/skills.ts CHANGED
@@ -3,9 +3,9 @@
3
3
  *
4
4
  * A task agent's skills (reference links + documents, resolved cloud-side from
5
5
  * its persona + team) are written to a per-agent `SKILL.md` inside the task
6
- * workspace. The workspace is bind-mounted into the container at `/workspace`
7
- * (ADR-014), so writing on the host makes the file appear in the container —
8
- * no `docker cp`/`exec` needed (same mechanism as attachments).
6
+ * workspace. Bind-mounted container workspaces use contained host writes;
7
+ * machine/self tasks use the environment file transport because their
8
+ * workspace is not mounted at the host's taskWorkspaceDir (ADR-121).
9
9
  *
10
10
  * Each agent gets its OWN file under `.moondeck/agents/<id>/` so agents in a shared
11
11
  * container don't see each other's material; the agent's system preamble points
@@ -20,12 +20,12 @@
20
20
  */
21
21
 
22
22
  import { taskWorkspaceDir } from "./env";
23
- import { dockerCli } from "./docker-exec";
24
23
  import {
25
24
  taskAppContainerName,
26
25
  taskContainerCli,
27
26
  } from "./task-container-cli";
28
27
  import { runtimeAuthorityDockerExecArgs } from "./runtime-authority";
28
+ import type { TaskEnvironmentHandle } from "./task-environment/types";
29
29
  import type { RosterAgent, RosterSkill } from "./agents/types";
30
30
  import {
31
31
  SKILL_FILES_DIR,
@@ -78,84 +78,91 @@ function previousSkillFiles(workspace: string, folder: readonly string[]): strin
78
78
  }
79
79
  }
80
80
 
81
- /**
82
- * Each agent's skills work still in flight through the task's runtime
83
- * (macOS), by task and agent. A write while one is in flight waits for it,
84
- * then reads the folder and writes its layout, so no deletion or write of an
85
- * older layout ever lands after a newer one. On Linux every step is done at
86
- * once and nothing waits here.
87
- */
88
- const skillsInFlight = new Map<string, Promise<void>>();
89
- /**
90
- * Each agent's latest write, so a queued write that a newer one replaced is
91
- * skipped. Only queued writes read it, so a key is dropped once nothing is
92
- * queued for it: the runner is long-lived, and tasks and agents come and go.
93
- */
94
- const skillWrites = new Map<string, number>();
81
+ /** Serialize each agent's layouts, including cleanup, through completion. */
82
+ const skillsInFlight = new Map<string, Promise<string | null>>();
95
83
 
96
- /** Tests only: how many agents the runner still holds skills state for. */
97
84
  export function skillsStateForTests(): { writes: number; inFlight: number } {
98
- return { writes: skillWrites.size, inFlight: skillsInFlight.size };
85
+ return { writes: skillsInFlight.size, inFlight: skillsInFlight.size };
99
86
  }
100
87
 
101
- /**
102
- * Write an agent's SKILL.md into the task workspace (idempotent: overwrites,
103
- * or removes the file when the agent has no skills). A split skill's files
104
- * go beside it in `skills/`, written before the index that names them.
105
- * Files the previous layout wrote and this one does not are removed first;
106
- * never a file this layout writes. Returns the container path when written
107
- * (or queued behind runtime work still in flight), else null. Best-effort —
108
- * a write failure is swallowed so a skills problem never blocks the agent
109
- * from running.
110
- */
88
+ export type SkillEnvironment = Pick<TaskEnvironmentHandle, "descriptor" | "readWorkspaceFile" | "writeWorkspaceFile" | "exec">;
89
+
90
+ export interface SkillDelivery {
91
+ path: string | null;
92
+ installedPackages: string[];
93
+ }
94
+
95
+ /** A path is returned only after every write and cleanup has succeeded. */
111
96
  export function writeAgentSkills(
112
97
  taskId: string,
113
98
  agent: RosterAgent,
114
99
  runtime?: () => Promise<RuntimeNamespace | null>,
115
- ): string | null {
100
+ environment?: SkillEnvironment,
101
+ ): Promise<string | null> {
116
102
  const key = `${taskId}\0${agent.id}`;
117
- const generation = (skillWrites.get(key) ?? 0) + 1;
118
- skillWrites.set(key, generation);
119
- const result = flatSkills(agent).length === 0 ? null : containerSkillFile(agent.id);
120
- const inFlight = skillsInFlight.get(key);
121
- if (inFlight) {
122
- // Behind the runtime work of an earlier write; only the latest queued one runs.
123
- track(key, inFlight.then(() => (skillWrites.get(key) === generation ? writeSkillsNow(taskId, agent, runtime)?.done : undefined)));
124
- return result;
125
- }
126
- const attempt = writeSkillsNow(taskId, agent, runtime);
127
- if (attempt?.done) {
128
- track(key, attempt.done);
129
- } else {
130
- // Done at once (or refused), with nothing queued: no state to keep.
131
- skillWrites.delete(key);
132
- }
133
- return attempt === null ? null : attempt.path;
134
- }
135
-
136
- /**
137
- * Hold `work` as the agent's in-flight skills work until it settles. When
138
- * it is still the latest (nothing newer queued behind it), the agent's
139
- * state goes with it, however the work ended.
140
- */
141
- function track(key: string, work: Promise<void>): void {
142
- const settled = work.catch(() => {}).finally(() => {
143
- if (skillsInFlight.get(key) !== settled) return;
144
- skillsInFlight.delete(key);
145
- skillWrites.delete(key);
103
+ const previous = skillsInFlight.get(key);
104
+ const run = async (): Promise<string | null> => {
105
+ try {
106
+ if (environment) return await writeSkillsViaEnvironment(agent, environment);
107
+ const attempt = writeSkillsNow(taskId, agent, runtime);
108
+ await attempt.done;
109
+ return attempt.path;
110
+ } catch (error) {
111
+ console.warn(`[skills] ${taskId}/${agent.id}: skills write failed: ${String(error)}`);
112
+ return null;
113
+ }
114
+ };
115
+ const work = previous ? previous.then(run) : run();
116
+ const settled = work.finally(() => {
117
+ if (skillsInFlight.get(key) === settled) skillsInFlight.delete(key);
146
118
  });
147
119
  skillsInFlight.set(key, settled);
120
+ return settled;
121
+ }
122
+
123
+ /** Machine/self workspaces have no host bind mount. Use their file transport. */
124
+ async function writeSkillsViaEnvironment(agent: RosterAgent, environment: SkillEnvironment): Promise<string | null> {
125
+ // Agent IDs become a path component; reject traversal at this boundary too.
126
+ if (!/^[a-zA-Z0-9_-]+$/.test(agent.id)) throw new Error("invalid skills agent id");
127
+ const directory = `${environment.descriptor.workspacePath}/.moondeck/agents/${agent.id}`;
128
+ const folder = `${directory}/${SKILL_FILES_DIR}`;
129
+ const manifest = `${folder}/${SKILL_FILES_MANIFEST}`;
130
+ const prior = await environment.readWorkspaceFile(manifest, { maxBytes: 256 * 1024 });
131
+ const previous = prior ? Buffer.from(prior).toString("utf8").split("\n").filter(isSkillFileName) : [];
132
+ const layout = renderSkillLayout(agent);
133
+ const names = layout.files.map((file) => file.name);
134
+ if (names.some((name) => !isSkillFileName(name))) throw new Error("invalid skill file name");
135
+ const hasSkills = flatSkills(agent).length > 0;
136
+ const stale = previous.filter((name) => !names.includes(name)).map((name) => `${folder}/${name}`);
137
+ if (previous.length && !names.length) stale.push(manifest);
138
+ if (!hasSkills) stale.push(`${directory}/SKILL.md`);
139
+ if (stale.length) {
140
+ const result = await environment.exec({
141
+ argv: ["/bin/rm", "-f", "--", ...stale], user: "node",
142
+ projectEnvProfile: "maintenance", timeoutMs: 30_000, maxOutputBytes: 4096,
143
+ });
144
+ if (result.exitCode !== 0) throw new Error(`skills cleanup exited ${result.exitCode}`);
145
+ }
146
+ if (!hasSkills) return null;
147
+ for (const file of layout.files) {
148
+ await environment.writeWorkspaceFile(`${folder}/${file.name}`, Buffer.from(file.content));
149
+ }
150
+ if (names.length) await environment.writeWorkspaceFile(manifest, Buffer.from(`${names.join("\n")}\n`));
151
+ // Publish the index last, only after every document it names is present.
152
+ const path = `${directory}/SKILL.md`;
153
+ await environment.writeWorkspaceFile(path, Buffer.from(layout.skillMd));
154
+ return path;
148
155
  }
149
156
 
150
157
  /**
151
158
  * One write, done at once where the host can. What only the runtime can do
152
- * is in `done`, in order: removals first, then writes. Null when refused.
159
+ * is in `done`, in order: removals first, then writes. Throws when refused.
153
160
  */
154
161
  function writeSkillsNow(
155
162
  taskId: string,
156
163
  agent: RosterAgent,
157
164
  runtime?: () => Promise<RuntimeNamespace | null>,
158
- ): { path: string | null; done?: Promise<void> } | null {
165
+ ): { path: string | null; done?: Promise<void> } {
159
166
  // Into the task's own .moondeck, never through a link the task put there
160
167
  // (#cb3j0z). Where only the task's runtime can make the agent's directory
161
168
  // (macOS), it is made there once the runtime is reachable, then the file
@@ -188,64 +195,61 @@ function writeSkillsNow(
188
195
  });
189
196
  };
190
197
  const deferred = (): Promise<void> | undefined => {
191
- if (later.length === 0 || !runtime) return undefined;
198
+ if (later.length === 0) return undefined;
199
+ if (!runtime) throw new Error("skills cleanup requires the task runtime");
192
200
  return (async () => {
193
201
  const reached = await runtime();
194
- if (!reached) return;
202
+ if (!reached) throw new Error("skills runtime is unavailable");
195
203
  for (const step of later) await step(reached);
196
204
  })();
197
205
  };
198
- try {
199
- const previous = previousSkillFiles(workspace, folder);
200
- const previousEntries = previous.length
201
- ? [...previous.map((name) => [...folder, name]), [...folder, SKILL_FILES_MANIFEST]]
202
- : [];
203
- if (flatSkills(agent).length === 0) {
204
- remove([...previousEntries, file], new Set());
205
- return { path: null, done: deferred() };
206
+ const previous = previousSkillFiles(workspace, folder);
207
+ const previousEntries = previous.length
208
+ ? [...previous.map((name) => [...folder, name]), [...folder, SKILL_FILES_MANIFEST]]
209
+ : [];
210
+ if (flatSkills(agent).length === 0) {
211
+ remove([...previousEntries, file], new Set());
212
+ return { path: null, done: deferred() };
213
+ }
214
+ const { skillMd, files } = renderSkillLayout(agent);
215
+ const names = files.map((f) => f.name);
216
+ if (names.some((name) => !isSkillFileName(name))) throw new Error("invalid skill file name");
217
+ const keep = new Set(names);
218
+ const writes: { parts: string[]; bytes: Uint8Array }[] = [
219
+ ...files.map((f) => ({ parts: [...folder, f.name], bytes: Buffer.from(f.content) })),
220
+ ...(files.length ? [{ parts: [...folder, SKILL_FILES_MANIFEST], bytes: Buffer.from(`${names.join("\n")}\n`) }] : []),
221
+ { parts: file, bytes: Buffer.from(skillMd) },
222
+ ];
223
+ // Stale: what the previous layout wrote and this one does not, removed
224
+ // before the new manifest is written. A flat layout keeps none.
225
+ remove(
226
+ files.length
227
+ ? previous.filter((name) => !keep.has(name)).map((name) => [...folder, name])
228
+ : previousEntries,
229
+ keep,
230
+ );
231
+ const directories = files.length ? [directory, folder] : [directory];
232
+ const writeAll = () => {
233
+ for (const write of writes) writeContainedFileSync(workspace, write.parts, write.bytes);
234
+ };
235
+ if (!directories.every((d) => makeContainedDirectoriesSync(workspace, d))) {
236
+ let written = false;
237
+ try {
238
+ writeAll();
239
+ written = true;
240
+ } catch (error) {
241
+ if (!(error instanceof WorkspaceDirectoryMissingError) || !runtime) throw error;
206
242
  }
207
- const { skillMd, files } = renderSkillLayout(agent);
208
- const names = files.map((f) => f.name);
209
- if (names.some((name) => !isSkillFileName(name))) return null;
210
- const keep = new Set(names);
211
- const writes: { parts: string[]; bytes: Uint8Array }[] = [
212
- ...files.map((f) => ({ parts: [...folder, f.name], bytes: Buffer.from(f.content) })),
213
- ...(files.length ? [{ parts: [...folder, SKILL_FILES_MANIFEST], bytes: Buffer.from(`${names.join("\n")}\n`) }] : []),
214
- { parts: file, bytes: Buffer.from(skillMd) },
215
- ];
216
- // Stale: what the previous layout wrote and this one does not, removed
217
- // before the new manifest is written. A flat layout keeps none.
218
- remove(
219
- files.length
220
- ? previous.filter((name) => !keep.has(name)).map((name) => [...folder, name])
221
- : previousEntries,
222
- keep,
223
- );
224
- const directories = files.length ? [directory, folder] : [directory];
225
- const writeAll = () => {
226
- for (const write of writes) writeContainedFileSync(workspace, write.parts, write.bytes);
227
- };
228
- if (!directories.every((d) => makeContainedDirectoriesSync(workspace, d))) {
229
- let written = false;
230
- try {
243
+ if (!written) {
244
+ later.push(async (reached) => {
245
+ for (const d of directories) await makeContainedDirectories(workspace, d, reached);
231
246
  writeAll();
232
- written = true;
233
- } catch (error) {
234
- if (!(error instanceof WorkspaceDirectoryMissingError) || !runtime) throw error;
235
- }
236
- if (!written) {
237
- later.push(async (reached) => {
238
- for (const d of directories) await makeContainedDirectories(workspace, d, reached);
239
- writeAll();
240
- });
241
- }
242
- return { path: containerSkillFile(agent.id), done: deferred() };
247
+ });
243
248
  }
244
- writeAll();
245
249
  return { path: containerSkillFile(agent.id), done: deferred() };
246
- } catch {
247
- return null;
248
250
  }
251
+ writeAll();
252
+ return { path: containerSkillFile(agent.id), done: deferred() };
249
253
  }
250
254
 
251
255
  // ---------------------------------------------------------------------------
@@ -475,8 +479,10 @@ export async function installPackageSkills(
475
479
  console.warn(`[skills] ${taskId}: git skill ${s.name} failed: ${why}`);
476
480
  continue;
477
481
  }
478
- await exec(container, ["mkdir", "-p", "/home/node/.claude/skills"]);
479
- await exec(container, ["touch", marker]);
482
+ for (const cmd of [["mkdir", "-p", "/home/node/.claude/skills"], ["touch", marker]]) {
483
+ const result = await exec(container, cmd);
484
+ if (result.status !== 0) throw new Error(`package marker write failed (exit ${result.status}): ${result.stderr.trim()}`);
485
+ }
480
486
  console.log(`[skills] ${taskId}: installed git skill ${s.name}`);
481
487
  done.push(installedSkillPath(s));
482
488
  } else if (s.source === "cli") {
@@ -498,8 +504,10 @@ export async function installPackageSkills(
498
504
  console.warn(`[skills] ${taskId}: install cmd for ${s.name} failed: ${c.stderr.trim()}`);
499
505
  continue;
500
506
  }
501
- await exec(container, ["mkdir", "-p", "/home/node/.claude/skills"]);
502
- await exec(container, ["touch", marker]);
507
+ for (const cmd of [["mkdir", "-p", "/home/node/.claude/skills"], ["touch", marker]]) {
508
+ const result = await exec(container, cmd);
509
+ if (result.status !== 0) throw new Error(`package marker write failed (exit ${result.status}): ${result.stderr.trim()}`);
510
+ }
503
511
  console.log(`[skills] ${taskId}: ran install command for ${s.name}`);
504
512
  done.push(installedSkillPath(s));
505
513
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.6",
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
 
package/src/main.ts CHANGED
@@ -1632,6 +1632,8 @@ function buildCapabilities(): HostCapabilities {
1632
1632
  return {
1633
1633
  version: packageVersion(),
1634
1634
  customConnections: credentialsMode() === "active",
1635
+ // ADR-168: leased accounts' allowed models are read and honoured.
1636
+ accountModelLimits: true,
1635
1637
  engineConnectCustom: signInBoxMode(),
1636
1638
  engineConnectCustomManual: signInBoxMode(),
1637
1639
  internalConnections: isOwnedInternalConnectionRuntime(internalRuntimeProvider()),
@@ -0,0 +1,103 @@
1
+ /**
2
+ * ADR-168: an AI account's allowed models. One module for the cloud (which
3
+ * stores and checks the list) and the runner (which picks and rotates
4
+ * accounts by it), so the two can never disagree about what "this account
5
+ * allows that model" means. Pure: no runtime imports.
6
+ *
7
+ * Ids are the roster's: what an agent's `model` field holds for its engine
8
+ * kind (`supportedModels` in lib/agent-catalog.ts, mirrored from
9
+ * ./engine-models.ts). Before any comparison both sides go through
10
+ * `canonicalAccountModel`:
11
+ *
12
+ * - every kind: surrounding whitespace is dropped;
13
+ * - `claude`: case-folded, a context suffix (`opus[1m]`) dropped, and a full
14
+ * Claude model id (`claude-sonnet-5-5`, `claude-opus-4-8-20260101`) read as
15
+ * its family alias (`sonnet`, `opus`) — the only ids the Claude roster uses;
16
+ * - `codex`, `grok`: case-folded (their CLIs treat slugs case-insensitively);
17
+ * - any other kind (`cursor`, `kimi`, `opencode`, …): kept verbatim, since
18
+ * their ids are free-form `provider/model` strings.
19
+ *
20
+ * Null (or an empty list) means every model, so an untouched account behaves
21
+ * exactly as before. A limited account runs only the models it lists: an
22
+ * agent with no model set runs on it only when the caller resolves that blank
23
+ * to a concrete default first (the cloud uses the catalog default of a
24
+ * `required` kind; a blank `optional` model is the CLI's own choice, which a
25
+ * limited account cannot vouch for).
26
+ */
27
+
28
+ const CLAUDE_FAMILIES = ["fable", "opus", "sonnet", "haiku"] as const;
29
+ const CASE_FOLDED_KINDS = new Set(["claude", "codex", "grok"]);
30
+
31
+ /** Most models a single account may list. */
32
+ export const MAX_ALLOWED_MODELS = 200;
33
+ /** Longest model id kept. */
34
+ export const MAX_ALLOWED_MODEL_CHARS = 200;
35
+
36
+ /** The id a model is compared by, for one engine kind. */
37
+ export function canonicalAccountModel(kind: string, model: string): string {
38
+ let id = model.trim();
39
+ if (CASE_FOLDED_KINDS.has(kind)) id = id.toLowerCase();
40
+ if (kind !== "claude") return id;
41
+ id = id.replace(/\[[^\]]*\]$/, "");
42
+ const full = /^claude-([a-z]+)(?:-|$)/.exec(id);
43
+ if (full && (CLAUDE_FAMILIES as readonly string[]).includes(full[1]!)) return full[1]!;
44
+ return id;
45
+ }
46
+
47
+ /**
48
+ * The stored form of a list: canonical, de-duplicated, in the order given;
49
+ * null for "every model" (null, undefined or nothing left).
50
+ */
51
+ export function normalizeAllowedModels(
52
+ kind: string,
53
+ models: readonly string[] | null | undefined,
54
+ ): string[] | null {
55
+ if (!models) return null;
56
+ const out: string[] = [];
57
+ for (const model of models) {
58
+ const id = canonicalAccountModel(kind, model);
59
+ if (id && !out.includes(id)) out.push(id);
60
+ }
61
+ return out.length ? out : null;
62
+ }
63
+
64
+ /** Whether an account with this list may run `model` for `kind`. A blank
65
+ * model is allowed only on an account that allows every model. */
66
+ export function accountAllowsModel(
67
+ allowed: readonly string[] | null | undefined,
68
+ kind: string,
69
+ model: string | null | undefined,
70
+ ): boolean {
71
+ if (!allowed || allowed.length === 0) return true;
72
+ const id = model ? canonicalAccountModel(kind, model) : "";
73
+ if (!id) return false;
74
+ return allowed.some((entry) => canonicalAccountModel(kind, entry) === id);
75
+ }
76
+
77
+ /** Parse the stored JSON (`uai_credentials.allowed_models`). Anything
78
+ * unreadable reads as an empty list — no model — never as "every model":
79
+ * a value this code cannot read must fail closed. */
80
+ export function parseAllowedModels(raw: string | null | undefined): string[] | null {
81
+ if (raw === null || raw === undefined || raw === "") return null;
82
+ try {
83
+ const value: unknown = JSON.parse(raw);
84
+ if (value === null) return null;
85
+ if (!Array.isArray(value) || !value.every((m) => typeof m === "string")) return [];
86
+ return value.length ? (value as string[]) : null;
87
+ } catch {
88
+ return [];
89
+ }
90
+ }
91
+
92
+ /** True when a manifest's `allowedModels` value is well-formed. */
93
+ export function isAllowedModelsWire(value: unknown): value is string[] {
94
+ return (
95
+ Array.isArray(value) &&
96
+ value.length > 0 &&
97
+ value.length <= MAX_ALLOWED_MODELS &&
98
+ value.every(
99
+ (m) => typeof m === "string" && m.length > 0 && m.length <= MAX_ALLOWED_MODEL_CHARS,
100
+ ) &&
101
+ new Set(value).size === value.length
102
+ );
103
+ }
package/src/protocol.ts CHANGED
@@ -4123,6 +4123,9 @@ export function isHostConfigAckFrame(
4123
4123
  */
4124
4124
  export interface HostCapabilities {
4125
4125
  customConnections?: boolean;
4126
+ /** ADR-168: this runner reads a leased account's `allowedModels` and picks
4127
+ * and rotates accounts by the agent's model. */
4128
+ accountModelLimits?: boolean;
4126
4129
  engineConnectCustom?: boolean;
4127
4130
  engineConnectCustomManual?: boolean;
4128
4131
  internalConnections?: boolean;