@moondeck/station 1.0.5 → 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.
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
  }
@@ -1,6 +1,7 @@
1
1
  import type { TaskEnvironmentHandle } from "./task-environment/types";
2
2
  import { isEnvironmentTransportProvider } from "./task-environment/types";
3
3
  import { MACHINE_GATEWAY_TUNNEL_PORT } from "./machine-gateway-tunnel";
4
+ import { MACHINE_SSH_CONNECT_TIMEOUT_SECONDS } from "./machine-exec";
4
5
  import {
5
6
  installMachineProjectEnvLoader,
6
7
  installMachineTaskForwarderAsset,
@@ -23,16 +24,51 @@ type TaskForwarderNodePath =
23
24
  | "/usr/local/bin/node"
24
25
  | typeof APPLE_FORWARDER_NODE_PATH;
25
26
 
27
+ /**
28
+ * How long the launcher waits for the forwarder's READY (F5, test 6.2: 2 of 5
29
+ * AWS-host starts failed at the old 5 s). It must outlast the child's own
30
+ * verdict, so a slow child reports its own failure instead of being cut off:
31
+ * node start-up, then up to SECONDS of SECRET_INPUT_TIMEOUT_MS (5 s,
32
+ * uai-task-forwarder.mjs) reading the secret from stdin, then a loopback
33
+ * listen. The old 5 s deadline equalled that stdin budget alone.
34
+ */
35
+ export const TASK_FORWARDER_READY_SECONDS = 20;
36
+ /** Bound on stopping a previous forwarder before the new one starts. */
37
+ export const OLD_FORWARDER_STOP_SECONDS = 5;
38
+ /**
39
+ * The exec budget, built from what may happen before the launcher answers
40
+ * (review #tgxadc: an 8 s connect, a 5 s old-forwarder stop and a child
41
+ * ready at 18 s exceeded the old 30 s, and the kill took the diagnostics):
42
+ * ssh's connect and handshake (MACHINE_SSH_CONNECT_TIMEOUT_SECONDS, 10 s),
43
+ * the old-forwarder stop (5 s) and the READY wait (20 s), each measured on
44
+ * a whole-second clock (+1 s each), and 4 s for the remaining shell steps
45
+ * and the answer: 41 s. On a direct exec (no ssh) the connect term only
46
+ * adds slack. The launcher thus always answers, with its report, before
47
+ * the exec is killed.
48
+ */
49
+ export const LAUNCH_EXEC_TIMEOUT_MS =
50
+ (MACHINE_SSH_CONNECT_TIMEOUT_SECONDS + OLD_FORWARDER_STOP_SECONDS + 1 + TASK_FORWARDER_READY_SECONDS + 1 + 4) * 1_000;
51
+ /** The whole thrown message, in UTF-8 bytes. */
52
+ export const MAX_LAUNCH_ERROR_BYTES = 2_048;
53
+ const ERROR_LOG_TAIL_BYTES = 1_024;
54
+
26
55
  // Shared by initial machine provisioning and every recovery topology. Keep
27
56
  // the ownership/process proof in lockstep with task-up.sh's container
28
57
  // launcher. The generation secret arrives on stdin; no task file, argv entry,
29
58
  // or environment variable ever contains it.
30
- const START_TASK_FORWARDER = String.raw`set -eu
59
+ //
60
+ // On failure it names which one (the child exited, with its status, or was
61
+ // not ready in time) and appends the tail of the child's error.log, so the
62
+ // thrown error carries the real cause before any cleanup removes the machine.
63
+ export const START_TASK_FORWARDER = String.raw`set -eu
31
64
  task_id=$1
32
65
  generation=$2
33
66
  gateway_host=$3
34
67
  gateway_port=$4
35
68
  node_path=$5
69
+ ready_seconds=$6
70
+ case "$ready_seconds" in ''|*[!0-9]*) exit 1 ;; esac
71
+ [ "$ready_seconds" -ge 1 ] && [ "$ready_seconds" -le 25 ] || exit 1
36
72
  case "$node_path" in
37
73
  /usr/bin/node | /usr/local/bin/node) ;;
38
74
  ${APPLE_FORWARDER_NODE_PATH})
@@ -66,10 +102,11 @@ if [ -f "$pid_file" ] && [ ! -L "$pid_file" ]; then
66
102
  && printf '%s\n' "$old_args" | /bin/grep -Fxq '/usr/local/share/uai/uai-task-forwarder.mjs' \
67
103
  && printf '%s\n' "$old_args" | /bin/grep -Fxq "$task_id"; then
68
104
  /bin/kill -TERM "$old_pid"
69
- attempts=0
70
- while /bin/kill -0 "$old_pid" 2>/dev/null && [ "$attempts" -lt 50 ]; do
105
+ # Wall clock, so the stop stays within the exec budget however slow
106
+ # each fork is on a cold machine.
107
+ stop_deadline=$((SECONDS + ${OLD_FORWARDER_STOP_SECONDS}))
108
+ while /bin/kill -0 "$old_pid" 2>/dev/null && [ "$SECONDS" -lt "$stop_deadline" ]; do
71
109
  /bin/sleep 0.1
72
- attempts=$((attempts + 1))
73
110
  done
74
111
  if /bin/kill -0 "$old_pid" 2>/dev/null; then
75
112
  /bin/kill -KILL "$old_pid"
@@ -102,22 +139,91 @@ forwarder_pid=$!
102
139
  exec 3<&-
103
140
  printf '%s\n' "$forwarder_pid" > "$pid_file"
104
141
 
105
- attempts=0
106
- while [ "$attempts" -lt 50 ]; do
107
- /bin/kill -0 "$forwarder_pid" 2>/dev/null || exit 1
142
+ report_log() {
143
+ if [ -s "$error_file" ] && [ ! -L "$error_file" ]; then
144
+ printf '%s\n' "forwarder error.log (last ${ERROR_LOG_TAIL_BYTES} bytes):" >&2
145
+ /usr/bin/tail -c ${ERROR_LOG_TAIL_BYTES} "$error_file" >&2 || true
146
+ else
147
+ printf '%s\n' "forwarder error.log is empty" >&2
148
+ fi
149
+ }
150
+
151
+ # Wall clock, not an iteration count: on a cold machine each /bin/sleep fork
152
+ # is slow too, and the deadline must hold inside the exec budget.
153
+ deadline=$((SECONDS + ready_seconds))
154
+ while :; do
155
+ if ! /bin/kill -0 "$forwarder_pid" 2>/dev/null; then
156
+ status=0
157
+ wait "$forwarder_pid" || status=$?
158
+ printf '%s\n' "task env forwarder exited with status $status before it was ready" >&2
159
+ report_log
160
+ exit 1
161
+ fi
108
162
  if [ -f "$ready_file" ] \
109
163
  && [ "$(/bin/cat "$ready_file" 2>/dev/null || true)" = READY ]; then
110
164
  exit 0
111
165
  fi
166
+ # SECONDS counts whole seconds: -gt waits at least ready_seconds, at most
167
+ # one more.
168
+ if [ "$SECONDS" -gt "$deadline" ]; then
169
+ printf '%s\n' "task env forwarder was not ready within $ready_seconds s (pid $forwarder_pid still running)" >&2
170
+ report_log
171
+ exit 1
172
+ fi
112
173
  /bin/sleep 0.1
113
- attempts=$((attempts + 1))
114
- done
115
- exit 1`;
174
+ done`;
116
175
 
117
176
  export interface TaskEnvForwarderLaunchOptions {
118
177
  gatewayHost: string;
119
178
  gatewayPort: number;
120
179
  nodePath: TaskForwarderNodePath;
180
+ /** Test seam; production always uses TASK_FORWARDER_READY_SECONDS. */
181
+ readySeconds?: number;
182
+ }
183
+
184
+ /**
185
+ * The thrown message, at most MAX_LAUNCH_ERROR_BYTES of UTF-8 (review
186
+ * #tgxadc: the detail alone was bounded, and invalid bytes from the child's
187
+ * log grow threefold as U+FFFD). Keeps the launcher's verdict line (which
188
+ * failure, the child's status) and as much of the log's END as fits, the
189
+ * newest lines, cut between characters, never inside one.
190
+ */
191
+ export function launchFailureMessage(outcome: string, detail: string): string {
192
+ const head = `task env forwarder failed to start (${outcome})`;
193
+ const whole = detail ? `${head}: ${detail}` : head;
194
+ if (Buffer.byteLength(whole) <= MAX_LAUNCH_ERROR_BYTES) return whole;
195
+ const newline = detail.indexOf("\n");
196
+ const verdict = newline === -1 ? "" : detail.slice(0, newline);
197
+ const rest = newline === -1 ? detail : detail.slice(newline + 1);
198
+ const lead = `${head}: ${utf8Prefix(verdict, 512)}${verdict ? "\n" : ""}…`;
199
+ return lead + utf8Suffix(rest, MAX_LAUNCH_ERROR_BYTES - Buffer.byteLength(lead));
200
+ }
201
+
202
+ /** The longest prefix of `text` within `bytes` UTF-8 bytes, whole code points. */
203
+ function utf8Prefix(text: string, bytes: number): string {
204
+ let used = 0;
205
+ let out = "";
206
+ for (const char of text) {
207
+ const size = Buffer.byteLength(char);
208
+ if (used + size > bytes) break;
209
+ used += size;
210
+ out += char;
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /** The longest suffix of `text` within `bytes` UTF-8 bytes, whole code points. */
216
+ function utf8Suffix(text: string, bytes: number): string {
217
+ const chars = Array.from(text);
218
+ let used = 0;
219
+ let start = chars.length;
220
+ while (start > 0) {
221
+ const size = Buffer.byteLength(chars[start - 1]!);
222
+ if (used + size > bytes) break;
223
+ used += size;
224
+ start -= 1;
225
+ }
226
+ return chars.slice(start).join("");
121
227
  }
122
228
 
123
229
  /** Launch or replace one authenticated task forwarder. Consumes and wipes
@@ -149,11 +255,12 @@ export async function launchTaskEnvForwarder(
149
255
  options.gatewayHost,
150
256
  String(options.gatewayPort),
151
257
  options.nodePath,
258
+ String(options.readySeconds ?? TASK_FORWARDER_READY_SECONDS),
152
259
  ],
153
260
  user: "root",
154
261
  projectEnvProfile: "maintenance",
155
262
  stdin: secret,
156
- timeoutMs: 30_000,
263
+ timeoutMs: LAUNCH_EXEC_TIMEOUT_MS,
157
264
  maxOutputBytes: STEP_OUTPUT_BYTES,
158
265
  });
159
266
  if (
@@ -162,12 +269,11 @@ export async function launchTaskEnvForwarder(
162
269
  result.stdoutTruncated ||
163
270
  result.stderrTruncated
164
271
  ) {
165
- throw new Error(
166
- `task env forwarder failed to start: ${Buffer.from(result.stderr)
167
- .toString("utf8")
168
- .trim()
169
- .slice(-512) || `exit ${String(result.exitCode)}`}`,
170
- );
272
+ const detail = Buffer.from(result.stderr).toString("utf8").trim();
273
+ const outcome = result.signal !== null
274
+ ? `killed by ${result.signal} (the ${LAUNCH_EXEC_TIMEOUT_MS / 1000} s launch budget ran out)`
275
+ : `exit ${String(result.exitCode)}`;
276
+ throw new Error(launchFailureMessage(outcome, detail));
171
277
  }
172
278
  } finally {
173
279
  secret.fill(0);
@@ -1230,6 +1230,9 @@ export function createMachineHostTaskEnvironmentProvider(
1230
1230
  throw error;
1231
1231
  }
1232
1232
  return {
1233
+ // The Station posts the replacement note and, once the cloud has it,
1234
+ // clears the notice (src/index.ts): never before.
1235
+ ...(provisioned.lossNotices?.length ? { lossNotices: provisioned.lossNotices } : {}),
1233
1236
  handle: withTaskDownResult(handle),
1234
1237
  result: {
1235
1238
  // Recorded as the task's runtime identity (the compose-project
@@ -1241,6 +1244,7 @@ export function createMachineHostTaskEnvironmentProvider(
1241
1244
  ...(warnings.length > 0
1242
1245
  ? { initWarning: warnings.join("\n") }
1243
1246
  : {}),
1247
+ ...(provisioned.replacedLostEnvironment ? { environmentReplaced: true as const } : {}),
1244
1248
  },
1245
1249
  };
1246
1250
  },