@moondeck/station 1.0.4 → 1.0.6

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/src/main.ts CHANGED
@@ -1,8 +1,19 @@
1
1
  #!/usr/bin/env tsx
2
+ import { randomUUID } from "node:crypto";
2
3
  import { stationAgentCliAdvertisable } from "../lib/agent-cli";
4
+ import {
5
+ AGENT_DEPENDENCY_RECHECK_MS,
6
+ AgentDependencyMonitor,
7
+ agentDependencyFix,
8
+ currentHostOs,
9
+ runCheckDeps,
10
+ setAgentDependencyRecheckRequester,
11
+ type AgentDependencyRuntime,
12
+ } from "../lib/agent-dependencies";
3
13
  import { PREVIEW_UPSTREAM_PROTOCOL_FEATURE, parsePreviewUpstream, tunnelPreviewUpstream } from "./preview-upstream";
4
14
  import { preparePreviewUpstream, previewRequestHeaders, isPreviewConnectFailure } from "../lib/preview-upstream";
5
15
  import { describeClose, suspendedFor } from "./bridge-diagnostics";
16
+ import { startProcessWakeDetector } from "./process-wake";
6
17
  import { internalHostGatewayAdvertisable } from "../lib/custom-connection-launch";
7
18
  import "./load-env";
8
19
  import { discoverCustomConnection, saveCustomConnection, saveCustomConnectionManual } from "../lib/custom-connection-capture";
@@ -184,7 +195,8 @@ import {
184
195
  onContainerRuntimeChange,
185
196
  containerRuntimeRecheckRequester,
186
197
  setContainerRuntimeRecheckRequester,
187
- startContainerRuntimeAutoRecheck,
198
+ syncContainerRuntimeAutoRecheck,
199
+ nudgeContainerRuntimeAutoRecheck,
188
200
  suspendContainerRuntime,
189
201
  containerRuntimeMachineIdentity,
190
202
  pinnedContainerRuntimeMachineIdentity,
@@ -192,6 +204,7 @@ import {
192
204
  rejectContainerRuntimeSelection,
193
205
  reprobeContainerRuntimeMachineIdentity,
194
206
  } from "../lib/container-runtime";
207
+ import { startStandardImageMaintenanceSchedule } from "../lib/standard-image-schedule";
195
208
  import { machineTasksEnabled, persistedTaskEnvironmentsMatchMachine, reconstructPersistedTaskEnvironment } from "../lib/task-environment";
196
209
  import { reconcileRunningTaskPersonCredentials } from "../lib/task-person-credentials";
197
210
  import { logVnodePressure } from "../lib/vnode-pressure";
@@ -297,7 +310,7 @@ import {
297
310
  onAgentClisReady,
298
311
  standardRuntimes,
299
312
  } from "../lib/standard-image";
300
- import { hostCommands, hostEvents, setManagedHostRestartHook } from "./index";
313
+ import { hostCommands, hostEvents, setManagedHostRestartHook, setSystemNotePublisher } from "./index";
301
314
  import { EventOutbox, transmitEventOutbox } from "./event-outbox";
302
315
  import {
303
316
  HostErrorCode,
@@ -399,7 +412,9 @@ import {
399
412
  engineAccountScopeFromWire,
400
413
  isEngineAccountLabel,
401
414
  isEngineConnectKind,
415
+ isTaskNoteDurableAckFrame,
402
416
  } from "./protocol";
417
+ import { createTaskNotePublisher } from "./task-note-publisher";
403
418
  import { PROJECT_ENV_POLICY_EPOCHS } from "./project-env-policy";
404
419
  import {
405
420
  completeProjectEnvBindingCapabilityAfterRuntimeActivation,
@@ -522,7 +537,63 @@ const bridgeUrl =
522
537
  process.env.UAI_CLOUD_URL ?? `ws://127.0.0.1:${bridgePort}/host`;
523
538
 
524
539
  let ws: WebSocket | null = null;
540
+ /** Which note path the connected cloud supports, from its event.resume. */
541
+ const taskNotePublisher = createTaskNotePublisher({
542
+ sendDurable: (taskId, noteId, text) =>
543
+ ws?.readyState === WebSocket.OPEN ? publishDurableTaskNote(ws, taskId, noteId, text) : Promise.resolve(false),
544
+ publishLegacy: (taskId, text) => {
545
+ const seq = eventOutbox.enqueue({ kind: "system.note", taskId, text });
546
+ flushEvents();
547
+ return eventOutbox.whenAcked(seq);
548
+ },
549
+ });
550
+ /** task.note.durable requests awaiting the cloud's stored/refused answer. */
551
+ const durableNoteAcks = new Map<string, (stored: boolean) => void>();
552
+ const DURABLE_NOTE_ACK_TIMEOUT_MS = 30_000;
553
+
554
+ /** Ask the cloud to store a note once; true only once it says stored. */
555
+ function publishDurableTaskNote(socket: WebSocket, taskId: string, noteId: string, text: string): Promise<boolean> {
556
+ const opId = randomUUID().replaceAll("-", "");
557
+ return new Promise<boolean>((resolve) => {
558
+ const timer = setTimeout(() => {
559
+ if (durableNoteAcks.delete(opId)) resolve(false);
560
+ }, DURABLE_NOTE_ACK_TIMEOUT_MS);
561
+ timer.unref?.();
562
+ durableNoteAcks.set(opId, (stored) => {
563
+ clearTimeout(timer);
564
+ resolve(stored);
565
+ });
566
+ try {
567
+ send(socket, { kind: "task.note.durable", opId, taskId, noteId, text });
568
+ } catch {
569
+ durableNoteAcks.delete(opId);
570
+ clearTimeout(timer);
571
+ resolve(false);
572
+ }
573
+ });
574
+ }
525
575
  let stopping = false;
576
+
577
+ // Owner ask 4 (2026-11-09): the task scripts' dependency check, advertised
578
+ // as `agentDependencies` and never a gate (lib/agent-dependencies.ts). It
579
+ // follows the pinned runtime, so it runs only once one is pinned; the timer
580
+ // clears the state after an install without a restart.
581
+ const hostOs = currentHostOs();
582
+ const agentDependencies = new AgentDependencyMonitor({
583
+ check: (runtime) => runCheckDeps(runtime),
584
+ fix: (missing) => agentDependencyFix(missing, hostOs),
585
+ changed: () => sendCapabilities(),
586
+ warn: (message) => console.warn(message),
587
+ });
588
+ function agentDependencyRuntime(): AgentDependencyRuntime | null {
589
+ if (sidecarMode()) return null;
590
+ const runtime = containerRuntimeState();
591
+ return runtime.status === "ready" ? runtime.provider : null;
592
+ }
593
+ function recheckAgentDependencies(): void {
594
+ if (stopping) return;
595
+ void agentDependencies.recheck(agentDependencyRuntime());
596
+ }
526
597
  const openRouterBudgets = new OpenRouterBudgetPoller({ emit: frame => {
527
598
  if (!stopping && credentialFramesReady && ws?.readyState === WebSocket.OPEN) send(ws, frame);
528
599
  } });
@@ -619,6 +690,7 @@ const pendingRuntimeIsolationStatuses = new StoppedTaskStatusQueue(
619
690
  },
620
691
  );
621
692
  let stopRuntimeAutoRecheck = (): void => {};
693
+ let stopProcessWakeDetector = (): void => {};
622
694
  const runtimeActivationTail = new RuntimeActivationTail({
623
695
  isCurrent: runtimeActivationIsCurrent,
624
696
  onError: reportRuntimeActivationError,
@@ -954,10 +1026,13 @@ function reconcileStores(): Promise<void> {
954
1026
  // UAI_IMAGE_MAINTENANCE=external — a cloud job keeps the payload AMI fresh —
955
1027
  // and reconciles only once, at start. A sidecar (ADR-133) has no image.
956
1028
  if (env.UAI_IMAGE_MAINTENANCE === "host" && !sidecarMode()) {
957
- const maintenanceTimer = setInterval(() => {
958
- void ensureStandardImage().catch(() => undefined);
959
- }, MAINTENANCE_INTERVAL_MS);
960
- maintenanceTimer.unref?.();
1029
+ startStandardImageMaintenanceSchedule({
1030
+ intervalMs: MAINTENANCE_INTERVAL_MS,
1031
+ // The public state: `ready` only once activation's fences (persisted
1032
+ // environment identity, writable-container quarantine) have released it.
1033
+ runtimeStatus: () => containerRuntimeCapabilityState().status,
1034
+ run: () => ensureStandardImage(),
1035
+ });
961
1036
  }
962
1037
  // ADR-135: one refresher per rotating credential. Owned host → the in-process
963
1038
  // loop refreshes and re-pushes; Uai-operated host → the broker Lambda
@@ -1303,6 +1378,13 @@ hostEvents.subscribe((event) => {
1303
1378
  eventOutbox.enqueue(event);
1304
1379
  flushEvents();
1305
1380
  });
1381
+ // F6 (review #tgxadc): a note whose delivery decides what the runner forgets
1382
+ // waits for the cloud's ack of its own outbox entry.
1383
+ // A cloud that stores the note before it acks, once per noteId (review
1384
+ // #mta79m), is asked directly. Only a cloud confirmed not to support that
1385
+ // gets the legacy outbox event, acked once handed to its router; until the
1386
+ // connection has negotiated, a note waits (src/task-note-publisher.ts).
1387
+ setSystemNotePublisher((taskId, text, noteId) => taskNotePublisher.publish(taskId, text, noteId));
1306
1388
  // ADR-153: the secrets proxy starts before the gateway generations are
1307
1389
  // recovered, so their env resolvers already see it, and registers as the
1308
1390
  // gateway's TLS consumer. Null under the kill switch (UAI_SECRETS_PROXY=off),
@@ -1654,6 +1736,8 @@ function buildCapabilities(): HostCapabilities {
1654
1736
  githubUsers: connectedUserIds(),
1655
1737
  // ADR-154 §13: where the switch to cloud credentials stands, and why.
1656
1738
  credentialsSwitch: credentialsActivation.status(),
1739
+ // Owner ask 4: what the task scripts lack on PATH. Report-only.
1740
+ ...(agentDependencies.state() === undefined ? {} : { agentDependencies: agentDependencies.state() }),
1657
1741
  };
1658
1742
  }
1659
1743
 
@@ -2155,17 +2239,16 @@ setAdvertisementFallback((kind) => hasStoredEngineAccounts(kind));
2155
2239
  // says: the leased lanes and the Managed Engine, which leases nothing (Kimi,
2156
2240
  // with no lane yet, is left out).
2157
2241
  setLeasedAdvertisement(() => (credentialsMode() === "active" ? CLOUD_CREDENTIAL_KINDS : null));
2242
+ setAgentDependencyRecheckRequester(recheckAgentDependencies);
2243
+ recheckAgentDependencies();
2244
+ setInterval(recheckAgentDependencies, AGENT_DEPENDENCY_RECHECK_MS).unref();
2158
2245
  onRegistryChange(() => sendCapabilities());
2159
2246
  onContainerRuntimeChange((next, previous) => {
2160
2247
  if (stopping) return;
2161
2248
  sendCapabilities();
2162
- if (next.status === "ready") {
2163
- stopRuntimeAutoRecheck();
2164
- stopRuntimeAutoRecheck = () => {};
2165
- } else if (previous.status === "ready") {
2166
- stopRuntimeAutoRecheck();
2167
- stopRuntimeAutoRecheck = startContainerRuntimeAutoRecheck();
2168
- }
2249
+ recheckAgentDependencies();
2250
+ // Idempotent: never a second loop, and a running one keeps its backoff.
2251
+ stopRuntimeAutoRecheck = syncContainerRuntimeAutoRecheck();
2169
2252
  if (
2170
2253
  containerRuntimeBecameReady(next, previous) ||
2171
2254
  containerRuntimeActivationRequired()
@@ -2176,8 +2259,15 @@ onContainerRuntimeChange((next, previous) => {
2176
2259
  );
2177
2260
  }
2178
2261
  });
2179
- stopRuntimeAutoRecheck = startContainerRuntimeAutoRecheck();
2262
+ stopRuntimeAutoRecheck = syncContainerRuntimeAutoRecheck();
2180
2263
  installContainerRuntimeRecheckRequester();
2264
+ // A wake is when a daemon hung in sleep/dark-wake comes back: an unavailable
2265
+ // runtime is probed now, not at its next backoff step. Process-level, so a
2266
+ // Mac that lost its bridge before sleeping still nudges; the per-connection
2267
+ // suspended-for warning in connect() only logs. A no-op while ready.
2268
+ stopProcessWakeDetector = startProcessWakeDetector({
2269
+ onWake: () => void nudgeContainerRuntimeAutoRecheck("system wake detected"),
2270
+ });
2181
2271
  // Re-advertise when a gh token is added/removed (ADR-033) so the host page's
2182
2272
  // per-host connected state updates promptly.
2183
2273
  onGithubChange(() => sendCapabilities());
@@ -3145,6 +3235,7 @@ async function connect(): Promise<void> {
3145
3235
  case "pong":
3146
3236
  break;
3147
3237
  case "event.resume":
3238
+ taskNotePublisher.negotiated(frame.features ?? []);
3148
3239
  bridgeResumed();
3149
3240
  // ADR-103: the cloud named its watermark — rewind the transmit
3150
3241
  // cursor to it (null = no state, replay nothing) and start draining.
@@ -3163,6 +3254,14 @@ async function connect(): Promise<void> {
3163
3254
  case "task.machine.retire.ack":
3164
3255
  taskFilesMachineRetirementOutbox?.acknowledge(frame);
3165
3256
  break;
3257
+ case "task.note.durable.ack": {
3258
+ const pending = durableNoteAcks.get(frame.opId);
3259
+ if (pending) {
3260
+ durableNoteAcks.delete(frame.opId);
3261
+ pending(frame.outcome === "stored");
3262
+ }
3263
+ break;
3264
+ }
3166
3265
  case "command":
3167
3266
  void handleCommand(socket, frame);
3168
3267
  break;
@@ -3964,6 +4063,13 @@ async function connect(): Promise<void> {
3964
4063
 
3965
4064
  socket.on("close", (code, reason) => {
3966
4065
  cleanup();
4066
+ // A note this connection carried is not known stored: the next start
4067
+ // sends it again, and the cloud keeps one per noteId.
4068
+ for (const [opId, settle] of durableNoteAcks) {
4069
+ durableNoteAcks.delete(opId);
4070
+ settle(false);
4071
+ }
4072
+ taskNotePublisher.disconnected();
3967
4073
  const text = reason.toString("utf8");
3968
4074
  if (stopping) {
3969
4075
  markDisconnected();
@@ -4976,8 +5082,12 @@ function parseCloudFrame(data: RawData): CloudToHost | null {
4976
5082
  frame.kind === "event.resume" &&
4977
5083
  (frame.afterSeq === null || typeof frame.afterSeq === "number")
4978
5084
  ) {
4979
- return { kind: "event.resume", afterSeq: frame.afterSeq };
5085
+ const features = Array.isArray(frame.features)
5086
+ ? frame.features.filter((feature): feature is string => typeof feature === "string" && feature.length <= 64).slice(0, 64)
5087
+ : undefined;
5088
+ return { kind: "event.resume", afterSeq: frame.afterSeq, ...(features ? { features } : {}) };
4980
5089
  }
5090
+ if (isTaskNoteDurableAckFrame(frame)) return frame;
4981
5091
  if (frame.kind === "event.ack" && typeof frame.seq === "number") {
4982
5092
  return { kind: "event.ack", seq: frame.seq };
4983
5093
  }
@@ -5555,6 +5665,7 @@ function rejectFrameDuringShutdown(
5555
5665
  case "pong":
5556
5666
  case "event.resume":
5557
5667
  case "event.ack":
5668
+ case "task.note.durable.ack":
5558
5669
  case "tunnel.data":
5559
5670
  case "tunnel.requestEnd":
5560
5671
  case "tunnel.close":
@@ -6298,6 +6409,7 @@ function requestShutdown(signal: NodeJS.Signals): void {
6298
6409
  }
6299
6410
  void mcpGateway.stop();
6300
6411
  managedMutationDrain.stopAccepting();
6412
+ stopProcessWakeDetector();
6301
6413
  stopRuntimeAutoRecheck();
6302
6414
  runtimeActivationTail.stop();
6303
6415
  shutdownRequested = true;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Process-level suspend detector: one unref'd interval for the life of the
3
+ * process, independent of the bridge. The per-connection check in connect()
4
+ * only runs while a socket is open, so a Mac that dropped its connection
5
+ * before it slept never reported its wake (and an unavailable container
6
+ * runtime waited for its next backoff step instead of being probed).
7
+ */
8
+
9
+ import { suspendedFor } from "./bridge-diagnostics";
10
+
11
+ export const PROCESS_WAKE_TICK_MS = 5_000;
12
+
13
+ export function startProcessWakeDetector(deps: {
14
+ onWake: (suspendedMs: number) => void;
15
+ intervalMs?: number;
16
+ now?: () => number;
17
+ }): () => void {
18
+ const intervalMs = deps.intervalMs ?? PROCESS_WAKE_TICK_MS;
19
+ const now = deps.now ?? Date.now;
20
+ let lastTick = now();
21
+ const timer = setInterval(() => {
22
+ const at = now();
23
+ const suspended = suspendedFor(lastTick, at, intervalMs);
24
+ lastTick = at;
25
+ if (suspended === null) return;
26
+ try {
27
+ deps.onWake(suspended);
28
+ } catch (error) {
29
+ console.warn(
30
+ `[host-agent] wake handler failed: ${error instanceof Error ? error.message : String(error)}`,
31
+ );
32
+ }
33
+ }, intervalMs);
34
+ timer.unref?.();
35
+ return () => clearInterval(timer);
36
+ }
package/src/protocol.ts CHANGED
@@ -4202,6 +4202,11 @@ export interface HostCapabilities {
4202
4202
  * what stops it. Optional: hosts before 0.9.171 omit it, and the cloud
4203
4203
  * then says only that the runner has not switched. */
4204
4204
  credentialsSwitch?: CredentialsSwitchCapability;
4205
+ /** What this Station's task scripts need on PATH and lack (their own gate,
4206
+ * scripts/agent/_deps.sh). Report-only: the Station never refuses a task
4207
+ * over it. Absent while unchecked (runtime not ready, sidecar mode) and on
4208
+ * Stations before 1.0.5. The cloud drops a malformed one alone. */
4209
+ agentDependencies?: AgentDependencyCapability;
4205
4210
  }
4206
4211
 
4207
4212
  /**
@@ -4241,6 +4246,54 @@ export const MAX_CREDENTIALS_SWITCH_BLOCKERS = 20;
4241
4246
  export const MAX_CREDENTIALS_SWITCH_BLOCKER_CHARS = 300;
4242
4247
  export const MAX_CREDENTIALS_SWITCH_PROJECTS = 100;
4243
4248
 
4249
+ /**
4250
+ * The task scripts' dependency check, as the Station last ran it
4251
+ * (check-deps.sh). `missing` names binaries (`sqlite3`, `docker`, …) and
4252
+ * `docker-compose-plugin`; `fix` is a copyable command for this machine's
4253
+ * OS when the Station knows one (e.g. `sudo dnf install -y sqlite` on
4254
+ * Amazon Linux 2023). The Compose plugin has no such package there.
4255
+ */
4256
+ export type AgentDependencyCapability =
4257
+ | { status: "ok" }
4258
+ | { status: "missing"; missing: string[]; fix?: string };
4259
+
4260
+ export const MAX_AGENT_DEPENDENCIES = 8;
4261
+ export const MAX_AGENT_DEPENDENCY_FIX_CHARS = 200;
4262
+ /** A dependency name: a binary on PATH, or `docker-compose-plugin`. */
4263
+ export const AGENT_DEPENDENCY_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/;
4264
+
4265
+ /** The capability, exact and bounded; undefined when it is not one. The
4266
+ * cloud drops a malformed one alone, never the frame around it. */
4267
+ export function parseAgentDependencyCapability(value: unknown): AgentDependencyCapability | undefined {
4268
+ if (!isPlainRecord(value)) return undefined;
4269
+ if (value.status === "ok") {
4270
+ return Object.keys(value).length === 1 ? { status: "ok" } : undefined;
4271
+ }
4272
+ if (value.status !== "missing") return undefined;
4273
+ if (Object.keys(value).some((key) => key !== "status" && key !== "missing" && key !== "fix")) return undefined;
4274
+ const { missing, fix } = value;
4275
+ if (
4276
+ !Array.isArray(missing) ||
4277
+ missing.length < 1 ||
4278
+ missing.length > MAX_AGENT_DEPENDENCIES ||
4279
+ !missing.every((name) => typeof name === "string" && AGENT_DEPENDENCY_NAME.test(name)) ||
4280
+ new Set(missing).size !== missing.length
4281
+ ) {
4282
+ return undefined;
4283
+ }
4284
+ if (fix === undefined) return { status: "missing", missing: [...missing] as string[] };
4285
+ if (
4286
+ typeof fix !== "string" ||
4287
+ fix.trim().length === 0 ||
4288
+ fix.length > MAX_AGENT_DEPENDENCY_FIX_CHARS ||
4289
+ // One line, printable: it is shown as a copyable command.
4290
+ !/^[\x20-\x7e]+$/.test(fix)
4291
+ ) {
4292
+ return undefined;
4293
+ }
4294
+ return { status: "missing", missing: [...missing] as string[], fix };
4295
+ }
4296
+
4244
4297
  /** The capability, exact and bounded; undefined when it is not one. The
4245
4298
  * cloud drops a malformed one alone, never the frame around it. */
4246
4299
  export function parseCredentialsSwitchCapability(value: unknown): CredentialsSwitchCapability | undefined {
@@ -4348,6 +4401,10 @@ export interface TaskUpResult {
4348
4401
  envSchemas?: ProjectEnvSchemaObservation[];
4349
4402
  /** Degraded start: uai-init failed twice; the task is up without deps/editor. */
4350
4403
  initWarning?: string;
4404
+ /** F6: this start replaced the task's terminated machine with a fresh one
4405
+ * (work only on the old machine is gone). The Station posts its own feed
4406
+ * note; the cloud may ignore the flag. */
4407
+ environmentReplaced?: true;
4351
4408
  }
4352
4409
 
4353
4410
  export interface TaskDownResult {
@@ -4969,6 +5026,60 @@ export interface TaskMachineRetireFrame {
4969
5026
 
4970
5027
  /** Durable acceptance, not completion: after `accepted` the cloud owns
4971
5028
  * retrying the persisted exact-instance stop even if this socket disappears. */
5029
+ /**
5030
+ * F6 (review #mta79m): a feed note the Station must know is stored, the
5031
+ * machine-replaced warning. The cloud stores it once per (task, noteId) and
5032
+ * acks only after the row is committed; a storage failure gets no ack, and
5033
+ * the Station tries again at the task's next start. Sent only to a cloud that
5034
+ * advertised DURABLE_TASK_NOTE_FEATURE in its event.resume.
5035
+ */
5036
+ export interface TaskNoteDurableFrame {
5037
+ kind: "task.note.durable";
5038
+ opId: string;
5039
+ taskId: string;
5040
+ /** The note's identity; the same id is stored at most once per task. */
5041
+ noteId: string;
5042
+ text: string;
5043
+ }
5044
+
5045
+ export interface TaskNoteDurableAckFrame {
5046
+ kind: "task.note.durable.ack";
5047
+ opId: string;
5048
+ /** stored: committed now or earlier; refused: never (not this host's task). */
5049
+ outcome: "stored" | "refused";
5050
+ }
5051
+
5052
+ export const DURABLE_TASK_NOTE_FEATURE = "durable-task-note-v1";
5053
+ export const MAX_DURABLE_TASK_NOTE_ID_CHARS = 128;
5054
+ export const MAX_DURABLE_TASK_NOTE_BYTES = 4 * 1024;
5055
+
5056
+ export function isTaskNoteDurableFrame(value: unknown): value is TaskNoteDurableFrame {
5057
+ const frame = exactWireObject(value, ["kind", "opId", "taskId", "noteId", "text"]);
5058
+ return Boolean(
5059
+ frame &&
5060
+ frame.kind === "task.note.durable" &&
5061
+ isHostOpId(frame.opId) &&
5062
+ isTaskMachineRetireTaskId(frame.taskId) &&
5063
+ typeof frame.noteId === "string" &&
5064
+ frame.noteId.length > 0 &&
5065
+ frame.noteId.length <= MAX_DURABLE_TASK_NOTE_ID_CHARS &&
5066
+ /^[A-Za-z0-9@._:-]+$/.test(frame.noteId) &&
5067
+ typeof frame.text === "string" &&
5068
+ frame.text.trim().length > 0 &&
5069
+ utf8ByteLength(frame.text) <= MAX_DURABLE_TASK_NOTE_BYTES,
5070
+ );
5071
+ }
5072
+
5073
+ export function isTaskNoteDurableAckFrame(value: unknown): value is TaskNoteDurableAckFrame {
5074
+ const frame = exactWireObject(value, ["kind", "opId", "outcome"]);
5075
+ return Boolean(
5076
+ frame &&
5077
+ frame.kind === "task.note.durable.ack" &&
5078
+ isHostOpId(frame.opId) &&
5079
+ (frame.outcome === "stored" || frame.outcome === "refused"),
5080
+ );
5081
+ }
5082
+
4972
5083
  export interface TaskMachineRetireAckFrame {
4973
5084
  kind: "task.machine.retire.ack";
4974
5085
  opId: string;
@@ -5133,7 +5244,13 @@ export type CloudToHost =
5133
5244
  // replays every outbox entry with seq > afterSeq. `null` means the cloud
5134
5245
  // has no watermark for this boot (fresh boot, or lost KV) — the host sends
5135
5246
  // only entries it never transmitted, replaying nothing.
5136
- | { kind: "event.resume"; afterSeq: number | null }
5247
+ | {
5248
+ kind: "event.resume";
5249
+ afterSeq: number | null;
5250
+ /** What this cloud supports beyond the base protocol (absent: none).
5251
+ * Older Stations read only afterSeq. */
5252
+ features?: string[];
5253
+ }
5137
5254
  // ADR-103: cumulative — the host trims outbox entries with seq <= seq.
5138
5255
  | { kind: "event.ack"; seq: number }
5139
5256
  // ADR-133 leases: the cloud's answer to a sidecar's `lease.request`.
@@ -5148,6 +5265,7 @@ export type CloudToHost =
5148
5265
  | CredentialRefreshResultFrame
5149
5266
  | CredentialsActivateResultFrame
5150
5267
  | TaskMachineRetireAckFrame
5268
+ | TaskNoteDurableAckFrame
5151
5269
  | McpCaptureProbeFrame
5152
5270
  | McpCaptureCompleteFrame
5153
5271
  | McpCaptureCancelFrame
@@ -5298,6 +5416,7 @@ export type HostToCloud =
5298
5416
  | CredentialsActivateFrame
5299
5417
  | CredentialsActivatedFrame
5300
5418
  | TaskMachineRetireFrame
5419
+ | TaskNoteDurableFrame
5301
5420
  | McpCaptureAckFrame
5302
5421
  | PersonCaptureAckFrame
5303
5422
  | GithubRevokeAckFrame
@@ -0,0 +1,65 @@
1
+ /**
2
+ * How the Station publishes a note whose delivery decides what it forgets
3
+ * (F6, the machine-replaced warning). A cloud that advertised
4
+ * DURABLE_TASK_NOTE_FEATURE in its event.resume stores the note once per
5
+ * noteId before it acks (task.note.durable). Only a cloud CONFIRMED not to
6
+ * have it gets the legacy system.note event, which carries no noteId. Until
7
+ * the current connection has negotiated (disconnected, or before its
8
+ * event.resume), a note waits rather than taking the legacy path with a cloud
9
+ * that may support the durable one (review follow-up on cd295336).
10
+ */
11
+ import { DURABLE_TASK_NOTE_FEATURE } from "./protocol";
12
+
13
+ export interface TaskNotePublisherDeps {
14
+ /** task.note.durable on the open connection; true once stored. */
15
+ sendDurable(taskId: string, noteId: string, text: string): Promise<boolean>;
16
+ /** The legacy system.note event; true once the cloud acked its entry. */
17
+ publishLegacy(taskId: string, text: string): Promise<boolean>;
18
+ }
19
+
20
+ export interface TaskNotePublisher {
21
+ /** The connection's event.resume arrived, with what the cloud advertised. */
22
+ negotiated(features: readonly string[]): void;
23
+ /** The connection closed: what the next cloud supports is unknown again. */
24
+ disconnected(): void;
25
+ publish(taskId: string, text: string, noteId: string): Promise<boolean>;
26
+ }
27
+
28
+ type Mode = "unknown" | "durable" | "legacy";
29
+
30
+ export function createTaskNotePublisher(deps: TaskNotePublisherDeps): TaskNotePublisher {
31
+ let mode: Mode = "unknown";
32
+ /** Bumped by every negotiation and disconnect: which connection's verdict
33
+ * `mode` is. */
34
+ let generation = 0;
35
+ let waiters: Array<() => void> = [];
36
+ const negotiation = (): Promise<void> =>
37
+ mode === "unknown" ? new Promise((resolve) => waiters.push(resolve)) : Promise.resolve();
38
+ return {
39
+ negotiated(features) {
40
+ mode = features.includes(DURABLE_TASK_NOTE_FEATURE) ? "durable" : "legacy";
41
+ generation += 1;
42
+ const ready = waiters;
43
+ waiters = [];
44
+ for (const resolve of ready) resolve();
45
+ },
46
+ disconnected() {
47
+ mode = "unknown";
48
+ generation += 1;
49
+ },
50
+ async publish(taskId, text, noteId) {
51
+ // Review #de9k8j: a verdict read before an await may belong to a
52
+ // connection that has since closed, and the next one may have
53
+ // negotiated differently. Decide only on the mode read in the same turn
54
+ // as the send, and wait again whenever it is unknown or changed.
55
+ for (;;) {
56
+ const seen = mode === "unknown" ? -1 : generation;
57
+ await negotiation();
58
+ if (mode !== "unknown" && (seen === -1 || seen === generation)) break;
59
+ }
60
+ return mode === "durable"
61
+ ? deps.sendDurable(taskId, noteId, text)
62
+ : deps.publishLegacy(taskId, text);
63
+ },
64
+ };
65
+ }