@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/src/index.ts CHANGED
@@ -33,6 +33,7 @@ import { cloneRepo } from "../lib/repo-clone";
33
33
  import { handleFilesOp } from "../lib/shared-files";
34
34
  import type { SharedFilesMode } from "../lib/shared-files-s3";
35
35
  import {
36
+ abandonTaskRecovery,
36
37
  getOrchestrator,
37
38
  inspectTaskRuntimeContainer,
38
39
  proveAppleTaskRuntimeContract,
@@ -241,7 +242,7 @@ export type {
241
242
  PreviewPortDeclaration,
242
243
  PreviewPortRuntime,
243
244
  } from "../lib/preview-ports";
244
- import { isEnvironmentTransportProvider } from "../lib/task-environment/types";
245
+ import { isEnvironmentTransportProvider, type EnvironmentLossNotice } from "../lib/task-environment/types";
245
246
  import { awaitSidecarReady, sidecarMode } from "../lib/sidecar";
246
247
  import { guardSidecarMachine } from "../lib/sidecar-guard";
247
248
  import { projectEnvBindingCapability } from "../lib/project-env-feature";
@@ -1279,6 +1280,7 @@ async function taskUpOn(
1279
1280
  }
1280
1281
  recordHostEvent(input.task.id, "task.created");
1281
1282
  let environmentLocator: TaskEnvironmentLocator | undefined;
1283
+ let machineLossNotices: readonly EnvironmentLossNotice[] = [];
1282
1284
  // The locator of everything this start may create, recorded before any
1283
1285
  // of it exists: once set, the row must keep it.
1284
1286
  let runtimePrepared = false;
@@ -1405,6 +1407,7 @@ async function taskUpOn(
1405
1407
  recordPrepared,
1406
1408
  );
1407
1409
  environmentLocator = provisioned.handle.descriptor.locator;
1410
+ machineLossNotices = provisioned.lossNotices ?? [];
1408
1411
  // ADR-153 §4: the task's own schema observations, read from the
1409
1412
  // bases task-up recorded before its container started (a machine
1410
1413
  // captures its own). Stored once; a resume reuses them.
@@ -1515,6 +1518,13 @@ async function taskUpOn(
1515
1518
  }`,
1516
1519
  );
1517
1520
  }
1521
+ // F6: Resume found the task's machine terminated and launched a fresh
1522
+ // one from the task's branch. Say so before anyone looks for work that
1523
+ // was only on the old machine's disk.
1524
+ // One note per lost machine, oldest first, one at a time.
1525
+ if (machineLossNotices.length > 0) {
1526
+ void deliverMachineLossNotices(input.task.id, machineLossNotices);
1527
+ }
1518
1528
  // Degraded start (uai-init failed twice): the task is up, but say so
1519
1529
  // in the feed — a silent half-start reads as a broken product.
1520
1530
  if (result.value.initWarning) {
@@ -1705,6 +1715,16 @@ export const hostCommands: HostCommands = {
1705
1715
  async taskDown(ctx, input) {
1706
1716
  logCommand(ctx, "taskDown", input.taskId);
1707
1717
  const orphanGc = input.cleanup?.kind === "orphan-gc";
1718
+ // F4: deletion is terminal intent. Before queueing behind the task's
1719
+ // lifecycle slot, end what would otherwise keep running ahead of it: the
1720
+ // machine gateway tunnel's respawn loop, and the task's boot recovery
1721
+ // retries, whose barrier the slot waits on. Only for the run this
1722
+ // teardown names: a delayed teardown of an older run must leave the
1723
+ // newer one alone (the exact check repeats inside the slot).
1724
+ if (teardownNamesCurrentRun(input, orphanGc)) {
1725
+ stopMachineGatewayTunnel(input.taskId);
1726
+ abandonTaskRecovery(input.taskId);
1727
+ }
1708
1728
  // ADR-154: teardown ends its run's start (orphan GC: every start of the
1709
1729
  // task) before it queues behind it.
1710
1730
  const interrupting = activeCloudCredentials();
@@ -2494,6 +2514,119 @@ function taskEnvironmentStatusResult(status: TaskEnvironmentStatus) {
2494
2514
  };
2495
2515
  }
2496
2516
 
2517
+ /** Whether a teardown will pass its in-slot run check (taskDown below):
2518
+ * orphan GC always; otherwise exactly the current assignment's epoch, or a
2519
+ * v0 teardown of a task that has no v1 assignment. Read before the slot,
2520
+ * so only for releasing work that is safe to stop early. */
2521
+ function teardownNamesCurrentRun(input: TaskDownInput, orphanGc: boolean): boolean {
2522
+ if (orphanGc) return true;
2523
+ const runEpoch = input.task?.runEpoch;
2524
+ const state = readTaskRunEpochState(input.taskId);
2525
+ if (runEpoch === undefined) return state === null;
2526
+ return state !== null && state.highestRunEpoch === runEpoch;
2527
+ }
2528
+
2529
+ /** Resolves true only once the cloud holds the note; `noteId` lets a cloud
2530
+ * that stores notes durably keep at most one per (task, noteId). */
2531
+ type SystemNotePublisher = (taskId: string, text: string, noteId: string) => Promise<boolean>;
2532
+ let systemNotePublisher: SystemNotePublisher | null = null;
2533
+
2534
+ /** main.ts binds the outbox-acknowledged publisher. Without one (tests, other
2535
+ * entry points) a note is emitted and taken as published. */
2536
+ export function setSystemNotePublisher(publisher: SystemNotePublisher | null): void {
2537
+ systemNotePublisher = publisher;
2538
+ }
2539
+
2540
+ /** Loss notices the cloud confirmed in this process, by task and loss id:
2541
+ * if clearing one failed, the next start only retries the clearing. */
2542
+ const confirmedLossNotices = new Set<string>();
2543
+ /** The delivery under way per task. Each start's run queues behind it, so a
2544
+ * task never has two notices attempted at once (review #2cp6r4). */
2545
+ const lossNoticeDeliveries = new Map<string, Promise<void>>();
2546
+
2547
+ /**
2548
+ * F6 (reviews #tgxadc, #2cp6r4): tell the user their old machines are gone,
2549
+ * each exactly once. A task's notices go one at a time, oldest first, behind
2550
+ * any delivery already under way for the task. Each is marked attempted
2551
+ * (persisted, never undone) before its first publish and resent unchanged on
2552
+ * every retry. The next is attempted only once the current one is
2553
+ * acknowledged and cleared, so at most one notice per task is ever attempted
2554
+ * but unacknowledged. A crash, a refused publication or a lost ack stops the
2555
+ * run; the next start resumes from that same notice.
2556
+ */
2557
+ export function deliverMachineLossNotices(
2558
+ taskId: string,
2559
+ notices: readonly EnvironmentLossNotice[],
2560
+ ): Promise<void> {
2561
+ const previous = lossNoticeDeliveries.get(taskId) ?? Promise.resolve();
2562
+ const run = previous.then(async () => {
2563
+ for (const notice of notices) {
2564
+ if (!(await deliverOnce(taskId, notice))) return;
2565
+ }
2566
+ });
2567
+ const tracked = run.finally(() => {
2568
+ if (lossNoticeDeliveries.get(taskId) === tracked) lossNoticeDeliveries.delete(taskId);
2569
+ });
2570
+ lossNoticeDeliveries.set(taskId, tracked);
2571
+ return tracked;
2572
+ }
2573
+
2574
+ /** True once the notice is delivered and cleared (or already gone). */
2575
+ async function deliverOnce(taskId: string, notice: EnvironmentLossNotice): Promise<boolean> {
2576
+ const key = `${taskId}\u0000${notice.id}`;
2577
+ if (!confirmedLossNotices.has(key)) {
2578
+ // Persisted BEFORE the publish: from here on the entry is immutable, and
2579
+ // the text below is what it carries for good. A mark that cannot be
2580
+ // written sends nothing.
2581
+ let lostEnvironments: number | null;
2582
+ try {
2583
+ lostEnvironments = notice.markAttempted();
2584
+ } catch (error) {
2585
+ console.warn(`[machine] task ${taskId}: could not mark the machine-replaced note attempted; the next start sends it: ${error instanceof Error ? error.message : String(error)}`);
2586
+ return false;
2587
+ }
2588
+ // Cleared by an earlier run meanwhile.
2589
+ if (lostEnvironments === null) return true;
2590
+ const text = machineReplacedNote({ lostEnvironments });
2591
+ let published = false;
2592
+ try {
2593
+ published = systemNotePublisher
2594
+ ? await systemNotePublisher(taskId, text, `machine-loss:${notice.id}`)
2595
+ : (getOrchestrator().emitSystemNote(taskId, text), true);
2596
+ } catch (error) {
2597
+ console.warn(`[machine] task ${taskId}: posting the machine-replaced note failed: ${error instanceof Error ? error.message : String(error)}`);
2598
+ }
2599
+ if (!published) {
2600
+ console.warn(`[machine] task ${taskId}: the machine-replaced note was not confirmed; the next start resends it unchanged`);
2601
+ return false;
2602
+ }
2603
+ confirmedLossNotices.add(key);
2604
+ }
2605
+ try {
2606
+ notice.acknowledge();
2607
+ } catch (error) {
2608
+ // Still attempted on disk: the next notice must wait for this clearing.
2609
+ console.warn(`[machine] task ${taskId}: could not clear the machine-replaced notice: ${error instanceof Error ? error.message : String(error)}`);
2610
+ return false;
2611
+ }
2612
+ return true;
2613
+ }
2614
+
2615
+ /** The note for one loss, or for a summary of several (review #d0p42f). */
2616
+ export function machineReplacedNote(notice: Pick<EnvironmentLossNotice, "lostEnvironments">): string {
2617
+ const count = notice.lostEnvironments ?? 1;
2618
+ if (count <= 1) return MACHINE_REPLACED_NOTE;
2619
+ return (
2620
+ `${String(count)} of this task's machines had been terminated, so this start launched a new one and set the task up again from its branch. ` +
2621
+ "Anything on those machines that was not pushed (uncommitted or unpushed changes, local files) is gone."
2622
+ );
2623
+ }
2624
+
2625
+ /** F6: the feed note for a start that replaced a terminated machine. */
2626
+ export const MACHINE_REPLACED_NOTE =
2627
+ "This task's machine had been terminated, so this start launched a new one and set the task up again from its branch. " +
2628
+ "Anything on the old machine that was not pushed (uncommitted or unpushed changes, local files) is gone.";
2629
+
2497
2630
  function taskDownResultForInput(
2498
2631
  input: TaskDownInput,
2499
2632
  providerResult: TaskDownResult,
package/src/main.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env tsx
2
+ import { randomUUID } from "node:crypto";
2
3
  import { stationAgentCliAdvertisable } from "../lib/agent-cli";
3
4
  import {
4
5
  AGENT_DEPENDENCY_RECHECK_MS,
@@ -309,7 +310,7 @@ import {
309
310
  onAgentClisReady,
310
311
  standardRuntimes,
311
312
  } from "../lib/standard-image";
312
- import { hostCommands, hostEvents, setManagedHostRestartHook } from "./index";
313
+ import { hostCommands, hostEvents, setManagedHostRestartHook, setSystemNotePublisher } from "./index";
313
314
  import { EventOutbox, transmitEventOutbox } from "./event-outbox";
314
315
  import {
315
316
  HostErrorCode,
@@ -411,7 +412,9 @@ import {
411
412
  engineAccountScopeFromWire,
412
413
  isEngineAccountLabel,
413
414
  isEngineConnectKind,
415
+ isTaskNoteDurableAckFrame,
414
416
  } from "./protocol";
417
+ import { createTaskNotePublisher } from "./task-note-publisher";
415
418
  import { PROJECT_ENV_POLICY_EPOCHS } from "./project-env-policy";
416
419
  import {
417
420
  completeProjectEnvBindingCapabilityAfterRuntimeActivation,
@@ -534,6 +537,41 @@ const bridgeUrl =
534
537
  process.env.UAI_CLOUD_URL ?? `ws://127.0.0.1:${bridgePort}/host`;
535
538
 
536
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
+ }
537
575
  let stopping = false;
538
576
 
539
577
  // Owner ask 4 (2026-11-09): the task scripts' dependency check, advertised
@@ -1340,6 +1378,13 @@ hostEvents.subscribe((event) => {
1340
1378
  eventOutbox.enqueue(event);
1341
1379
  flushEvents();
1342
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));
1343
1388
  // ADR-153: the secrets proxy starts before the gateway generations are
1344
1389
  // recovered, so their env resolvers already see it, and registers as the
1345
1390
  // gateway's TLS consumer. Null under the kill switch (UAI_SECRETS_PROXY=off),
@@ -1587,6 +1632,8 @@ function buildCapabilities(): HostCapabilities {
1587
1632
  return {
1588
1633
  version: packageVersion(),
1589
1634
  customConnections: credentialsMode() === "active",
1635
+ // ADR-168: leased accounts' allowed models are read and honoured.
1636
+ accountModelLimits: true,
1590
1637
  engineConnectCustom: signInBoxMode(),
1591
1638
  engineConnectCustomManual: signInBoxMode(),
1592
1639
  internalConnections: isOwnedInternalConnectionRuntime(internalRuntimeProvider()),
@@ -3190,6 +3237,7 @@ async function connect(): Promise<void> {
3190
3237
  case "pong":
3191
3238
  break;
3192
3239
  case "event.resume":
3240
+ taskNotePublisher.negotiated(frame.features ?? []);
3193
3241
  bridgeResumed();
3194
3242
  // ADR-103: the cloud named its watermark — rewind the transmit
3195
3243
  // cursor to it (null = no state, replay nothing) and start draining.
@@ -3208,6 +3256,14 @@ async function connect(): Promise<void> {
3208
3256
  case "task.machine.retire.ack":
3209
3257
  taskFilesMachineRetirementOutbox?.acknowledge(frame);
3210
3258
  break;
3259
+ case "task.note.durable.ack": {
3260
+ const pending = durableNoteAcks.get(frame.opId);
3261
+ if (pending) {
3262
+ durableNoteAcks.delete(frame.opId);
3263
+ pending(frame.outcome === "stored");
3264
+ }
3265
+ break;
3266
+ }
3211
3267
  case "command":
3212
3268
  void handleCommand(socket, frame);
3213
3269
  break;
@@ -4009,6 +4065,13 @@ async function connect(): Promise<void> {
4009
4065
 
4010
4066
  socket.on("close", (code, reason) => {
4011
4067
  cleanup();
4068
+ // A note this connection carried is not known stored: the next start
4069
+ // sends it again, and the cloud keeps one per noteId.
4070
+ for (const [opId, settle] of durableNoteAcks) {
4071
+ durableNoteAcks.delete(opId);
4072
+ settle(false);
4073
+ }
4074
+ taskNotePublisher.disconnected();
4012
4075
  const text = reason.toString("utf8");
4013
4076
  if (stopping) {
4014
4077
  markDisconnected();
@@ -5021,8 +5084,12 @@ function parseCloudFrame(data: RawData): CloudToHost | null {
5021
5084
  frame.kind === "event.resume" &&
5022
5085
  (frame.afterSeq === null || typeof frame.afterSeq === "number")
5023
5086
  ) {
5024
- return { kind: "event.resume", afterSeq: frame.afterSeq };
5087
+ const features = Array.isArray(frame.features)
5088
+ ? frame.features.filter((feature): feature is string => typeof feature === "string" && feature.length <= 64).slice(0, 64)
5089
+ : undefined;
5090
+ return { kind: "event.resume", afterSeq: frame.afterSeq, ...(features ? { features } : {}) };
5025
5091
  }
5092
+ if (isTaskNoteDurableAckFrame(frame)) return frame;
5026
5093
  if (frame.kind === "event.ack" && typeof frame.seq === "number") {
5027
5094
  return { kind: "event.ack", seq: frame.seq };
5028
5095
  }
@@ -5600,6 +5667,7 @@ function rejectFrameDuringShutdown(
5600
5667
  case "pong":
5601
5668
  case "event.resume":
5602
5669
  case "event.ack":
5670
+ case "task.note.durable.ack":
5603
5671
  case "tunnel.data":
5604
5672
  case "tunnel.requestEnd":
5605
5673
  case "tunnel.close":
@@ -0,0 +1,103 @@
1
+ /**
2
+ * ADR-168: an AI account's allowed models. One module for the cloud (which
3
+ * stores and checks the list) and the runner (which picks and rotates
4
+ * accounts by it), so the two can never disagree about what "this account
5
+ * allows that model" means. Pure: no runtime imports.
6
+ *
7
+ * Ids are the roster's: what an agent's `model` field holds for its engine
8
+ * kind (`supportedModels` in lib/agent-catalog.ts, mirrored from
9
+ * ./engine-models.ts). Before any comparison both sides go through
10
+ * `canonicalAccountModel`:
11
+ *
12
+ * - every kind: surrounding whitespace is dropped;
13
+ * - `claude`: case-folded, a context suffix (`opus[1m]`) dropped, and a full
14
+ * Claude model id (`claude-sonnet-5-5`, `claude-opus-4-8-20260101`) read as
15
+ * its family alias (`sonnet`, `opus`) — the only ids the Claude roster uses;
16
+ * - `codex`, `grok`: case-folded (their CLIs treat slugs case-insensitively);
17
+ * - any other kind (`cursor`, `kimi`, `opencode`, …): kept verbatim, since
18
+ * their ids are free-form `provider/model` strings.
19
+ *
20
+ * Null (or an empty list) means every model, so an untouched account behaves
21
+ * exactly as before. A limited account runs only the models it lists: an
22
+ * agent with no model set runs on it only when the caller resolves that blank
23
+ * to a concrete default first (the cloud uses the catalog default of a
24
+ * `required` kind; a blank `optional` model is the CLI's own choice, which a
25
+ * limited account cannot vouch for).
26
+ */
27
+
28
+ const CLAUDE_FAMILIES = ["fable", "opus", "sonnet", "haiku"] as const;
29
+ const CASE_FOLDED_KINDS = new Set(["claude", "codex", "grok"]);
30
+
31
+ /** Most models a single account may list. */
32
+ export const MAX_ALLOWED_MODELS = 200;
33
+ /** Longest model id kept. */
34
+ export const MAX_ALLOWED_MODEL_CHARS = 200;
35
+
36
+ /** The id a model is compared by, for one engine kind. */
37
+ export function canonicalAccountModel(kind: string, model: string): string {
38
+ let id = model.trim();
39
+ if (CASE_FOLDED_KINDS.has(kind)) id = id.toLowerCase();
40
+ if (kind !== "claude") return id;
41
+ id = id.replace(/\[[^\]]*\]$/, "");
42
+ const full = /^claude-([a-z]+)(?:-|$)/.exec(id);
43
+ if (full && (CLAUDE_FAMILIES as readonly string[]).includes(full[1]!)) return full[1]!;
44
+ return id;
45
+ }
46
+
47
+ /**
48
+ * The stored form of a list: canonical, de-duplicated, in the order given;
49
+ * null for "every model" (null, undefined or nothing left).
50
+ */
51
+ export function normalizeAllowedModels(
52
+ kind: string,
53
+ models: readonly string[] | null | undefined,
54
+ ): string[] | null {
55
+ if (!models) return null;
56
+ const out: string[] = [];
57
+ for (const model of models) {
58
+ const id = canonicalAccountModel(kind, model);
59
+ if (id && !out.includes(id)) out.push(id);
60
+ }
61
+ return out.length ? out : null;
62
+ }
63
+
64
+ /** Whether an account with this list may run `model` for `kind`. A blank
65
+ * model is allowed only on an account that allows every model. */
66
+ export function accountAllowsModel(
67
+ allowed: readonly string[] | null | undefined,
68
+ kind: string,
69
+ model: string | null | undefined,
70
+ ): boolean {
71
+ if (!allowed || allowed.length === 0) return true;
72
+ const id = model ? canonicalAccountModel(kind, model) : "";
73
+ if (!id) return false;
74
+ return allowed.some((entry) => canonicalAccountModel(kind, entry) === id);
75
+ }
76
+
77
+ /** Parse the stored JSON (`uai_credentials.allowed_models`). Anything
78
+ * unreadable reads as an empty list — no model — never as "every model":
79
+ * a value this code cannot read must fail closed. */
80
+ export function parseAllowedModels(raw: string | null | undefined): string[] | null {
81
+ if (raw === null || raw === undefined || raw === "") return null;
82
+ try {
83
+ const value: unknown = JSON.parse(raw);
84
+ if (value === null) return null;
85
+ if (!Array.isArray(value) || !value.every((m) => typeof m === "string")) return [];
86
+ return value.length ? (value as string[]) : null;
87
+ } catch {
88
+ return [];
89
+ }
90
+ }
91
+
92
+ /** True when a manifest's `allowedModels` value is well-formed. */
93
+ export function isAllowedModelsWire(value: unknown): value is string[] {
94
+ return (
95
+ Array.isArray(value) &&
96
+ value.length > 0 &&
97
+ value.length <= MAX_ALLOWED_MODELS &&
98
+ value.every(
99
+ (m) => typeof m === "string" && m.length > 0 && m.length <= MAX_ALLOWED_MODEL_CHARS,
100
+ ) &&
101
+ new Set(value).size === value.length
102
+ );
103
+ }
package/src/protocol.ts CHANGED
@@ -4123,6 +4123,9 @@ export function isHostConfigAckFrame(
4123
4123
  */
4124
4124
  export interface HostCapabilities {
4125
4125
  customConnections?: boolean;
4126
+ /** ADR-168: this runner reads a leased account's `allowedModels` and picks
4127
+ * and rotates accounts by the agent's model. */
4128
+ accountModelLimits?: boolean;
4126
4129
  engineConnectCustom?: boolean;
4127
4130
  engineConnectCustomManual?: boolean;
4128
4131
  internalConnections?: boolean;
@@ -4401,6 +4404,10 @@ export interface TaskUpResult {
4401
4404
  envSchemas?: ProjectEnvSchemaObservation[];
4402
4405
  /** Degraded start: uai-init failed twice; the task is up without deps/editor. */
4403
4406
  initWarning?: string;
4407
+ /** F6: this start replaced the task's terminated machine with a fresh one
4408
+ * (work only on the old machine is gone). The Station posts its own feed
4409
+ * note; the cloud may ignore the flag. */
4410
+ environmentReplaced?: true;
4404
4411
  }
4405
4412
 
4406
4413
  export interface TaskDownResult {
@@ -5022,6 +5029,60 @@ export interface TaskMachineRetireFrame {
5022
5029
 
5023
5030
  /** Durable acceptance, not completion: after `accepted` the cloud owns
5024
5031
  * retrying the persisted exact-instance stop even if this socket disappears. */
5032
+ /**
5033
+ * F6 (review #mta79m): a feed note the Station must know is stored, the
5034
+ * machine-replaced warning. The cloud stores it once per (task, noteId) and
5035
+ * acks only after the row is committed; a storage failure gets no ack, and
5036
+ * the Station tries again at the task's next start. Sent only to a cloud that
5037
+ * advertised DURABLE_TASK_NOTE_FEATURE in its event.resume.
5038
+ */
5039
+ export interface TaskNoteDurableFrame {
5040
+ kind: "task.note.durable";
5041
+ opId: string;
5042
+ taskId: string;
5043
+ /** The note's identity; the same id is stored at most once per task. */
5044
+ noteId: string;
5045
+ text: string;
5046
+ }
5047
+
5048
+ export interface TaskNoteDurableAckFrame {
5049
+ kind: "task.note.durable.ack";
5050
+ opId: string;
5051
+ /** stored: committed now or earlier; refused: never (not this host's task). */
5052
+ outcome: "stored" | "refused";
5053
+ }
5054
+
5055
+ export const DURABLE_TASK_NOTE_FEATURE = "durable-task-note-v1";
5056
+ export const MAX_DURABLE_TASK_NOTE_ID_CHARS = 128;
5057
+ export const MAX_DURABLE_TASK_NOTE_BYTES = 4 * 1024;
5058
+
5059
+ export function isTaskNoteDurableFrame(value: unknown): value is TaskNoteDurableFrame {
5060
+ const frame = exactWireObject(value, ["kind", "opId", "taskId", "noteId", "text"]);
5061
+ return Boolean(
5062
+ frame &&
5063
+ frame.kind === "task.note.durable" &&
5064
+ isHostOpId(frame.opId) &&
5065
+ isTaskMachineRetireTaskId(frame.taskId) &&
5066
+ typeof frame.noteId === "string" &&
5067
+ frame.noteId.length > 0 &&
5068
+ frame.noteId.length <= MAX_DURABLE_TASK_NOTE_ID_CHARS &&
5069
+ /^[A-Za-z0-9@._:-]+$/.test(frame.noteId) &&
5070
+ typeof frame.text === "string" &&
5071
+ frame.text.trim().length > 0 &&
5072
+ utf8ByteLength(frame.text) <= MAX_DURABLE_TASK_NOTE_BYTES,
5073
+ );
5074
+ }
5075
+
5076
+ export function isTaskNoteDurableAckFrame(value: unknown): value is TaskNoteDurableAckFrame {
5077
+ const frame = exactWireObject(value, ["kind", "opId", "outcome"]);
5078
+ return Boolean(
5079
+ frame &&
5080
+ frame.kind === "task.note.durable.ack" &&
5081
+ isHostOpId(frame.opId) &&
5082
+ (frame.outcome === "stored" || frame.outcome === "refused"),
5083
+ );
5084
+ }
5085
+
5025
5086
  export interface TaskMachineRetireAckFrame {
5026
5087
  kind: "task.machine.retire.ack";
5027
5088
  opId: string;
@@ -5186,7 +5247,13 @@ export type CloudToHost =
5186
5247
  // replays every outbox entry with seq > afterSeq. `null` means the cloud
5187
5248
  // has no watermark for this boot (fresh boot, or lost KV) — the host sends
5188
5249
  // only entries it never transmitted, replaying nothing.
5189
- | { kind: "event.resume"; afterSeq: number | null }
5250
+ | {
5251
+ kind: "event.resume";
5252
+ afterSeq: number | null;
5253
+ /** What this cloud supports beyond the base protocol (absent: none).
5254
+ * Older Stations read only afterSeq. */
5255
+ features?: string[];
5256
+ }
5190
5257
  // ADR-103: cumulative — the host trims outbox entries with seq <= seq.
5191
5258
  | { kind: "event.ack"; seq: number }
5192
5259
  // ADR-133 leases: the cloud's answer to a sidecar's `lease.request`.
@@ -5201,6 +5268,7 @@ export type CloudToHost =
5201
5268
  | CredentialRefreshResultFrame
5202
5269
  | CredentialsActivateResultFrame
5203
5270
  | TaskMachineRetireAckFrame
5271
+ | TaskNoteDurableAckFrame
5204
5272
  | McpCaptureProbeFrame
5205
5273
  | McpCaptureCompleteFrame
5206
5274
  | McpCaptureCancelFrame
@@ -5351,6 +5419,7 @@ export type HostToCloud =
5351
5419
  | CredentialsActivateFrame
5352
5420
  | CredentialsActivatedFrame
5353
5421
  | TaskMachineRetireFrame
5422
+ | TaskNoteDurableFrame
5354
5423
  | McpCaptureAckFrame
5355
5424
  | PersonCaptureAckFrame
5356
5425
  | 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
+ }