@cotal-ai/core 0.171.1 → 0.171.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,153 @@
1
+ import { isPrincipalOwnerToken, parseSubject } from "./subjects.js";
2
+ import { authenticatedChannelMessage, isRecord } from "./endpoint-inbound.js";
3
+ /** A usable delivery-message id (#624): a string, possibly empty (the never-a-key case), but
4
+ * never absent and never a non-string. An absent or non-string id is a malformed envelope under
5
+ * SPEC sec 5; each delivery pump handles it per its own class (durable term, live drop, history
6
+ * skip) so it never reaches the receiver's id-keyed machinery as `undefined`. */
7
+ export function isUsableMessageId(id) {
8
+ return typeof id === "string";
9
+ }
10
+ /** Map an authenticated parsed-subject kind to the message class surfaced to "message" listeners.
11
+ * Throws on `ctl` (control-plane is request/reply, never a "message") — per repo convention, no
12
+ * silent default: an unexpected delivering kind is a bug, not something to swallow. */
13
+ export function kindFromParsed(kind) {
14
+ switch (kind) {
15
+ case "chat":
16
+ return "channel";
17
+ case "inst":
18
+ return "dm";
19
+ case "svc":
20
+ return "anycast";
21
+ default:
22
+ throw new Error(`cannot derive a message kind from subject kind "${kind}"`);
23
+ }
24
+ }
25
+ /** SPEC §5 on receive: a delivery comes from the principal its subject names. The payload is an
26
+ * object whose `from.id` is the subject's sender, and the subject's owner is a real principal, not
27
+ * an old-shape alias. Every receive path asks this one predicate. What a path does with a refusal
28
+ * (drop, skip, ack, term or reject) and its own extra checks (a usable id, its own echo) stay with
29
+ * the path. */
30
+ export function isFromSubjectSender(msg, parsed) {
31
+ return isRecord(msg) && isRecord(msg.from) && msg.from.id === parsed.sender && isPrincipalOwnerToken(parsed.owner);
32
+ }
33
+ /** Routing fields in the envelope are advisory. The broker forge-locks sender (and for DMs,
34
+ * recipient) into the subject. Callers MUST already have passed {@link isFromSubjectSender}
35
+ * (SPEC §5). This derives the remaining
36
+ * routing tokens from the subject for rows that survived — it does not rewrite a mismatched
37
+ * `from.id`. Live tails, channel backfill, and channel recall skip the mismatch; history
38
+ * does the same (#388). The row's other fields pass through UNTOUCHED, so what the caller's
39
+ * row type already verified stays verified (#1413). */
40
+ export function authenticatedMessage(msg, parsed) {
41
+ if (parsed.kind === "chat" || parsed.kind === "evp")
42
+ return authenticatedChannelMessage(msg, parsed.rest);
43
+ if (parsed.kind === "inst")
44
+ return authenticatedDmMessage(msg, parsed.rest);
45
+ if (parsed.kind === "svc")
46
+ return authenticatedAnycastMessage(msg, parsed.rest);
47
+ return msg;
48
+ }
49
+ function authenticatedDmMessage(msg, to) {
50
+ if (msg.to === to && msg.channel === undefined && msg.toService === undefined)
51
+ return msg;
52
+ const { channel: _channel, toService: _toService, ...base } = msg;
53
+ return { ...base, to };
54
+ }
55
+ function authenticatedAnycastMessage(msg, toService) {
56
+ if (msg.toService === toService && msg.to === undefined && msg.channel === undefined)
57
+ return msg;
58
+ const { to: _to, channel: _channel, ...base } = msg;
59
+ return { ...base, toService };
60
+ }
61
+ /** A DM-only copy's delivery. An ack, nak or in-progress signal on a closed connection is refused
62
+ * with a throw instead of being dropped silently: the copy stays unacked and the broker redelivers it. */
63
+ export function dmOnlyDelivery(m, ackWaitMs, nc) {
64
+ const open = (what) => {
65
+ if (!nc || nc.isClosed())
66
+ throw new Error(`DM-only ${what} refused: the connection that delivered this copy is closed; the broker will redeliver it`);
67
+ };
68
+ return {
69
+ ack: () => { open("ack"); m.ack(); },
70
+ nak: () => { open("nak"); m.nak(); },
71
+ durable: true,
72
+ redelivery: { deliveryCount: m.info.deliveryCount, ackWaitMs, working: () => { open("in-progress signal"); m.working(); } },
73
+ };
74
+ }
75
+ /** History drain keeps `m.json()` and used to throw the subject away. SPEC §5: on receive, verify
76
+ * `from.id` equals the subject sender; on mismatch, a missing `from`, or an unparseable delivery
77
+ * subject, reject and never surface. Fail closed on shape too: a stored JSON `null` or a truthy
78
+ * non-object `from` must not throw mid-array. Do not echo-drop `from.id === this.card.id`:
79
+ * god-view history must include the viewer's own sends. */
80
+ export function historyMessageFromDelivery(m) {
81
+ let raw;
82
+ try {
83
+ raw = m.json();
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ if (!isHistoryDrainEnvelope(raw))
89
+ return undefined;
90
+ if (!isVerifiedHistoryRow(raw))
91
+ return undefined;
92
+ const parsed = parseSubject(m.subject);
93
+ if (!parsed || !isFromSubjectSender(raw, parsed))
94
+ return undefined;
95
+ return authenticatedMessage(raw, parsed);
96
+ }
97
+ /** The members `HistoryMessage` promises beyond the drain envelope (#1413): a full
98
+ * `EndpointRef` (`from.name`, and `from.role` only when a string), a finite `ts`, a string
99
+ * `space`, `parts` the drain could read, and the optional members in their promised shape
100
+ * when present. Every field the PUBLIC row type promises is checked here, before the row is
101
+ * returned. A row missing one is dropped, never returned with that member silently
102
+ * `undefined` under the full type — a consumer reading `msg.ts`, `msg.space`, `msg.parts`
103
+ * or `msg.from.name` must not be able to reach one that was never there. Nothing is invented
104
+ * for an absent field.
105
+ *
106
+ * `parts` is held to READABLE, not to `isMessagePart`: every member must be an object with a
107
+ * string `kind` (so `partsToText` can read `part.kind` without throwing), but a keyless
108
+ * `{kind:"data"}` row from a pre-#1404 producer is not dropped — history must surface it.
109
+ * `mentions`, `replyTo`, and `contextId` keep exactly their `CotalMessage` shapes when
110
+ * present: an array of strings, a string, a string. */
111
+ function isVerifiedHistoryRow(row) {
112
+ if (typeof row.from.name !== "string")
113
+ return false;
114
+ if (row.from.role !== undefined && typeof row.from.role !== "string")
115
+ return false;
116
+ if (typeof row.ts !== "number" || !Number.isFinite(row.ts))
117
+ return false;
118
+ if (typeof row.space !== "string")
119
+ return false;
120
+ if (!Array.isArray(row.parts) || !row.parts.every(isReadableMessagePart))
121
+ return false;
122
+ if (row.mentions !== undefined &&
123
+ (!Array.isArray(row.mentions) || !row.mentions.every((name) => typeof name === "string")))
124
+ return false;
125
+ if (row.replyTo !== undefined && typeof row.replyTo !== "string")
126
+ return false;
127
+ if (row.contextId !== undefined && typeof row.contextId !== "string")
128
+ return false;
129
+ return true;
130
+ }
131
+ /** A part `partsToText` can read without throwing: an object with a string `kind` (#1413).
132
+ * Deliberately weaker than `isMessagePart` — a keyless `{kind:"data"}` part passes here —
133
+ * because history must surface rows a pre-#1404 producer wrote, not drop them. */
134
+ export function isReadableMessagePart(value) {
135
+ return isRecord(value) && typeof value.kind === "string";
136
+ }
137
+ /**
138
+ * Narrow enough for the type checker and for fail-closed history: object envelope, usable `id`,
139
+ * object `from`. That is what lets `authenticatedMessage` take the row without a cast.
140
+ *
141
+ * Does NOT verify SPEC §5 message shape. It does not require a string `from.id` (the SPEC §5
142
+ * comparison still rejects a mismatch) or exactly one route key. The members the PUBLIC
143
+ * history row promises beyond this envelope — a full EndpointRef `from` (`name`/`role`), a
144
+ * finite `ts`, a string `space` — are checked by {@link isVerifiedHistoryRow} before the row
145
+ * is returned (#1413). Well-formed `parts` still belong to `isCotalMessage` (Plane-3), and
146
+ * history must not use that guard: a publisher now REFUSES a `data` part carrying a non-JSON
147
+ * value, but a keyless `{kind:"data"}` row from a pre-fix producer can still sit in a stream,
148
+ * and history must surface it rather than drop it.
149
+ */
150
+ function isHistoryDrainEnvelope(value) {
151
+ return isRecord(value) && isUsableMessageId(value.id) && isRecord(value.from);
152
+ }
153
+ //# sourceMappingURL=endpoint-messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint-messages.js","sourceRoot":"","sources":["../src/endpoint-messages.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAsB,MAAM,eAAe,CAAC;AAExF,OAAO,EAAE,2BAA2B,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAE9E;;;kFAGkF;AAClF,MAAM,UAAU,iBAAiB,CAAC,EAAW;IAC3C,OAAO,OAAO,EAAE,KAAK,QAAQ,CAAC;AAChC,CAAC;AAED;;wFAEwF;AACxF,MAAM,UAAU,cAAc,CAAC,IAA2B;IACxD,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,M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AC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IAC5G,IAAI,GAAG,CAAC,OAAO,KAAK,SAAS,IAAI,OAAO,GAAG,CAAC,OAAO,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IAC/E,IAAI,GAAG,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,GAAG,CAAC,SAAS,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACnF,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;mFAEmF;AACnF,MAAM,UAAU,qBAAqB,CAAC,KAAc;IAClD,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC;AAC3D,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAS,sBAAsB,CAAC,KAAc;IAC5C,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,iBAAiB,CAAC,KAAK,CAAC,EAAE,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChF,CAAC"}
@@ -0,0 +1,295 @@
1
+ import type { NatsConnection } from "@nats-io/transport-node";
2
+ import type { AgentCard, ChannelMode, CotalMessage, Delivery, MessageMeta } from "./types.js";
3
+ import type { ClusterDocument } from "./endpoint-cluster.js";
4
+ import type { EpPrincipalCommandDef, EpPrincipalServeHandle } from "./endpoint-serve.js";
5
+ import type { EpPrincipal } from "./endpoint-subjects.js";
6
+ /** Takes a daemon answers at once; one more is refused as busy, so the holder keeps its copy and
7
+ * asks again rather than queueing work the daemon cannot bound. */
8
+ export declare const MAX_TAKES_IN_FLIGHT = 64;
9
+ /** How often the daemon runs the anycast records maintenance pass. */
10
+ export declare const ANYCAST_SWEEP_MS: number;
11
+ /** How long a holder waits for the daemon to answer a take. */
12
+ export declare const ANYCAST_TAKE_TIMEOUT_MS = 5000;
13
+ /** The DLV count a stored copy was written under, from its {@link DELIVERY_LIMIT_HEADER} (SPEC §8):
14
+ * a whole number of at least 1, null for `none`, and 1000 when the header is absent, since only a
15
+ * daemon from before the count was configurable writes a copy without it and its count was 1000.
16
+ * Throws on any other value. */
17
+ export declare function deliveryLimitOf(value: string | undefined): number | null;
18
+ /** Space joined when none is given on the CLI (the `cotal-<space>` cmux tab, etc.). */
19
+ export declare const DEFAULT_SPACE = "main";
20
+ /** The longest delay `setTimeout` honors, 2^31-1 ms. */
21
+ export declare const MAX_TIMER_MS = 2147483647;
22
+ export interface EndpointOptions {
23
+ /** Trusted composition custody of each opened transport, including replacement epochs.
24
+ * Called before binding so the owner can await its terminal closed signal on bind failure. */
25
+ onConnection?: (nc: NatsConnection) => void;
26
+ /** A planned credential swap dials a second connection, calls {@link onConnection}, and flushes
27
+ * before it reconnects the resident connection. The second connection closes after that
28
+ * reconnect. `onConnection` must accept a connection that exists only for the swap. Serve
29
+ * subscriptions that share an incarnation queue keep dispatch while the resident connection
30
+ * is down. Without this option the resident connection reconnects in place. */
31
+ overlapOnConnectionRenewal?: boolean;
32
+ /** Await local admission checks before presence, consumers and the ready event on each bind. */
33
+ beforeBind?: () => Promise<void>;
34
+ /** The collaboration to join. */
35
+ space: string;
36
+ /** Identity. `id` is generated if omitted. */
37
+ card: Omit<AgentCard, "id"> & {
38
+ id?: string;
39
+ };
40
+ /** Opaque presence label. Omitted reads COTAL_ENVIRONMENT; null omits the label without reading it. */
41
+ environment?: string | null;
42
+ /** This incarnation's lifecycle UID (SPEC §13.1), minted ONCE per lifecycle by the provisioning
43
+ * authority (manager/CLI: `mintLifecycleUid()`) and PERSISTED with the agent — never re-minted per
44
+ * process, or a supervised restart would abandon the durable inbox. REQUIRED to bind/create the
45
+ * lifecycle-keyed messaging durables (`dm_…-<uid>`, `dlv_…-<uid>`, `chathist_…-<uid>`) — an
46
+ * endpoint without one (a pure operator/daemon connection) can not consume DM/chat history. */
47
+ lifecycleUid?: string;
48
+ /** The CHAT stream sequence this incarnation had reached before its preservation cut (a supervised
49
+ * preserve/resume, never a fresh join). The boot backfill reads only what came after it instead of
50
+ * the whole retained window. Core reads no environment variable for this — the caller (a launcher)
51
+ * resolves it and passes it explicitly. */
52
+ backfillFloor?: number;
53
+ /** The accepted-row token of this credential's issuance (SPEC 13.15). Set when the launcher
54
+ * minted the credential as an issuance: after connecting, the endpoint reads the generation the
55
+ * ISSUER bound under this token (a broker-enforced per-key read) and pins it into every caller
56
+ * rail it forms. A token that resolves to no row, or to another incarnation's reference, fails
57
+ * the connect: the rails would be refused at the broker anyway, and a silent legacy fallback is
58
+ * exactly what the versioned rail exists to rule out. */
59
+ acceptedToken?: string;
60
+ servers?: string;
61
+ /** Connection token (soft-shared auth). Mutually exclusive with user/pass. */
62
+ token?: string;
63
+ /** Username/password auth (both required together). */
64
+ user?: string;
65
+ pass?: string;
66
+ /** NATS user creds file *content* (JWT + nkey seed), or a SOURCE that mints/reads a fresh copy.
67
+ * When set, the endpoint authenticates as that user and adopts the creds' identity as its card.id.
68
+ *
69
+ * A STRING is the ordinary static cred. A FUNCTION is the STANDING-RENEWAL seam for
70
+ * bounded-lifetime standing creds: the endpoint fetches before the first connect, re-fetches at
71
+ * 75% of each JWT's lifetime (then swaps the connection onto the fresh cred with a controlled
72
+ * reconnect) and on rebuilds, and every (re)connect attempt presents the freshest copy — the
73
+ * broker's expiry-close is only the backstop for a missed swap.
74
+ * The two source shapes are the renewal classes: a seed-holder self-remints (the manager's
75
+ * supervisor), a seed-less daemon re-reads its manager-reminted creds file (delivery). A source
76
+ * requires explicit `card.id` (the pinned identity); every fetched cred MUST carry that same nkey
77
+ * or the endpoint fails loud — renewal may never silently swap identity. A fetch failure is
78
+ * emitted as a "warning" event and retried; the connection stays up until its current JWT expires,
79
+ * so a dead reminter is loud without instantly dropping the mesh. Node rethrows unhandled "error"
80
+ * events, so a retry notice must not use that channel (#891). Once the cached cred expires,
81
+ * the endpoint refuses to present it to the broker and keeps retrying the source with backoff. */
82
+ creds?: string | (() => Promise<string>);
83
+ /** USER-MODE auth: a validated Cotal user bearer (the JWT from `cotal login` → the IdP bridge), or a
84
+ * SOURCE that mints a fresh one. When set, the endpoint connects through the auth callout — presenting
85
+ * {@link sentinelCreds} + the bearer, the broker mints its scoped data-account JWT.
86
+ *
87
+ * A STRING is a one-shot bearer for connection-lifetime ≤ bearer-lifetime callers (the CLI): the
88
+ * owner+actor PRINCIPAL is derived from it (`sub`, `act.actor`), and the connection dies at the
89
+ * bearer-bound JWT expiry. A FUNCTION is a bearer source for long-lived endpoints (spawned agents):
90
+ * the endpoint fetches before the first connect, renews at a random point between 50% and 80% of
91
+ * each token's lifetime (then swaps the connection onto it with a controlled reconnect) and on
92
+ * rebuilds, and every (re)connect attempt presents the freshest unexpired token — so reconnects
93
+ * outlive any single bearer, and none presents an expired one.
94
+ * A source requires explicit `card.owner` + `card.actor` (there is no bearer to derive them from at
95
+ * construction); every fetched bearer MUST carry that same principal or the endpoint fails loud.
96
+ * A fetch failure is emitted as one "warning" event per run of failures and retried on a jittered,
97
+ * capped backoff — the connection stays up until its current JWT expires, so a dead auth service
98
+ * surfaces loudly without instantly dropping the mesh. A failure that carries a numeric
99
+ * `retryAfterSeconds` is retried when those seconds have passed instead, not before.
100
+ * Node rethrows unhandled "error" events, so a retry notice must not use that channel (#891).
101
+ * Mutually exclusive with `creds`/`token`/`user`/`pass`; requires `sentinelCreds`. */
102
+ bearer?: string | (() => Promise<string>);
103
+ /** The shared, deny-all auth-account sentinel creds presented alongside {@link bearer} so the connect
104
+ * lands in the callout account (`createCalloutAuth().sentinelCreds`). Powerless on its own. */
105
+ sentinelCreds?: string;
106
+ /** Require a TLS connection to the server. */
107
+ tls?: boolean;
108
+ /** Native NATS PING interval for this endpoint's resident connection, in milliseconds.
109
+ * Defaults to 10 seconds. Pair with transportMaxPingOut. No probe connection. */
110
+ transportPingIntervalMs?: number;
111
+ /** Unanswered native PING count before the resident transport becomes stale. Defaults to 2.
112
+ * Pair with transportPingIntervalMs for bounded silent loss. */
113
+ transportMaxPingOut?: number;
114
+ /** How long the first connect may take before it fails with the transport's TimeoutError, in
115
+ * milliseconds. Omitted uses the transport's default. */
116
+ transportConnectTimeoutMs?: number;
117
+ /** Channels to subscribe to; the first concrete one is the default broadcast target. Omitted or
118
+ * empty ⇒ NO channels: the endpoint joins nothing, and {@link CotalEndpoint.multicast} refuses
119
+ * a call with no explicit channel rather than picking one. */
120
+ channels?: string[];
121
+ /** The credential's complete channel read ACL when the composition has it. An explicit empty list
122
+ * means provisioning omitted the DLV durable. When omitted, static credentials select the optional
123
+ * bind from their presented publish permissions; bearer callers need the resolved ACL. A denied
124
+ * bind still refuses startup. */
125
+ allowSubscribe?: string[];
126
+ /** Presence heartbeat interval (ms). */
127
+ heartbeatMs?: number;
128
+ /** Presence liveness window (ms); a peer is considered gone after this. */
129
+ ttlMs?: number;
130
+ /** Publish our own presence (default true). */
131
+ registerPresence?: boolean;
132
+ /** Track the roster of peers with a live watch (default true). Every watcher receives every
133
+ * member's heartbeat, so a space of K watching members moves K² deliveries per heartbeat. An
134
+ * endpoint that only needs the roster when it acts sets this false and calls
135
+ * {@link CotalEndpoint.readPresence} instead (SPEC §6). */
136
+ watchPresence?: boolean;
137
+ /** Keep the channel registry cache (default true). An endpoint that watches presence watches the
138
+ * registry; a consumer that reads presence on demand reads the registry on demand too
139
+ * ({@link CotalEndpoint.readChannels}), and any other endpoint keeps no cache. A presence-only
140
+ * supervisor sets this false to track the roster WITHOUT opening the channel-registry cache — so
141
+ * its cred needs no channel-registry read grant (residual 2). A consumer always opens the
142
+ * registry, because the join-time replay decision reads it. */
143
+ watchChannels?: boolean;
144
+ /** Read presence and the channel registry ONCE at start instead of watching them (default false),
145
+ * for an endpoint that does one thing and stops (`cotal send`, a roster probe). Each read is a
146
+ * batched Direct Get of every key's last record, so it binds no consumer. A watch's ordered consumer
147
+ * outlives {@link CotalEndpoint.stop} by the broker's five-minute inactive threshold, because the
148
+ * operator and agent profiles hold no CONSUMER.DELETE on these buckets (#691), and one per
149
+ * short-lived process piles up until the broker refuses new consumers there (#4091). The roster
150
+ * and the channel cache hold the state at start and never update, and no sweep runs. Requires
151
+ * `consume` and `registerPresence` false. */
152
+ readOnce?: boolean;
153
+ /** Consume ONLY this endpoint's own existing DM durable, for a credential that can read nothing
154
+ * else. The endpoint binds `dm_<owner>-<actor>-<uid>` and opens no channel registry, presence,
155
+ * KV, channel subscription, `dlv_` durable, history reader or JetStream manager. It never creates
156
+ * the durable: a missing one fails start with {@link DmDurableMissingError}, a refused bind with
157
+ * {@link DmBindRefusedError}. Each authenticated DM goes to `handler`, one at a time; the next is
158
+ * not read until the previous handler settles. The `message` event does not fire in this mode.
159
+ * {@link CotalEndpoint.stop} resolves only after the connection is closed and the running handler
160
+ * has settled; a rejecting handler still lets the connection close, and stop throws, keeping
161
+ * custody, when closure or settlement within `settleTimeoutMs` (default 30000) is unproved.
162
+ * A copy received after stop begins or after a reconnect replaces the connection is never
163
+ * handed to the handler and stays unacked for broker redelivery; an ack, nak or in-progress
164
+ * signal on a closed connection throws.
165
+ * Requires static or sourced creds or a bearer, `consume` true, `registerPresence`,
166
+ * `watchPresence` and `watchChannels` false, and no channels, role, `readOnce` or `acceptedToken`. */
167
+ dmOnly?: DmOnlyOptions;
168
+ /** Create inbound stream consumers (DM / chat / anycast). Default true; a pure observer sets false. */
169
+ consume?: boolean;
170
+ /** Initial per-channel attention overrides to publish in presence from the first heartbeat (the
171
+ * connector's file-default seed). Mirror only — never read back into delivery. */
172
+ channelModes?: Record<string, ChannelMode>;
173
+ /** How long an unacked (un-surfaced) message waits before redelivery (ms). */
174
+ ackWaitMs?: number;
175
+ /** Retire this instance's durable consumers after it's been gone this long (ms). */
176
+ inactiveThresholdMs?: number;
177
+ }
178
+ /** A peer subscribed to a channel — broker truth (a chat-stream consumer) joined with
179
+ * presence for liveness. `live: false` is a stale ghost: the durable lingers (reconnect
180
+ * grace) but presence says the peer is gone/offline. */
181
+ export interface ChannelMember {
182
+ id: string;
183
+ name: string;
184
+ role?: string;
185
+ live: boolean;
186
+ }
187
+ /** See {@link EndpointOptions.dmOnly}. */
188
+ export interface DmOnlyOptions {
189
+ /** Receives each authenticated DM. A resolved promise does not ack: call `delivery.ack()`. A
190
+ * rejection is emitted as `error` and leaves the copy unacked, so the broker redelivers it. */
191
+ handler: (msg: CotalMessage, delivery: Delivery, meta: MessageMeta) => void | Promise<void>;
192
+ /** How long {@link CotalEndpoint.stop} waits for a running handler, in milliseconds. */
193
+ settleTimeoutMs?: number;
194
+ }
195
+ /** This endpoint's own `dm_` durable does not exist. A DM-only endpoint, and any endpoint on an
196
+ * authenticated mesh, binds the durable its provisioner created and never creates one. */
197
+ export declare class DmDurableMissingError extends Error {
198
+ readonly stream: string;
199
+ readonly durable: string;
200
+ readonly code: "dm-durable-missing";
201
+ constructor(stream: string, durable: string);
202
+ }
203
+ /** The broker refused a DM-only endpoint's bind of its own `dm_` durable. No other credential or
204
+ * read path is tried. */
205
+ export declare class DmBindRefusedError extends Error {
206
+ readonly stream: string;
207
+ readonly durable: string;
208
+ readonly code: "dm-bind-refused";
209
+ constructor(stream: string, durable: string, cause: unknown);
210
+ }
211
+ /** Raw NATS transport liveness for the endpoint's CURRENT connection epoch. This is deliberately
212
+ * separate from the `connection` event, which means the full Cotal bind is ready. */
213
+ export interface TransportState {
214
+ connected: boolean;
215
+ /** The server nats.js named for this edge. Omitted when the runtime supplied none. */
216
+ server?: string;
217
+ }
218
+ /**
219
+ * Events: "message" (CotalMessage), "presence" (PresenceEvent), "roster" (Presence[]), "error" (Error),
220
+ * "connection" ({ connected: boolean }) — true on every successful (re)bind (initial start, manual
221
+ * reconnect, AND background self-heal), false the moment the connection drops (rebuild null window /
222
+ * terminal close). Lets an in-process agent track connectedness off the endpoint's own (re)binds
223
+ * instead of an imperative flag the self-heal path can't reach; "transport" ({ connected, server? })
224
+ * is the lower-level NATS socket edge, true before the full bind finishes and false during an internal
225
+ * nats.js reconnect without changing `connection` readiness. "stored-copies-full" ({ limit: number }): a
226
+ * stored copy arrived with the store at the count the copy was written under ({@link deliveryLimitOf}),
227
+ * so the store may have discarded older copies before this session read them; emitted for each such
228
+ * copy. A lowering of the count or an age set on the store removes copies without this event.
229
+ *
230
+ * Callers MUST attach an "error" listener before `start()`: async faults (incl. NATS
231
+ * permission denials, surfaced via `watchStatus`) are emitted as "error", and Node throws
232
+ * synchronously on an unhandled "error" — a missing listener turns any such fault into a
233
+ * process crash instead of a logged denial.
234
+ */
235
+ /** One page of a mediated history read: the newest `limit` messages, oldest-first WITHIN the page.
236
+ *
237
+ * `complete` is the honest-truncation signal and the reason this is not just `CotalMessage[]`:
238
+ * `true` means the page reaches the start of the channel's RETAINED history (nothing older is on
239
+ * the stream to read), `false` means older messages exist behind it. A caller that cannot tell
240
+ * those apart renders "there is more" as "this is the beginning of the conversation". It says
241
+ * nothing about messages already aged out by retention — no reader can see those. */
242
+ export type HistoryPage = {
243
+ items: CotalMessage[];
244
+ complete: boolean;
245
+ };
246
+ /** The NEWEST prefix-from-the-end of `items` whose serialized `readHistory` reply fits `budget`
247
+ * bytes, order preserved. Returns `[]` when not even the newest single message fits — the caller
248
+ * must refuse loudly there rather than serve an empty page, which would read as "no history".
249
+ *
250
+ * The `ControlReply` around the items rides the same NATS message, so it is charged too: items
251
+ * that fit on their own can still make a reply the broker refuses.
252
+ *
253
+ * Measured in ENCODED bytes, not `string.length`: a page of multi-byte text would otherwise be
254
+ * undercounted and still overflow the broker. Same discipline as `assertFactFits`. */
255
+ export declare function fitHistoryPage(items: CotalMessage[], budget: number): CotalMessage[];
256
+ /** What {@link CotalEndpoint.servePrincipal} keeps to re-bind on every replaced connection. */
257
+ export interface PrincipalServeIntent {
258
+ readonly serve: {
259
+ endpoint: string;
260
+ cluster: ClusterDocument;
261
+ handlers: EpPrincipalCommandDef[];
262
+ };
263
+ readonly self: EpPrincipal;
264
+ /** Its key in {@link principalServers}. */
265
+ readonly serverKey: string;
266
+ /** The binding on the connection it was made on, and every binding not yet retired: the current
267
+ * one and those on replaced connections whose handlers are still finishing, so `stop` awaits
268
+ * them. */
269
+ binding?: {
270
+ nc: NatsConnection;
271
+ handle: EpPrincipalServeHandle;
272
+ };
273
+ readonly handles: EpPrincipalServeHandle[];
274
+ /** The connection on which the broker last accepted the subscription. */
275
+ readyOn?: NatsConnection;
276
+ /** Ended: stopped, or refused by the broker. */
277
+ ended: boolean;
278
+ readySettled: boolean;
279
+ resolveReady(): void;
280
+ rejectReady(e: Error): void;
281
+ resolveFailed(e: Error): void;
282
+ }
283
+ /** A served principal endpoint (SPEC 13.21). */
284
+ export interface PrincipalServe {
285
+ /** Resolves once the broker accepted this process's subscription; rejects with its refusal. */
286
+ readonly ready: Promise<void>;
287
+ /** Resolves with the refusal that ended the serve, including one that arrives on a replaced
288
+ * connection after `ready` resolved. Never rejects, and never resolves after `stop`. */
289
+ readonly failed: Promise<Error>;
290
+ /** Unsubscribe, abort every handler's `signal`, and wait for each handler in flight until its
291
+ * request's deadline at most, which the route caps at 30 s. A reply that comes after that is
292
+ * dropped. */
293
+ stop(): Promise<void>;
294
+ }
295
+ //# sourceMappingURL=endpoint-options.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint-options.d.ts","sourceRoot":"","sources":["../src/endpoint-options.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAC9D,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AACzF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAA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EAAE,MAAM,EAAE,MAAM,GAAG,YAAY,EAAE,CAYpF;AAED,+FAA+F;AAC/F,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,KAAK,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,eAAe,CAAC;QAAC,QAAQ,EAAE,qBAAqB,EAAE,CAAA;KAAE,CAAC;IAClG,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,2CAA2C;IAC3C,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B;;gBAEY;IACZ,OAAO,CAAC,EAAE;QAAE,EAAE,EAAE,cAAc,CAAC;QAAC,MAAM,EAAE,sBAAsB,CAAA;KAAE,CAAC;IACjE,QAAQ,CAAC,OAAO,EAAE,sBAAsB,EAAE,CAAC;IAC3C,yEAAyE;IACzE,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,gDAAgD;IAChD,KAAK,EAAE,OAAO,CAAC;IACf,YAAY,EAAE,OAAO,CAAC;IACtB,YAAY,IAAI,IAAI,CAAC;IACrB,WAAW,CAAC,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;IAC5B,aAAa,CAAC,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;CAC/B;AAED,gDAAgD;AAChD,MAAM,WAAW,cAAc;IAC7B,+FAA+F;IAC/F,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9B;6FACyF;IACzF,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;IAChC;;mBAEe;IACf,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB"}
@@ -0,0 +1,75 @@
1
+ import { DELIVERY_LIMIT_HEADER, PLANE3_MAX_MSGS_PER_SUBJECT } from "./backup-config.js";
2
+ /** Takes a daemon answers at once; one more is refused as busy, so the holder keeps its copy and
3
+ * asks again rather than queueing work the daemon cannot bound. */
4
+ export const MAX_TAKES_IN_FLIGHT = 64;
5
+ /** How often the daemon runs the anycast records maintenance pass. */
6
+ export const ANYCAST_SWEEP_MS = 10 * 60 * 1000;
7
+ /** How long a holder waits for the daemon to answer a take. */
8
+ export const ANYCAST_TAKE_TIMEOUT_MS = 5_000;
9
+ /** The DLV count a stored copy was written under, from its {@link DELIVERY_LIMIT_HEADER} (SPEC §8):
10
+ * a whole number of at least 1, null for `none`, and 1000 when the header is absent, since only a
11
+ * daemon from before the count was configurable writes a copy without it and its count was 1000.
12
+ * Throws on any other value. */
13
+ export function deliveryLimitOf(value) {
14
+ if (value === undefined || value === "")
15
+ return PLANE3_MAX_MSGS_PER_SUBJECT;
16
+ if (value === "none")
17
+ return null;
18
+ if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value)))
19
+ throw new Error(`plane-3 delivery: ${DELIVERY_LIMIT_HEADER} ${JSON.stringify(value)} is not a count`);
20
+ return Number(value);
21
+ }
22
+ /** Space joined when none is given on the CLI (the `cotal-<space>` cmux tab, etc.). */
23
+ export const DEFAULT_SPACE = "main";
24
+ /** The longest delay `setTimeout` honors, 2^31-1 ms. */
25
+ export const MAX_TIMER_MS = 2_147_483_647;
26
+ /** This endpoint's own `dm_` durable does not exist. A DM-only endpoint, and any endpoint on an
27
+ * authenticated mesh, binds the durable its provisioner created and never creates one. */
28
+ export class DmDurableMissingError extends Error {
29
+ stream;
30
+ durable;
31
+ code = "dm-durable-missing";
32
+ constructor(stream, durable) {
33
+ super(`dm-durable-missing: durable "${durable}" on stream "${stream}" does not exist; this endpoint binds an existing durable and never creates one`);
34
+ this.stream = stream;
35
+ this.durable = durable;
36
+ this.name = "DmDurableMissingError";
37
+ }
38
+ }
39
+ /** The broker refused a DM-only endpoint's bind of its own `dm_` durable. No other credential or
40
+ * read path is tried. */
41
+ export class DmBindRefusedError extends Error {
42
+ stream;
43
+ durable;
44
+ code = "dm-bind-refused";
45
+ constructor(stream, durable, cause) {
46
+ super(`dm-bind-refused: binding durable "${durable}" on stream "${stream}" was refused (${cause instanceof Error ? cause.message : String(cause)})`, { cause });
47
+ this.stream = stream;
48
+ this.durable = durable;
49
+ this.name = "DmBindRefusedError";
50
+ }
51
+ }
52
+ /** The NEWEST prefix-from-the-end of `items` whose serialized `readHistory` reply fits `budget`
53
+ * bytes, order preserved. Returns `[]` when not even the newest single message fits — the caller
54
+ * must refuse loudly there rather than serve an empty page, which would read as "no history".
55
+ *
56
+ * The `ControlReply` around the items rides the same NATS message, so it is charged too: items
57
+ * that fit on their own can still make a reply the broker refuses.
58
+ *
59
+ * Measured in ENCODED bytes, not `string.length`: a page of multi-byte text would otherwise be
60
+ * undercounted and still overflow the broker. Same discipline as `assertFactFits`. */
61
+ export function fitHistoryPage(items, budget) {
62
+ const enc = new TextEncoder();
63
+ // The reply with no items, at its longer `complete` value.
64
+ let used = enc.encode(JSON.stringify({ ok: true, data: { items: [], complete: false } })).length;
65
+ let first = items.length; // index of the oldest kept item
66
+ for (let i = items.length - 1; i >= 0; i--) {
67
+ const size = enc.encode(JSON.stringify(items[i])).length + 1; // + the `,` separator
68
+ if (used + size > budget)
69
+ break;
70
+ used += size;
71
+ first = i;
72
+ }
73
+ return first === items.length ? [] : items.slice(first);
74
+ }
75
+ //# sourceMappingURL=endpoint-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint-options.js","sourceRoot":"","sources":["../src/endpoint-options.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAExF;oEACoE;AACpE,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AACtC,sEAAsE;AACtE,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC/C,+DAA+D;AAC/D,MAAM,CAAC,MAAM,uBAAuB,GAAG,KAAK,CAAC;AAE7C;;;iCAGiC;AACjC,MAAM,UAAU,eAAe,CAAC,KAAyB;IACvD,IAAI,KAAK,K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AAW,YAAO,GAAP,OAAO,CAAQ;QAE3D,IAAI,CAAC,IAAI,GAAG,oBAAoB,CAAC;IACnC,CAAC;CACF;AAqCD;;;;;;;;uFAQuF;AACvF,MAAM,UAAU,cAAc,CAAC,KAAqB,EAAE,MAAc;IAClE,MAAM,GAAG,GAAG,IAAI,WAAW,EAAE,CAAC;IAC9B,2DAA2D;IAC3D,IAAI,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAwB,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;IACvH,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,gCAAgC;IAC1D,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC3C,MAAM,IAAI,GAAG,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,sBAAsB;QACpF,IAAI,IAAI,GAAG,IAAI,GAAG,MAAM;YAAE,MAAM;QAChC,IAAI,IAAI,IAAI,CAAC;QACb,KAAK,GAAG,CAAC,CAAC;IACZ,CAAC;IACD,OAAO,KAAK,KAAK,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC1D,CAAC"}
@@ -115,8 +115,8 @@ export declare class EndpointSubscriptions {
115
115
  durable: boolean;
116
116
  reason?: string;
117
117
  }>;
118
- /** Leave a channel mid-session — MANAGER-FREE for the live read: close the core subscription. For a
119
- * Plane-3 durable channel, the membership is tombstoned FIRST at the leave cursor (SPEC §7: leave is
118
+ /** Leave a channel mid-session — MANAGER-FREE for the live read: close the core subscription. Any
119
+ * Plane-3 membership is tombstoned FIRST at the leave cursor (SPEC §7: leave is
120
120
  * a hard read boundary for the backstop — a pre-leave entry stays deliverable, `seq > leaveCursor` is
121
121
  * denied). FAIL-CLOSED: if the tombstone can't be confirmed the call throws and the leave is NOT
122
122
  * applied (live sub stays up, local mirror intact) so the caller can retry — never close the live
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint-subscriptions.d.ts","sourceRoot":"","sources":["../src/endpoint-subscriptions.ts"],"names":[],"mappings":"AAGA,OAAO,EAAuC,KAAK,cAAc,EAAE,MAAM,yBAAyB,CAAC;AACnG,OAAO,EAAuC,KAAK,YAAY,EAAE,KAAK,gBAAgB,EAAc,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClJ,OAAO,EAAO,KAAK,EAAE,EAAgB,MAAM,aAAa,CAAC;AAIzD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAIrE,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,eAAe,EAAqB,gBAAgB,EAAmB,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAqBtJ,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,EAAE,CAAC,MAAM,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC7C,QAAQ,CAAC,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,CAAC;IAChC,IAAI,CAAC,EAAE;QAAE,IAAI,IAAI,IAAI,CAAA;KAAE,CAAC;IACxB,QAAQ,CAAC,EAAE,YAAY,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,GAAG,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IACnB,WAAW,CAAC,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,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AK,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAoCtE,4EAA4E;IACtE,sBAAsB,IAAI,OAAO,CAAC,IAAI,CAAC;CAe9C;AAED;;+EAE+E;AAC/E,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAKhE"}
@@ -150,8 +150,8 @@ export class EndpointSubscriptions {
150
150
  const backfilled = await this.backfillArmed(armed);
151
151
  return { joined: true, backfilled, durable, ...(reason !== undefined ? { reason } : {}) };
152
152
  }
153
- /** Leave a channel mid-session — MANAGER-FREE for the live read: close the core subscription. For a
154
- * Plane-3 durable channel, the membership is tombstoned FIRST at the leave cursor (SPEC §7: leave is
153
+ /** Leave a channel mid-session — MANAGER-FREE for the live read: close the core subscription. Any
154
+ * Plane-3 membership is tombstoned FIRST at the leave cursor (SPEC §7: leave is
155
155
  * a hard read boundary for the backstop — a pre-leave entry stays deliverable, `seq > leaveCursor` is
156
156
  * denied). FAIL-CLOSED: if the tombstone can't be confirmed the call throws and the leave is NOT
157
157
  * applied (live sub stays up, local mirror intact) so the caller can retry — never close the live
@@ -161,16 +161,14 @@ export class EndpointSubscriptions {
161
161
  if (!this.jsm)
162
162
  throw new Error(this.notLiveMsg());
163
163
  let left = this.channels.includes(channel);
164
- if (this.readsChannelsOnDemand)
165
- await this.readChannels();
166
- // Auth + durable-class ⇒ a Plane-3 membership may exist; tombstone it BEFORE touching local state.
164
+ // A concrete channel or family may still have a Plane-3 membership regardless of its current policy.
167
165
  // Discover the channel's rows across this principal's lifecycles, including memberships absent
168
166
  // from the local mirror. Keep each row's generation guard. fetchMemberships throws on a
169
167
  // responder-present error, so a leave whose
170
168
  // tombstone can't be confirmed propagates (live sub stays up, mirror intact) for the caller to retry
171
169
  // — reporting `left` while the trusted reader keeps transferring to DLV is the fail-open leak. A
172
170
  // genuine no-responder (open / no delivery daemon, no Plane-3) means there is no membership to tombstone.
173
- if (this.authed && (isChannelFamily(channel) || effectiveDeliveryClass(this.channelConfigs.get(channel), this.channelDefaults) === "durable")) {
171
+ if (this.authed && (isChannelFamily(channel) || isConcreteChannel(channel))) {
174
172
  const memberships = await this.fetchMemberships(channel);
175
173
  if (memberships === undefined && this.plane3Channels.has(channel))
176
174
  await this.durableLeaveChannel(channel, this.plane3Channels.get(channel));