@cotal-ai/core 0.166.3 → 0.167.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 (68) hide show
  1. package/dist/agent-endpoint.d.ts +242 -0
  2. package/dist/agent-endpoint.d.ts.map +1 -0
  3. package/dist/agent-endpoint.js +183 -0
  4. package/dist/agent-endpoint.js.map +1 -0
  5. package/dist/backup-config.d.ts +2 -2
  6. package/dist/endpoint-call.d.ts +34 -1
  7. package/dist/endpoint-call.d.ts.map +1 -1
  8. package/dist/endpoint-call.js +209 -116
  9. package/dist/endpoint-call.js.map +1 -1
  10. package/dist/endpoint-cluster.d.ts +6 -1
  11. package/dist/endpoint-cluster.d.ts.map +1 -1
  12. package/dist/endpoint-cluster.js +25 -1
  13. package/dist/endpoint-cluster.js.map +1 -1
  14. package/dist/endpoint-delivery-lease.d.ts +184 -0
  15. package/dist/endpoint-delivery-lease.d.ts.map +1 -0
  16. package/dist/endpoint-delivery-lease.js +270 -0
  17. package/dist/endpoint-delivery-lease.js.map +1 -0
  18. package/dist/endpoint-envelope.d.ts +4 -3
  19. package/dist/endpoint-envelope.d.ts.map +1 -1
  20. package/dist/endpoint-envelope.js +19 -2
  21. package/dist/endpoint-envelope.js.map +1 -1
  22. package/dist/endpoint-grants.d.ts +31 -1
  23. package/dist/endpoint-grants.d.ts.map +1 -1
  24. package/dist/endpoint-grants.js +62 -1
  25. package/dist/endpoint-grants.js.map +1 -1
  26. package/dist/endpoint-presence.d.ts +296 -0
  27. package/dist/endpoint-presence.d.ts.map +1 -0
  28. package/dist/endpoint-presence.js +784 -0
  29. package/dist/endpoint-presence.js.map +1 -0
  30. package/dist/endpoint-serve.d.ts +76 -2
  31. package/dist/endpoint-serve.d.ts.map +1 -1
  32. package/dist/endpoint-serve.js +340 -147
  33. package/dist/endpoint-serve.js.map +1 -1
  34. package/dist/endpoint-service.d.ts +5 -1
  35. package/dist/endpoint-service.d.ts.map +1 -1
  36. package/dist/endpoint-service.js +2 -1
  37. package/dist/endpoint-service.js.map +1 -1
  38. package/dist/endpoint-subjects.d.ts +76 -2
  39. package/dist/endpoint-subjects.d.ts.map +1 -1
  40. package/dist/endpoint-subjects.js +113 -2
  41. package/dist/endpoint-subjects.js.map +1 -1
  42. package/dist/endpoint-verbs.d.ts +1 -1
  43. package/dist/endpoint-verbs.d.ts.map +1 -1
  44. package/dist/endpoint-verbs.js +1 -1
  45. package/dist/endpoint-verbs.js.map +1 -1
  46. package/dist/endpoint.d.ts +115 -188
  47. package/dist/endpoint.d.ts.map +1 -1
  48. package/dist/endpoint.js +319 -788
  49. package/dist/endpoint.js.map +1 -1
  50. package/dist/index.d.ts +1 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +1 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/peer-label.d.ts +6 -5
  55. package/dist/peer-label.d.ts.map +1 -1
  56. package/dist/peer-label.js +7 -6
  57. package/dist/peer-label.js.map +1 -1
  58. package/dist/provision.d.ts +6 -0
  59. package/dist/provision.d.ts.map +1 -1
  60. package/dist/provision.js +26 -1
  61. package/dist/provision.js.map +1 -1
  62. package/dist/subjects.d.ts +3 -2
  63. package/dist/subjects.d.ts.map +1 -1
  64. package/dist/subjects.js +10 -2
  65. package/dist/subjects.js.map +1 -1
  66. package/dist/types.d.ts +11 -0
  67. package/dist/types.d.ts.map +1 -1
  68. package/package.json +1 -1
@@ -1,8 +1,9 @@
1
1
  import { spacePrefix } from "./subjects.js";
2
- import { endpointToken, assertCommandToken, assertLifecycleToken, epClassQueueGroup, deriveReplySubject, parseEpSubject, EP_RAIL_V1, } from "./endpoint-subjects.js";
2
+ import { endpointToken, assertCommandToken, assertLifecycleToken, epClassQueueGroup, deriveReplySubject, parseEpSubject, EP_RAIL_V1, EP_PRINCIPAL_AUTHORITIES, derivePrincipalReplySubject, epPrincipalServeFilter, isPrincipalAuthority, } from "./endpoint-subjects.js";
3
3
  import { EpEnvelopeError, parseEndpointRequest, checkRequestSubjectAgreement, assertClassMatches, assertArgsValid, assertOutputValid, EP_BIND_REFUSED, EP_TARGET_UNMAPPED, } from "./endpoint-envelope.js";
4
- import { compileContract, assertCompiledContract, VOID_SCHEMA } from "./schema-profile.js";
4
+ import { compileContract, assertCompiledContract, singleDocumentClosure, VOID_SCHEMA } from "./schema-profile.js";
5
5
  import { assertServeGrantAuthorized } from "./endpoint-service.js";
6
+ import { parseClusterDocument } from "./endpoint-cluster.js";
6
7
  import { GOVERNED_TRAIT_URNS, TRAIT_GUARDED, TRAIT_PRICED, assertGovernedSurfaceFor, assertGovernedPreEffect, } from "./endpoint-traits.js";
7
8
  import { parseDescribeObservation } from "./endpoint-describe-observation.js";
8
9
  const describeContexts = new WeakMap();
@@ -20,7 +21,7 @@ const describeContexts = new WeakMap();
20
21
  * someone else); a different EPOCH on the same instance is `expired`, as everywhere else.
21
22
  *
22
23
  * Both refusals carry {@link EP_BIND_REFUSED}, meaning NOTHING RAN — true only while this stays
23
- * ahead of every effect in `handle`, including the governed gate, which may consume a one-use
24
+ * ahead of every effect in `runRequest`, including the governed gate, which may consume a one-use
24
25
  * priced proof.
25
26
  */
26
27
  function assertBoundIncarnation(env, identity) {
@@ -126,6 +127,132 @@ async function assertTargetModeAuthorized(env, parsed, opts) {
126
127
  ? `the durable spawner record does not name the caller as ${t.owner}.${t.actor}'s spawner (SPEC 13.2: child mode is a fresh spawner check, never the grant alone)`
127
128
  : `the authorization ledger holds no live grant for this caller on ${t.owner}.${t.actor} (SPEC 13.2: ledger mode is a fresh ledger read, fail closed)`);
128
129
  }
130
+ const enc = new TextEncoder();
131
+ const dec = new TextDecoder();
132
+ function successReply(id, data) {
133
+ return { v: 1, id, ok: true, ...(data !== undefined ? { data } : {}) };
134
+ }
135
+ function encodeReply(reply) {
136
+ return enc.encode(JSON.stringify(reply));
137
+ }
138
+ /** Stored-message delivery is not a caller publication on this subject (§13.3). Native
139
+ * provenance is dropped before parsing, authorization or replies: there is no authenticated caller
140
+ * to answer. Header names are matched, not values; an empty marker is still a marker. */
141
+ function carriesStoredProvenance(msg) {
142
+ for (const [name] of msg.headers ?? [])
143
+ if (/^Nats-(Stream|Subject|Sequence|Time-Stamp)$/i.test(name))
144
+ return true;
145
+ return false;
146
+ }
147
+ /** One request through the shared pipeline: subject parse, envelope parse, subject agreement, the
148
+ * route's addressee check, class match, digest binding, the route's admission, args validation, the
149
+ * route's seam checks, dispatch, the outcome stamp, and the derived reply. */
150
+ async function runRequest(nc, steps, pick, msg) {
151
+ const receivedAtMonotonicMs = performance.now();
152
+ const parsed = steps.parse(msg.subject);
153
+ if (!parsed)
154
+ return; // no sender: MUST NOT be handled (§13.2)
155
+ let env;
156
+ let dispatched = false;
157
+ let returned = false;
158
+ let reply;
159
+ try {
160
+ const original = JSON.parse(dec.decode(msg.data));
161
+ env = parseEndpointRequest(original);
162
+ checkRequestSubjectAgreement(env, parsed);
163
+ // §13.2 FIRST among the semantic gates, and deliberately ahead of the command's own class,
164
+ // contract, and args: whether this instance is the addressee at all is settled before
165
+ // anything is said about the command it names. It also has to precede the governed gate,
166
+ // which can consume a one-use priced proof — the refusal claims nothing ran, so nothing may.
167
+ steps.addressed(env, parsed);
168
+ // A route served by one subscription for every command meets a command it does not serve.
169
+ const def = pick(parsed);
170
+ if (def === undefined)
171
+ throw new EpEnvelopeError("unimplemented", `command "${parsed.command}" is not served here`);
172
+ assertClassMatches(env, def.class);
173
+ bindContract(env, def);
174
+ // §13.2: the command admits only its declared form — before args validation, so an
175
+ // unadmitted form learns nothing about the input contract.
176
+ steps.admit(parsed, def);
177
+ // §13.7: args validate against the input schema BEFORE any effect (bad-request).
178
+ assertArgsValid(def.validate.args, env.args);
179
+ const obligations = await steps.beforeEffect(env, parsed, def);
180
+ const requestId = env.id;
181
+ const ctx = steps.context({
182
+ parsed, env, def, subject: msg.subject, original, receivedAtMonotonicMs, obligations,
183
+ replyFits: (data, ceiling) => {
184
+ const maxPayload = nc.info?.max_payload;
185
+ if (!Number.isSafeInteger(maxPayload) || maxPayload === undefined || maxPayload <= 0)
186
+ throw new EpEnvelopeError("unavailable", "the serving connection has no valid payload ceiling");
187
+ if (!Number.isSafeInteger(ceiling) || ceiling <= 0)
188
+ throw new EpEnvelopeError("failed-precondition", "reply byte ceiling must be a positive safe integer");
189
+ return encodeReply(successReply(requestId, data)).byteLength <= Math.min(ceiling, maxPayload);
190
+ },
191
+ });
192
+ dispatched = true;
193
+ if (!env.replyExpected) {
194
+ await def.handler(ctx);
195
+ return; // cast: the responder MUST NOT reply (§13.5)
196
+ }
197
+ const data = await def.handler(ctx);
198
+ returned = true;
199
+ // §13.7: the reply validates against the output schema BEFORE it is published, under the
200
+ // same fixed budget as args — an invalid reply is a server bug and fails loud, never
201
+ // reaches the caller as success.
202
+ assertOutputValid(def.validate.output, data);
203
+ reply = successReply(env.id, data);
204
+ }
205
+ catch (err) {
206
+ if (env && !env.replyExpected)
207
+ return; // a failed cast stays silent (§13.5 at-most-once)
208
+ const error = err instanceof EpEnvelopeError
209
+ ? err.toEpError()
210
+ : { code: "internal", message: err?.message ?? String(err) };
211
+ // §13.3: a refusal raised before dispatch MUST say nothing ran, one raised after the handler
212
+ // returned MUST say it ran, and an omitted outcome reads as `unknown`. Deciding it here, from
213
+ // where the loop stands, covers every check on either side of the handler, including one
214
+ // added later and a body that never parsed into an envelope. A handler's own throw keeps
215
+ // whatever outcome it stated: the loop cannot tell how far it got.
216
+ // The id echoes the request where one parsed; the reply subject is already nonce-scoped
217
+ // to exactly this request's caller, so attribution never rides the echo.
218
+ const stated = !dispatched ? "not-executed" : returned ? "executed" : undefined;
219
+ reply = { v: 1, id: env?.id ?? "invalid", ok: false, error: stated === undefined ? error : { ...error, outcome: stated } };
220
+ }
221
+ // Replacing a reply that cannot be serialized or published changes nothing about whether the
222
+ // command ran, so each replacement below keeps the outcome the replaced reply stated, and a
223
+ // success states `executed`.
224
+ const outcome = reply.ok ? "executed" : reply.error?.outcome;
225
+ let bytes;
226
+ try {
227
+ bytes = encodeReply(reply);
228
+ }
229
+ catch (err) {
230
+ // A non-serializable payload or refusal detail (cycle, BigInt) must not silently drop the reply.
231
+ const fallback = { v: 1, id: reply.id, ok: false, error: { code: "internal", message: `the reply does not serialize: ${err.message}`, ...(outcome !== undefined ? { outcome } : {}) } };
232
+ bytes = enc.encode(JSON.stringify(fallback));
233
+ }
234
+ const replySubject = steps.replySubject(parsed);
235
+ try {
236
+ nc.publish(replySubject, bytes);
237
+ }
238
+ catch (err) {
239
+ // The publish itself refused the message — a reply over the broker's `max_payload` is the
240
+ // reachable case, and a VALID payload can reach here now that the §13.8 validate budget
241
+ // reports instead of refusing (that throw used to stop an oversized output before it was
242
+ // ever encoded, which masked this path). `runRequest()` is invoked from a subscription
243
+ // callback whose rejection is swallowed by design, so an escaping throw here does not surface
244
+ // anywhere: it leaves the caller with SILENCE until its own deadline. That is precisely the
245
+ // outcome the non-serializable branch above already exists to prevent, so it gets the same
246
+ // treatment. The replacement fits by construction — its message is one integer and a
247
+ // bounded string — and `resource-exhausted` matches the §13.4 fact preflight, which refuses
248
+ // an over-`max_payload` acceptance loudly rather than spilling it.
249
+ const refused = {
250
+ v: 1, id: reply.id, ok: false,
251
+ error: { code: "resource-exhausted", message: `the serialized reply is ${bytes.length} bytes and the broker refused it (${err?.message ?? String(err)}); a reply that cannot be published is refused loudly, never dropped`, ...(outcome !== undefined ? { outcome } : {}) },
252
+ };
253
+ nc.publish(replySubject, enc.encode(JSON.stringify(refused)));
254
+ }
255
+ }
129
256
  /**
130
257
  * Serve an authorized instance's granted commands on the three §13.2 rails, exactly the
131
258
  * per-command forms the serve credential grants (§13.9 {@link epServeSubscribeRows}): the class
@@ -171,6 +298,12 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
171
298
  assertServeGrantAuthorized(serve); // §13.9: the serve table consumes ONLY registry-authorized serve authority
172
299
  if (serve.space !== space)
173
300
  throw new Error(`the serve artifact was authorized for space "${serve.space}", not "${space}" (SPEC 13.9)`);
301
+ // SPEC 13.21: a command that declares principal-route authority words is served on that route
302
+ // only. Default deny both ways, as for modes: a service route never serves one.
303
+ for (const cmd of serve.commands) {
304
+ if (serve.surface[cmd].authorities !== undefined)
305
+ throw new Error(`command "${cmd}" declares principal-route authorities; a service route never serves it (SPEC 13.21)`);
306
+ }
174
307
  const identity = { endpoint: serve.endpoint, instanceId: serve.instanceId, epoch: serve.epoch };
175
308
  const e = endpointToken(identity.endpoint);
176
309
  const iId = assertLifecycleToken(identity.instanceId, "instanceId");
@@ -293,40 +426,15 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
293
426
  const p = spacePrefix(space);
294
427
  const subs = [];
295
428
  const pending = new Set();
296
- const enc = new TextEncoder();
297
- function successReply(id, data) {
298
- return { v: 1, id, ok: true, ...(data !== undefined ? { data } : {}) };
299
- }
300
- function encodeReply(reply) {
301
- return enc.encode(JSON.stringify(reply));
302
- }
303
- const dec = new TextDecoder();
304
429
  const needsDescribeContext = describe.public !== true;
305
- const handle = async (def, msg) => {
306
- const receivedAtMonotonicMs = performance.now();
307
- const parsed = parseEpSubject(msg.subject);
308
- if (!parsed || parsed.plane !== "request")
309
- return; // no sender: MUST NOT be handled (§13.2)
310
- let env;
311
- let dispatched = false;
312
- let returned = false;
313
- let reply;
314
- try {
315
- const originalEnvelope = JSON.parse(dec.decode(msg.data));
316
- env = parseEndpointRequest(originalEnvelope);
317
- checkRequestSubjectAgreement(env, parsed);
318
- // §13.2 FIRST among the semantic gates, and deliberately ahead of the command's own class,
319
- // contract, and args: whether this instance is the addressee at all is settled before
320
- // anything is said about the command it names. It also has to precede the governed gate,
321
- // which can consume a one-use priced proof — the refusal claims nothing ran, so nothing may.
322
- assertBoundIncarnation(env, identity);
323
- assertClassMatches(env, def.class);
324
- bindContract(env, def);
325
- // §13.2: the command admits only its REGISTERED target modes — before args validation,
326
- // so an unadmitted mode learns nothing about the input contract.
327
- assertModeAdmitted(parsed, def);
328
- // §13.7: args validate against the input schema BEFORE any effect (bad-request).
329
- assertArgsValid(def.validate.args, env.args);
430
+ const steps = {
431
+ parse: (subject) => {
432
+ const parsed = parseEpSubject(subject);
433
+ return parsed && parsed.plane === "request" ? parsed : null;
434
+ },
435
+ addressed: (env) => assertBoundIncarnation(env, identity),
436
+ admit: (parsed, def) => assertModeAdmitted(parsed, def),
437
+ beforeEffect: async (env, parsed, def) => {
330
438
  // §13.3/§13.9: target currency resolves against the FRESH mapping immediately before
331
439
  // effect — static agreement is not currency; casts have effects too.
332
440
  await assertTargetCurrent(env, opts.resolveTarget);
@@ -338,127 +446,57 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
338
446
  // the handler.
339
447
  if (parsed.target?.mode === "child" || parsed.target?.mode === "ledger")
340
448
  await assertTargetCurrent(env, opts.resolveTarget);
449
+ if (!def.governed)
450
+ return undefined;
341
451
  // §13.7/§13.9 governed pre-effect gate, for calls AND casts (casts have effects too):
342
452
  // guard-then-priced, every anomalous answer refuses, both seams bounded. Construction
343
453
  // refused a governed def without enforcement, so the snapshot is present and total here.
344
- let obligations;
345
- if (def.governed) {
346
- ({ obligations } = await assertGovernedPreEffect({
347
- enforcement: enforcement,
348
- endpoint: identity.endpoint,
349
- command: def.command,
350
- caller: parsed.caller,
351
- requestId: env.id,
352
- space,
353
- ...(env.auth !== undefined ? { auth: env.auth } : {}),
354
- ...(env.deadlineMs !== undefined ? { deadlineMs: env.deadlineMs } : {}),
355
- }));
356
- // §13.2/§13.3 TOCTOU: the gate AWAITED guard/proof, so a target mapping or child/ledger
357
- // grant can have rotated since the last currency read — re-resolve currency, re-run the
358
- // dynamic authorization, and then (because the child/ledger authorization is ITSELF an
359
- // await the mapping can rotate during) re-resolve currency a FINAL time immediately
360
- // before the effect. This is the SAME currency → auth → currency discipline the
361
- // pre-gate path above follows; currency → auth alone leaves the last await unfenced.
362
- // A one-use priced proof MAY be consumed before this refusal fires: fail-closed, no
363
- // effect occurs, and the caller retries with a fresh request id and proof.
454
+ const { obligations } = await assertGovernedPreEffect({
455
+ enforcement: enforcement,
456
+ endpoint: identity.endpoint,
457
+ command: def.command,
458
+ caller: parsed.caller,
459
+ requestId: env.id,
460
+ space,
461
+ ...(env.auth !== undefined ? { auth: env.auth } : {}),
462
+ ...(env.deadlineMs !== undefined ? { deadlineMs: env.deadlineMs } : {}),
463
+ });
464
+ // §13.2/§13.3 TOCTOU: the gate AWAITED guard/proof, so a target mapping or child/ledger
465
+ // grant can have rotated since the last currency read — re-resolve currency, re-run the
466
+ // dynamic authorization, and then (because the child/ledger authorization is ITSELF an
467
+ // await the mapping can rotate during) re-resolve currency a FINAL time immediately
468
+ // before the effect. This is the SAME currency → auth → currency discipline the
469
+ // pre-gate path above follows; currency → auth alone leaves the last await unfenced.
470
+ // A one-use priced proof MAY be consumed before this refusal fires: fail-closed, no
471
+ // effect occurs, and the caller retries with a fresh request id and proof.
472
+ await assertTargetCurrent(env, opts.resolveTarget);
473
+ await assertTargetModeAuthorized(env, parsed, opts);
474
+ if (parsed.target?.mode === "child" || parsed.target?.mode === "ledger")
364
475
  await assertTargetCurrent(env, opts.resolveTarget);
365
- await assertTargetModeAuthorized(env, parsed, opts);
366
- if (parsed.target?.mode === "child" || parsed.target?.mode === "ledger")
367
- await assertTargetCurrent(env, opts.resolveTarget);
368
- }
369
- const requestId = env.id;
476
+ return obligations;
477
+ },
478
+ context: ({ parsed, env, def, subject, original, receivedAtMonotonicMs, obligations, replyFits }) => {
370
479
  const ctx = {
371
480
  identity, subject: parsed, request: env, receivedAtMonotonicMs,
372
481
  ...(obligations !== undefined ? { obligations } : {}),
373
- replyFits: (data, ceiling) => {
374
- const maxPayload = nc.info?.max_payload;
375
- if (!Number.isSafeInteger(maxPayload) || maxPayload === undefined || maxPayload <= 0)
376
- throw new EpEnvelopeError("unavailable", "the serving connection has no valid payload ceiling");
377
- if (!Number.isSafeInteger(ceiling) || ceiling <= 0)
378
- throw new EpEnvelopeError("failed-precondition", "reply byte ceiling must be a positive safe integer");
379
- return encodeReply(successReply(requestId, data)).byteLength <= Math.min(ceiling, maxPayload);
380
- },
482
+ replyFits,
381
483
  };
382
484
  if (def.command === "describe" && needsDescribeContext) {
383
- const observed = parseDescribeObservation(space, msg.subject, originalEnvelope);
384
- describeContexts.set(ctx, Object.freeze({ subject: msg.subject, fingerprint: observed.fingerprint,
485
+ const observed = parseDescribeObservation(space, subject, original);
486
+ describeContexts.set(ctx, Object.freeze({ subject, fingerprint: observed.fingerprint,
385
487
  identity: Object.freeze({ ...identity }), receivedAtMonotonicMs, replyExpected: observed.replyExpected,
386
488
  ...(observed.deadlineMs === undefined ? {} : { deadlineMs: observed.deadlineMs }) }));
387
489
  }
388
- dispatched = true;
389
- if (!env.replyExpected) {
390
- await def.handler(ctx);
391
- return; // cast: the responder MUST NOT reply (§13.5)
392
- }
393
- const data = await def.handler(ctx);
394
- returned = true;
395
- // §13.7: the reply validates against the output schema BEFORE it is published, under the
396
- // same fixed budget as args — an invalid reply is a server bug and fails loud, never
397
- // reaches the caller as success.
398
- assertOutputValid(def.validate.output, data);
399
- reply = successReply(env.id, data);
400
- }
401
- catch (err) {
402
- if (env && !env.replyExpected)
403
- return; // a failed cast stays silent (§13.5 at-most-once)
404
- const error = err instanceof EpEnvelopeError
405
- ? err.toEpError()
406
- : { code: "internal", message: err?.message ?? String(err) };
407
- // §13.3: a refusal raised before dispatch MUST say nothing ran, one raised after the handler
408
- // returned MUST say it ran, and an omitted outcome reads as `unknown`. Deciding it here, from
409
- // where the loop stands, covers every check on either side of the handler, including one
410
- // added later and a body that never parsed into an envelope. A handler's own throw keeps
411
- // whatever outcome it stated: the loop cannot tell how far it got.
412
- // The id echoes the request where one parsed; the reply subject is already nonce-scoped
413
- // to exactly this request's caller, so attribution never rides the echo.
414
- const stated = !dispatched ? "not-executed" : returned ? "executed" : undefined;
415
- reply = { v: 1, id: env?.id ?? "invalid", ok: false, error: stated === undefined ? error : { ...error, outcome: stated } };
416
- }
417
- // Replacing a reply that cannot be serialized or published changes nothing about whether the
418
- // command ran, so each replacement below keeps the outcome the replaced reply stated, and a
419
- // success states `executed`.
420
- const outcome = reply.ok ? "executed" : reply.error?.outcome;
421
- let bytes;
422
- try {
423
- bytes = encodeReply(reply);
424
- }
425
- catch (err) {
426
- // A non-serializable payload or refusal detail (cycle, BigInt) must not silently drop the reply.
427
- const fallback = { v: 1, id: reply.id, ok: false, error: { code: "internal", message: `the reply does not serialize: ${err.message}`, ...(outcome !== undefined ? { outcome } : {}) } };
428
- bytes = enc.encode(JSON.stringify(fallback));
429
- }
430
- const replySubject = deriveReplySubject(space, parsed, identity);
431
- try {
432
- nc.publish(replySubject, bytes);
433
- }
434
- catch (err) {
435
- // The publish itself refused the message — a reply over the broker's `max_payload` is the
436
- // reachable case, and a VALID payload can reach here now that the §13.8 validate budget
437
- // reports instead of refusing (that throw used to stop an oversized output before it was
438
- // ever encoded, which masked this path). `handle()` is invoked from a subscription callback
439
- // whose rejection is swallowed by design, so an escaping throw here does not surface
440
- // anywhere: it leaves the caller with SILENCE until its own deadline. That is precisely the
441
- // outcome the non-serializable branch above already exists to prevent, so it gets the same
442
- // treatment. The replacement fits by construction — its message is one integer and a
443
- // bounded string — and `resource-exhausted` matches the §13.4 fact preflight, which refuses
444
- // an over-`max_payload` acceptance loudly rather than spilling it.
445
- const refused = {
446
- v: 1, id: reply.id, ok: false,
447
- error: { code: "resource-exhausted", message: `the serialized reply is ${bytes.length} bytes and the broker refused it (${err?.message ?? String(err)}); a reply that cannot be published is refused loudly, never dropped`, ...(outcome !== undefined ? { outcome } : {}) },
448
- };
449
- nc.publish(replySubject, enc.encode(JSON.stringify(refused)));
450
- }
490
+ return ctx;
491
+ },
492
+ replySubject: (parsed) => deriveReplySubject(space, parsed, identity),
451
493
  };
452
494
  for (const def of defs) {
453
495
  const cmd = def.command;
454
496
  const cb = (_err, msg) => {
455
- // Stored-message delivery is not a caller publication on this subject. Drop native
456
- // provenance before parsing, authorization or replies: there is no authenticated caller
457
- // to answer. Match header names, not values; an empty marker is still a marker.
458
- for (const [name] of msg.headers ?? [])
459
- if (/^Nats-(Stream|Subject|Sequence|Time-Stamp)$/i.test(name))
460
- return;
461
- const run = handle(def, msg).catch(() => { });
497
+ if (carriesStoredProvenance(msg))
498
+ return;
499
+ const run = runRequest(nc, steps, () => def, msg).catch(() => { });
462
500
  pending.add(run);
463
501
  void run.finally(() => pending.delete(run));
464
502
  };
@@ -483,6 +521,154 @@ export function serveEndpoint(nc, space, serve, commands, describe, opts = {}) {
483
521
  },
484
522
  };
485
523
  }
524
+ /**
525
+ * Serve a principal's own command set on the principal route (SPEC 13.21), on one connection.
526
+ * `Endpoint.servePrincipal` is the entry point an agent uses: it adds the refusals for an open mesh
527
+ * and a static credential, re-binds on every replaced connection and owns the presence field.
528
+ *
529
+ * The cluster is a core constant, not a registration: construction parses it and refuses a command
530
+ * that declares no `authorities`, one that is not ephemeral, one with a governed trait (this route
531
+ * has no governed gate), and a set of defs that is not exactly the cluster's commands with compiled
532
+ * contracts equal to the declared digests. `describe` is built here: it answers the cluster inline,
533
+ * the same answer for every caller, and admits every authority word.
534
+ *
535
+ * The subscription is this process's own head with no queue group. Each request runs the shared
536
+ * pipeline: a head that is not this process is dropped with no reply, the subject's authority word
537
+ * MUST be one the command declares (`permission-denied`), and the reply goes to the subject derived
538
+ * from this process and the parsed caller, never to a transport reply field.
539
+ */
540
+ export function servePrincipalRoute(nc, space, self, serve) {
541
+ const filter = epPrincipalServeFilter(space, serve.endpoint, self);
542
+ const cluster = parseClusterDocument(serve.cluster);
543
+ const declared = new Map(cluster.commands.map((c) => [c.name, c]));
544
+ for (const c of cluster.commands) {
545
+ if (c.authorities === undefined)
546
+ throw new Error(`command "${c.name}" declares no authorities; a command is served on the principal route only when it lists the words it admits (SPEC 13.21)`);
547
+ if (c.class !== "ephemeral")
548
+ throw new Error(`command "${c.name}" is class "${c.class}"; the principal route serves ephemeral commands only (SPEC 13.21)`);
549
+ const governed = (c.traits ?? []).filter((t) => GOVERNED_TRAIT_URNS.includes(t));
550
+ if (governed.length > 0)
551
+ throw new Error(`command "${c.name}" declares governed trait(s) ${governed.join(", ")}; the principal route has no governed gate, and a governed command is never served unenforced (SPEC 13.7)`);
552
+ }
553
+ const defs = [];
554
+ for (const def of serve.handlers) {
555
+ assertCommandToken(def.command);
556
+ if (def.command === "describe")
557
+ throw new Error("describe is reserved and built from the cluster; a custom describe def is refused (SPEC 13.21)");
558
+ if (defs.some((d) => d.command === def.command))
559
+ throw new Error(`command "${def.command}" is served twice`);
560
+ const decl = declared.get(def.command);
561
+ if (decl === undefined)
562
+ throw new Error(`command "${def.command}" is not in the cluster; the served table is exactly the cluster's commands (SPEC 13.21)`);
563
+ const input = assertCompiledContract(def.contract?.input, `command "${def.command}" input contract`);
564
+ const output = assertCompiledContract(def.contract?.output, `command "${def.command}" output contract`);
565
+ if (input.closureDigest !== decl.inputDigest || output.closureDigest !== decl.outputDigest)
566
+ throw new Error(`command "${def.command}" compiled contracts ${input.closureDigest}/${output.closureDigest} do not equal the declared ${decl.inputDigest}/${decl.outputDigest} (SPEC 13.7)`);
567
+ defs.push({
568
+ command: def.command, class: "ephemeral",
569
+ digests: { input: decl.inputDigest, output: decl.outputDigest },
570
+ validate: { args: input.validate, output: output.validate },
571
+ authorities: new Set(decl.authorities),
572
+ handler: def.handler,
573
+ });
574
+ }
575
+ for (const c of cluster.commands)
576
+ if (!defs.some((d) => d.command === c.name))
577
+ throw new Error(`command "${c.name}" has no def; a declared command nobody serves is a construction bug (SPEC 13.21)`);
578
+ const answer = deepFreeze({
579
+ public: true,
580
+ descriptor: {
581
+ endpoint: serve.endpoint,
582
+ owner: self.owner,
583
+ protocol: { v: 1 },
584
+ clusters: [{
585
+ digest: singleDocumentClosure(serve.cluster).closureDigest,
586
+ commands: cluster.commands.map((c) => c.name),
587
+ document: structuredClone(serve.cluster),
588
+ }],
589
+ },
590
+ });
591
+ defs.push({
592
+ command: "describe",
593
+ class: "ephemeral",
594
+ validate: describeValidators(),
595
+ authorities: new Set(EP_PRINCIPAL_AUTHORITIES),
596
+ handler: () => answer,
597
+ });
598
+ const byCommand = new Map(defs.map((d) => [d.command, d]));
599
+ const steps = {
600
+ parse: (subject) => {
601
+ const parsed = parseEpSubject(subject);
602
+ if (!parsed || parsed.plane !== "principal-request")
603
+ return null;
604
+ // The addressee check on this route: a request whose head is not this process was not
605
+ // addressed to it and is dropped with no reply. It needs only the subject, so it runs here.
606
+ const h = parsed.principal;
607
+ if (parsed.endpoint !== serve.endpoint || h.owner !== self.owner || h.actor !== self.actor || h.uid !== self.uid || h.runtimeId !== self.runtimeId)
608
+ return null;
609
+ return parsed;
610
+ },
611
+ addressed: () => { },
612
+ admit: (parsed, def) => {
613
+ if (!isPrincipalAuthority(parsed.authority) || !def.authorities.has(parsed.authority))
614
+ throw new EpEnvelopeError("permission-denied", `command "${def.command}" does not admit the "${parsed.authority}" authority; a command serves only the words its declaration lists (SPEC 13.21)`);
615
+ },
616
+ beforeEffect: async () => undefined,
617
+ context: ({ parsed, env, receivedAtMonotonicMs, replyFits }) => ({
618
+ endpoint: serve.endpoint, principal: self, caller: parsed.caller, authority: parsed.authority,
619
+ request: env, receivedAtMonotonicMs, replyFits,
620
+ }),
621
+ replySubject: (parsed) => derivePrincipalReplySubject(space, parsed, self),
622
+ };
623
+ const pending = new Set();
624
+ let refusal;
625
+ let markRefused;
626
+ const refused = new Promise((resolve) => { markRefused = resolve; });
627
+ const sub = nc.subscribe(filter, {
628
+ callback: (err, msg) => {
629
+ if (err) {
630
+ if (refusal === undefined) {
631
+ refusal = new EpEnvelopeError("permission-denied", `the broker refused this process's subscription to its principal-route subject "${filter}": ${err.message}. The credential holds no serve row for it, which a credential minted before the rows existed does not; reconnect after the auth service runs a release that mints them (SPEC 13.21)`);
632
+ markRefused(refusal);
633
+ }
634
+ return;
635
+ }
636
+ if (carriesStoredProvenance(msg))
637
+ return;
638
+ const run = runRequest(nc, steps, (parsed) => byCommand.get(parsed.command), msg).catch(() => { });
639
+ pending.add(run);
640
+ void run.finally(() => pending.delete(run));
641
+ },
642
+ });
643
+ // A refused subscription arrives as the broker's `-ERR`, which it writes before the `PONG` that
644
+ // answers the flush, and nats-core hands it to the callback above before it settles the flush.
645
+ const check = async () => {
646
+ await nc.flush();
647
+ if (refusal !== undefined)
648
+ throw refusal;
649
+ };
650
+ const ready = check();
651
+ ready.catch(() => { });
652
+ return {
653
+ filter,
654
+ ready,
655
+ refused,
656
+ check,
657
+ async stop() {
658
+ const gone = nc.closed().then(() => undefined);
659
+ await Promise.race([sub.drain().catch(() => undefined), gone]);
660
+ await Promise.allSettled([...pending]);
661
+ },
662
+ };
663
+ }
664
+ function deepFreeze(v) {
665
+ if (v !== null && typeof v === "object") {
666
+ for (const child of Object.values(v))
667
+ deepFreeze(child);
668
+ Object.freeze(v);
669
+ }
670
+ return v;
671
+ }
486
672
  /** The declared {@link DescribeAnswer} output schema. The answer's own two fields are closed;
487
673
  * the descriptor level is deliberately OPEN to additive evolution (§13.7: protocol.v stays 1
488
674
  * across additive changes), with the identity, protocol pin, digest grammar, and non-empty
@@ -519,17 +705,24 @@ const DESCRIBE_ANSWER_SCHEMA = {
519
705
  },
520
706
  },
521
707
  };
708
+ let describeCompiled;
522
709
  /** The reserved describe's compiled validators (§13.7): the canonical VOID input (a describe
523
710
  * carrying any args is `bad-request` at the same pre-effect seam as every command, BEFORE the
524
711
  * authorization-view lookup) and the declared {@link DescribeAnswer} output. Compiled once,
525
712
  * lazily, through the same profile compiler every registered contract rides. */
526
- let describeValidate;
527
713
  function describeValidators() {
528
- describeValidate ??= {
529
- args: compileContract({ root: VOID_SCHEMA }).validate,
530
- output: compileContract({ root: DESCRIBE_ANSWER_SCHEMA }).validate,
531
- };
532
- return describeValidate;
714
+ const c = describeContracts();
715
+ return { args: c.input.validate, output: c.output.validate };
716
+ }
717
+ /** The reserved describe's compiled contracts: the canonical void input and the declared
718
+ * {@link DescribeAnswer} output. A caller validates a describe answer with the output, and pins
719
+ * neither digest on the request (§13.7). */
720
+ export function describeContracts() {
721
+ describeCompiled ??= Object.freeze({
722
+ input: compileContract({ root: VOID_SCHEMA }),
723
+ output: compileContract({ root: DESCRIBE_ANSWER_SCHEMA }),
724
+ });
725
+ return describeCompiled;
533
726
  }
534
727
  /** The reserved describe handler (internal: {@link serveEndpoint} is the only constructor —
535
728
  * §13.7 makes describe mandatory and this seam non-replaceable). The authorization policy is