@moondeck/station 1.0.11 → 1.0.13

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.
@@ -1,3 +1,4 @@
1
+ import { effectiveCloudUrl } from "./cloud-endpoint";
1
2
  import { isOwnedInternalConnectionRuntime } from "./internal-connections";
2
3
  import { accountAllowsModel } from "../src/model-limits";
3
4
  import { prepareNodeData } from "./node-state";
@@ -2695,7 +2696,7 @@ export class Orchestrator {
2695
2696
  await this.closeIdleStaleSessions(channel);
2696
2697
  if (!this.isActiveChannel(channel)) return;
2697
2698
 
2698
- const apiUrl = apiUrlFromCloudUrl(env.UAI_CLOUD_URL);
2699
+ const apiUrl = apiUrlFromCloudUrl(effectiveCloudUrl(env.UAI_CLOUD_URL));
2699
2700
  const cliSecret = loadTaskCliSecret(channel.taskId);
2700
2701
  const cliWritten = await materializeAgentCli(
2701
2702
  task,
@@ -4725,7 +4726,7 @@ export class Orchestrator {
4725
4726
  // workspace. Each agent's OWN task token — carrying only ITS permissions — is
4726
4727
  // injected per-agent via its docker exec env below, so per-persona permissions
4727
4728
  // are actually enforced. Best-effort, host-side.
4728
- const apiUrl = apiUrlFromCloudUrl(env.UAI_CLOUD_URL);
4729
+ const apiUrl = apiUrlFromCloudUrl(effectiveCloudUrl(env.UAI_CLOUD_URL));
4729
4730
  const cliSecret = loadTaskCliSecret(channel.taskId);
4730
4731
  const cliWritten = await materializeAgentCli(
4731
4732
  task,
@@ -6104,7 +6105,7 @@ export class Orchestrator {
6104
6105
  const task = getHostTask(channel.taskId);
6105
6106
  if (!agent || !task || task.statusMirror !== "running") return;
6106
6107
 
6107
- const apiUrl = apiUrlFromCloudUrl(env.UAI_CLOUD_URL);
6108
+ const apiUrl = apiUrlFromCloudUrl(effectiveCloudUrl(env.UAI_CLOUD_URL));
6108
6109
  const cliSecret = loadTaskCliSecret(channel.taskId);
6109
6110
  const base = agentCliEnv(
6110
6111
  channel.taskId,
@@ -6324,7 +6325,7 @@ export class Orchestrator {
6324
6325
  return true;
6325
6326
  }
6326
6327
 
6327
- const apiUrl = apiUrlFromCloudUrl(env.UAI_CLOUD_URL);
6328
+ const apiUrl = apiUrlFromCloudUrl(effectiveCloudUrl(env.UAI_CLOUD_URL));
6328
6329
  const cliSecret = loadTaskCliSecret(channel.taskId);
6329
6330
  const base = agentCliEnv(
6330
6331
  channel.taskId,
@@ -6535,7 +6536,7 @@ export class Orchestrator {
6535
6536
  return true;
6536
6537
  }
6537
6538
 
6538
- const apiUrl = apiUrlFromCloudUrl(env.UAI_CLOUD_URL);
6539
+ const apiUrl = apiUrlFromCloudUrl(effectiveCloudUrl(env.UAI_CLOUD_URL));
6539
6540
  const cliSecret = loadTaskCliSecret(channel.taskId);
6540
6541
  const base = agentCliEnv(
6541
6542
  channel.taskId,
@@ -8126,6 +8127,12 @@ export function buildSystemPreamble(
8126
8127
  "<command>` in the shell. Your permissions:",
8127
8128
  `\`${(agent.permissions ?? []).join(", ")}\`. Commands: \`projects list\`,`,
8128
8129
  "`people list`, `task list`" +
8130
+ (agent.permissions?.includes("issues.read")
8131
+ ? ", `issue list`, `issue show KEY-N`, `issue current` (Issue reads; add --json for structured output)"
8132
+ : "") +
8133
+ (agent.permissions?.includes("issues.read") && agent.permissions?.includes("issues.write")
8134
+ ? ", `issue create --title T`, `issue update KEY-N`, `issue link KEY-N`, `issue unlink KEY-N` (Issue writes; see the guide for flags)"
8135
+ : "") +
8129
8136
  (agent.permissions?.includes("tasks.create")
8130
8137
  ? ", `task create --name <n> --prompt <p> [--projects id,id] [--agents handle,handle] [--astronaut engine/model/effort] [--start --request-id <logical-run-id>]`"
8131
8138
  : "") +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.11",
3
+ "version": "1.0.13",
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>",
package/src/main.ts CHANGED
@@ -30,6 +30,10 @@ import { sampleDiskPressure } from "../lib/disk-pressure";
30
30
  import { TASK_SECRETS_FEATURE, isTaskSecretStagingPut } from "./task-secrets";
31
31
  import { writeTaskSecretStaging } from "../lib/task-secret-staging";
32
32
 
33
+ import { parse as parseDotenv } from "dotenv";
34
+ import { initCloudEndpoint } from "../lib/cloud-endpoint";
35
+ import { writeEnvValuesAtomic } from "../lib/env-file";
36
+ import { enrollmentJournalPending } from "../lib/enrollment-state";
33
37
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
34
38
  import {
35
39
  request as httpRequest,
@@ -160,10 +164,12 @@ import { followLeavingLegacy, proxyTaskEnvSnapshot } from "../lib/task-env-sourc
160
164
  import { recoverActiveTaskGateways } from "../lib/task-gateway-recovery";
161
165
  import { addHostBreadcrumb, captureHostError, initHostObs, setHostObsTag } from "../lib/obs";
162
166
  import {
167
+ envLocalPath,
163
168
  hostIdFilePath,
164
169
  packageVersion,
165
170
  readPersistedHostId,
166
171
  serviceLogPath,
172
+ uaiHome,
167
173
  uiAssetsDir,
168
174
  uiPortFilePath,
169
175
  } from "./paths";
@@ -534,8 +540,18 @@ const token = requireEnv("UAI_HOST_TOKEN");
534
540
 
535
541
  const bridgePort = parsePort(process.env.UAI_HOST_BRIDGE_PORT, 8789);
536
542
  const hostId = process.env.UAI_HOST_ID ?? ensureHostId();
537
- const bridgeUrl =
538
- process.env.UAI_CLOUD_URL ?? `ws://127.0.0.1:${bridgePort}/host`;
543
+ // The Station's one effective cloud endpoint (lib/cloud-endpoint.ts): the bridge, GitHub token exchange and
544
+ // the task CLI base URL all read it, so a guarded migration to the API host moves them together.
545
+ const cloudEndpoint = initCloudEndpoint({
546
+ env: process.env,
547
+ readEnvLocal: () => parseDotenv(readFileSync(envLocalPath(), "utf8")),
548
+ journalPending: () => enrollmentJournalPending(uaiHome()),
549
+ persist: (values) => writeEnvValuesAtomic(envLocalPath(), values),
550
+ log: (message) => console.log(message),
551
+ defaultUrl: `ws://127.0.0.1:${bridgePort}/host`,
552
+ });
553
+ const bridgeUrl = (): string => cloudEndpoint.url();
554
+ let migrationTimer: NodeJS.Timeout | null = null;
539
555
 
540
556
  let ws: WebSocket | null = null;
541
557
  /** Which note path the connected cloud supports, from its event.resume. */
@@ -1529,7 +1545,7 @@ async function startLocalUi(): Promise<void> {
1529
1545
  portFilePath: uiPortFilePath(),
1530
1546
  startPort: parsePort(process.env.UAI_HOST_UI_PORT, 5876),
1531
1547
  version: packageVersion(),
1532
- cloudUrl: bridgeUrl,
1548
+ cloudUrl: cloudEndpoint.url(),
1533
1549
  hostId,
1534
1550
  logPath: serviceLogPath(),
1535
1551
  monitorOnly: signInBoxMode(),
@@ -3048,8 +3064,9 @@ async function connect(): Promise<void> {
3048
3064
  // previous generation down before constructing its replacement so a late
3049
3065
  // file read/child-process event can never escape onto the new socket.
3050
3066
  if (!(await remoteOperationsReadyForConnect(requestGeneration))) return;
3051
- console.log(`[host-agent] connecting ${bridgeUrl}`);
3052
- const socket = new WebSocket(bridgeUrl, { perMessageDeflate: WS_DEFLATE, handshakeTimeout: BRIDGE_SILENCE_MS });
3067
+ const connectUrl = bridgeUrl();
3068
+ console.log(`[host-agent] connecting ${connectUrl}`);
3069
+ const socket = new WebSocket(connectUrl, { perMessageDeflate: WS_DEFLATE, handshakeTimeout: BRIDGE_SILENCE_MS });
3053
3070
  ws = socket;
3054
3071
 
3055
3072
  let ready = false;
@@ -3237,6 +3254,7 @@ async function connect(): Promise<void> {
3237
3254
  if (!ready) {
3238
3255
  ready = true;
3239
3256
  reconnectAttempt = 0;
3257
+ cloudEndpoint.onAuthenticated();
3240
3258
  markConnected();
3241
3259
  console.log(`[host-agent] connected as ${hostId}`);
3242
3260
  setHostObsTag(hostId);
@@ -3251,6 +3269,7 @@ async function connect(): Promise<void> {
3251
3269
  break;
3252
3270
  case "event.resume":
3253
3271
  taskNotePublisher.negotiated(frame.features ?? []);
3272
+ scheduleEndpointMigration(socket, frame.features);
3254
3273
  bridgeResumed();
3255
3274
  // ADR-103: the cloud named its watermark — rewind the transmit
3256
3275
  // cursor to it (null = no state, replay nothing) and start draining.
@@ -4072,6 +4091,8 @@ async function connect(): Promise<void> {
4072
4091
  socket.on("error", bridgeRecovery.guard((err: Error) => {
4073
4092
  if (cleaned || requestGeneration !== connectionRequestGeneration || ws !== socket) return;
4074
4093
  markCloudError(err.message);
4094
+ // Only connection/TLS failures ever count toward an endpoint fallback (never a credential rejection).
4095
+ if (!ready) cloudEndpoint.onConnectFailure(err);
4075
4096
  if (!stopping) {
4076
4097
  console.warn(`[host-agent] bridge error: ${err.message}`);
4077
4098
  }
@@ -4080,6 +4101,9 @@ async function connect(): Promise<void> {
4080
4101
  function handleClose(code: number, reason: Buffer): void {
4081
4102
  if (cleaned || requestGeneration !== connectionRequestGeneration || ws !== socket) return;
4082
4103
  cleanup();
4104
+ cancelEndpointMigration();
4105
+ // An attempt that ends without authenticating (refusal, early close, rejection) is what ends a trial.
4106
+ if (!ready) cloudEndpoint.onAttemptEnded();
4083
4107
  // A note this connection carried is not known stored: the next start
4084
4108
  // sends it again, and the cloud keeps one per noteId.
4085
4109
  for (const [opId, settle] of durableNoteAcks) {
@@ -6506,6 +6530,35 @@ export function requestManagedHostRestart(): void {
6506
6530
  // Remote hostUpdate/hostRestart commands reuse the exact activation restart.
6507
6531
  setManagedHostRestartHook(requestManagedHostRestart);
6508
6532
 
6533
+ /** Stop any pending endpoint move; called when the socket that scheduled it closes, so a stale timer can
6534
+ * never block scheduling on the next socket. */
6535
+ function cancelEndpointMigration(): void {
6536
+ if (migrationTimer) clearTimeout(migrationTimer);
6537
+ migrationTimer = null;
6538
+ }
6539
+
6540
+ /** The cloud said (a boolean feature, never a URL) that Stations may move to the API host, or this Station
6541
+ * fell back and has earned its one return. After a jittered delay, and only while idle, retry the connection
6542
+ * on the compiled API URL; the endpoint module decides eligibility, persists only after the first
6543
+ * authenticated session, and falls back on connection failures. */
6544
+ function scheduleEndpointMigration(socket: WebSocket, features: readonly string[] | undefined): void {
6545
+ const delay = cloudEndpoint.noteSessionFeatures(features) ?? cloudEndpoint.scheduleReturn();
6546
+ if (delay === null || migrationTimer) return;
6547
+ let attempts = 0;
6548
+ const attempt = (): void => {
6549
+ migrationTimer = null;
6550
+ if (stopping || ws !== socket || socket.readyState !== WebSocket.OPEN) return;
6551
+ if (!isIdleForManagedHostUpdate() && attempts++ < 12) {
6552
+ migrationTimer = setTimeout(attempt, 5 * 60_000 + Math.floor(Math.random() * 5 * 60_000));
6553
+ migrationTimer.unref?.();
6554
+ return;
6555
+ }
6556
+ if (isIdleForManagedHostUpdate() && (cloudEndpoint.beginTrial() || cloudEndpoint.beginReturn())) socket.close(1000, "moving the cloud endpoint");
6557
+ };
6558
+ migrationTimer = setTimeout(attempt, delay);
6559
+ migrationTimer.unref?.();
6560
+ }
6561
+
6509
6562
  /** Automatic host updates wait only for in-flight work to drain. Running
6510
6563
  * tasks are deliberately not counted: durable sessions survive the service
6511
6564
  * restart, and gating on their existence made a busy host un-updatable