@moondeck/station 1.0.7 → 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.
@@ -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
+ }
@@ -683,3 +683,71 @@ export function hostWorkspaceWrite(
683
683
  ): Promise<void> {
684
684
  return writeContainedFile(hostWorkspaceRoot, workspacePathParts(descriptor, path), bytes);
685
685
  }
686
+
687
+ // Runs as the task user inside its Linux runtime. Pin every directory; refuse
688
+ // links and special files. Rename a new inode instead of truncating a hardlink.
689
+ // No shell interpolation, cloud URL, credential, or task-supplied code.
690
+ const ATOMIC_WORKSPACE_WRITER = String.raw`
691
+ (() => {
692
+ const fs = require('node:fs');
693
+ const [root, path, mode] = process.argv.slice(1);
694
+ const parts = JSON.parse(path);
695
+ const C = fs.constants;
696
+ let dir = fs.openSync(root, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW);
697
+ let pending;
698
+ try {
699
+ for (const part of parts.slice(0, -1)) {
700
+ const at = '/proc/self/fd/' + dir + '/' + part;
701
+ if (mode !== 'probe') { try { fs.mkdirSync(at); } catch (e) { if (e.code !== 'EEXIST') throw e; } }
702
+ const next = fs.openSync(at, C.O_RDONLY | C.O_DIRECTORY | C.O_NOFOLLOW);
703
+ fs.closeSync(dir); dir = next;
704
+ }
705
+ const target = '/proc/self/fd/' + dir + '/' + parts.at(-1);
706
+ let exists = false;
707
+ const inspect = () => { const st = fs.lstatSync(target); if (!st.isFile() || st.nlink !== 1) throw Error('unsafe attachment target'); };
708
+ try { inspect(); exists = true; }
709
+ catch (e) { if (e.code !== 'ENOENT') throw e; }
710
+ if (mode === 'probe') { process.stdout.write(exists ? 'present' : 'missing'); return; }
711
+ if (mode === 'preserve' && exists) { fs.readFileSync(0); return; }
712
+ pending = '/proc/self/fd/' + dir + '/.initial-' + require('node:crypto').randomUUID();
713
+ const fd = fs.openSync(pending, C.O_WRONLY | C.O_CREAT | C.O_EXCL | C.O_NOFOLLOW, 0o644);
714
+ try { fs.writeFileSync(fd, fs.readFileSync(0)); } finally { fs.closeSync(fd); }
715
+ if (mode === 'preserve') {
716
+ try { fs.linkSync(pending, target); } catch (e) { if (e.code !== 'EEXIST') throw e; inspect(); }
717
+ fs.unlinkSync(pending);
718
+ } else fs.renameSync(pending, target);
719
+ pending = undefined;
720
+ } catch (e) {
721
+ if (mode === 'probe' && e.code === 'ENOENT') process.stdout.write('missing');
722
+ else throw e;
723
+ } finally {
724
+ if (pending) fs.unlinkSync(pending);
725
+ fs.closeSync(dir);
726
+ }
727
+ })();
728
+ `;
729
+
730
+
731
+ /** Atomically publish bytes through the task user in its Linux runtime.
732
+ * Unlike a shell redirect, this refuses symlink components and hardlinks;
733
+ * unlike host-side mkdir, it is also contained on macOS-hosted providers. */
734
+ export async function writeContainedRuntimeFile(
735
+ environment: Pick<TaskEnvironmentHandle, "exec" | "descriptor">,
736
+ parts: readonly string[],
737
+ bytes: Uint8Array,
738
+ mode: "replace" | "preserve" | "probe" = "replace",
739
+ ): Promise<boolean> {
740
+ checkedParts(parts);
741
+ const result = await environment.exec({
742
+ argv: ["node", "-e", ATOMIC_WORKSPACE_WRITER, environment.descriptor.workspacePath, JSON.stringify(parts), mode],
743
+ projectEnvProfile: "maintenance",
744
+ stdin: bytes,
745
+ timeoutMs: 120_000,
746
+ maxOutputBytes: 4096,
747
+ });
748
+ if (result.exitCode !== 0) throw new Error(`Could not safely write a workspace file: ${Buffer.from(result.stderr).toString("utf8")}`);
749
+ if (mode !== "probe") return true;
750
+ const status = Buffer.from(result.stdout).toString("utf8");
751
+ if (status !== "present" && status !== "missing") throw new Error("Invalid workspace probe response");
752
+ return status === "present";
753
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moondeck/station",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
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>",
@@ -104,6 +104,14 @@
104
104
  "./never-proxied-domains": {
105
105
  "types": "./src/never-proxied-domains.ts",
106
106
  "default": "./src/never-proxied-domains.ts"
107
+ },
108
+ "./initial-attachments": {
109
+ "types": "./src/initial-attachments.ts",
110
+ "default": "./src/initial-attachments.ts"
111
+ },
112
+ "./initial-attachment-materialization": {
113
+ "types": "./lib/initial-attachments.ts",
114
+ "default": "./lib/initial-attachments.ts"
107
115
  }
108
116
  },
109
117
  "scripts": {
package/src/index.ts CHANGED
@@ -54,6 +54,7 @@ import {
54
54
  prepareTaskGithubGitCredential,
55
55
  type TaskGithubGitCredential,
56
56
  } from "../lib/github-git-auth";
57
+ import { handleInitialAttachmentCommand } from "../lib/initial-attachment-command";
57
58
  import { readAttachment, writeAttachment } from "../lib/attachments";
58
59
  import { readFileSync } from "node:fs";
59
60
  import { resolve } from "node:path";
@@ -2334,6 +2335,17 @@ export const hostCommands: HostCommands = {
2334
2335
  }
2335
2336
  },
2336
2337
 
2338
+ async initialAttachmentWrite(ctx, input) {
2339
+ logCommand(ctx, "initialAttachmentWrite", input.taskId, input.operation ?? "write");
2340
+ try {
2341
+ return ok(await handleInitialAttachmentCommand(input, {
2342
+ runTaskLifecycle: (taskId, work) => getOrchestrator().runTaskLifecycle(taskId, work),
2343
+ getTask: getHostTask,
2344
+ environment: reconstructHostTaskEnvironment,
2345
+ }));
2346
+ } catch (error) { return failFromUnknown(error); }
2347
+ },
2348
+
2337
2349
  async attachmentWrite(ctx, input) {
2338
2350
  logCommand(ctx, "attachmentWrite", input.taskId, input.filename);
2339
2351
  try {
@@ -0,0 +1,74 @@
1
+ /** Only explicit personal brief-upload references are startup inputs. */
2
+ export const INITIAL_ATTACHMENT_CHUNK = 3 * 1024 * 1024;
3
+ export const INITIAL_ATTACHMENT_MAX = 200 * 1024 * 1024;
4
+ export const INITIAL_ATTACHMENT_FEATURE = "initial-attachments-v1";
5
+ const PREFIX = "/workspace/files/me/";
6
+
7
+ export function initialAttachmentParts(path: string): string[] {
8
+ if (!path.startsWith(PREFIX)) throw new Error("Invalid initial attachment path");
9
+ const parts = path.slice(PREFIX.length).split("/");
10
+ if (parts.length !== 3 || parts[0] !== "task-uploads" ||
11
+ !/^[a-z0-9][a-z0-9-]{0,99}$/.test(parts[1]!) ||
12
+ !/^[A-Za-z0-9._-]+$/.test(parts[2]!) || [".", ".."].includes(parts[2]!)) {
13
+ throw new Error("Invalid initial attachment path");
14
+ }
15
+ return ["files", "me", ...parts];
16
+ }
17
+
18
+ export function initialAttachmentPaths(texts: readonly (string | null | undefined)[]): string[] {
19
+ const paths = new Set<string>();
20
+ for (const text of texts) {
21
+ // Chat treats fenced/inline code and escaped delimiters as literal text.
22
+ // Explicit references elsewhere (including within prose) are attachments.
23
+ let fenced = false;
24
+ const visible: string[] = [];
25
+ for (const line of (text ?? "").split("\n")) {
26
+ if (fenced && /^\s*```+\s*$/.test(line)) { fenced = false; continue; }
27
+ if (!fenced && /^\s*```+/.test(line)) { fenced = true; continue; }
28
+ if (fenced) continue;
29
+ visible.push(line);
30
+ }
31
+ const rendered = visible.join("\n").replace(/\\[\\`*_{}[\]()#+\-.!~>|]/g, " ").replace(/`[^`]+`/g, " ");
32
+ const refs = /\[image:\s*([^\]\r\n]+)\]|\[[^\]\r\n]+\]\(([^)\s]+)\)/g;
33
+ for (const match of rendered.matchAll(refs)) {
34
+ const path = (match[1] ?? match[2])!.trim();
35
+ // Other personal links are ordinary chat references, not brief uploads.
36
+ // A malformed reference inside the upload namespace still fails closed.
37
+ if (path !== `${PREFIX}task-uploads` && !path.startsWith(`${PREFIX}task-uploads/`)) continue;
38
+ initialAttachmentParts(path);
39
+ paths.add(path);
40
+ }
41
+ }
42
+ return [...paths];
43
+ }
44
+
45
+ export interface InitialAttachmentWriteInput {
46
+ operation?: "probe" | "abort";
47
+ preserveExisting?: boolean;
48
+ taskId: string;
49
+ runEpoch: number;
50
+ transferId: string;
51
+ path: string;
52
+ offset: number;
53
+ size: number;
54
+ dataBase64: string;
55
+ }
56
+
57
+ /** Used by bridge dispatch and the receiver; malformed commands never acquire a lifecycle slot. */
58
+ export function parseInitialAttachmentInput(value: unknown): InitialAttachmentWriteInput {
59
+ if (!value || typeof value !== "object") throw new Error("Invalid initial attachment transfer");
60
+ const input = value as InitialAttachmentWriteInput;
61
+ if (typeof input.taskId !== "string" || !/^[a-zA-Z0-9-]{1,100}$/.test(input.taskId) ||
62
+ typeof input.path !== "string" ||
63
+ !Number.isSafeInteger(input.runEpoch) || input.runEpoch < 0 ||
64
+ typeof input.transferId !== "string" || !/^[a-zA-Z0-9-]{1,100}$/.test(input.transferId) ||
65
+ ![undefined, "probe", "abort"].includes(input.operation) ||
66
+ (input.preserveExisting !== undefined && typeof input.preserveExisting !== "boolean") ||
67
+ typeof input.dataBase64 !== "string" || input.dataBase64.length > Math.ceil(INITIAL_ATTACHMENT_CHUNK / 3) * 4 ||
68
+ !Number.isSafeInteger(input.offset) || input.offset < 0 ||
69
+ !Number.isSafeInteger(input.size) || input.size < 0 || input.size > INITIAL_ATTACHMENT_MAX) {
70
+ throw new Error("Invalid initial attachment transfer");
71
+ }
72
+ initialAttachmentParts(input.path);
73
+ return input;
74
+ }
package/src/main.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env tsx
2
+ import { parseInitialAttachmentInput } from "./initial-attachments";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { stationAgentCliAdvertisable } from "../lib/agent-cli";
4
5
  import {
@@ -1641,6 +1642,7 @@ function buildCapabilities(): HostCapabilities {
1641
1642
  protocolFeatures: [
1642
1643
  PREVIEW_UPSTREAM_PROTOCOL_FEATURE,
1643
1644
  "host-workspace-file-read-v1",
1645
+ "initial-attachments-v1",
1644
1646
  ASSIGNMENT_EVIDENCE_PROTOCOL_FEATURE,
1645
1647
  FIRST_TURN_DEDUP_PROTOCOL_FEATURE,
1646
1648
  LEAD_EVIDENCE_PROTOCOL_FEATURE,
@@ -4801,6 +4803,8 @@ async function dispatchCommand(
4801
4803
  return hostCommands.taskProjectCompensate(ctx, expectTaskProjectFence(args[0], "task project compensate input"));
4802
4804
  case "taskProjectStatus":
4803
4805
  return hostCommands.taskProjectStatus(ctx, expectTaskProjectStatusInput(args, 0));
4806
+ case "initialAttachmentWrite":
4807
+ return hostCommands.initialAttachmentWrite(ctx, parseInitialAttachmentInput(args[0]));
4804
4808
  case "attachmentWrite":
4805
4809
  return hostCommands.attachmentWrite(
4806
4810
  ctx,
@@ -5831,6 +5835,7 @@ const HOST_COMMAND_NAMES = {
5831
5835
  taskProjectActivate: true,
5832
5836
  taskProjectCompensate: true,
5833
5837
  taskProjectStatus: true,
5838
+ initialAttachmentWrite: true,
5834
5839
  attachmentWrite: true,
5835
5840
  attachmentRead: true,
5836
5841
  workspaceFileRead: true,
package/src/protocol.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { InitialAttachmentWriteInput } from "./initial-attachments";
1
2
  export * from "./custom-connections";
2
3
  export * from "./preview-upstream";
3
4
  import type { PreviewUpstream } from "./preview-upstream";
@@ -53,6 +54,7 @@ export enum HostErrorCode {
53
54
  NoSuchAgent = "no_such_agent",
54
55
  NoSuchPermission = "no_such_permission",
55
56
  HostUnavailable = "host_unavailable",
57
+ InitialAttachmentsUnsupported = "initial_attachments_unsupported",
56
58
  Internal = "internal",
57
59
  PayloadTooLarge = "payload_too_large",
58
60
  }
@@ -4958,6 +4960,7 @@ export interface HostCommands {
4958
4960
  ctx: CommandContext,
4959
4961
  input: TaskProjectStatusInput,
4960
4962
  ): Promise<HostCommandResult<TaskProjectStatusResult>>;
4963
+ initialAttachmentWrite(ctx: CommandContext, input: InitialAttachmentWriteInput): Promise<HostCommandResult<{ exists: boolean } | undefined>>;
4961
4964
  attachmentWrite(
4962
4965
  ctx: CommandContext,
4963
4966
  input: { taskId: string; filename: string; dataBase64: string },