@moondeck/station 1.0.14 → 1.0.15

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.
@@ -242,8 +242,10 @@ const SERVER_COMMAND = "sh";
242
242
  /** Exported for the test that locks the pin/browser invariants. */
243
243
  export const SERVER_ARGS: [string, string] = ["-lc", SERVER_LAUNCHER];
244
244
 
245
- /** The `browser` server definition every engine gets. */
246
- const SERVER_DEF = { command: SERVER_COMMAND, args: SERVER_ARGS };
245
+ /** The `browser` server definition every engine gets (exported for the
246
+ * Gemini writer, gemini-mcp-config.ts, which lists it in each agent's own
247
+ * agy dir). */
248
+ export const SERVER_DEF = { command: SERVER_COMMAND, args: SERVER_ARGS };
247
249
 
248
250
  /** Cursor reads stdio servers from ~/.cursor/mcp.json (the adapter passes
249
251
  * `--approve-mcps`); same JSON shape as Claude's project file. */
@@ -113,6 +113,25 @@ export function writeTaskFileArgv(path: string, mode: "600" | "644"): [string, .
113
113
  return ["/usr/bin/python3", "-I", "-c", TASK_FILE_WRITE_HELPER, TASK_HOME, path.slice(TASK_HOME.length + 1), mode];
114
114
  }
115
115
 
116
+ /** The exec that writes `relative` under `dir`, a directory directly in the
117
+ * task's home that must already exist (`TASK_FILE_WRITE_HELPER` rooted at
118
+ * it: opened O_NOFOLLOW, never created, so a rewrite can't recreate a home a
119
+ * cleanup removed, and a symlink in its place is refused). */
120
+ export function writeExistingTaskDirFileArgv(
121
+ dir: string,
122
+ relative: string,
123
+ mode: "600" | "644",
124
+ ): [string, ...string[]] {
125
+ const name = dir.startsWith(`${TASK_HOME}/`) ? dir.slice(TASK_HOME.length + 1) : "";
126
+ if (!/^[A-Za-z0-9._-]+$/.test(name) || name === "." || name === "..") {
127
+ throw new Error("a task directory is not directly in the task home");
128
+ }
129
+ if (relative.split("/").some((part) => part === "" || part === "." || part === "..")) {
130
+ throw new Error("a task file path must be a plain relative path");
131
+ }
132
+ return ["/usr/bin/python3", "-I", "-c", TASK_FILE_WRITE_HELPER, dir, relative, mode];
133
+ }
134
+
116
135
  /** A credential is written only into the runtime of the task it belongs to:
117
136
  * the cleanup that must delete it refuses any other task's runtime. */
118
137
  export function assertTaskRuntime(environment: TaskWriteEnvironment, taskId: string): void {
@@ -0,0 +1,120 @@
1
+ /**
2
+ * ADR-178: MCP servers for Gemini (agy) agents.
3
+ *
4
+ * agy reads its MCP servers from `<gemini dir>/config/mcp_config.json`, and
5
+ * every Gemini agent runs with a gemini dir of its own (`agy --gemini_dir`):
6
+ * a subscription agent's `/home/node/.gemini-acct-<account>-agent-<agent>`,
7
+ * an API-key agent's `/home/node/.gemini-uai-key-agent-<agent>`. So unlike
8
+ * Codex or Grok there is no shared home to reconcile and no user entry to
9
+ * keep: Uai owns each of these files whole and writes the complete list.
10
+ *
11
+ * The format is agy's own, as `agy mcp add` writes it (agy 1.5.16, read from
12
+ * the file the binary wrote, not guessed):
13
+ *
14
+ * { "mcpServers": {
15
+ * "<stdio>": { "args": [...], "command": "...", "disabled": false,
16
+ * "env": { "K": "V" } }, // env optional
17
+ * "<http>": { "disabled": false, "headers": { "K": "V" }, // optional
18
+ * "serverUrl": "http://…" } } }
19
+ *
20
+ * The list is the same one every other engine gets: the watchable browser
21
+ * (stdio, the ADR-053 launcher) while the task has browser testing on, and
22
+ * each MCP connection the host gateway serves the task, at the same gateway
23
+ * URL Codex and Grok get (`taskGatewayServerUrls`). The URL's path token is
24
+ * the gateway's auth, so the content only ever travels over the writer's
25
+ * stdin and is never logged; a failure is a fixed message.
26
+ *
27
+ * Written with the no-follow task-file writer (task-files.ts), mode 0600, as
28
+ * node, only into the dir derived from the agent's own id. The dir is
29
+ * already inventoried as a whole for cleanup (a subscription home by
30
+ * writeEngineHome, an API-key dir by the orchestrator), so the file goes with
31
+ * it.
32
+ */
33
+
34
+ import { createHash } from "node:crypto";
35
+ import { SERVER_DEF } from "./browser-testing";
36
+ import { geminiKeyHome } from "./credential-consumers/engines";
37
+ import {
38
+ assertTaskRuntime,
39
+ runInTask,
40
+ TASK_HOME,
41
+ writeExistingTaskDirFileArgv,
42
+ writeTaskFileArgv,
43
+ type TaskWriteEnvironment,
44
+ } from "./credential-consumers/task-files";
45
+
46
+ /** Where agy keeps its MCP list, relative to its gemini dir. */
47
+ export const GEMINI_MCP_CONFIG_FILE = "config/mcp_config.json";
48
+
49
+ /** The slug the browser server takes in every engine's config. A gateway
50
+ * connection of the same name is left out, as Claude's merge keeps the
51
+ * browser entry over it. */
52
+ export const GEMINI_BROWSER_SERVER = "browser";
53
+
54
+ export interface GeminiMcpServers {
55
+ /** List the watchable browser (the task has browser testing on). */
56
+ browser: boolean;
57
+ /** Gateway URL by connection slug. */
58
+ gateway: Readonly<Record<string, string>>;
59
+ }
60
+
61
+ /** The whole mcp_config.json for one agent, in agy's format. An empty list is
62
+ * still a valid file (`{"mcpServers": {}}`), never a 0-byte one. */
63
+ export function geminiMcpConfigJson(servers: GeminiMcpServers): string {
64
+ const mcpServers: Record<string, unknown> = {};
65
+ if (servers.browser) {
66
+ mcpServers[GEMINI_BROWSER_SERVER] = {
67
+ args: [...SERVER_DEF.args],
68
+ command: SERVER_DEF.command,
69
+ disabled: false,
70
+ };
71
+ }
72
+ for (const slug of Object.keys(servers.gateway).sort()) {
73
+ if (Object.hasOwn(mcpServers, slug)) continue;
74
+ mcpServers[slug] = { disabled: false, serverUrl: servers.gateway[slug] };
75
+ }
76
+ return `${JSON.stringify({ mcpServers }, null, 2)}\n`;
77
+ }
78
+
79
+ /** A content fingerprint to skip rewriting an unchanged file (kept in
80
+ * memory only; never logged). */
81
+ export function geminiMcpConfigHash(content: string): string {
82
+ return createHash("sha256").update(content).digest("hex");
83
+ }
84
+
85
+ const SUBSCRIPTION_PREFIX = `${TASK_HOME}/.gemini-acct-`;
86
+
87
+ /** True only for `agentId`'s own gemini dir: its API-key dir, or a
88
+ * subscription account's home derived for it (`<home>-agent-<agent>`). */
89
+ export function isGeminiAgentDir(agentId: string, dir: string): boolean {
90
+ if (dir === geminiKeyHome(agentId)) return true;
91
+ const suffix = `-agent-${agentId.replace(/[^A-Za-z0-9_-]/g, "_")}`;
92
+ if (!dir.startsWith(SUBSCRIPTION_PREFIX) || !dir.endsWith(suffix)) return false;
93
+ const account = dir.slice(SUBSCRIPTION_PREFIX.length, dir.length - suffix.length);
94
+ return /^[A-Za-z0-9_-]+$/.test(account);
95
+ }
96
+
97
+ /**
98
+ * Write `content` as `<dir>/config/mcp_config.json`, 0600, through the
99
+ * no-follow writer. `create` is for the spawn that is about to run agy in
100
+ * `dir` (already inventoried): missing directories are created owner-only.
101
+ * A rewrite passes `create: false`, so the dir must still exist: a home a
102
+ * cleanup removed is never recreated by a later MCP change.
103
+ */
104
+ export async function writeGeminiMcpConfig(
105
+ environment: TaskWriteEnvironment,
106
+ taskId: string,
107
+ agentId: string,
108
+ dir: string,
109
+ content: string,
110
+ options: { create: boolean; admit: () => void },
111
+ ): Promise<void> {
112
+ assertTaskRuntime(environment, taskId);
113
+ if (!isGeminiAgentDir(agentId, dir)) {
114
+ throw new Error("not this Gemini agent's own agy dir");
115
+ }
116
+ const argv = options.create
117
+ ? writeTaskFileArgv(`${dir}/${GEMINI_MCP_CONFIG_FILE}`, "600")
118
+ : writeExistingTaskDirFileArgv(dir, GEMINI_MCP_CONFIG_FILE, "600");
119
+ await runInTask(environment, argv, content, "writing the Gemini agent's MCP config", options.admit);
120
+ }
@@ -2330,6 +2330,41 @@ function shellQuote(value: string): string {
2330
2330
  return `'${value.replace(/'/g, `'\\''`)}'`;
2331
2331
  }
2332
2332
 
2333
+ /** ADR-121: a machine dials the gateway through its ssh REVERSE tunnel — the
2334
+ * host's loopback appears at the machine's own 127.0.0.1:PORT
2335
+ * (machine-gateway-tunnel.ts). host.docker.internal / vmnet addresses are
2336
+ * container topology a machine can never route. */
2337
+ async function gatewayHostFor(
2338
+ environment?: Partial<Pick<TaskEnvironmentHandle, "descriptor">>,
2339
+ ): Promise<string> {
2340
+ return isEnvironmentTransportProvider(environment?.descriptor?.locator.provider)
2341
+ ? "127.0.0.1"
2342
+ : await taskGatewayHost();
2343
+ }
2344
+
2345
+ /**
2346
+ * The gateway URL of each slug under the task's EXISTING ACL token, the same
2347
+ * URL `setupMcpTaskConfig` writes for every other engine (which must have
2348
+ * succeeded for these connections first: it writes the ACL). Null when the
2349
+ * task has no ACL yet. For engines that keep their MCP list in a file of
2350
+ * their own, written by a separate writer (Gemini: gemini-mcp-config.ts).
2351
+ * Never log the result: the path token is the gateway's auth.
2352
+ */
2353
+ export async function taskGatewayServerUrls(
2354
+ taskId: string,
2355
+ slugs: readonly string[],
2356
+ environment?: Partial<Pick<TaskEnvironmentHandle, "descriptor">>,
2357
+ ): Promise<Record<string, string> | null> {
2358
+ const acl = readAcl(taskId);
2359
+ if (!acl || typeof acl.token !== "string" || acl.token.length === 0) return null;
2360
+ const host = await gatewayHostFor(environment);
2361
+ const urls: Record<string, string> = {};
2362
+ for (const slug of slugs) {
2363
+ urls[slug] = `http://${host}:${MCP_GATEWAY_PORT}/t/${acl.token}/${slug}`;
2364
+ }
2365
+ return urls;
2366
+ }
2367
+
2333
2368
  /** Config homes are independent, but every Uai/browser writer must remain
2334
2369
  * behind one flock. Run a bounded batch at a time so the supported account ×
2335
2370
  * agent count cannot turn the outer timeout into a deterministic failure. */
@@ -2385,6 +2420,9 @@ const MCP_CONFIG_GROK_BATCH_BUDGET_S = 2 + Math.ceil(MAX_MANIFEST_MCP / 4);
2385
2420
  * - OpenCode — ~/.config/opencode/opencode.json `mcp` block (type:"remote",
2386
2421
  * oauth:false so it treats the gateway URL as a plain server; the path
2387
2422
  * token is the auth).
2423
+ * - Gemini — NOT here: each agent's own agy dir gets a whole-file
2424
+ * mcp_config.json from gemini-mcp-config.ts (the orchestrator writes it
2425
+ * after this succeeds, with `taskGatewayServerUrls`).
2388
2426
  * Safe to re-run every ensure. `engineKinds` is the roster's agent kinds.
2389
2427
  */
2390
2428
  export async function setupMcpTaskConfig(
@@ -2417,14 +2455,8 @@ export async function setupMcpTaskConfig(
2417
2455
  throw new Error("invalid Codex MCP connection slug");
2418
2456
  }
2419
2457
  const acl = ensureTaskGatewayAcl(taskId, connections);
2420
- // ADR-121: a machine dials the gateway through its ssh REVERSE tunnel —
2421
- // the host's loopback appears at the machine's own 127.0.0.1:PORT
2422
- // (machine-gateway-tunnel.ts). host.docker.internal / vmnet addresses
2423
- // are container topology a machine can never route.
2424
- const gatewayHost =
2425
- isEnvironmentTransportProvider(environment?.descriptor?.locator.provider)
2426
- ? "127.0.0.1"
2427
- : await taskGatewayHost();
2458
+ // ADR-121: a machine dials through its reverse tunnel (gatewayHostFor).
2459
+ const gatewayHost = await gatewayHostFor(environment);
2428
2460
  const urlFor = (slug: string): string =>
2429
2461
  `http://${gatewayHost}:${MCP_GATEWAY_PORT}/t/${acl.token}/${slug}`;
2430
2462
 
@@ -242,7 +242,9 @@ import {
242
242
  LEASED_ENGINE_KINDS,
243
243
  MANAGED_ENGINE_KIND,
244
244
  } from "../src/cloud-credentials";
245
- import { clearTaskGatewayAcl, setupMcpTaskConfig } from "./mcp-gateway";
245
+ import { clearTaskGatewayAcl, setupMcpTaskConfig, taskGatewayServerUrls } from "./mcp-gateway";
246
+ import { GEMINI_DIR_ENV } from "./agents/gemini";
247
+ import { geminiMcpConfigHash, geminiMcpConfigJson, writeGeminiMcpConfig } from "./gemini-mcp-config";
246
248
  import {
247
249
  reactivateTaskGatewayTask,
248
250
  removeTaskGatewayTask,
@@ -458,6 +460,17 @@ interface Channel {
458
460
  /** Serialize gateway config writes so two ensures cannot publish stale
459
461
  * content and then memoize the newer fingerprint over it. */
460
462
  mcpConfigWrite: Promise<void> | null;
463
+ /** The connection set the last successful gateway publication wrote (and
464
+ * the gateway ACL holds): what Gemini agents' own configs list. */
465
+ mcpServedConnections: Array<{ slug: string }> | null;
466
+ /** ADR-178: each Gemini agent's own agy dir (from its spawn), whose
467
+ * mcp_config.json Uai keeps current. */
468
+ geminiMcpDirs: Map<string, string>;
469
+ /** What was last written in each of those dirs (a content hash). */
470
+ geminiMcpWritten: Map<string, string>;
471
+ /** Serializes Gemini config writes: each computes its content when it
472
+ * runs, so the last write carries the latest state. */
473
+ geminiMcpWrite: Promise<unknown> | null;
461
474
  /** Account provisioning can overwrite per-engine config without changing
462
475
  * the desired gateway fingerprint. A monotonic epoch prevents an older
463
476
  * in-flight writer from clearing a newer provisioning mutation. */
@@ -1511,6 +1524,10 @@ export class Orchestrator {
1511
1524
  mcpConnections: spec.mcpConnections ?? [],
1512
1525
  mcpLeaseConnections: null,
1513
1526
  mcpConfigWrite: null,
1527
+ mcpServedConnections: null,
1528
+ geminiMcpDirs: new Map(),
1529
+ geminiMcpWritten: new Map(),
1530
+ geminiMcpWrite: null,
1514
1531
  mcpConfigDirtyEpoch: 1,
1515
1532
  mcpConfigAppliedEpoch: 0,
1516
1533
  mcpProvisionAffectedKinds: new Set(),
@@ -2150,6 +2167,12 @@ export class Orchestrator {
2150
2167
  }
2151
2168
 
2152
2169
  if (!this.isActiveChannel(channel)) return unavailable;
2170
+ // ADR-178: Gemini agents' own configs list the browser while it's on;
2171
+ // rewritten before the sessions below are marked to recycle.
2172
+ if (channel.geminiMcpDirs.size > 0 && setup.configured) {
2173
+ await this.ensureGeminiMcpConfig(channel);
2174
+ if (!this.isActiveChannel(channel)) return unavailable;
2175
+ }
2153
2176
 
2154
2177
  channel.browserReady = setup.ready && setup.configured;
2155
2178
  if (setup.changed) {
@@ -2380,6 +2403,14 @@ export class Orchestrator {
2380
2403
  grokHomes,
2381
2404
  );
2382
2405
  if (!configured || !this.isActiveChannel(channel)) return;
2406
+ channel.mcpServedConnections = connections.map(({ slug }) => ({ slug }));
2407
+ // ADR-178: every Gemini agent's own agy dir lists the same servers,
2408
+ // rewritten before any session is marked to recycle below. No await
2409
+ // without a Gemini agent: other engines' timing stays as it was.
2410
+ if (channel.geminiMcpDirs.size > 0) {
2411
+ await this.ensureGeminiMcpConfig(channel, providerEnvironment);
2412
+ if (!this.isActiveChannel(channel)) return;
2413
+ }
2383
2414
  channel.configGeneration += 1;
2384
2415
  channel.mcpConfigFingerprint = fingerprint;
2385
2416
  // Only acknowledge the epoch this write observed. If provisioning dirtied
@@ -2440,6 +2471,83 @@ export class Orchestrator {
2440
2471
  }
2441
2472
  }
2442
2473
 
2474
+ /**
2475
+ * ADR-178: keep each Gemini agent's `<gemini dir>/config/mcp_config.json`
2476
+ * listing what every other engine gets: the browser while the task has it
2477
+ * on, and the gateway's served connections at the same URLs. `spawn` names
2478
+ * the agent about to start agy in `dir`: it is registered and always
2479
+ * written (its dirs may be missing). Otherwise every registered dir whose
2480
+ * content changed is rewritten, never recreated. Serialized per channel;
2481
+ * a failure is logged with a fixed message and the agent still starts (as
2482
+ * every other engine's config write). Resolves to the agents written.
2483
+ */
2484
+ private ensureGeminiMcpConfig(
2485
+ channel: Channel,
2486
+ environment?: TaskEnvironmentHandle<unknown>,
2487
+ spawn?: { agentId: string; dir: string },
2488
+ ): Promise<string[]> {
2489
+ const run = (channel.geminiMcpWrite ?? Promise.resolve())
2490
+ .catch(() => undefined)
2491
+ .then(() => this.writeGeminiMcpPass(channel, environment, spawn));
2492
+ channel.geminiMcpWrite = run;
2493
+ return run.finally(() => {
2494
+ if (channel.geminiMcpWrite === run) channel.geminiMcpWrite = null;
2495
+ });
2496
+ }
2497
+
2498
+ private async writeGeminiMcpPass(
2499
+ channel: Channel,
2500
+ environment: TaskEnvironmentHandle<unknown> | undefined,
2501
+ spawn: { agentId: string; dir: string } | undefined,
2502
+ ): Promise<string[]> {
2503
+ if (!this.isActiveChannel(channel)) return [];
2504
+ if (spawn) channel.geminiMcpDirs.set(spawn.agentId, spawn.dir);
2505
+ for (const agentId of [...channel.geminiMcpDirs.keys()]) {
2506
+ if (!channel.roster.some((agent) => agent.id === agentId && agent.kind === "gemini")) {
2507
+ channel.geminiMcpWritten.delete(channel.geminiMcpDirs.get(agentId)!);
2508
+ channel.geminiMcpDirs.delete(agentId);
2509
+ }
2510
+ }
2511
+ const targets: Array<[string, string]> = spawn
2512
+ ? channel.geminiMcpDirs.get(spawn.agentId) === spawn.dir ? [[spawn.agentId, spawn.dir]] : []
2513
+ : [...channel.geminiMcpDirs];
2514
+ const target = environment ?? channel.agentHandle ?? undefined;
2515
+ if (targets.length === 0 || !target) return [];
2516
+ const slugs = (channel.mcpServedConnections ?? []).map(({ slug }) => slug);
2517
+ const gateway = slugs.length > 0
2518
+ ? await taskGatewayServerUrls(channel.taskId, slugs, target)
2519
+ : {};
2520
+ // No ACL although connections were published: the task is being torn
2521
+ // down; write nothing rather than a list without its servers.
2522
+ if (gateway === null || !this.isActiveChannel(channel)) return [];
2523
+ const content = geminiMcpConfigJson({ browser: channel.browserTesting, gateway });
2524
+ const hash = geminiMcpConfigHash(content);
2525
+ const written: string[] = [];
2526
+ for (const [agentId, dir] of targets) {
2527
+ if (!spawn && channel.geminiMcpWritten.get(dir) === hash) continue;
2528
+ try {
2529
+ await writeGeminiMcpConfig(target, channel.taskId, agentId, dir, content, {
2530
+ create: spawn !== undefined,
2531
+ admit: () => {
2532
+ if (!this.isActiveChannel(channel) || channel.geminiMcpDirs.get(agentId) !== dir) {
2533
+ throw new Error("the Gemini agent moved");
2534
+ }
2535
+ },
2536
+ });
2537
+ channel.geminiMcpWritten.set(dir, hash);
2538
+ written.push(agentId);
2539
+ } catch (err) {
2540
+ channel.geminiMcpWritten.delete(dir);
2541
+ console.warn(
2542
+ `[orchestrator] ${channel.taskId}/${agentId}: writing its Gemini MCP config failed: ${
2543
+ err instanceof Error ? err.message : String(err)
2544
+ }`,
2545
+ );
2546
+ }
2547
+ }
2548
+ return written;
2549
+ }
2550
+
2443
2551
  /** Close stale sessions that are idle, without recursively reconciling. */
2444
2552
  private async closeIdleStaleSessions(channel: Channel): Promise<number> {
2445
2553
  let recycled = 0;
@@ -4246,6 +4354,17 @@ export class Orchestrator {
4246
4354
  } else if (kind === "codex") {
4247
4355
  boundArgs = await this.isolateCodexHome(environment, agentId, args);
4248
4356
  }
4357
+ // ADR-178: agy reads its MCP servers from its own gemini dir, so that
4358
+ // dir gets the task's list before agy can start in it. The API-key path
4359
+ // binds without the gateway write the subscription path awaits, so
4360
+ // publish (a no-op when current) first.
4361
+ const geminiDir = kind === "gemini" ? boundArgs.agentEnv?.[GEMINI_DIR_ENV] : undefined;
4362
+ if (geminiDir) {
4363
+ await this.ensureMcpConfig(channel);
4364
+ if (!this.isActiveChannel(channel)) return null;
4365
+ await this.ensureGeminiMcpConfig(channel, environment, { agentId, dir: geminiDir });
4366
+ if (!this.isActiveChannel(channel)) return null;
4367
+ }
4249
4368
  while (this.isActiveChannel(channel)) {
4250
4369
  if (recovery && !this.recoveryIsCurrent(channel, agentId, recovery)) {
4251
4370
  channel.reconcileAgain = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.14",
3
+ "version": "1.0.15",
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>",