@cotal-ai/core 0.168.0 → 0.169.0

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.
Files changed (60) hide show
  1. package/dist/agent-file.d.ts.map +1 -1
  2. package/dist/agent-file.js +12 -9
  3. package/dist/agent-file.js.map +1 -1
  4. package/dist/connector-setup.d.ts +2 -0
  5. package/dist/connector-setup.d.ts.map +1 -1
  6. package/dist/connector.d.ts +8 -11
  7. package/dist/connector.d.ts.map +1 -1
  8. package/dist/control-exchange.d.ts +114 -0
  9. package/dist/control-exchange.d.ts.map +1 -0
  10. package/dist/control-exchange.js +416 -0
  11. package/dist/control-exchange.js.map +1 -0
  12. package/dist/endpoint-call.d.ts +2 -1
  13. package/dist/endpoint-call.d.ts.map +1 -1
  14. package/dist/endpoint-call.js +14 -7
  15. package/dist/endpoint-call.js.map +1 -1
  16. package/dist/endpoint-delivery-plane.d.ts +337 -0
  17. package/dist/endpoint-delivery-plane.d.ts.map +1 -0
  18. package/dist/endpoint-delivery-plane.js +1291 -0
  19. package/dist/endpoint-delivery-plane.js.map +1 -0
  20. package/dist/endpoint-envelope.d.ts +2 -1
  21. package/dist/endpoint-envelope.d.ts.map +1 -1
  22. package/dist/endpoint-envelope.js +9 -3
  23. package/dist/endpoint-envelope.js.map +1 -1
  24. package/dist/endpoint-history.d.ts +370 -0
  25. package/dist/endpoint-history.d.ts.map +1 -0
  26. package/dist/endpoint-history.js +969 -0
  27. package/dist/endpoint-history.js.map +1 -0
  28. package/dist/endpoint-inbound.d.ts +10 -0
  29. package/dist/endpoint-inbound.d.ts.map +1 -0
  30. package/dist/endpoint-inbound.js +28 -0
  31. package/dist/endpoint-inbound.js.map +1 -0
  32. package/dist/endpoint-serve.d.ts +11 -1
  33. package/dist/endpoint-serve.d.ts.map +1 -1
  34. package/dist/endpoint-serve.js +42 -5
  35. package/dist/endpoint-serve.js.map +1 -1
  36. package/dist/endpoint-subjects.d.ts +3 -0
  37. package/dist/endpoint-subjects.d.ts.map +1 -1
  38. package/dist/endpoint-subjects.js +3 -0
  39. package/dist/endpoint-subjects.js.map +1 -1
  40. package/dist/endpoint.d.ts +64 -253
  41. package/dist/endpoint.d.ts.map +1 -1
  42. package/dist/endpoint.js +177 -2015
  43. package/dist/endpoint.js.map +1 -1
  44. package/dist/index.d.ts +2 -1
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +4 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/launch-material.d.ts +9 -3
  49. package/dist/launch-material.d.ts.map +1 -1
  50. package/dist/launch-material.js +22 -2
  51. package/dist/launch-material.js.map +1 -1
  52. package/dist/provision-permissions.d.ts.map +1 -1
  53. package/dist/provision-permissions.js +7 -1
  54. package/dist/provision-permissions.js.map +1 -1
  55. package/dist/remote-manager-authority.d.ts +1 -1
  56. package/dist/run-journal.d.ts +2 -0
  57. package/dist/run-journal.d.ts.map +1 -1
  58. package/dist/run-journal.js +1 -1
  59. package/dist/run-journal.js.map +1 -1
  60. package/package.json +5 -1
@@ -1,3 +1,4 @@
1
+ export { MULTI_FILTER_BATCH, MULTI_FILTER_READ_CONCURRENCY } from "./endpoint-history.js";
1
2
  import { type NativeConnectionBinding } from "./native-connection.js";
2
3
  import { EventEmitter } from "node:events";
3
4
  import { connect, type NatsConnection } from "@nats-io/transport-node";
@@ -8,13 +9,13 @@ import { type SecretStoreIdentity } from "./secret-store.js";
8
9
  import { type ResolvedService, type SubmitAndFollowGoalOptions } from "./endpoint-invoke.js";
9
10
  import type { EpCaller, EpPrincipal, IssuedCaller, PrincipalAuthority } from "./endpoint-subjects.js";
10
11
  import { type EpPrincipalCommandDef } from "./endpoint-serve.js";
11
- import type { ClusterDocument } from "./endpoint-cluster.js";
12
12
  import type { EndpointReply } from "./endpoint-envelope.js";
13
13
  import type { CompiledContract } from "./schema-profile.js";
14
14
  import { type RegistryEndpointsInput, type RegistryEndpointsOutput } from "./registry-contract.js";
15
15
  import type { EpVerbTarget, EpAttributedReply } from "./endpoint-verbs.js";
16
16
  import type { AgentCard, ChannelConfig, ControlReply, ControlRequest, ControlRequestInit, Delivery, EndpointRef, MessageMeta, Part, Presence, PresencePrompts, PresenceStatus, PresenceCondition, AttentionMode, ChannelMode, CotalMessage, DmHistoryRead, HistoryMessage, DeliveryClass, MembershipChange, MembershipSnapshot } from "./types.js";
17
17
  import type { DeliveryLeaseInfo, ManagerLeaseInfo } from "./lease.js";
18
+ import { type MaybePromise } from "./endpoint-delivery-plane.js";
18
19
  import { type AnycastStatus } from "./anycast-requests.js";
19
20
  import { type ParsedSubject } from "./subjects.js";
20
21
  import { isPermissionDenied } from "./permission-denied.js";
@@ -27,26 +28,6 @@ export declare const DEFAULT_SERVER = "nats://127.0.0.1:4222";
27
28
  export declare function deliveryLimitOf(value: string | undefined): number | null;
28
29
  /** Space joined when none is given on the CLI (the `cotal-<space>` cmux tab, etc.). */
29
30
  export declare const DEFAULT_SPACE = "main";
30
- /** How many channel filters one multi-filter consumer create may carry.
31
- *
32
- * A create names every requested channel in one request, so the request grows with the channel
33
- * count and the CLIENT's request timeout is what gives way, not the broker: the create is never
34
- * refused, it just does not answer. Measured on an isolated broker, one message per channel,
35
- * `limit=5`: 70 filters answer in 43ms, 1,000 in 246ms, 5,000 in 5,345ms, and 10,000 does not
36
- * answer at all, failing `timeout` after 5,023ms. Note 5,000 SUCCEEDED while taking longer than
37
- * 10,000 took to fail, which is what says the ceiling is on the create request rather than on the
38
- * read: past roughly 5s the create itself is what times out.
39
- *
40
- * 1,000 is chosen from that sweep rather than from the failure point: it is a fifth of the largest
41
- * count that still answered, and it answers in a quarter second, so a batch stays far away from
42
- * both the timeout and the response-deadline budget the dashboard has to share with its DM read.
43
- * A space with the 69 chat channels this was built for is still ONE read, so the round-trip claim
44
- * in #1210 is unchanged at that size. */
45
- export declare const MULTI_FILTER_BATCH = 1000;
46
- /** How many filter batches may be in flight at once. Bounded because the point of #1210 was to stop
47
- * issuing one read per channel: a space large enough to need batches must not get the fan-out back
48
- * under another name. */
49
- export declare const MULTI_FILTER_READ_CONCURRENCY = 4;
50
31
  export interface EndpointOptions {
51
32
  /** Trusted composition custody of each opened transport, including replacement epochs.
52
33
  * Called before binding so the owner can await its terminal closed signal on bind failure. */
@@ -243,9 +224,23 @@ export interface TransportState {
243
224
  /** The server nats.js named for this edge. Omitted when the runtime supplied none. */
244
225
  server?: string;
245
226
  }
246
- /** A value or a promise of it — the Plane-3 `aclFor` reads the durable ACL registry FRESH per entry
247
- * (async), so the reader/fan-out call sites await it. */
248
- type MaybePromise<T> = T | Promise<T>;
227
+ /**
228
+ * Events: "message" (CotalMessage), "presence" (PresenceEvent), "roster" (Presence[]), "error" (Error),
229
+ * "connection" ({ connected: boolean }) — true on every successful (re)bind (initial start, manual
230
+ * reconnect, AND background self-heal), false the moment the connection drops (rebuild null window /
231
+ * terminal close). Lets an in-process agent track connectedness off the endpoint's own (re)binds
232
+ * instead of an imperative flag the self-heal path can't reach; "transport" ({ connected, server? })
233
+ * is the lower-level NATS socket edge, true before the full bind finishes and false during an internal
234
+ * nats.js reconnect without changing `connection` readiness. "stored-copies-full" ({ limit: number }): a
235
+ * stored copy arrived with the store at the count the copy was written under ({@link deliveryLimitOf}),
236
+ * so the store may have discarded older copies before this session read them; emitted for each such
237
+ * copy. A lowering of the count or an age set on the store removes copies without this event.
238
+ *
239
+ * Callers MUST attach an "error" listener before `start()`: async faults (incl. NATS
240
+ * permission denials, surfaced via `watchStatus`) are emitted as "error", and Node throws
241
+ * synchronously on an unhandled "error" — a missing listener turns any such fault into a
242
+ * process crash instead of a logged denial.
243
+ */
249
244
  /** One page of a mediated history read: the newest `limit` messages, oldest-first WITHIN the page.
250
245
  *
251
246
  * `complete` is the honest-truncation signal and the reason this is not just `CotalMessage[]`:
@@ -274,7 +269,9 @@ export interface PrincipalServe {
274
269
  /** Resolves with the refusal that ended the serve, including one that arrives on a replaced
275
270
  * connection after `ready` resolved. Never rejects, and never resolves after `stop`. */
276
271
  readonly failed: Promise<Error>;
277
- /** Unsubscribe and wait for the handlers in flight. */
272
+ /** Unsubscribe, abort every handler's `signal`, and wait for each handler in flight until its
273
+ * request's deadline at most, which the route caps at 30 s. A reply that comes after that is
274
+ * dropped. */
278
275
  stop(): Promise<void>;
279
276
  }
280
277
  export declare class CotalEndpoint extends EventEmitter {
@@ -369,10 +366,9 @@ export declare class CotalEndpoint extends EventEmitter {
369
366
  /** Caller-owned membership watches survive a connection rebuild as INTENT. Their iterators are
370
367
  * connection-scoped and are stopped/re-created around the epoch swap. */
371
368
  private readonly membershipFeedWatches;
372
- /** The live `ctl.delivery` serve subscription (delivery daemon) — re-created on every (re)connect by
373
- * {@link armDeliveryControl}; tracked so the stale one is dropped on reconnect. */
374
- private deliveryServeSub?;
375
- private deliveryAdminServeSub?;
369
+ /** The plane-3 delivery daemon side of this endpoint (fan-out writer, trusted reader, control
370
+ * responders) and the agent's DELIVER pump. Every dependency is read when it is used. */
371
+ private readonly deliveryPlane;
376
372
  /** The anycast take responder, the request records it writes, and their maintenance timer
377
373
  * (delivery daemon, SPEC §8.1). Bound with the other Plane-3 responders and dropped with them. */
378
374
  private takeServeSub?;
@@ -384,24 +380,6 @@ export declare class CotalEndpoint extends EventEmitter {
384
380
  private anycastUnavailable?;
385
381
  private anycastSweep?;
386
382
  private takesInFlight;
387
- /** The lifecycles whose membership inventory this daemon has been asked for, as principal to uids
388
- * (#4965). A durable join or leave bound to one of them is refused, so no row of a retiring lifecycle
389
- * is written after its inventory read starts. An entry goes when a later inventory for the same
390
- * principal finds its ACL row retired; an alias that never retires again keeps its one entry until
391
- * the daemon restarts. This is the second layer of the fence: it covers a manager that does not
392
- * narrow the ACL row before the inventory, on this daemon process only. The first is the ACL row
393
- * each join re-reads around its write (`durableJoinFor`'s `aclFence`), which holds across daemons. */
394
- private readonly retiringLifecycles;
395
- /** The durable joins and leaves running now, by `<principal>/<lifecycleUid>`: the writes an
396
- * inventory of that lifecycle waits for before it reads. */
397
- private readonly membershipWrites;
398
- /** True once {@link quiescePlane3} has stopped serving this shard pending an ownership answer.
399
- * Guards {@link armPlane3} so a RECONNECT cannot silently resume serving mid-question. */
400
- private plane3Quiesced;
401
- /** When set, this endpoint hosts the Plane-3 fan-out writer + trusted reader (the server-side delivery
402
- * daemon). `aclFor` maps an owner id to its current read ACL (`allowSubscribe`) for the reader's
403
- * re-authorization — read FRESH per entry from the durable ACL registry KV, hence async. */
404
- private plane3?;
405
383
  /** Local cache of the channel registry (key = channel token), kept by a KV watch or, on an
406
384
  * endpoint that reads it on demand, by {@link readChannels}. */
407
385
  private readonly channelConfigs;
@@ -411,9 +389,7 @@ export declare class CotalEndpoint extends EventEmitter {
411
389
  /** Orders {@link readChannels} results: a read that settles after a newer one was applied is dropped. */
412
390
  private channelReadGeneration;
413
391
  private channelReadApplied;
414
- /** Serializes history reads ({@link collectHistory}): they share the fixed per-instance
415
- * `chathist_<id>` consumer, so overlapping reads would delete/recreate it under one another. */
416
- private histLock;
392
+ private readonly history;
417
393
  private readonly subs;
418
394
  /** The observer feeds {@link tap} was asked for. This is INTENT, re-subscribed by {@link bindTap}
419
395
  * on every (re)connect: a rebuild after an outage the library could not ride out closes the old
@@ -468,9 +444,6 @@ export declare class CotalEndpoint extends EventEmitter {
468
444
  /** `$JS.API.CONSUMER.DELETE.<stream>.<prefix>_` for each of this connection's own KV watches and
469
445
  * running membership scans (see {@link recordOwnWatchConsumer}). */
470
446
  private readonly ownWatchDeletePrefixes;
471
- /** Per stream, the history-reader names of this connection's current reader id and the reads
472
- * waiting for one (see {@link acquireHistoryReader}). */
473
- private readonly historyReaderSlots;
474
447
  /** True until the first successful connect completes its boot backfill — distinguishes first-connect
475
448
  * (backfill the boot channels' history) from a reconnect (reopen the core-subs, no re-backfill).
476
449
  * Persists across reconnect (NOT connection-scoped). Replaces the legacy chat-durable consumed-cursor
@@ -875,7 +848,14 @@ export declare class CotalEndpoint extends EventEmitter {
875
848
  * running in the background so the endpoint never stays dead, and rethrows so the caller
876
849
  * can report it. */
877
850
  reconnect(): Promise<void>;
878
- /** The presence epoch moves first: a bind still awaiting the broker must find it moved
851
+ /** Stop the endpoint and close its connection.
852
+ *
853
+ * Every principal serve ends first: its handlers' `signal` aborts, and stop waits for each
854
+ * handler in flight until its request's deadline at most, so a handler that never settles does
855
+ * not hold stop open longer than 30 s, the route's cap on a deadline. A reply that comes after
856
+ * that is dropped.
857
+ *
858
+ * The presence epoch moves first: a bind still awaiting the broker must find it moved
879
859
  * before any await below gives it a window to install a watch on a stopped endpoint
880
860
  * (see {@link startPresenceWatch}). */
881
861
  stop(): Promise<void>;
@@ -951,6 +931,7 @@ export declare class CotalEndpoint extends EventEmitter {
951
931
  *
952
932
  * `expectedLastSubjectSeq` is a parameter because it is a header VALUE: sizing at 0 and publishing
953
933
  * at 123456 differ by five bytes.
934
+ * `expectedLastMsgId` is measured when given, so a caller that may send it can size for it.
954
935
  *
955
936
  * Residual: `ts` is re-stamped at publish, so the two differ in value — not in length until
956
937
  * epoch-millis needs a 14th digit.
@@ -960,6 +941,7 @@ export declare class CotalEndpoint extends EventEmitter {
960
941
  parts: Part[];
961
942
  id: string;
962
943
  expectedLastSubjectSeq: number;
944
+ expectedLastMsgId?: string;
963
945
  mentions?: string[];
964
946
  replyTo?: string;
965
947
  contextId?: string;
@@ -982,6 +964,10 @@ export declare class CotalEndpoint extends EventEmitter {
982
964
  * means "the subject must be empty". A mismatch throws, and the throw stays classifiable by the
983
965
  * already-public {@link isCasLoss} — the error is deliberately **not wrapped**, since wrapping
984
966
  * would hide the `err_code` that classification reads.
967
+ * - `expectedLastMsgId`, when given, becomes `Nats-Expected-Last-Msg-Id`. The broker checks it after
968
+ * its dedup cache, so a fresh value nobody has published turns a publish into a probe: an id the
969
+ * cache holds answers `duplicate: true` with the stored sequence, and any other id is refused
970
+ * with error 10070 before anything is stored.
985
971
  *
986
972
  * @throws if the endpoint is not live, the channel is not concrete, `id` is malformed, `parts` is
987
973
  * empty, or `expectedLastSubjectSeq` is not a non-negative safe integer.
@@ -991,6 +977,7 @@ export declare class CotalEndpoint extends EventEmitter {
991
977
  parts: Part[];
992
978
  id: string;
993
979
  expectedLastSubjectSeq: number;
980
+ expectedLastMsgId?: string;
994
981
  mentions?: string[];
995
982
  replyTo?: string;
996
983
  contextId?: string;
@@ -1577,65 +1564,6 @@ export declare class CotalEndpoint extends EventEmitter {
1577
1564
  * `before` pages toward the past: pass the `seq` of the oldest message you already have.
1578
1565
  */
1579
1566
  private streamHistory;
1580
- /** This connection's history-reader id, the key of its credential's reader deletes
1581
- * ({@link historyReaderConsumer}). A static credential's is its connId, the nkey it signs with.
1582
- * Under the auth callout the connId is the inbox nonce this client chose, so the callout keys the
1583
- * deletes on {@link calloutReaderId} instead: the server's id and the client id it assigned this
1584
- * connection, which the client reads from the server's INFO and does not choose. */
1585
- private historyReaderId;
1586
- /** Take one of this connection's history-reader names on `stream` ({@link historyReaderConsumer})
1587
- * for one read. The read holds the name for its whole walk and creates and deletes a consumer
1588
- * under it at each step, so this connection keeps at most {@link HISTORY_READERS} reader consumers
1589
- * on a stream (#4123). A read past that many waits for a name, and `signal` ends the wait. A
1590
- * reconnect under the auth callout changes the reader id, and reads from then on take the new
1591
- * id's names. */
1592
- private acquireHistoryReader;
1593
- /** Give a read's history-reader name back and wake one read waiting for a name. A name whose
1594
- * delete failed is set aside instead. */
1595
- private releaseHistoryReader;
1596
- /** Keep `slot` out of use until a consumer under it would have expired, then free it. */
1597
- private setAsideHistoryReader;
1598
- /** Create the reader consumer for one step of a read, under the read's name. It is a plain pull
1599
- * consumer: an nats.js ordered consumer renames itself on every rebuild, and the observer and admin
1600
- * credentials may delete only these exact names.
1601
- *
1602
- * Every create carries a fresh description. NATS answers a create whose config equals the existing
1603
- * consumer's with that consumer, delivery state and all (measured on nats-server 2.15), and a read
1604
- * repeats the same config on the same name. Without the description a reader left under the name
1605
- * would come back as if new: a `DeliverPolicy.Last` reader that already delivered its message
1606
- * reports nothing pending, which reads as an empty channel. With it, a create on a name in use is
1607
- * refused, and a consumer that does not carry this step's description is never used.
1608
- *
1609
- * A consumer already under the name is never deleted, whoever left it: another holder of this
1610
- * credential, a process that stopped mid-read, or this endpoint when a delete's answer was lost and
1611
- * the name was taken again since. The read moves to a free name, and the taken one stays out of use
1612
- * until such a consumer would have expired. */
1613
- private openHistoryReader;
1614
- /** Delete the read's reader consumer; already gone is the same outcome. A failed delete may still
1615
- * have run with its answer lost, and the name may be taken again before this endpoint could tell,
1616
- * so the name is set aside when the read gives it back rather than deleted again later. A refused
1617
- * delete means the credential was minted before the observer and admin profiles held their reader
1618
- * deletes. Each read would then leave a reader for the inactive threshold, which is how a polling
1619
- * dashboard filled the stream's consumer limit (#4123), so the read fails and says to remint
1620
- * rather than leak quietly, and reads on the stream fail at once until that reader expires. */
1621
- private closeHistoryReader;
1622
- private readerDeleteRefused;
1623
- /** The oldest stream sequence matching `subject`, or 0 when the subject has no messages.
1624
- * Mirror of {@link lastMatchingSeq}: same CREATE/INFO/NEXT/DELETE surface, `DeliverPolicy.All`
1625
- * instead of `Last`, first delivered seq instead of last. Read credentials already hold this. */
1626
- private firstMatchingSeq;
1627
- /** The newest stream sequence matching `subject`, or 0 when the subject has no messages.
1628
- *
1629
- * One reader consumer at `DeliverPolicy.Last` with this subject's filter: its `num_pending`
1630
- * (available from the create, before anything is delivered) is 0 for an empty subject, and
1631
- * otherwise one message carries the sequence. Same CREATE/INFO/NEXT/DELETE surface `drainWindow`
1632
- * already uses, so no broker authority is added. */
1633
- private lastMatchingSeq;
1634
- /** Drain every message matching `subject` with sequence in `[start, ceiling]`, oldest-first.
1635
- * One reader consumer, one batched pull — `AckPolicy.None`, so no per-message ack
1636
- * round trip. Fetches exactly the pending count so it returns as soon as the window is
1637
- * delivered rather than blocking for the pull's full expiry. */
1638
- private drainWindow;
1639
1567
  /**
1640
1568
  * Surface the connection's async status errors on our `error` event. NATS reports
1641
1569
  * publish permission violations *only* here (subscription ones too), never on the
@@ -2075,71 +2003,6 @@ export declare class CotalEndpoint extends EventEmitter {
2075
2003
  onDeliveryCredsAdopted?: () => void;
2076
2004
  startupComplete?: () => boolean;
2077
2005
  }): Promise<void>;
2078
- /** Whether an ALREADY-DISPATCHED unit of Plane-3 work may still take effect.
2079
- *
2080
- * Unsubscribing stops NEW work; it cannot recall work already in flight. A handler that entered
2081
- * before {@link quiescePlane3} and awaited broker I/O inside it resumes AFTER the freeze, and a
2082
- * reviewer traced the ordering that makes that a split rather than a latency blip: the loser
2083
- * accepts a unit and awaits, the loser is descheduled, the successor acquires the shard and flips
2084
- * its lease READY, then the loser resumes and answers or acks for a shard it no longer holds.
2085
- * Subscription counts and parked-pull readings cannot see it, because the effect is the reply and
2086
- * the ack rather than the binding.
2087
- *
2088
- * So each work path re-asks HERE, at the point of effect, after its awaits and before it acts.
2089
- * The lease keeps one ROW, not one SERVER; this is the half that keeps one server. An unacked
2090
- * message is not lost by refusing: a stopped consumer redelivers it to whoever holds the shard
2091
- * next, which is the same property quiescing already relies on. */
2092
- private plane3MayAct;
2093
- /** Serve one runtime durable-membership control request (the server-side delivery daemon). The caller
2094
- * id is the authenticated subject sender ({@link serveControl} fail-closes on a mismatch). Validation
2095
- * is against the durable ACL registry — the SAME KV the reader re-auths against (single source of
2096
- * truth, no in-memory ledger to drift). */
2097
- private handleDeliveryControl;
2098
- /** Validate the channel ARG shape only: non-blank, valid, concrete (NO ACL check, that is op-specific).
2099
- * `family` also admits a channel family such as `review.>` (a membership join or leave, #5404).
2100
- * Returns the channel on success or a ControlReply error to short-circuit. */
2101
- private checkDurableChannelArg;
2102
- /** JOIN requires the channel be within the caller's CURRENT read ACL (you can't durable-subscribe a
2103
- * channel you may not read). A family must lie inside one ACL entry, so every channel under it is
2104
- * readable. */
2105
- private deliveryJoin;
2106
- /** Whether `lifecycleUid`'s exact ACL row still allows reads, so an inventory of it came from a
2107
- * caller that did not fence. A row narrowed to no reads, or retired or absent, is fenced. A read
2108
- * that fails answers true: the caller keeps its in-memory mark, which only ever refuses. */
2109
- private lifecycleAclUnfenced;
2110
- /** Run one durable join or leave that writes `principal`'s rows of `lifecycleUid`, refused once that
2111
- * lifecycle's inventory has been asked for ({@link retiringLifecycles}). The check and the
2112
- * registration have no await between them, so an inventory either finds this write running and
2113
- * waits for it, or this write finds the inventory's mark and is refused. */
2114
- private membershipWrite;
2115
- /** LEAVE must NOT require current-ACL coverage. Leave fires precisely when the ACL was narrowed/revoked
2116
- * (a refused live sub → {@link closeRefusedMembership}); gating the tombstone on the current ACL would
2117
- * loop forever and leave the SPEC §7 boundary open (the membership could resume if the ACL is later
2118
- * restored). The guards are: authenticated caller (serveControl), concrete channel, a finite generation
2119
- * (the join epoch — without it a stale/replayed leave could tombstone a newer rejoin), and an EXISTING
2120
- * own membership; `durableLeaveFor` → `tombstoneMember` then enforces the generation match. */
2121
- private deliveryLeave;
2122
- /** Serve one MEDIATED HISTORY READ (`readHistory`, the client side is {@link readHistory}). The daemon
2123
- * holds the consumer so the caller does not have to: this is a privilege reduction, not a new
2124
- * capability, and it is the shape SPEC's "Mediated reads (normative)" rule asks for.
2125
- *
2126
- * THE ONE INVARIANT THIS METHOD EXISTS FOR: authorization is read FRESH on every call and never
2127
- * cached across calls. A consumer pins its authorization when it is created, so a revoked caller
2128
- * keeps being served by a consumer it already holds; re-reading here is what makes a revocation
2129
- * stop the very NEXT read. Cache this and the verb loses its only advantage over the raw consumer
2130
- * path.
2131
- *
2132
- * AUTHORITY (SPEC §9.6): "current read ACL" is the effective broker-accepted credential. The
2133
- * durable registry is a live mirror of that credential, not a second grant source. History
2134
- * authorizes against `allowSubscribe ∩ issuedAllowSubscribe` — the live row (so revocation via
2135
- * plain commitAcl still stops the next read) intersected with the mint-time ceiling (so a
2136
- * registry widen without a remint cannot grant what the JWT does not). Raising the ceiling is
2137
- * {@link reissueAcl}, which is what provision does when it bakes the list into the JWT.
2138
- *
2139
- * The caller arrives as an alias (the control subject carries owner+actor, never a uid) and is the
2140
- * AUTHENTICATED subject sender — `serveControl` has already fail-closed on any payload that names a
2141
- * different principal, so `caller` cannot be self-asserted. */
2142
- private deliveryReadHistory;
2143
2006
  /** Stop serving Plane-3 WITHOUT tearing down the connection, so a daemon that has just learned its
2144
2007
  * lease may no longer be its own can stop acting on the shard while it finds out for certain.
2145
2008
  *
@@ -2175,19 +2038,12 @@ export declare class CotalEndpoint extends EventEmitter {
2175
2038
  * That is a readiness lie surviving a transient broker error, the daemon claims a responder it does
2176
2039
  * not have, which is the #1318 outage wearing the readiness flag instead of the exit path. */
2177
2040
  rearmPlane3(): Promise<void>;
2178
- /** (Re)bind the Plane-3 fan-out writer + trusted reader. Idempotent — the durables resume from their
2179
- * cursor. Called by {@link startPlane3} once AND by {@link connectAndBind} on every (re)connect, so
2180
- * the delivery daemon's reconnect RE-ARMS the backstop + the ctl.delivery responder. Without this, a broker blip would silently kill
2181
- * the loops while `durableJoinFor` kept reporting `durable:true` (the impl-review's BLOCKER-1). No-op
2182
- * unless this endpoint hosts Plane-3 (`this.plane3` set). */
2041
+ /** Forwards to the delivery plane's {@link EndpointDeliveryPlane.plane3MayAct}. */
2042
+ private plane3MayAct;
2043
+ /** Forwards to the delivery plane's {@link EndpointDeliveryPlane.armPlane3}. */
2183
2044
  private armPlane3;
2184
- /** (Re)register the `ctl.delivery` control responder on the CURRENT connection. A reconnect drains the
2185
- * old connection (the old sub is dead and `clearConnectionScoped` leaves caller-owned subs alone), so
2186
- * this MUST run on every arm — otherwise durable join/leave/list silently lose their responder after a
2187
- * broker blip. The stale sub is dropped (unsubscribed + removed from `this.subs`) before re-creating.
2188
- * `boundReply` is essential here: the daemon holds a wildcard reply-publish grant, so the serve path
2189
- * must reject any reply target outside the authenticated sender's own subtree (confused-deputy fix). */
2190
- private armDeliveryControl;
2045
+ /** Forwards to the delivery plane's {@link EndpointDeliveryPlane.pumpDlv}. */
2046
+ private pumpDlv;
2191
2047
  /** (Re)bind the anycast take responder and the request records maintenance on the current
2192
2048
  * connection (SPEC §8.1). The records bucket is created here as well as at space setup, so a mesh
2193
2049
  * that predates it gets one when its daemon restarts at this version. */
@@ -2289,31 +2145,32 @@ export declare class CotalEndpoint extends EventEmitter {
2289
2145
  * is about something being wedged). Neither may ever mean health. */
2290
2146
  private probeFailureOutcome;
2291
2147
  /**
2292
- * Serve this process's own endpoint on the principal route (SPEC 13.21): a core-defined command
2293
- * set about this principal, addressed by its own principal, lifecycle UID and runtime id, with no
2294
- * registration. Revision 1 defines one endpoint, `agent` (SPEC 13.22).
2148
+ * Serve this process's `agent` endpoint on the principal route (SPEC 13.21, 13.22): the
2149
+ * `AGENT_CLUSTER` command set about this principal, addressed by its own principal, lifecycle UID
2150
+ * and runtime id, with no registration. `handlers` serves the cluster's commands with
2151
+ * `AGENT_CONTRACTS`; `describe` is built in.
2295
2152
  *
2296
2153
  * Throws on an open mesh and on a static credential, where no row names who may call, without a
2297
- * lifecycle UID, before the endpoint has started, for an endpoint it already serves, and for a
2298
- * cluster with a command that declares no `authorities` (see {@link servePrincipalRoute}). It
2299
- * subscribes this process's own subject with no queue group.
2154
+ * lifecycle UID, before the endpoint has started, while it already serves `agent`, for an
2155
+ * `endpoint` or `cluster` field, which this entry point does not take, and for a set of handlers
2156
+ * that is not the cluster's commands with its contracts. It subscribes this process's own subject
2157
+ * with no queue group.
2300
2158
  *
2301
2159
  * `ready` is a positive check: it resolves only after the broker accepted the subscription
2302
2160
  * (subscribe, flush, and no permission violation for that subject), and rejects with the
2303
2161
  * refusal, which a credential minted before the rows existed gets. The serve is INTENT: every
2304
2162
  * replaced connection subscribes again and runs the check again, and a refusal there ends the
2305
- * serve, resolves `failed` and clears the presence field. `stop` unsubscribes and waits for the
2306
- * handlers in flight.
2163
+ * serve, resolves `failed` and clears the presence field. `stop` unsubscribes, aborts the
2164
+ * handlers' `signal`, and waits for each handler in flight until its request's deadline at most.
2307
2165
  */
2308
- servePrincipal(serve: {
2309
- endpoint: string;
2310
- cluster: ClusterDocument;
2166
+ servePrincipal(spec: {
2311
2167
  handlers: EpPrincipalCommandDef[];
2312
2168
  }): PrincipalServe;
2313
2169
  /** Subscribe `intent` on `nc`. */
2314
2170
  private bindPrincipalHandle;
2315
- /** A request or reply subject (or filter) of the principal route in this space. */
2316
- private isPrincipalRouteSubject;
2171
+ /** A principal-route refusal a call or a serve reports itself: a request publish, a serve
2172
+ * subscription or a reply read. Only a reply publish is left, which no call or serve awaits. */
2173
+ private ownedPrincipalRouteRefusal;
2317
2174
  /** Track one binding: a refusal ends the serve, and an accepted subscription on the current
2318
2175
  * connection shows the presence field. */
2319
2176
  private armPrincipalServe;
@@ -2327,7 +2184,8 @@ export declare class CotalEndpoint extends EventEmitter {
2327
2184
  private endPrincipalServe;
2328
2185
  /** Mark `intent` ended and release what it holds in this endpoint and in this process. */
2329
2186
  private forgetPrincipalServe;
2330
- /** Stop serving `intent` and wait for its handlers in flight. The ending is synchronous, so a
2187
+ /** Stop serving `intent` and wait for its handlers in flight, each until its request's deadline
2188
+ * at most. The ending is synchronous, so a
2331
2189
  * `ready` still waiting for the broker rejects before the caller's next step. `republish` writes
2332
2190
  * presence without the `prompts` field; the endpoint's own stop writes it offline instead. */
2333
2191
  private stopPrincipalServe;
@@ -2336,8 +2194,8 @@ export declare class CotalEndpoint extends EventEmitter {
2336
2194
  * prompts it holds `open` or `sent`, and a counter that goes up by one each time a prompt opens or
2337
2195
  * changes state. The field shows only while the `agent` endpoint is served and the broker accepted
2338
2196
  * its subscription on the current connection. Until this is called it shows `open: 0` with the
2339
- * highest `seq` this process used under its runtime id, or 0. Throws when the `agent` endpoint is
2340
- * not served, and a RangeError for a `seq` below one this runtime already used.
2197
+ * fresh `seq` the serve took from {@link nextPromptsSeq} when it started. Throws when the `agent`
2198
+ * endpoint is not served, and a RangeError for a `seq` below one this runtime already used.
2341
2199
  */
2342
2200
  setPromptsPresence(prompts: PresencePrompts): Promise<void>;
2343
2201
  /**
@@ -2374,52 +2232,6 @@ export declare class CotalEndpoint extends EventEmitter {
2374
2232
  };
2375
2233
  signal?: AbortSignal;
2376
2234
  }): Promise<EndpointReply>;
2377
- /** Serve one PRIVILEGED delivery-admin request (the D5 rail-split). The cred layer is the caller
2378
- * boundary — only the supervisor profile can publish here — and `serveControl`'s sender check +
2379
- * bounded reply still apply on top. `reloadCreds` is the class-2 renewal ADOPTION step: re-read
2380
- * the renewal-owner-re-signed creds file, pin, swap the live connection, reconnect the membership
2381
- * feed's rw connection, and reply with proof (identities + the adopted JWT windows) — or a
2382
- * structured failure (e.g. the file was never re-signed), never a silent partial. */
2383
- private handleDeliveryAdmin;
2384
- /** Create one of the daemon's Plane-3 durables. A named create is idempotent for the same config,
2385
- * and a denial is never taken for existence. The one conflict accepted is this durable as a full
2386
- * restore recreated it, starting after its recorded ACK floor ({@link isRestoredConsumer}); every
2387
- * other failure propagates. */
2388
- private addPlane3Durable;
2389
- /** Fan-out loop: bind the privileged `fanout` durable on CHAT and route each message (routing only —
2390
- * the trusted reader is the auth gate). */
2391
- private runFanout;
2392
- /** Route ONE chat message to eligible owners' mixed inboxes. `durable` channel → its `durable-active`
2393
- * members within interval; `live` channel → `@mention` targets authorized to read it (ACL only).
2394
- * On either class, a mention of an agent whose read ACL excludes the channel is reported to the
2395
- * sender with a mention notice. Members KV is scanned FRESH per message (no cache — red-team
2396
- * BLOCKER-1 catch-up correctness). */
2397
- private fanOutMessage;
2398
- private deliveryLimitRead?;
2399
- /** The DLV count the trusted writer stamps on a copy (SPEC §8): the stream's `max_msgs_per_subject`,
2400
- * read at most {@link DELIVERY_LIMIT_READ_MS} before the write, as a whole number or `none`. */
2401
- private deliveryLimitStamp;
2402
- /** Trusted-reader loop: bind the single privileged `reader` durable over `dinbox.>` and re-authorize
2403
- * + transfer each entry. */
2404
- private runReader;
2405
- /** Whether one of the lifecycle's rows covering concrete `channel`, the channel's own or a family
2406
- * above it, is eligible for the post at `seq`. One exact read per row, the channel's own first. */
2407
- private lifecycleCoversPost;
2408
- /** Remove a retired lifecycle's member row for `channel`, when one exists. Best effort: the row
2409
- * authorizes nothing (its ACL row is retired), and the next entry fan-out writes against it
2410
- * brings the reader back here. */
2411
- private removeRetiredMemberRow;
2412
- /** Re-authorize ONE mixed-inbox entry and transfer it to the owner's DELIVER store. Deny (drop) on a
2413
- * revoked/narrowed ACL or out-of-interval seq; on transfer success, ack the mixed entry (durability
2414
- * has moved to DLV — an §8 equivalent per-member at-least-once mechanism). The agent acks DLV. */
2415
- private readerHandle;
2416
- /** Agent-side: bind + pump our pre-created Plane-3 DELIVER durable (`dlv_<id>`). Every message here is
2417
- * delivery-daemon-written (DLV is delivery-write-only, broker-enforced) and is a CHANNEL message by contract
2418
- * (the backstop never carries DMs), so `kind=channel` is path-derived (SPEC §4) and the body is
2419
- * trusted (no spoof-guard). `durable:true` — real JetStream ack, coalesced with the core-sub live
2420
- * copy by `MeshAgent.ingest`. No-op when the durable isn't present (open mode / not provisioned). A read
2421
- * list declared on a credential that cannot fetch the durable refuses. */
2422
- private pumpDlv;
2423
2235
  /** Agent-side: request a Plane-3 durable backstop for a channel via the server-side delivery daemon (ctl.delivery). Throws
2424
2236
  * when no privileged writer is present (open / no delivery daemon). 30s timeout — activation catch-up may
2425
2237
  * run before the reply (the window is small, but a busy channel can take more than the 5s default). */
@@ -2586,7 +2398,6 @@ export declare class CotalEndpoint extends EventEmitter {
2586
2398
  * calls must be serial — every reader here awaits to completion, so they are.
2587
2399
  */
2588
2400
  private collectHistory;
2589
- private collectHistoryInner;
2590
2401
  /** Read a channel's retained history up to `upToSeq` (the join frontier) and emit each message
2591
2402
  * as a `historical` "message" event. `sinceMs` bounds how far back via a native consumer
2592
2403
  * `start_time` (now − window); unset ⇒ the full retained window. `floorSeq`, when set, is a