@moondeck/station 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
  }
@@ -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.6",
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>",
@@ -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"
@@ -100,6 +104,14 @@
100
104
  "./never-proxied-domains": {
101
105
  "types": "./src/never-proxied-domains.ts",
102
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"
103
115
  }
104
116
  },
105
117
  "scripts": {
@@ -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/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 {
@@ -1632,6 +1633,8 @@ function buildCapabilities(): HostCapabilities {
1632
1633
  return {
1633
1634
  version: packageVersion(),
1634
1635
  customConnections: credentialsMode() === "active",
1636
+ // ADR-168: leased accounts' allowed models are read and honoured.
1637
+ accountModelLimits: true,
1635
1638
  engineConnectCustom: signInBoxMode(),
1636
1639
  engineConnectCustomManual: signInBoxMode(),
1637
1640
  internalConnections: isOwnedInternalConnectionRuntime(internalRuntimeProvider()),
@@ -1639,6 +1642,7 @@ function buildCapabilities(): HostCapabilities {
1639
1642
  protocolFeatures: [
1640
1643
  PREVIEW_UPSTREAM_PROTOCOL_FEATURE,
1641
1644
  "host-workspace-file-read-v1",
1645
+ "initial-attachments-v1",
1642
1646
  ASSIGNMENT_EVIDENCE_PROTOCOL_FEATURE,
1643
1647
  FIRST_TURN_DEDUP_PROTOCOL_FEATURE,
1644
1648
  LEAD_EVIDENCE_PROTOCOL_FEATURE,
@@ -4799,6 +4803,8 @@ async function dispatchCommand(
4799
4803
  return hostCommands.taskProjectCompensate(ctx, expectTaskProjectFence(args[0], "task project compensate input"));
4800
4804
  case "taskProjectStatus":
4801
4805
  return hostCommands.taskProjectStatus(ctx, expectTaskProjectStatusInput(args, 0));
4806
+ case "initialAttachmentWrite":
4807
+ return hostCommands.initialAttachmentWrite(ctx, parseInitialAttachmentInput(args[0]));
4802
4808
  case "attachmentWrite":
4803
4809
  return hostCommands.attachmentWrite(
4804
4810
  ctx,
@@ -5829,6 +5835,7 @@ const HOST_COMMAND_NAMES = {
5829
5835
  taskProjectActivate: true,
5830
5836
  taskProjectCompensate: true,
5831
5837
  taskProjectStatus: true,
5838
+ initialAttachmentWrite: true,
5832
5839
  attachmentWrite: true,
5833
5840
  attachmentRead: true,
5834
5841
  workspaceFileRead: true,