@cotal-ai/core 0.168.0 → 0.170.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 (118) hide show
  1. package/dist/agent-file.d.ts +9 -5
  2. package/dist/agent-file.d.ts.map +1 -1
  3. package/dist/agent-file.js +30 -17
  4. package/dist/agent-file.js.map +1 -1
  5. package/dist/anycast-requests.d.ts +8 -1
  6. package/dist/anycast-requests.d.ts.map +1 -1
  7. package/dist/anycast-requests.js +47 -0
  8. package/dist/anycast-requests.js.map +1 -1
  9. package/dist/backup-config.d.ts +5 -2
  10. package/dist/backup-config.d.ts.map +1 -1
  11. package/dist/backup-config.js +7 -2
  12. package/dist/backup-config.js.map +1 -1
  13. package/dist/backup.d.ts +6 -0
  14. package/dist/backup.d.ts.map +1 -1
  15. package/dist/backup.js +11 -4
  16. package/dist/backup.js.map +1 -1
  17. package/dist/connector-setup.d.ts +2 -0
  18. package/dist/connector-setup.d.ts.map +1 -1
  19. package/dist/connector.d.ts +8 -11
  20. package/dist/connector.d.ts.map +1 -1
  21. package/dist/control-exchange.d.ts +114 -0
  22. package/dist/control-exchange.d.ts.map +1 -0
  23. package/dist/control-exchange.js +416 -0
  24. package/dist/control-exchange.js.map +1 -0
  25. package/dist/endpoint-binding.d.ts.map +1 -1
  26. package/dist/endpoint-binding.js +2 -0
  27. package/dist/endpoint-binding.js.map +1 -1
  28. package/dist/endpoint-call.d.ts +2 -1
  29. package/dist/endpoint-call.d.ts.map +1 -1
  30. package/dist/endpoint-call.js +14 -7
  31. package/dist/endpoint-call.js.map +1 -1
  32. package/dist/endpoint-channel-discovery.d.ts +102 -0
  33. package/dist/endpoint-channel-discovery.d.ts.map +1 -0
  34. package/dist/endpoint-channel-discovery.js +170 -0
  35. package/dist/endpoint-channel-discovery.js.map +1 -0
  36. package/dist/endpoint-control-plane.d.ts +204 -0
  37. package/dist/endpoint-control-plane.d.ts.map +1 -0
  38. package/dist/endpoint-control-plane.js +627 -0
  39. package/dist/endpoint-control-plane.js.map +1 -0
  40. package/dist/endpoint-delivery-plane.d.ts +337 -0
  41. package/dist/endpoint-delivery-plane.d.ts.map +1 -0
  42. package/dist/endpoint-delivery-plane.js +1291 -0
  43. package/dist/endpoint-delivery-plane.js.map +1 -0
  44. package/dist/endpoint-durable-backstop.d.ts +249 -0
  45. package/dist/endpoint-durable-backstop.d.ts.map +1 -0
  46. package/dist/endpoint-durable-backstop.js +485 -0
  47. package/dist/endpoint-durable-backstop.js.map +1 -0
  48. package/dist/endpoint-envelope.d.ts +2 -1
  49. package/dist/endpoint-envelope.d.ts.map +1 -1
  50. package/dist/endpoint-envelope.js +9 -3
  51. package/dist/endpoint-envelope.js.map +1 -1
  52. package/dist/endpoint-history.d.ts +370 -0
  53. package/dist/endpoint-history.d.ts.map +1 -0
  54. package/dist/endpoint-history.js +969 -0
  55. package/dist/endpoint-history.js.map +1 -0
  56. package/dist/endpoint-inbound.d.ts +10 -0
  57. package/dist/endpoint-inbound.d.ts.map +1 -0
  58. package/dist/endpoint-inbound.js +28 -0
  59. package/dist/endpoint-inbound.js.map +1 -0
  60. package/dist/endpoint-liveness.d.ts +105 -0
  61. package/dist/endpoint-liveness.d.ts.map +1 -0
  62. package/dist/endpoint-liveness.js +223 -0
  63. package/dist/endpoint-liveness.js.map +1 -0
  64. package/dist/endpoint-messaging.d.ts +229 -0
  65. package/dist/endpoint-messaging.d.ts.map +1 -0
  66. package/dist/endpoint-messaging.js +420 -0
  67. package/dist/endpoint-messaging.js.map +1 -0
  68. package/dist/endpoint-presence.d.ts +15 -0
  69. package/dist/endpoint-presence.d.ts.map +1 -1
  70. package/dist/endpoint-presence.js +35 -0
  71. package/dist/endpoint-presence.js.map +1 -1
  72. package/dist/endpoint-serve.d.ts +11 -1
  73. package/dist/endpoint-serve.d.ts.map +1 -1
  74. package/dist/endpoint-serve.js +42 -5
  75. package/dist/endpoint-serve.js.map +1 -1
  76. package/dist/endpoint-subjects.d.ts +3 -0
  77. package/dist/endpoint-subjects.d.ts.map +1 -1
  78. package/dist/endpoint-subjects.js +3 -0
  79. package/dist/endpoint-subjects.js.map +1 -1
  80. package/dist/endpoint-subscriptions.d.ts +199 -0
  81. package/dist/endpoint-subscriptions.d.ts.map +1 -0
  82. package/dist/endpoint-subscriptions.js +543 -0
  83. package/dist/endpoint-subscriptions.js.map +1 -0
  84. package/dist/endpoint.d.ts +96 -344
  85. package/dist/endpoint.d.ts.map +1 -1
  86. package/dist/endpoint.js +518 -3854
  87. package/dist/endpoint.js.map +1 -1
  88. package/dist/index.d.ts +3 -1
  89. package/dist/index.d.ts.map +1 -1
  90. package/dist/index.js +5 -1
  91. package/dist/index.js.map +1 -1
  92. package/dist/launch-material.d.ts +9 -3
  93. package/dist/launch-material.d.ts.map +1 -1
  94. package/dist/launch-material.js +22 -2
  95. package/dist/launch-material.js.map +1 -1
  96. package/dist/provision-jwt.d.ts.map +1 -1
  97. package/dist/provision-jwt.js +1 -0
  98. package/dist/provision-jwt.js.map +1 -1
  99. package/dist/provision-permissions.d.ts +1 -1
  100. package/dist/provision-permissions.d.ts.map +1 -1
  101. package/dist/provision-permissions.js +10 -1
  102. package/dist/provision-permissions.js.map +1 -1
  103. package/dist/remote-manager-authority.d.ts +1 -1
  104. package/dist/run-host.d.ts +4 -1
  105. package/dist/run-host.d.ts.map +1 -1
  106. package/dist/run-journal.d.ts +2 -0
  107. package/dist/run-journal.d.ts.map +1 -1
  108. package/dist/run-journal.js +1 -1
  109. package/dist/run-journal.js.map +1 -1
  110. package/dist/run-record.d.ts +4 -0
  111. package/dist/run-record.d.ts.map +1 -1
  112. package/dist/run-record.js +36 -0
  113. package/dist/run-record.js.map +1 -1
  114. package/dist/space-quiescence-resources.d.ts +30 -0
  115. package/dist/space-quiescence-resources.d.ts.map +1 -0
  116. package/dist/space-quiescence-resources.js +45 -0
  117. package/dist/space-quiescence-resources.js.map +1 -0
  118. package/package.json +5 -1
@@ -0,0 +1,485 @@
1
+ // The Plane-3 registries, leases and durable membership writes of CotalEndpoint, as an internal
2
+ // component. Moved verbatim from endpoint.ts; the endpoint keeps the public methods and forwards to
3
+ // them. Not re-exported by the index.
4
+ import { jetstream, jetstreamManager, JetStreamApiCodes } from "@nats-io/jetstream";
5
+ import { Kvm } from "@nats-io/kv";
6
+ import { openAclRegistry, readAcl, readAclForAlias, AmbiguousAclAlias, commitAcl as writeAclRecord, reissueAcl as writeAclReissue } from "./acls.js";
7
+ import { effectiveDeliveryClass, readChannelConfig, readChannelDefaults } from "./channels.js";
8
+ import { isCasLoss } from "./endpoint-records.js";
9
+ import { openMembersRegistry, commitMemberRevision, tombstoneMember, activateMember, readMember, deleteMember, listMembers } from "./members.js";
10
+ import { MANAGER_LEASE_TTL_MS, MANAGER_LEASE_ATTEMPT_MS } from "./streams.js";
11
+ import { chatStream, dinboxSubject, FANOUT_DURABLE, isConcreteChannel, managerBucket, MANAGER_LEASE_KEY, MANAGER_RENEWAL_LEASE_KEY, managerLeaseKey, memberKey, parsePrincipalKey } from "./subjects.js";
12
+ /** The Plane-3 durable backstop's state outside the delivery loops: the members and read-ACL
13
+ * registries, the manager and daemon-renewal leases, and the durable join and leave writes the
14
+ * delivery daemon serves. Internal: `CotalEndpoint` keeps the public methods and forwards to it. */
15
+ export class EndpointDurableBackstop {
16
+ deps;
17
+ constructor(deps) {
18
+ this.deps = deps;
19
+ }
20
+ get nc() { return this.deps.nc(); }
21
+ get js() { return this.deps.js(); }
22
+ get jsm() { return this.deps.jsm(); }
23
+ set jsm(manager) { if (manager)
24
+ this.deps.setJsm(manager); }
25
+ get space() { return this.deps.space(); }
26
+ get card() { return this.deps.card(); }
27
+ get authed() { return this.deps.authed(); }
28
+ get channelKv() { return this.deps.channelKv(); }
29
+ get presence() { return this.deps.presence(); }
30
+ get deliveryPlane() { return this.deps.deliveryPlane(); }
31
+ get membersKv() { return this.deps.membersKv(); }
32
+ set membersKv(kv) { this.deps.setMembersKv(kv); }
33
+ get aclKv() { return this.deps.aclKv(); }
34
+ set aclKv(kv) { this.deps.setAclKv(kv); }
35
+ get managerLeaseKv() { return this.deps.managerLeaseKv(); }
36
+ set managerLeaseKv(kv) { this.deps.setManagerLeaseKv(kv); }
37
+ get daemonRenewalLeaseRevision() { return this.deps.daemonRenewalLeaseRevision(); }
38
+ set daemonRenewalLeaseRevision(revision) { this.deps.setDaemonRenewalLeaseRevision(revision); }
39
+ notLiveMsg() { return this.deps.notLiveMsg(); }
40
+ consumerInfo(stream, durable) { return this.deps.consumerInfo(stream, durable); }
41
+ manager() { return this.deps.manager(); }
42
+ chatFrontier() { return this.deps.chatFrontier(); }
43
+ aclAllows(owner, lifecycleUid, channel) { return this.deps.aclAllows(owner, lifecycleUid, channel); }
44
+ catchupCopy(owner, lifecycleUid, channel, fromSeqExcl, toSeqIncl, generation) {
45
+ return this.deps.catchupCopy(owner, lifecycleUid, channel, fromSeqExcl, toSeqIncl, generation);
46
+ }
47
+ /** Lazily open the privileged members registry KV (delivery daemon / open-mode self). */
48
+ async membersRegistry() {
49
+ if (!this.nc)
50
+ throw new Error(this.notLiveMsg());
51
+ this.membersKv ??= await openMembersRegistry(this.nc, this.space);
52
+ return this.membersKv;
53
+ }
54
+ /** Lazily open the durable read-ACL registry KV. Privileged write (the manager records an agent's
55
+ * ACL at mint); the delivery daemon reads it fresh per durable entry to re-authorize. */
56
+ async aclRegistry() {
57
+ if (!this.nc)
58
+ throw new Error(this.notLiveMsg());
59
+ this.aclKv ??= await openAclRegistry(this.nc, this.space);
60
+ return this.aclKv;
61
+ }
62
+ /** Privileged ({@link DurableProvisioner}): record an agent's read ACL in the durable registry at
63
+ * provision/mint time — the same act as baking it into the JWT, persisted so the server-side
64
+ * delivery daemon can re-authorize the agent's durable entries and validate its runtime
65
+ * durable-joins without holding any in-memory ledger. Written ATOMICALLY ({@link writeAclRecord}),
66
+ * so a present record is always complete (`[]` = known no-read, never a half-write). */
67
+ async commitAcl(targetId, lifecycleUid, allowSubscribe) {
68
+ await writeAclRecord(await this.aclRegistry(), targetId, lifecycleUid, allowSubscribe);
69
+ }
70
+ /**
71
+ * Raise the mint-time ACL ceiling. Provision/remint only — see {@link reissueAcl}.
72
+ * Process discipline: call only in the same act that bakes `allowSubscribe` into the JWT; the
73
+ * write is not crypto-bound to credential bytes.
74
+ */
75
+ async reissueAcl(targetId, lifecycleUid, allowSubscribe) {
76
+ await writeAclReissue(await this.aclRegistry(), targetId, lifecycleUid, allowSubscribe);
77
+ }
78
+ /** The server-side delivery daemon's fresh-per-entry ACL read: one LIFECYCLE's current read ACL
79
+ * (`allowSubscribe`) from the durable registry (exact key `<owner>.<actor>.<uid>`), or `undefined`
80
+ * if no record (an unknown lifecycle — the reader DEFERS, never drops). A present `[]` (known
81
+ * no-read) returns `[]` (the reader DROPS). */
82
+ async aclForOwner(owner, lifecycleUid) {
83
+ return (await readAcl(await this.aclRegistry(), owner, lifecycleUid))?.record.allowSubscribe;
84
+ }
85
+ /** Resolve an ALIAS to its single live lifecycle-keyed ACL row (`readAclForAlias`): the daemon's
86
+ * authz seam for callers that arrive with alias identity only (a `ctl.delivery` durable-join).
87
+ * THROWS {@link AmbiguousAclAlias} on two live rows — first-match would let a stale lifecycle
88
+ * authorize the successor (SPEC 13.1: at most one live lifecycle per alias). */
89
+ async aclForAlias(principal) {
90
+ const row = await readAclForAlias(await this.aclRegistry(), principal);
91
+ if (row === undefined)
92
+ return undefined;
93
+ const allow = row.record.allowSubscribe;
94
+ // Legacy rows predate the ceiling field: treat missing as equal to allowSubscribe so behaviour
95
+ // matches what that row already exposed. New rows always carry an explicit ceiling.
96
+ const issued = row.record.issuedAllowSubscribe ?? allow;
97
+ return { allowSubscribe: allow, issuedAllowSubscribe: issued, lifecycleUid: row.lifecycleUid };
98
+ }
99
+ /** Ensure + bind the manager singleton-lease bucket. Mirrors the presence-bucket pattern (connectAndBind):
100
+ * AUTH mode OPENs the bucket pre-created at `cotal up` (the scoped `supervisor` cred holds no
101
+ * STREAM.CREATE — and `open` binds direct=false, so the CAS-conflict `kv.get` inside `acquire` rides
102
+ * STREAM.MSG.GET, the verb the supervisor grants, never DIRECT.GET). OPEN mode (no creds) create-firsts:
103
+ * `Kvm.open` binds LAZILY — it does NOT verify the stream exists or throw when it's missing (a fresh
104
+ * bucket then fails 'stream not found' on the first write), so `create` is the ensure-exists call (it
105
+ * makes the bucket or, when another endpoint already did, throws and we bind the existing one). Either
106
+ * way the per-KEY CAS create stays the only single-flight gate, so a lost bucket-create race never reads
107
+ * as "lease held". */
108
+ async managerLeaseRegistry() {
109
+ if (!this.nc)
110
+ throw new Error(this.notLiveMsg());
111
+ if (this.managerLeaseKv)
112
+ return this.managerLeaseKv;
113
+ // A JetStream client of its own, so every operation on this bucket carries the lease budget's
114
+ // attempt deadline rather than the library default. The default is TTL/2, which would let one
115
+ // attempt spend the whole renew window (see MANAGER_LEASE_ATTEMPT_MS). Scoped to this bucket:
116
+ // every op on it is a single small keyed request, and nothing else shares this client.
117
+ const kvm = new Kvm(jetstream(this.nc, { timeout: MANAGER_LEASE_ATTEMPT_MS }));
118
+ if (this.authed) {
119
+ this.managerLeaseKv = await kvm.open(managerBucket(this.space));
120
+ }
121
+ else {
122
+ try {
123
+ this.managerLeaseKv = await kvm.create(managerBucket(this.space), { ttl: MANAGER_LEASE_TTL_MS });
124
+ }
125
+ catch {
126
+ // OPEN mode has no broker ACLs, so a permission denial is impossible here. `create` is only
127
+ // the ensure-exists attempt; `open` below is the authority after either a pre-existing bucket
128
+ // or a create race, and it still throws if the bucket cannot actually be used.
129
+ this.managerLeaseKv = await kvm.open(managerBucket(this.space));
130
+ }
131
+ }
132
+ return this.managerLeaseKv;
133
+ }
134
+ /** Take or keep the per-SPACE daemon-credential renewal lease (#1634), returning whether THIS
135
+ * instance now holds it. One atomic CAS `create` per pass: it succeeds for whoever arrives first
136
+ * and throws for everyone else, so exactly one manager remints even when several share the
137
+ * daemon's store. The holder re-`update`s its own key by revision, which both keeps it and proves
138
+ * it never lost it. Losing the CAS is an ordinary outcome (a peer holds it) and returns false; it
139
+ * never fails a start. A crashed holder's key TTL-expires with the bucket, so the next pass hands
140
+ * the lease to a survivor with no operator step. */
141
+ async holdDaemonRenewalLease(instanceId) {
142
+ const kv = await this.managerLeaseRegistry();
143
+ const held = this.daemonRenewalLeaseRevision;
144
+ if (held !== undefined) {
145
+ try {
146
+ this.daemonRenewalLeaseRevision = await kv.update(MANAGER_RENEWAL_LEASE_KEY, this.encodeDaemonRenewalLease(instanceId), held);
147
+ return true;
148
+ }
149
+ catch {
150
+ // The revision moved (our key TTL-expired and a peer took it). Re-contend below rather than
151
+ // keep reminting on a lease we no longer hold.
152
+ this.daemonRenewalLeaseRevision = undefined;
153
+ }
154
+ }
155
+ try {
156
+ this.daemonRenewalLeaseRevision = await kv.create(MANAGER_RENEWAL_LEASE_KEY, this.encodeDaemonRenewalLease(instanceId));
157
+ return true;
158
+ }
159
+ catch {
160
+ return false; // another manager holds it: exactly one owner is the point
161
+ }
162
+ }
163
+ /** Release the renewal lease on a clean stop so a peer takes over at once rather than at the TTL.
164
+ * CAS-guarded, so a lease we already lost is never deleted out from under its new holder. */
165
+ async releaseDaemonRenewalLease() {
166
+ const held = this.daemonRenewalLeaseRevision;
167
+ this.daemonRenewalLeaseRevision = undefined;
168
+ if (held === undefined)
169
+ return;
170
+ try {
171
+ await (await this.managerLeaseRegistry()).delete(MANAGER_RENEWAL_LEASE_KEY, { previousSeq: held });
172
+ }
173
+ catch {
174
+ // Best-effort: a moved revision means it is not ours, and a broker failure is recovered by the
175
+ // bucket TTL. Shutdown must not claim deletion.
176
+ }
177
+ }
178
+ encodeDaemonRenewalLease(instanceId) {
179
+ return new TextEncoder().encode(JSON.stringify({ instanceId, since: Date.now() }));
180
+ }
181
+ /** Read the per-space daemon-credential renewal-lease row (the one {@link holdDaemonRenewalLease}
182
+ * CAS-writes), or `undefined` when nothing holds it. A `doctor auth --fix` that lost `hold` calls
183
+ * this through the SAME bucket the hold attempt opened, to name the live holder in its refusal —
184
+ * `managerLeaseKv` is private, so this is the exported read beside {@link readManagerLease}. */
185
+ async readDaemonRenewalLease() {
186
+ const e = await (await this.managerLeaseRegistry()).get(MANAGER_RENEWAL_LEASE_KEY);
187
+ if (!e || e.operation !== "PUT")
188
+ return undefined;
189
+ return JSON.parse(new TextDecoder().decode(e.value));
190
+ }
191
+ encodeManagerLease(info) {
192
+ return new TextEncoder().encode(JSON.stringify(info));
193
+ }
194
+ /** Acquire THIS logical instance's liveness lease via ATOMIC CAS create on its own per-instance key
195
+ * ({@link managerLeaseKey}). THROWS only if that SAME instance id already holds a live key (a same-root
196
+ * concurrent double-start, or a restart racing the crashed predecessor's not-yet-expired key) — a loud
197
+ * refusal, never a retry. A DIFFERENT instance (second workspace root ⇒ different id) creates its OWN
198
+ * key and coexists. A crashed holder's key auto-expires (bucket TTL). Returns the
199
+ * lease revision (for renew). */
200
+ async acquireManagerLease(info) {
201
+ return (await this.managerLeaseRegistry()).create(managerLeaseKey(info.instanceId), this.encodeManagerLease({ ...info, since: Date.now() }));
202
+ }
203
+ /** Renew THIS instance's held key (CAS update against `revision`) before the bucket TTL expires it.
204
+ * Throws if the revision moved (lost the lease). Returns the new revision. */
205
+ async renewManagerLease(info, revision) {
206
+ return (await this.managerLeaseRegistry()).update(managerLeaseKey(info.instanceId), this.encodeManagerLease({ ...info, since: Date.now() }), revision);
207
+ }
208
+ /** Read THIS instance's OWN lease key, keyed (not the `lease.*` sweep {@link readManagerLease} does).
209
+ *
210
+ * `undefined` means the key IS NOT THERE — a definite absence, established by a completed read.
211
+ * A read that could not be completed THROWS instead, so a caller can tell "it is gone" from "I could
212
+ * not find out". That distinction is the whole point of the method: a renew that got no answer has
213
+ * proved nothing, and only a definite answer here may be acted on.
214
+ *
215
+ * `created` is the broker's write time of the row (epoch ms), which is what the bucket TTL counts
216
+ * from. */
217
+ async readOwnManagerLease(instanceId) {
218
+ const e = await (await this.managerLeaseRegistry()).get(managerLeaseKey(instanceId));
219
+ if (!e || e.operation !== "PUT")
220
+ return undefined;
221
+ return { info: JSON.parse(new TextDecoder().decode(e.value)), revision: e.revision, created: e.created.getTime() };
222
+ }
223
+ /** Release THIS instance's key on clean shutdown so a same-id restart re-acquires immediately. CAS-guarded
224
+ * by `revision`: if we already LOST it (renew gap) the stored revision has moved, and the conditional
225
+ * delete is refused and rejects, like any broker failure; a shutdown that must finish anyway catches
226
+ * it. Keyed per instance, so a release NEVER touches a sibling manager's key (security pin 6). */
227
+ async releaseManagerLease(instanceId, revision) {
228
+ const kv = await this.managerLeaseRegistry();
229
+ if (revision === undefined)
230
+ await kv.delete(managerLeaseKey(instanceId));
231
+ else
232
+ await kv.delete(managerLeaseKey(instanceId), { previousSeq: revision });
233
+ }
234
+ /** Read a live manager liveness lease, or undefined if NONE (no manager instance holds the space). A
235
+ * presence/existence check for the CLI's `spawn -f` reuse and `waitLeaseGone`, which only need "is any
236
+ * manager here". Open-only — never creates the bucket, so a probe that finds no manager leaves none
237
+ * behind. (Instance-precise enumeration for the class scatter comes from the registration records KV
238
+ * in 3b-4, not this liveness bucket.)
239
+ *
240
+ * MULTI-INSTANCE EXACT, and it has to be read that way rather than as a point get. Several managers
241
+ * may hold one space, each renewing its own `lease.<instanceId>`. A single `last_by_subj` over
242
+ * `lease.*` returns the newest message under the wildcard REGARDLESS OF KEY — so a stopping peer's
243
+ * DEL tombstone, being newest, answered "no manager here" while a sibling was alive and renewing.
244
+ * Only an explicit `kv.delete` writes that tombstone: a manager whose lease TTL-expires is removed by
245
+ * limits and leaves nothing behind, so the poisoning case was the ORDINARY one (stop a manager
246
+ * cleanly, then `spawn -f`), not the crash. Enumerating live entries collapses to the greatest
247
+ * revision PER KEY and drops keys whose final state is a marker, so a peer's DEL can only retire that
248
+ * peer's own key and can never mask a live one. */
249
+ async readManagerLease() {
250
+ if (!this.nc)
251
+ return undefined;
252
+ try {
253
+ const jsm = this.jsm ?? (this.jsm = await jetstreamManager(this.nc));
254
+ const stream = `KV_${managerBucket(this.space)}`;
255
+ const prefix = `$KV.${managerBucket(this.space)}.${MANAGER_LEASE_KEY}.`;
256
+ // STREAM.INFO to learn WHICH instance keys exist, then one point-get per key. NOT a bucket
257
+ // scan: `liveKvEntries` binds a push consumer, and this principal's grant on this bucket is
258
+ // STREAM.INFO + STREAM.MSG.GET + the `lease.*` publish only (`provision.ts`, supervisor). A
259
+ // consumer here is a permissions violation for the very callers this probe serves, and no
260
+ // open-mesh test can see that, because an open mesh has no permissions to violate.
261
+ const info = await jsm.streams.info(stream, { subjects_filter: `${prefix}*` });
262
+ let newest;
263
+ for (const subject of Object.keys(info.state.subjects ?? {})) {
264
+ // `last_by_subj` is CORRECT PER KEY and wrong across keys. Scoped to one instance's subject
265
+ // it returns that instance's latest state, so a DEL here retires only its own key. The
266
+ // defect was asking one wildcard for the newest message in the whole subtree, where a
267
+ // stopping peer's tombstone outranks a live sibling's older PUT.
268
+ let m;
269
+ try {
270
+ m = await jsm.streams.getMessage(stream, { last_by_subj: subject });
271
+ }
272
+ catch (e) {
273
+ if (e.code === JetStreamApiCodes.NoMessageFound)
274
+ continue;
275
+ throw e;
276
+ }
277
+ if (m === null)
278
+ continue; // key vanished between INFO and GET: it is not a live holder
279
+ // A 10037 above means the key vanished between INFO and GET: it is not a live holder. A
280
+ // denial or failed read is not absence and is rethrown.
281
+ const op = m.header?.get("KV-Operation");
282
+ if (op === "DEL" || op === "PURGE" || m.data.length === 0)
283
+ continue;
284
+ if (newest === undefined || m.seq > newest.seq)
285
+ newest = { data: m.data, seq: m.seq };
286
+ }
287
+ if (newest === undefined)
288
+ return undefined;
289
+ return JSON.parse(new TextDecoder().decode(newest.data));
290
+ }
291
+ catch (e) {
292
+ // ABSENCE MUST BE PROVEN, NOT INFERRED FROM A FAILED READ. Exactly two outcomes mean "genuinely
293
+ // no manager": 10037, no message on the subtree, and a missing bucket — this probe is open-only
294
+ // and on an authed mesh nothing creates it until a manager first takes a lease, so a space that
295
+ // has never run one has no stream to read. Every OTHER failure (a JetStream hiccup, a request
296
+ // timeout, a permissions refusal, or `liveKvEntries` refusing a pass that died mid-delivery) used
297
+ // to return undefined here as well, and every caller reads undefined as "the space is empty": the
298
+ // CLI's `spawn -f` reuse stands a SECOND manager up against a live one and `waitLeaseGone` reports
299
+ // the space free. A read that failed is not evidence of absence, so refuse loudly rather than
300
+ // degrade (AGENTS.md: no fallbacks). This is the wider of the two doors the point-get fix closes:
301
+ // it needs only a transient error, where the tombstone path needed a peer to stop.
302
+ const code = e.code;
303
+ if (code === 10037)
304
+ return undefined;
305
+ if (code === 404 || /stream not found/i.test(e?.message ?? ""))
306
+ return undefined;
307
+ throw e;
308
+ }
309
+ }
310
+ /** Privileged: one owner's NON-TOMBSTONED durable memberships as `{channel, generation, activated}` —
311
+ * the server-side delivery daemon serves this to a connecting agent (the `listMemberships` op on
312
+ * `ctl.delivery`). The agent seeds its leave mirror from the ACTIVATED ones (the confirmed backstops),
313
+ * but the non-activated ones are returned too so `leaveChannel` can discover + close a record that
314
+ * still routes under the pure-interval predicate (a crash-stuck pending activation) — without reading
315
+ * the privileged KV itself. */
316
+ async ownerMemberships(owner, lifecycleUid) {
317
+ // LIFECYCLE-EXACT (SPEC 13.1): an alias-wide listing would hand a same-alias successor the
318
+ // PREDECESSOR's rows/generations (both incarnations share the alias), and a first-match consumer
319
+ // like leaveChannel could then act on the wrong incarnation's state. Rows are filtered to the
320
+ // caller's own uid; the uid is caller-asserted but confined to its own authenticated alias, the
321
+ // same trust shape as durableLeave.
322
+ const recs = await listMembers(await this.membersRegistry(), { owner });
323
+ return recs
324
+ .filter((r) => r.lifecycleUid === lifecycleUid && r.leaveCursor === undefined)
325
+ .map((r) => ({ channel: r.channel, generation: r.generation, activated: r.activated === true }));
326
+ }
327
+ /** Effective delivery class read AUTHORITATIVELY from the registry KV (not the watch cache) — so a
328
+ * `live`→`durable` flip is seen by fan-out without a cache-propagation gap (red-team MED-3), and a
329
+ * reader just started need not wait for the cache to fill. */
330
+ async deliveryClassFresh(channel) {
331
+ if (!this.channelKv)
332
+ return effectiveDeliveryClass(undefined, undefined);
333
+ const [cfg, defaults] = await Promise.all([
334
+ isConcreteChannel(channel) ? readChannelConfig(this.channelKv, channel) : Promise.resolve(undefined),
335
+ readChannelDefaults(this.channelKv),
336
+ ]);
337
+ return effectiveDeliveryClass(cfg, defaults);
338
+ }
339
+ /** Collision-safe `@mention` → owner-id resolution: a name that resolves to exactly one present
340
+ * peer wins; 0 or >1 matches drop (never fan a directed durable copy to an unrelated same-named
341
+ * bystander — red-team LOW; SPEC §4 unique instance id). */
342
+ resolveOwnerByName(name) {
343
+ const matches = [...this.presence.values()].filter((p) => p.card.name.toLowerCase() === name.toLowerCase());
344
+ return matches.length === 1 ? matches[0].card.id : undefined;
345
+ }
346
+ /** Plane-3 publish-dedupe key for a fan-out/transfer entry: the message id plus the member
347
+ * lifecycle (`keySuffix`). One message reaches one lifecycle once, whichever membership row and
348
+ * whichever writer (fan-out or any row's catch-up) produced the copy (#5404), within the stream's
349
+ * duplicate window. An empty `msg.id` contributes NO msgID (#673, SPEC §4: two `id: ""` posts MUST
350
+ * NOT collapse to one delivery) — a plain publish, never an empty or salted one — so an id-less
351
+ * message is at-least-once on the durable plane (a redelivery may reach the member twice; the
352
+ * receiver already treats each as its own delivery). */
353
+ plane3MsgId(entry, keySuffix) {
354
+ return entry.msg.id === "" ? {} : { msgID: `${entry.msg.id}:${keySuffix}` };
355
+ }
356
+ /** Publish one fan-out entry into a member LIFECYCLE's mixed inbox (`dinbox.<o>.<a>.<uid>`, SPEC
357
+ * §13.1: fan-out addresses the member row's RECORDED lifecycle, never the alias's current
358
+ * occupant), idempotent via `Nats-Msg-Id` (`<msgId>:<principal>:<lifecycleUid>`) so a catch-up copy
359
+ * and a racing fan-out copy collapse, from the same row or from two rows that both cover the post.
360
+ * The `principal` is the member's owner+actor dot-form. */
361
+ async publishDinbox(principal, lifecycleUid, entry) {
362
+ if (!this.js)
363
+ return;
364
+ const p = parsePrincipalKey(principal);
365
+ if (!p)
366
+ throw new Error(`publishDinbox: "${principal}" is not a valid member principal <owner>.<actor>`);
367
+ await this.js.publish(dinboxSubject(this.space, p.owner, p.actor, lifecycleUid), JSON.stringify(entry), {
368
+ // JetStream dedupe is STREAM-WIDE, so the id must carry the LIFECYCLE too: with an alias-keyed
369
+ // id, lifecycle A's copy would suppress a same-alias successor B's copy of the same message —
370
+ // cross-lifecycle suppression, not dedup. It carries no row generation: two rows of one
371
+ // lifecycle covering the post must collapse to one copy.
372
+ ...this.plane3MsgId(entry, `${principal}:${lifecycleUid}`),
373
+ });
374
+ }
375
+ /** The fan-out consumer's delivered stream-seq — the activation-fence upper bound (red-team
376
+ * BLOCKER-1: the shared fan-out cursor advances independently of the stream frontier). */
377
+ async fanoutDeliveredSeq() {
378
+ const info = await this.consumerInfo(chatStream(this.space), FANOUT_DURABLE);
379
+ return info?.delivered?.stream_seq ?? 0;
380
+ }
381
+ /**
382
+ * Privileged durable-JOIN write (v3: the delivery daemon calls this from its `ctl.delivery` handler
383
+ * after validating channel ⊆ the caller's read ACL): capture `joinCursor`, commit a `durable-active`
384
+ * record (CAS + generation bump), then ACTIVATION CATCH-UP idempotently copies `(joinCursor, fence]`
385
+ * into the owner inbox where `fence = max(frontier, fanoutDelivered)` — fan-out owns `seq > fence`.
386
+ * Idempotent against a timeout-retry (an already-activated membership no-ops). Returns `{durable:false}`
387
+ * only when a concurrent leave or rejoin superseded the activation. Catch-up copies what the stream
388
+ * still holds and does not judge retention: a post the history limit removed before its copy was
389
+ * taken is outside the durable guarantee (SPEC §4), and stream state cannot show which channel a
390
+ * removed sequence belonged to.
391
+ *
392
+ * Runs on the daemon (which hosts the fan-out/reader loops + the members KV), so catch-up + the
393
+ * activation fence read are in-process — no cross-process cursor read.
394
+ *
395
+ * `aclFence` (the `ctl.delivery` join always sets it) re-reads the lifecycle's exact ACL row
396
+ * immediately before the write that creates or reopens its row, and again after it. When the channel
397
+ * is no longer within that row, the join is refused, and a row it already wrote is removed first.
398
+ * A retirement narrows that ACL row before it reads the lifecycle's inventory (fenceLifecycleAcl),
399
+ * so a row written too late for the inventory removes itself, whichever daemon process wrote it.
400
+ * Without the option the write is a privileged assertion that consults no ACL.
401
+ */
402
+ async durableJoinFor(owner, channel, lifecycleUid, opts = {}) {
403
+ if (!this.js)
404
+ throw new Error(this.notLiveMsg());
405
+ await this.manager(); // ensure jsm — a non-consuming provisioner inits it lazily; catch-up + fence need it
406
+ const kv = await this.membersRegistry();
407
+ const existing = await readMember(kv, channel, owner, lifecycleUid);
408
+ const open = existing?.record.state === "durable-active" && existing.record.leaveCursor === undefined;
409
+ if (open && existing.record.activated)
410
+ return { durable: true, generation: existing.record.generation }; // fully activated — idempotent
411
+ // Either a NEW join (no record / a tombstone to supersede) → fresh joinCursor + bumped generation,
412
+ // OR a retry of an INCOMPLETE activation (durable-active but not yet activated, from an earlier
413
+ // crash or failed catch-up) → re-run catch-up over the SAME join window, no bump. The record is committed
414
+ // `activated:false` first and routes IN-INTERVAL immediately (fan-out + reader deliver via the
415
+ // pure-interval durableEligible) so no live message published during catch-up is lost. `activated`
416
+ // gates only the REPORT — durableJoin returns true / channelMembers lists the owner only after the
417
+ // catch-up confirms. A join that never completes catch-up still routes live (harmless: the agent is
418
+ // live-subscribed and DLV is id-deduped) but honestly reports durable:false and stays hidden.
419
+ const joinCursor = open ? existing.record.joinCursor : await this.chatFrontier();
420
+ const generation = open ? existing.record.generation : (existing?.record.generation ?? 0) + 1;
421
+ const base = {
422
+ channel, owner, lifecycleUid, state: "durable-active", joinCursor, generation,
423
+ activated: false, writerIdentity: this.card.id, updatedAt: Date.now(),
424
+ };
425
+ if (!open) {
426
+ if (opts.aclFence && !(await this.aclAllows(owner, lifecycleUid, channel)))
427
+ throw new Error(`durableJoin: "${channel}" is no longer within the read ACL of lifecycle ${lifecycleUid} (narrowed or retired); no membership row was written`);
428
+ const written = await commitMemberRevision(kv, base);
429
+ if (opts.aclFence)
430
+ await this.keepRowIfAclAllows(kv, owner, lifecycleUid, channel, written.revision);
431
+ }
432
+ const fence = Math.max(await this.chatFrontier(), await this.fanoutDeliveredSeq());
433
+ await this.catchupCopy(owner, lifecycleUid, channel, joinCursor, fence, generation);
434
+ // Flip → reported durable, ATOMICALLY: refuse if a concurrent SAME-generation leave (tombstone) or a
435
+ // rejoin superseded this pending join while catch-up ran. A blind same-gen commit would clobber the
436
+ // tombstone (clear leaveCursor) and resurrect the membership, reopening §7 (review-general-2 BLOCKER).
437
+ const activated = await activateMember(kv, channel, owner, lifecycleUid, generation, joinCursor);
438
+ if (!activated)
439
+ return { durable: false, reason: "activation superseded by a concurrent leave or rejoin", generation };
440
+ return { durable: true, generation };
441
+ }
442
+ /** The post-write half of {@link durableJoinFor}'s `aclFence`: keep the row just written (at
443
+ * `revision`) only on proof that the lifecycle's ACL row still allows the channel, and refuse the
444
+ * join otherwise. When the ACL row proves the channel is no longer allowed, no row of the lifecycle
445
+ * on that channel is wanted, so the row goes by its exact key whoever wrote its latest revision.
446
+ * When the read itself fails, nothing is proven either way, so only this write is taken back: a
447
+ * later revision belongs to another join of the same lifecycle, which may have been authorized. */
448
+ async keepRowIfAclAllows(kv, owner, lifecycleUid, channel, revision) {
449
+ let disallowed = false;
450
+ let why;
451
+ try {
452
+ if (await this.aclAllows(owner, lifecycleUid, channel))
453
+ return;
454
+ disallowed = true;
455
+ why = "was narrowed or retired while the row was written";
456
+ }
457
+ catch (e) {
458
+ why = `could not be re-read after the row was written (${e.message})`;
459
+ }
460
+ const fail = (outcome, cause) => new Error(`durableJoin: the read ACL of lifecycle ${lifecycleUid} ${why}; ${outcome}`, cause === undefined ? undefined : { cause });
461
+ try {
462
+ if (disallowed)
463
+ await deleteMember(kv, channel, owner, lifecycleUid);
464
+ else
465
+ await kv.purge(memberKey(channel, owner, lifecycleUid), { previousSeq: revision });
466
+ }
467
+ catch (e) {
468
+ if (!disallowed && isCasLoss(e))
469
+ throw fail(`a later write replaced its "${channel}" row, which was left to that write`);
470
+ throw fail(`removing its "${channel}" row failed (${e.message})`, e);
471
+ }
472
+ throw fail(`its "${channel}" row was removed`);
473
+ }
474
+ /** Privileged durable-LEAVE write: tombstone the membership at `leaveCursor = frontier` so the
475
+ * backstop denies `seq > leaveCursor` while a pre-leave entry stays deliverable (SPEC §7 interval). */
476
+ async durableLeaveFor(owner, channel, lifecycleUid, expectedGeneration) {
477
+ if (!this.deliveryPlane.plane3)
478
+ return; // not a Plane-3 host — no membership to tombstone
479
+ const kv = await this.membersRegistry();
480
+ // expectedGeneration (captured by the agent at durableJoin) refuses a stale leave from tombstoning
481
+ // a newer rejoin (StaleMembershipWrite) — a durable-disable primitive otherwise.
482
+ await tombstoneMember(kv, channel, owner, lifecycleUid, await this.chatFrontier(), this.card.id, expectedGeneration);
483
+ }
484
+ }
485
+ //# sourceMappingURL=endpoint-durable-backstop.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"endpoint-durable-backstop.js","sourceRoot":"","sources":["../src/endpoint-durable-backstop.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,oGAAoG;AACpG,sCAAsC;AACtC,OAAO,EAAE,SAAS,EAAE,gBAAgB,EAAE,iBAAiB,EAAgG,MAAM,oBAAoB,CAAC;AAClL,OAAO,EAAE,GAAG,EAAW,MAAM,aAAa,CAAC;AAE3C,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,SAAS,IAAI,cAAc,EAAE,UAAU,IAAI,eAAe,EAAE,MAAM,WAAW,CAAC;AACrJ,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAG/F,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAElD,OAAO,EAAE,mBAAmB,EAAE,oBAAoB,EAAE,eAAe,EAAE,cAAc,EAAE,UAAU,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACjJ,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AAC9E,OAAO,EAAE,UAA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,OAAO,GAAG,EAAE,CAAC,CAAC,CAAC;QAClF,CAAC;QACD,MAAM,IAAI,CAAC,QAAQ,OAAO,mBAAmB,CAAC,CAAC;IACjD,CAAC;IAED;4GACwG;IACxG,KAAK,CAAC,eAAe,CAAC,KAAa,EAAE,OAAe,EAAE,YAAoB,EAAE,kBAA2B;QACrG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM;YAAE,OAAO,CAAC,kDAAkD;QAC1F,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,eAAe,EAAE,CAAC;QACxC,mGAAmG;QACnG,iFAAiF;QACjF,MAAM,eAAe,CAAC,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC,YAAY,EAAE,EAAE,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,kBAAkB,CAAC,CAAC;IACvH,CAAC;CACF"}
@@ -137,7 +137,8 @@ export declare function parseEndpointRequest(raw: unknown): EndpointRequest;
137
137
  * equal the subject sender principal (`sender-mismatch`). Currency of `target.actor`/
138
138
  * `target.lifecycleUid` against the live mapping is the handler's fresh-read (`expired`),
139
139
  * deliberately not checkable here. On the principal route (SPEC 13.21) the body carries no
140
- * target (`target-mismatch`) and no bind (`bad-request`), and a deadline is required. */
140
+ * target (`target-mismatch`) and no bind (`bad-request`), it is never a cast (`bad-request`), and a
141
+ * deadline of at most {@link EP_PRINCIPAL_MAX_DEADLINE_MS} is required (`bad-request`). */
141
142
  export declare function checkRequestSubjectAgreement(env: EndpointRequest, subject: ParsedEpRequest | ParsedEpPrincipalRequest): void;
142
143
  /** The contract-class agreement check (`class-mismatch`): the envelope's declared class MUST
143
144
  * equal the command's contract class. Split out because it needs the contract in hand. */
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint-envelope.d.ts","sourceRoot":"","sources":["../src/endpoint-envelope.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAA2B,MA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wBAAgB,oBAAoB,CAAC,GAAG,EAAE,OAAO,GAAG,eAAe,CA2FlE;AAED;;;;;;;;4FAQ4F;AAC5F,wBAAgB,4BAA4B,CAAC,GAAG,EAAE,eAAe,EAAE,OAAO,EAAE,eAAe,GAAG,wBAAwB,GAAG,IAAI,CAyD5H;AASD;2FAC2F;AAC3F,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,eAAe,EAAE,aAAa,EAAE,OAAO,GAAG,IAAI,CAGrF;AAED;;;;;;;;+EAQ+E;AAC/E,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,eAAe,EAAE,cAAc,EAAE,OAAO,GAAG,IAAI,CAKtF;AA+BD;iEACiE;AACjE,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,aAAa,CAY9D;AAED;gGACgG;AAChG,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,aAAa,CAS9D;AAuFD;;;;;;;;;;;;kEAYkE;AAClE,wBAAgB,eAAe,CAAC,QAAQ,EAAE,iBAAiB,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAYtH;AAED;;;;;;4CAM4C;AAC5C,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAUlF"}
@@ -1,5 +1,5 @@
1
1
  import { isContractDigest, isWellFormedUnicode } from "./canonical-json.js";
2
- import { assertCommandToken, assertIdToken, assertLifecycleToken, endpointToken } from "./endpoint-subjects.js";
2
+ import { assertCommandToken, assertIdToken, assertLifecycleToken, endpointToken, EP_PRINCIPAL_MAX_DEADLINE_MS } from "./endpoint-subjects.js";
3
3
  import { SCHEMA_PROFILE } from "./schema-bounds.js";
4
4
  // The error catalog + EpEnvelopeError live in a node-free module so the browser session bundle can
5
5
  // use them without dragging in schema-profile's load-time digest (node:crypto). Re-exported here so
@@ -227,21 +227,27 @@ export function parseEndpointRequest(raw) {
227
227
  * equal the subject sender principal (`sender-mismatch`). Currency of `target.actor`/
228
228
  * `target.lifecycleUid` against the live mapping is the handler's fresh-read (`expired`),
229
229
  * deliberately not checkable here. On the principal route (SPEC 13.21) the body carries no
230
- * target (`target-mismatch`) and no bind (`bad-request`), and a deadline is required. */
230
+ * target (`target-mismatch`) and no bind (`bad-request`), it is never a cast (`bad-request`), and a
231
+ * deadline of at most {@link EP_PRINCIPAL_MAX_DEADLINE_MS} is required (`bad-request`). */
231
232
  export function checkRequestSubjectAgreement(env, subject) {
232
233
  if (env.op.endpoint !== subject.endpoint)
233
234
  fail("op-mismatch", `op.endpoint "${env.op.endpoint}" does not agree with the subject endpoint "${subject.endpoint}"`);
234
235
  if (env.op.command !== subject.command)
235
236
  fail("op-mismatch", `op.command "${env.op.command}" does not agree with the subject command "${subject.command}"`);
236
237
  // The principal route (SPEC 13.21): the subject head is the target and its runtime id pins the
237
- // process, so a body that names either is refused, never ignored. A call has a deadline.
238
+ // process, so a body that names either is refused, never ignored. Every request is a call, and a
239
+ // call has a deadline.
238
240
  if (subject.plane === "principal-request") {
239
241
  if (env.target !== undefined)
240
242
  fail("target-mismatch", "a body target on the principal route is target-mismatch: the subject head is the target (SPEC 13.21)");
241
243
  if (env.bind !== undefined)
242
244
  fail("bad-request", "a bind on the principal route is refused: the runtime id in the subject pins the process (SPEC 13.21)");
245
+ if (!env.replyExpected)
246
+ fail("bad-request", "a cast on the principal route is refused: every command on it is request/reply (SPEC 13.21)");
243
247
  if (env.deadlineMs === undefined)
244
248
  fail("bad-request", "deadlineMs is required on the principal route (SPEC 13.21)");
249
+ if (env.deadlineMs > EP_PRINCIPAL_MAX_DEADLINE_MS)
250
+ fail("bad-request", `deadlineMs ${env.deadlineMs} exceeds the principal route's ${EP_PRINCIPAL_MAX_DEADLINE_MS}ms maximum (SPEC 13.21)`);
245
251
  assertSender(env, subject.caller);
246
252
  return;
247
253
  }