@openrobops/iso21423 0.0.0-stage → 0.1.3

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 (100) hide show
  1. package/README.md +358 -2
  2. package/dist/ccs-CU8XD5sl.d.cts +69 -0
  3. package/dist/ccs-CU8XD5sl.d.ts +69 -0
  4. package/dist/chunk-3JNSIJSX.js +31 -0
  5. package/dist/chunk-3JNSIJSX.js.map +1 -0
  6. package/dist/chunk-5ZIUSUHF.js +55 -0
  7. package/dist/chunk-5ZIUSUHF.js.map +1 -0
  8. package/dist/chunk-DMJ6T3RX.js +445 -0
  9. package/dist/chunk-DMJ6T3RX.js.map +1 -0
  10. package/dist/chunk-GPNR37CI.js +1915 -0
  11. package/dist/chunk-GPNR37CI.js.map +1 -0
  12. package/dist/chunk-JDO725KR.js +210 -0
  13. package/dist/chunk-JDO725KR.js.map +1 -0
  14. package/dist/chunk-JIYCTQXR.js +1 -0
  15. package/dist/chunk-JIYCTQXR.js.map +1 -0
  16. package/dist/chunk-JLUENXGS.js +48 -0
  17. package/dist/chunk-JLUENXGS.js.map +1 -0
  18. package/dist/chunk-JQAMNFAF.js +1 -0
  19. package/dist/chunk-JQAMNFAF.js.map +1 -0
  20. package/dist/chunk-LTPOAVGF.js +44 -0
  21. package/dist/chunk-LTPOAVGF.js.map +1 -0
  22. package/dist/chunk-ODBIFZN3.js +65 -0
  23. package/dist/chunk-ODBIFZN3.js.map +1 -0
  24. package/dist/chunk-OH2DOPKJ.js +107 -0
  25. package/dist/chunk-OH2DOPKJ.js.map +1 -0
  26. package/dist/chunk-QAA44UNO.js +1 -0
  27. package/dist/chunk-QAA44UNO.js.map +1 -0
  28. package/dist/chunk-RD7PYTIT.js +107 -0
  29. package/dist/chunk-RD7PYTIT.js.map +1 -0
  30. package/dist/chunk-UJC46NTA.js +13 -0
  31. package/dist/chunk-UJC46NTA.js.map +1 -0
  32. package/dist/chunk-UW6WTEPT.js +293 -0
  33. package/dist/chunk-UW6WTEPT.js.map +1 -0
  34. package/dist/chunk-W7DIDPTG.js +1 -0
  35. package/dist/chunk-W7DIDPTG.js.map +1 -0
  36. package/dist/core.cjs +2874 -0
  37. package/dist/core.cjs.map +1 -0
  38. package/dist/core.d.cts +996 -0
  39. package/dist/core.d.ts +996 -0
  40. package/dist/core.js +59 -0
  41. package/dist/core.js.map +1 -0
  42. package/dist/gateway.cjs +2937 -0
  43. package/dist/gateway.cjs.map +1 -0
  44. package/dist/gateway.d.cts +165 -0
  45. package/dist/gateway.d.ts +165 -0
  46. package/dist/gateway.js +21 -0
  47. package/dist/gateway.js.map +1 -0
  48. package/dist/geometry.cjs +98 -0
  49. package/dist/geometry.cjs.map +1 -0
  50. package/dist/geometry.d.cts +38 -0
  51. package/dist/geometry.d.ts +38 -0
  52. package/dist/geometry.js +14 -0
  53. package/dist/geometry.js.map +1 -0
  54. package/dist/identity-BGr2FJmC.d.cts +258 -0
  55. package/dist/identity-Bw8Dik5S.d.ts +258 -0
  56. package/dist/index.cjs +3327 -0
  57. package/dist/index.cjs.map +1 -0
  58. package/dist/index.d.cts +118 -0
  59. package/dist/index.d.ts +118 -0
  60. package/dist/index.js +193 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/schema.cjs +375 -0
  63. package/dist/schema.cjs.map +1 -0
  64. package/dist/schema.d.cts +28 -0
  65. package/dist/schema.d.ts +28 -0
  66. package/dist/schema.js +14 -0
  67. package/dist/schema.js.map +1 -0
  68. package/dist/session-RV32MFpV.d.cts +139 -0
  69. package/dist/session-ueiESY7Y.d.ts +139 -0
  70. package/dist/session.cjs +855 -0
  71. package/dist/session.cjs.map +1 -0
  72. package/dist/session.d.cts +94 -0
  73. package/dist/session.d.ts +94 -0
  74. package/dist/session.js +20 -0
  75. package/dist/session.js.map +1 -0
  76. package/dist/testing.cjs +205 -0
  77. package/dist/testing.cjs.map +1 -0
  78. package/dist/testing.d.cts +94 -0
  79. package/dist/testing.d.ts +94 -0
  80. package/dist/testing.js +169 -0
  81. package/dist/testing.js.map +1 -0
  82. package/dist/topics-BiVeZyTW.d.cts +43 -0
  83. package/dist/topics-BiVeZyTW.d.ts +43 -0
  84. package/dist/topics.cjs +134 -0
  85. package/dist/topics.cjs.map +1 -0
  86. package/dist/topics.d.cts +41 -0
  87. package/dist/topics.d.ts +41 -0
  88. package/dist/topics.js +30 -0
  89. package/dist/topics.js.map +1 -0
  90. package/dist/transport-BT4AjTn9.d.cts +61 -0
  91. package/dist/transport-BT4AjTn9.d.ts +61 -0
  92. package/dist/types.cjs +186 -0
  93. package/dist/types.cjs.map +1 -0
  94. package/dist/types.d.cts +83 -0
  95. package/dist/types.d.ts +83 -0
  96. package/dist/types.js +50 -0
  97. package/dist/types.js.map +1 -0
  98. package/dist/validators-Be0ce1b8.d.cts +29 -0
  99. package/dist/validators-Be0ce1b8.d.ts +29 -0
  100. package/package.json +48 -4
@@ -0,0 +1,1915 @@
1
+ import {
2
+ cancelRequest
3
+ } from "./chunk-3JNSIJSX.js";
4
+ import {
5
+ Iso21423Session,
6
+ createMqttTransport
7
+ } from "./chunk-DMJ6T3RX.js";
8
+ import {
9
+ nowTimestamp
10
+ } from "./chunk-UJC46NTA.js";
11
+ import {
12
+ validateMessage
13
+ } from "./chunk-UW6WTEPT.js";
14
+ import {
15
+ RESOURCE_CONFIG
16
+ } from "./chunk-LTPOAVGF.js";
17
+ import {
18
+ requestStatusTopic,
19
+ requestTopic
20
+ } from "./chunk-5ZIUSUHF.js";
21
+ import {
22
+ LOST_CONNECTION_STATE,
23
+ PROTOCOL_VERSION,
24
+ ROOT_NAMESPACE
25
+ } from "./chunk-RD7PYTIT.js";
26
+ import {
27
+ AuthorizationDenied,
28
+ BrokerUnavailable,
29
+ IllegalTransition,
30
+ Iso21423Error,
31
+ NotCapableError,
32
+ RequestFailed,
33
+ RequestTimeout
34
+ } from "./chunk-JLUENXGS.js";
35
+
36
+ // src/requests/stateMachine.ts
37
+ var REQUEST_TRANSITIONS = {
38
+ RECEIVED: [
39
+ "ACCEPTED",
40
+ "CANCELED",
41
+ // NP-2: RECEIVED→CANCELED disputed vs shared interaction model (Figure C.3 final artwork may differ)
42
+ "ABORTED"
43
+ ],
44
+ ACCEPTED: [
45
+ "EXECUTING",
46
+ "CANCELED",
47
+ "ABORTED",
48
+ // NP-2: ACCEPTED→ABORTED disputed vs shared interaction model (Figure C.3 final artwork may differ)
49
+ "RECOVERY"
50
+ // NP-2: ACCEPTED→RECOVERY disputed vs shared interaction model (Figure C.3 final artwork may differ)
51
+ ],
52
+ EXECUTING: ["SUCCEEDED", "CANCELED", "ABORTED", "RECOVERY"],
53
+ RECOVERY: ["CANCELED", "ABORTED"],
54
+ // NP-2: no RECOVERY→SUCCEEDED (disputed vs shared interaction model, Figure C.3 final artwork may differ)
55
+ CANCELED: [],
56
+ SUCCEEDED: [],
57
+ ABORTED: []
58
+ };
59
+ var DETAIL_TRANSITIONS = {
60
+ RECEIVED: ["ACCEPTED", "CANCELED", "ABORTED"],
61
+ ACCEPTED: ["EXECUTING", "CANCELED", "ABORTED"],
62
+ EXECUTING: ["SUCCEEDED", "CANCELED", "ABORTED"],
63
+ CANCELED: [],
64
+ SUCCEEDED: [],
65
+ ABORTED: []
66
+ };
67
+ function isTerminalRequestState(s) {
68
+ return REQUEST_TRANSITIONS[s].length === 0;
69
+ }
70
+ var Lifecycle = class {
71
+ constructor(table, initial) {
72
+ this.table = table;
73
+ this.#state = initial;
74
+ }
75
+ table;
76
+ #state;
77
+ get state() {
78
+ return this.#state;
79
+ }
80
+ canTransition(to) {
81
+ return this.table[this.#state].includes(to);
82
+ }
83
+ /** Moves to `to` if legal; throws {@link IllegalTransition} otherwise. */
84
+ transition(to) {
85
+ if (!this.canTransition(to)) {
86
+ throw new IllegalTransition(`illegal transition ${this.#state} \u2192 ${to}`);
87
+ }
88
+ this.#state = to;
89
+ }
90
+ isTerminal() {
91
+ return this.table[this.#state].length === 0;
92
+ }
93
+ };
94
+ var RequestLifecycle = class extends Lifecycle {
95
+ constructor() {
96
+ super(REQUEST_TRANSITIONS, "RECEIVED");
97
+ }
98
+ };
99
+ var DetailLifecycle = class extends Lifecycle {
100
+ constructor() {
101
+ super(DETAIL_TRANSITIONS, "RECEIVED");
102
+ }
103
+ };
104
+
105
+ // src/core/resources.ts
106
+ var RESOURCE_MESSAGE_KIND = {
107
+ identity: "entityIdentity",
108
+ status: "entityStatus",
109
+ batteryStatus: "batteryStatus",
110
+ odometry: "odometry",
111
+ localTrajectory: "localTrajectory",
112
+ globalPath: "globalPath",
113
+ globalPlan: "globalPlan",
114
+ request: "request",
115
+ requestStatus: "requestStatus",
116
+ activeRequestsStatus: "requestStatusArray",
117
+ disconnection: null,
118
+ footprint: null
119
+ };
120
+ function messageKindFor(resource) {
121
+ return RESOURCE_MESSAGE_KIND[resource] ?? null;
122
+ }
123
+
124
+ // src/core/subscription.ts
125
+ function composeSubscription(topicFilters, parts) {
126
+ let live = true;
127
+ const sub = {
128
+ topicFilters: Object.freeze([...topicFilters]),
129
+ get active() {
130
+ return live;
131
+ },
132
+ async unsubscribe() {
133
+ if (!live) return;
134
+ live = false;
135
+ await Promise.all(parts.map((p) => p.unsubscribe()));
136
+ },
137
+ async [Symbol.asyncDispose]() {
138
+ await sub.unsubscribe();
139
+ }
140
+ };
141
+ return sub;
142
+ }
143
+
144
+ // src/core/sequence.ts
145
+ import { mkdir, readFile, rename, writeFile } from "fs/promises";
146
+ import { homedir } from "os";
147
+ import { join } from "path";
148
+ function defaultStateDir() {
149
+ return process.env.ISO21423_STATE_DIR ?? join(homedir(), ".iso21423");
150
+ }
151
+ var FileSequenceStore = class {
152
+ constructor(dir = defaultStateDir()) {
153
+ this.dir = dir;
154
+ this.file = join(this.dir, "sequence.json");
155
+ }
156
+ dir;
157
+ file;
158
+ // ponytail: in-process serialization only; use a per-file lock if multiple processes share ISO21423_STATE_DIR
159
+ #queue = Promise.resolve();
160
+ async read() {
161
+ try {
162
+ return JSON.parse(await readFile(this.file, "utf8"));
163
+ } catch {
164
+ return {};
165
+ }
166
+ }
167
+ async load(entityUuid) {
168
+ return (await this.read())[entityUuid];
169
+ }
170
+ /** Queued so concurrent saves in one process read-modify-write the file one at a time. */
171
+ save(entityUuid, value) {
172
+ const result = this.#queue.then(() => this.writeOne(entityUuid, value));
173
+ this.#queue = result.then(() => void 0, () => void 0);
174
+ return result;
175
+ }
176
+ async writeOne(entityUuid, value) {
177
+ const all = await this.read();
178
+ all[entityUuid] = value;
179
+ await mkdir(this.dir, { recursive: true });
180
+ const tmp = `${this.file}.${process.pid}.tmp`;
181
+ await writeFile(tmp, JSON.stringify(all), "utf8");
182
+ await rename(tmp, this.file);
183
+ }
184
+ };
185
+ var BLOCK = 1e3;
186
+ var SequenceCounter = class _SequenceCounter {
187
+ constructor(entityUuid, store, counter, reservedThrough) {
188
+ this.entityUuid = entityUuid;
189
+ this.store = store;
190
+ this.counter = counter;
191
+ this.reservedThrough = reservedThrough;
192
+ }
193
+ entityUuid;
194
+ store;
195
+ counter;
196
+ reservedThrough;
197
+ static async open(entityUuid, store, onFallback) {
198
+ if (!store) return new _SequenceCounter(entityUuid, void 0, 0, Number.MAX_SAFE_INTEGER);
199
+ try {
200
+ const seed = await store.load(entityUuid) ?? 0;
201
+ await store.save(entityUuid, seed + BLOCK);
202
+ return new _SequenceCounter(entityUuid, store, seed, seed + BLOCK);
203
+ } catch (err) {
204
+ onFallback?.(err);
205
+ return new _SequenceCounter(entityUuid, void 0, Date.now(), Number.MAX_SAFE_INTEGER);
206
+ }
207
+ }
208
+ /** Returns the next sequenceId, persisting a fresh reservation block when the current one is exhausted. */
209
+ async next() {
210
+ this.counter += 1;
211
+ if (this.counter > this.reservedThrough && this.store) {
212
+ this.reservedThrough = this.counter + BLOCK;
213
+ await this.store.save(this.entityUuid, this.reservedThrough);
214
+ }
215
+ return this.counter;
216
+ }
217
+ };
218
+
219
+ // src/core/types.ts
220
+ function toTimestamp(t) {
221
+ if (typeof t === "string") return t;
222
+ return nowTimestamp(t ?? /* @__PURE__ */ new Date());
223
+ }
224
+
225
+ // src/core/policies.ts
226
+ var DEFAULT_PRIORITY = 100;
227
+ var priorityOf = (r) => r.priority ?? DEFAULT_PRIORITY;
228
+ var keyOf = (s) => ({ source: s.destination, sequenceId: s.requestSequenceId });
229
+ var policies = {
230
+ /** Only one active request at a time; any new request while one is active is rejected outright (no buffering). */
231
+ abortNew() {
232
+ return {
233
+ admit: (_pending, active) => active.length === 0 ? { action: "accept" } : { action: "reject", reason: "REJECTED" }
234
+ };
235
+ },
236
+ /** One active + one queued slot; the server aborts the displaced queue entry with REJECTED. */
237
+ queueReplace() {
238
+ const policy = {
239
+ admit: (_pending, active) => active.length === 0 ? { action: "accept" } : { action: "buffer" }
240
+ };
241
+ Object.assign(policy, { bufferLimit: 1 });
242
+ return policy;
243
+ },
244
+ /** One active request; unlimited FIFO queueing behind it. */
245
+ queueAfter() {
246
+ const policy = {
247
+ admit: (_pending, active) => active.length === 0 ? { action: "accept" } : { action: "buffer" }
248
+ };
249
+ Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY });
250
+ return policy;
251
+ },
252
+ /** Up to `max` concurrently active requests (unbounded by default); beyond that, buffer FIFO. */
253
+ parallel(max = Number.POSITIVE_INFINITY) {
254
+ const policy = {
255
+ admit: (_pending, active) => active.length < max ? { action: "accept" } : { action: "buffer" }
256
+ };
257
+ Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY });
258
+ return policy;
259
+ },
260
+ /** A pending request with strictly lower `priority` (Table C.1: lower number = higher priority) than every active request preempts all of them; otherwise it buffers, and the buffer drains by priority. */
261
+ priority() {
262
+ const policy = {
263
+ admit: (pending, active) => {
264
+ if (active.length === 0) return { action: "accept" };
265
+ const mine = priorityOf(pending);
266
+ const beatsAll = active.every(
267
+ (s) => mine < priorityOf(s)
268
+ );
269
+ return beatsAll ? { action: "preempt", preempt: active.map(keyOf) } : { action: "buffer" };
270
+ }
271
+ };
272
+ Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY, drainByPriority: true });
273
+ return policy;
274
+ }
275
+ };
276
+ var DEFAULT_EXECUTION_POLICY = policies.parallel();
277
+
278
+ // src/core/entityCache.ts
279
+ var EntityCache = class {
280
+ constructor(session) {
281
+ this.session = session;
282
+ }
283
+ session;
284
+ byUuid = /* @__PURE__ */ new Map();
285
+ listeners = { entity: [], lost: [], gone: [] };
286
+ disconnectionSubscribed = false;
287
+ /** Subscribed once per client session (decision 3): identities are cheap and always needed. */
288
+ async start() {
289
+ await this.session.subscribeTopic(
290
+ `${ROOT_NAMESPACE}/+/+/identity`,
291
+ null,
292
+ (raw, meta) => this.onIdentity(raw, meta),
293
+ { qos: 1 }
294
+ );
295
+ }
296
+ /** Disconnection tracking is only wired when someone actually calls discover(). */
297
+ async watchDisconnections() {
298
+ if (this.disconnectionSubscribed) return;
299
+ this.disconnectionSubscribed = true;
300
+ await this.session.subscribeTopic(
301
+ `${ROOT_NAMESPACE}/+/+/disconnection`,
302
+ null,
303
+ (raw, meta) => this.onDisconnection(raw, meta),
304
+ { qos: 1 }
305
+ );
306
+ }
307
+ entities() {
308
+ return [...this.byUuid.values()];
309
+ }
310
+ get(uuid) {
311
+ return this.byUuid.get(uuid);
312
+ }
313
+ managedBy(uuid) {
314
+ return this.entities().filter((e) => e.managedBy === uuid);
315
+ }
316
+ on(event, cb) {
317
+ this.listeners[event].push(cb);
318
+ }
319
+ /** Removal path for `on()` — not part of the public `EntityCatalog` interface (D-18 consumers
320
+ * never unsubscribe from discovery), but used internally so per-call listeners don't leak. */
321
+ off(event, cb) {
322
+ const arr = this.listeners[event];
323
+ const i = arr.indexOf(cb);
324
+ if (i !== -1) arr.splice(i, 1);
325
+ }
326
+ /** Destination entityType resolution for request topics (decision 2). */
327
+ entityTypeOf(uuid) {
328
+ return this.byUuid.get(uuid)?.entityType;
329
+ }
330
+ /** Known-accepts lookup for NotCapableError (decision 4); undefined = unknown entity. */
331
+ acceptsOf(uuid) {
332
+ const entry = this.byUuid.get(uuid);
333
+ if (!entry) return void 0;
334
+ return entry.identity.capabilities?.accepts?.requests;
335
+ }
336
+ onIdentity(raw, meta) {
337
+ const text = typeof raw === "string" ? raw : "";
338
+ if (text.length === 0) {
339
+ const gone = this.byUuid.get(meta.entityUuid);
340
+ if (gone) {
341
+ this.byUuid.delete(meta.entityUuid);
342
+ this.emit("gone", gone);
343
+ }
344
+ return;
345
+ }
346
+ let parsed;
347
+ try {
348
+ parsed = JSON.parse(text);
349
+ } catch {
350
+ return;
351
+ }
352
+ const result = validateMessage("entityIdentity", parsed);
353
+ if (!result.ok) return;
354
+ const identity = result.value;
355
+ const now = /* @__PURE__ */ new Date();
356
+ const prev = this.byUuid.get(meta.entityUuid);
357
+ const entry = {
358
+ entityUuid: meta.entityUuid,
359
+ entityType: identity.entityType ?? meta.entityType,
360
+ identity,
361
+ manages: identity.capabilities?.manages ?? [],
362
+ managedBy: identity.capabilities?.managedBy,
363
+ // Preserve connectivity status across an identity re-publish (e.g. an owned-retained
364
+ // resend after the transport reconnects, session.ts's handleConnectionState): only a
365
+ // disconnection message (onDisconnection) or a real reconnect-clear should change this.
366
+ lost: prev?.lost ?? false,
367
+ firstSeen: prev?.firstSeen ?? now,
368
+ lastSeen: now
369
+ };
370
+ this.byUuid.set(entry.entityUuid, entry);
371
+ this.emit("entity", entry);
372
+ }
373
+ onDisconnection(raw, meta) {
374
+ const entry = this.byUuid.get(meta.entityUuid);
375
+ if (!entry) return;
376
+ const text = typeof raw === "string" ? raw : "";
377
+ const lost = text.length > 0 && text.includes(LOST_CONNECTION_STATE);
378
+ if (lost === entry.lost) return;
379
+ const updated = { ...entry, lost, lastSeen: /* @__PURE__ */ new Date() };
380
+ this.byUuid.set(entry.entityUuid, updated);
381
+ if (lost) this.emit("lost", updated);
382
+ }
383
+ emit(event, e) {
384
+ for (const cb of this.listeners[event]) cb(e);
385
+ }
386
+ };
387
+
388
+ // src/core/requestHandle.ts
389
+ var RequestHandle = class {
390
+ /** @internal */
391
+ constructor(ctx, destRef, requestUuid, sourceUuid, sequenceId, destination, timeoutMs) {
392
+ this.ctx = ctx;
393
+ this.destRef = destRef;
394
+ this.requestUuid = requestUuid;
395
+ this.sourceUuid = sourceUuid;
396
+ this.sequenceId = sequenceId;
397
+ this.destination = destination;
398
+ this.timeoutMs = timeoutMs;
399
+ this.#completion = new Promise((resolve, reject) => {
400
+ this.#resolve = resolve;
401
+ this.#reject = reject;
402
+ });
403
+ this.#completion.catch(() => void 0);
404
+ }
405
+ ctx;
406
+ destRef;
407
+ requestUuid;
408
+ sourceUuid;
409
+ sequenceId;
410
+ destination;
411
+ timeoutMs;
412
+ createdAt = /* @__PURE__ */ new Date();
413
+ #latest;
414
+ #listeners = [];
415
+ #settled = false;
416
+ #resolve;
417
+ #reject;
418
+ #completion;
419
+ #timer;
420
+ #statusSub;
421
+ /** @internal — called by sendRequest once the status subscription is live. */
422
+ armTimeout(sub) {
423
+ this.#statusSub = sub;
424
+ this.#timer = setTimeout(() => {
425
+ this.settle(new RequestTimeout(
426
+ `no RECEIVED for request ${this.requestUuid} within ${this.timeoutMs} ms`
427
+ ));
428
+ }, this.timeoutMs);
429
+ this.#timer.unref?.();
430
+ }
431
+ /** @internal — one inbound requestStatus message. */
432
+ ingest(status) {
433
+ if (status.requestSequenceId !== this.sequenceId) return;
434
+ this.#latest = status;
435
+ if (this.#timer) {
436
+ clearTimeout(this.#timer);
437
+ this.#timer = void 0;
438
+ }
439
+ for (const cb of this.#listeners) cb(status);
440
+ if (!isTerminalRequestState(status.status)) return;
441
+ void this.clearRetainedRequest();
442
+ if (status.status === "SUCCEEDED") this.settle(void 0, status);
443
+ else this.settle(new RequestFailed(`request ${this.requestUuid} ended ${status.status}`, status));
444
+ }
445
+ /** @internal — connection lost while in flight (nodejs_api.md §12). */
446
+ failFast() {
447
+ this.settle(new BrokerUnavailable(`broker unavailable during request ${this.requestUuid}`));
448
+ }
449
+ latestStatus() {
450
+ return this.#latest;
451
+ }
452
+ /** @internal — the resolved topic ref (post R3 empty-destination resolution), for sendCancel. */
453
+ internalDestRef() {
454
+ return this.destRef;
455
+ }
456
+ /** Registers a callback for every inbound status update on this request (not just the terminal one); returns a token to stop receiving them. */
457
+ onStatus(handler) {
458
+ this.#listeners.push(handler);
459
+ return composeSubscription([requestStatusTopic(this.destRef, this.requestUuid)], [{
460
+ unsubscribe: async () => {
461
+ this.#listeners = this.#listeners.filter((h) => h !== handler);
462
+ }
463
+ }]);
464
+ }
465
+ /** Resolves with the terminal SUCCEEDED status, or rejects with {@link RequestFailed}/{@link RequestTimeout}/{@link BrokerUnavailable} — never both. */
466
+ completion() {
467
+ return this.#completion;
468
+ }
469
+ /** Sends a cancelRequest for this request (or one action within it, via `actionId`); a no-op once the request has already settled. */
470
+ async cancel(opts = {}) {
471
+ if (this.#settled) return;
472
+ await this.ctx.sendCancel(this, opts.actionId);
473
+ }
474
+ settle(error, status) {
475
+ if (this.#settled) return;
476
+ this.#settled = true;
477
+ if (this.#timer) {
478
+ clearTimeout(this.#timer);
479
+ this.#timer = void 0;
480
+ }
481
+ void this.#statusSub?.unsubscribe().catch(() => {
482
+ });
483
+ if (error) this.#reject(error);
484
+ else this.#resolve(status);
485
+ }
486
+ /** Sender duty: clear the retained request on a terminal status (ND-10). Never throws — if the
487
+ * broker publish fails, Task 8's janitor is the backstop that eventually clears stale
488
+ * retained requests. */
489
+ async clearRetainedRequest() {
490
+ try {
491
+ await this.ctx.session.clearRetained(requestTopic(this.destRef, this.requestUuid));
492
+ } catch {
493
+ }
494
+ }
495
+ };
496
+
497
+ // src/core/incomingRequest.ts
498
+ var IncomingRequest = class {
499
+ /** @internal */
500
+ constructor(request, requestUuid, sink) {
501
+ this.request = request;
502
+ this.requestUuid = requestUuid;
503
+ this.sink = sink;
504
+ this.#details = request.details.map(() => new DetailLifecycle());
505
+ this.#detailStatuses = request.details.map((d) => ({
506
+ type: d.type,
507
+ version: d.version,
508
+ ...d.blocking !== void 0 ? { blocking: d.blocking } : {},
509
+ status: { code: "RECEIVED" }
510
+ }));
511
+ }
512
+ request;
513
+ requestUuid;
514
+ sink;
515
+ #lifecycle = new RequestLifecycle();
516
+ #details;
517
+ #detailStatuses;
518
+ #recoveries;
519
+ #recoveryStatuses;
520
+ get source() {
521
+ return this.request.source;
522
+ }
523
+ get sequenceId() {
524
+ return this.request.sequenceId;
525
+ }
526
+ get state() {
527
+ return this.#lifecycle.state;
528
+ }
529
+ get isTerminal() {
530
+ return this.#lifecycle.isTerminal();
531
+ }
532
+ /** @internal — D-12: RECEIVED is published by the server before the handler sees this. */
533
+ async publishReceived() {
534
+ await this.emit();
535
+ }
536
+ async accept() {
537
+ await this.transitionTo("ACCEPTED");
538
+ }
539
+ /** Transitions straight to ABORTED with the given reason (e.g. for pre-flight rejections that never reach ACCEPTED). */
540
+ async reject(reason) {
541
+ await this.transitionTo("ABORTED", reason);
542
+ }
543
+ async updateStatus(update) {
544
+ await this.transitionTo(update.status, update.reason, update.message);
545
+ }
546
+ async updateDetailStatus(update) {
547
+ const lifecycle = this.#details[update.index];
548
+ const entry = this.#detailStatuses[update.index];
549
+ if (!lifecycle || !entry) {
550
+ throw new IllegalTransition(`no request detail at index ${update.index}`);
551
+ }
552
+ if (lifecycle.state !== update.status) lifecycle.transition(update.status);
553
+ entry.status = {
554
+ code: update.status,
555
+ ...update.reason ? { reason: update.reason } : {},
556
+ ...update.message ? { message: update.message } : {}
557
+ };
558
+ if (update.properties) entry.properties = { ...entry.properties, ...update.properties };
559
+ await this.emit();
560
+ }
561
+ async complete(terminal) {
562
+ await this.transitionTo(terminal.status, terminal.reason, terminal.message);
563
+ }
564
+ /** @internal — used by the executor for the RECOVERY phase: transitions the request to
565
+ * RECOVERY and seeds `recoveryStatuses` from the request's declared `recoveries`, mirroring
566
+ * how the constructor seeds `detailStatuses` from `request.details`. */
567
+ async enterRecovery(recoveries, reason) {
568
+ this.#recoveries = recoveries.map(() => new DetailLifecycle());
569
+ this.#recoveryStatuses = recoveries.map((d) => ({
570
+ type: d.type,
571
+ version: d.version,
572
+ ...d.blocking !== void 0 ? { blocking: d.blocking } : {},
573
+ status: { code: "RECEIVED" }
574
+ }));
575
+ await this.transitionTo("RECOVERY", reason);
576
+ }
577
+ /** @internal — used by the executor to report a recovery detail's progress/outcome. Unlike
578
+ * `updateDetailStatus`, recovery entries are never cascaded by a terminal request transition
579
+ * (RECOVERY has no detail-level equivalent — see cascadeDetails), so the executor must call
580
+ * this for every recovery detail as it finishes, not just the non-last ones. */
581
+ async updateRecoveryStatus(update) {
582
+ const lifecycle = this.#recoveries?.[update.index];
583
+ const entry = this.#recoveryStatuses?.[update.index];
584
+ if (!lifecycle || !entry) {
585
+ throw new IllegalTransition(`no recovery detail at index ${update.index}`);
586
+ }
587
+ if (update.status === "EXECUTING" && lifecycle.state === "RECEIVED") lifecycle.transition("ACCEPTED");
588
+ if (lifecycle.state !== update.status) lifecycle.transition(update.status);
589
+ entry.status = {
590
+ code: update.status,
591
+ ...update.reason ? { reason: update.reason } : {},
592
+ ...update.message ? { message: update.message } : {}
593
+ };
594
+ if (update.properties) entry.properties = { ...entry.properties, ...update.properties };
595
+ await this.emit();
596
+ }
597
+ async transitionTo(to, reason, message) {
598
+ this.#lifecycle.transition(to);
599
+ this.cascadeDetails(to);
600
+ await this.emit(reason, message);
601
+ }
602
+ // ponytail: a request-level transition implies at least that much progress on every detail
603
+ // still in flight — an app that only calls accept()/updateStatus()/complete() and never
604
+ // updateDetailStatus() for a given detail shouldn't leave it stuck at RECEIVED (or, worse,
605
+ // publish a dead request with a still-live detail underneath it). Details already at or past
606
+ // `to`, already terminal, or for which `to` has no detail-level equivalent (RECOVERY) are left
607
+ // untouched; explicit updateDetailStatus() calls after this are then no-ops state-wise. Mirrors
608
+ // onto the wire-visible #detailStatuses entry too (preserving any reason/message already set),
609
+ // not just the internal DetailLifecycle guard.
610
+ cascadeDetails(to) {
611
+ const target = to;
612
+ this.#details.forEach((lifecycle, i) => {
613
+ if (lifecycle.isTerminal() || lifecycle.state === target) return;
614
+ if (!lifecycle.canTransition(target)) return;
615
+ lifecycle.transition(target);
616
+ const entry = this.#detailStatuses[i];
617
+ entry.status = { ...entry.status, code: target };
618
+ });
619
+ }
620
+ /**
621
+ * Builds and publishes the current requestStatus snapshot. A `reason`/`message` passed here
622
+ * (from a request-level transition) is attached to the first detail status entry, not stored
623
+ * at the request level — the wire schema carries reason/message per-detail, not on the request.
624
+ */
625
+ async emit(reason, message) {
626
+ const status = {
627
+ source: this.sink.ownerUuid,
628
+ // decision 5
629
+ destination: this.request.source,
630
+ sequenceId: await this.sink.nextStatusSequenceId(),
631
+ requestSequenceId: this.request.sequenceId,
632
+ timestamp: toTimestamp(),
633
+ status: this.#lifecycle.state,
634
+ detailStatuses: this.#detailStatuses.map((d) => ({ ...d })),
635
+ ...this.#recoveryStatuses ? { recoveryStatuses: this.#recoveryStatuses.map((d) => ({ ...d })) } : {}
636
+ };
637
+ if (reason || message) {
638
+ const first = status.detailStatuses[0];
639
+ if (first) {
640
+ first.status = {
641
+ ...first.status,
642
+ ...reason ? { reason } : {},
643
+ ...message ? { message } : {}
644
+ };
645
+ }
646
+ }
647
+ await this.sink.publishStatus(this, status);
648
+ }
649
+ };
650
+
651
+ // src/core/executor.ts
652
+ var BLOCKING_STATES = ["STOP_CATEGORY_0", "STOP_CATEGORY_1", "STOP_CATEGORY_2", "WAIT_FOR_RESET"];
653
+ var STATE_EXEMPT_TYPES = /* @__PURE__ */ new Set(["cancelRequest", "pauseImr", "resumeImr"]);
654
+ var majorOf = (version) => version.split(".")[0] ?? version;
655
+ function groupSteps(details) {
656
+ const steps = [];
657
+ let i = 0;
658
+ while (i < details.length) {
659
+ if (details[i].blocking === false) {
660
+ const group = [];
661
+ while (i < details.length && details[i].blocking === false) {
662
+ group.push(i);
663
+ i++;
664
+ }
665
+ steps.push(group);
666
+ } else {
667
+ steps.push([i]);
668
+ i++;
669
+ }
670
+ }
671
+ return steps;
672
+ }
673
+ var ActionExecutor = class {
674
+ handlers = /* @__PURE__ */ new Map();
675
+ runs = /* @__PURE__ */ new Map();
676
+ /** Registers a handler for `type`; throws if one is already registered unless `override: true`. */
677
+ register(type, handler, opts) {
678
+ if (this.handlers.has(type) && !opts?.override) {
679
+ throw new Iso21423Error(
680
+ `onRequest: a handler for "${type}" is already registered \u2014 pass { override: true } to replace it`
681
+ );
682
+ }
683
+ this.handlers.set(type, handler);
684
+ }
685
+ hasHandlers() {
686
+ return this.handlers.size > 0;
687
+ }
688
+ runKey(source, sequenceId) {
689
+ return `${source}:${sequenceId}`;
690
+ }
691
+ /** Fires the AbortController for an admitted request the policy is preempting (Task 7 seam). */
692
+ cancel(key) {
693
+ const run = this.runs.get(this.runKey(key.source, key.sequenceId));
694
+ if (!run) return false;
695
+ run.cancelRequested = true;
696
+ run.controller.abort();
697
+ return true;
698
+ }
699
+ /** Entry point called once a request is admitted (RequestServer step 6 fallback). The run stays
700
+ * registered in `this.runs` (so a cancelRequest can still find it) until the request is fully
701
+ * terminal — including through the RECOVERY phase (controller ruling: RECOVERY→CANCELED is
702
+ * legal, so a cancel arriving mid-recovery must still resolve). */
703
+ async run(incoming, entity) {
704
+ const request = incoming.request;
705
+ const preflight = this.preflightReject(request, entity);
706
+ if (preflight) {
707
+ await incoming.reject(preflight);
708
+ return;
709
+ }
710
+ await incoming.accept();
711
+ await incoming.updateStatus({ status: "EXECUTING" });
712
+ const key = this.runKey(request.source, request.sequenceId);
713
+ const run = { controller: new AbortController(), cancelRequested: false };
714
+ this.runs.set(key, run);
715
+ try {
716
+ const outcome = await this.runSequence(
717
+ request.details,
718
+ request,
719
+ entity,
720
+ run,
721
+ true,
722
+ false,
723
+ (index, patch) => incoming.updateDetailStatus({ index, ...patch })
724
+ );
725
+ if (outcome.trigger === "success") {
726
+ await incoming.complete({ status: "SUCCEEDED" });
727
+ return;
728
+ }
729
+ let trigger = outcome.trigger;
730
+ let reason = outcome.reason;
731
+ let message = outcome.message;
732
+ if (request.recoveries && request.recoveries.length > 0) {
733
+ await incoming.enterRecovery(request.recoveries, reason);
734
+ run.controller = new AbortController();
735
+ run.cancelRequested = false;
736
+ const recoveryOutcome = await this.runSequence(
737
+ request.recoveries,
738
+ request,
739
+ entity,
740
+ run,
741
+ false,
742
+ true,
743
+ (index, patch) => incoming.updateRecoveryStatus({ index, ...patch })
744
+ );
745
+ if (recoveryOutcome.trigger !== "success") {
746
+ if (recoveryOutcome.trigger === "cancel") trigger = "cancel";
747
+ reason = recoveryOutcome.reason ?? reason;
748
+ message = recoveryOutcome.message ?? message;
749
+ }
750
+ }
751
+ const finalStatus = trigger === "cancel" ? "CANCELED" : "ABORTED";
752
+ await incoming.complete({ status: finalStatus, reason, message });
753
+ } finally {
754
+ this.runs.delete(key);
755
+ }
756
+ }
757
+ /** Runs one detail array (main details or recoveries) under the shared sequencing rules
758
+ * (item 3), atomic protection (item 4) and outcome mapping (item 5).
759
+ * - `allowSkipLastSuccess` lets the caller rely on the request-level terminal cascade for the
760
+ * very last detail of a clean success run (main details only).
761
+ * - `markRemainingCanceled`: recoveryStatuses is never cascaded by the request's terminal
762
+ * transition (unlike detailStatuses), so when the sequence stops early the caller must ask
763
+ * us to explicitly mark every not-yet-started item CANCELED (main details rely on the
764
+ * cascade instead and pass false here). */
765
+ async runSequence(items, request, entity, run, allowSkipLastSuccess, markRemainingCanceled, update) {
766
+ const steps = groupSteps(items);
767
+ for (let s = 0; s < steps.length; s++) {
768
+ const group = steps[s];
769
+ const results = await Promise.all(
770
+ group.map((index) => this.runOneDetail(index, items[index], request, entity, run, update))
771
+ );
772
+ const batchHasAbort = results.some((r) => r.outcome === "aborted");
773
+ const cancelledNow = run.controller.signal.aborted || run.cancelRequested;
774
+ for (let k = 0; k < group.length; k++) {
775
+ const index = group[k];
776
+ const result = results[k];
777
+ const isLastOverall = index === items.length - 1;
778
+ if (result.outcome === "succeeded") {
779
+ const skip = allowSkipLastSuccess && isLastOverall && !batchHasAbort && !cancelledNow;
780
+ if (!skip) {
781
+ await update(index, { status: "SUCCEEDED", ...result.properties ? { properties: result.properties } : {} });
782
+ }
783
+ } else {
784
+ await update(index, { status: "ABORTED", reason: result.reason, ...result.message ? { message: result.message } : {} });
785
+ }
786
+ }
787
+ if (batchHasAbort || cancelledNow) {
788
+ if (markRemainingCanceled) {
789
+ for (const index of steps.slice(s + 1).flat()) {
790
+ await update(index, { status: "CANCELED" });
791
+ }
792
+ }
793
+ const aborted = results.find((r) => r.outcome === "aborted");
794
+ return cancelledNow ? { trigger: "cancel", reason: aborted?.reason, message: aborted?.message } : { trigger: "abort", reason: aborted?.reason, message: aborted?.message };
795
+ }
796
+ }
797
+ return { trigger: "success" };
798
+ }
799
+ /**
800
+ * Runs a single detail's handler: publishes an EXECUTING status first, then invokes the
801
+ * registered handler (or produces an ACTION_NOT_IMPLEMENTED result if none exists), catching any
802
+ * thrown error as a GENERAL_FAILURE abort. Waits for any `ctx.progress()` updates issued during
803
+ * the handler call to finish publishing before returning.
804
+ */
805
+ async runOneDetail(index, detail, request, entity, run, update) {
806
+ const atomic = (detail.atomic ?? false) || (request.atomic ?? false);
807
+ const signal = atomic ? new AbortController().signal : run.controller.signal;
808
+ await update(index, { status: "EXECUTING" });
809
+ const pending = [];
810
+ const ctx = {
811
+ entity,
812
+ request,
813
+ signal,
814
+ progress: (properties) => {
815
+ pending.push(update(index, { status: "EXECUTING", properties }));
816
+ },
817
+ succeeded: (properties) => properties !== void 0 ? { outcome: "succeeded", properties } : { outcome: "succeeded" },
818
+ aborted: (reason, message) => message !== void 0 ? { outcome: "aborted", reason, message } : { outcome: "aborted", reason }
819
+ };
820
+ const typed = { ...detail, properties: detail.properties ?? {} };
821
+ const handler = this.handlers.get(detail.type);
822
+ let result;
823
+ try {
824
+ if (!handler) {
825
+ result = { outcome: "aborted", reason: "ACTION_NOT_IMPLEMENTED" };
826
+ } else {
827
+ result = await handler(typed, ctx);
828
+ }
829
+ } catch (err) {
830
+ result = { outcome: "aborted", reason: "GENERAL_FAILURE", message: err instanceof Error ? err.message : String(err) };
831
+ }
832
+ await Promise.all(pending);
833
+ return result;
834
+ }
835
+ /** Item 1: pre-flight rejection, first match wins across the four rule categories, each
836
+ * scanned over every detail in order. */
837
+ preflightReject(request, entity) {
838
+ for (const d of request.details) {
839
+ if (d.format !== void 0 && d.format !== "ISO-21423") return "FORMAT_NOT_SUPPORTED";
840
+ }
841
+ for (const d of request.details) {
842
+ if (majorOf(d.version) !== majorOf(PROTOCOL_VERSION)) return "VERSION_NOT_SUPPORTED";
843
+ }
844
+ for (const d of request.details) {
845
+ if (d.type !== "cancelRequest" && !this.handlers.has(d.type)) return "ACTION_NOT_IMPLEMENTED";
846
+ }
847
+ const states = entity.lastStates();
848
+ if (BLOCKING_STATES.some((s) => states.includes(s))) {
849
+ for (const d of request.details) {
850
+ if (!STATE_EXEMPT_TYPES.has(d.type)) return "INVALID_IMR_STATE_FOR_ACTION";
851
+ }
852
+ }
853
+ return void 0;
854
+ }
855
+ };
856
+ async function resolveCancelRequest(cancelReq, executors) {
857
+ const props = cancelReq.request.details[0]?.properties;
858
+ const key = props?.source !== void 0 && props.requestId !== void 0 ? { source: props.source, sequenceId: props.requestId } : void 0;
859
+ const found = key !== void 0 && [...executors].some((ex) => ex.cancel(key));
860
+ if (found) {
861
+ await cancelReq.accept();
862
+ await cancelReq.updateStatus({ status: "EXECUTING" });
863
+ await cancelReq.complete({ status: "SUCCEEDED" });
864
+ } else {
865
+ await cancelReq.reject("REJECTED");
866
+ }
867
+ }
868
+
869
+ // src/core/requestServer.ts
870
+ var RequestServer = class {
871
+ constructor(ctx) {
872
+ this.ctx = ctx;
873
+ this.sink = {
874
+ ownerUuid: ctx.ref.entityUuid,
875
+ nextStatusSequenceId: () => ctx.sequence.next(),
876
+ // D-15: same SequenceCounter as sendRequest
877
+ publishStatus: (req, status) => this.publishStatus(req, status)
878
+ };
879
+ }
880
+ ctx;
881
+ sessionSub;
882
+ registrations = [];
883
+ // ponytail: in-memory only — a process restart re-executes requests still retained on the
884
+ // broker; persist the key set alongside the sequence seed if that ever bites.
885
+ seen = /* @__PURE__ */ new Set();
886
+ activeStatuses = /* @__PURE__ */ new Map();
887
+ pendingRequests = [];
888
+ sink;
889
+ // Task 7: the executor is the fallback consumer once no acceptRequests filter matches — see
890
+ // handleAcceptedRequest / the cancelRequest branch of handleInbound below.
891
+ executor;
892
+ // Task 8 (FleetGateway) seams — both optional, set only by EntityHandle.setDispatchInterceptor /
893
+ // onRequestSettled when a gateway wires them; a plain client never touches either.
894
+ dispatchInterceptor;
895
+ requestSettledHook;
896
+ // ND-12 cancel-resolution seam: every managed handle's executor, consulted when a cancelRequest
897
+ // doesn't name a run in this server's own executor — a dispatched request actually runs in the
898
+ // target robot's executor, not the IMRFM's own.
899
+ managedExecutorsHook;
900
+ /** Idempotent: a second acceptRequests() on the same handle reuses the live subscription. */
901
+ async ensureStarted() {
902
+ if (this.sessionSub) return;
903
+ const filter = `${this.ctx.session.topicFor(this.ctx.ref, "request")}/+`;
904
+ this.sessionSub = await this.ctx.session.subscribeTopic(
905
+ filter,
906
+ null,
907
+ (msg, meta) => {
908
+ this.handleInbound(msg, meta).catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
909
+ },
910
+ { qos: 2 }
911
+ );
912
+ }
913
+ /** @internal — EntityHandle.onRequest wires the executor in here once, the first time it's used. */
914
+ setExecutor(executor, entity) {
915
+ this.executor = { executor, entity };
916
+ }
917
+ /** @internal — EntityHandle.setDispatchInterceptor (ND-12, IMRFM handle only). */
918
+ setDispatchInterceptor(cb) {
919
+ this.dispatchInterceptor = cb;
920
+ }
921
+ /** @internal — EntityHandle.setManagedExecutorsHook (ND-12 cancel resolution, IMRFM handle
922
+ * only). */
923
+ setManagedExecutorsHook(cb) {
924
+ this.managedExecutorsHook = cb;
925
+ }
926
+ /** @internal — EntityHandle.onRequestSettled (ND-10 janitor feed). */
927
+ setRequestSettledHook(cb) {
928
+ this.requestSettledHook = cb;
929
+ }
930
+ /** Adds a low-level request handler for `filter`; returns a deregistration function (not itself async — callers unsubscribe/teardown separately once `handlerCount` hits 0). */
931
+ register(filter, handler) {
932
+ const reg = { filter, handler };
933
+ this.registrations.push(reg);
934
+ return () => {
935
+ this.registrations = this.registrations.filter((r) => r !== reg);
936
+ };
937
+ }
938
+ get handlerCount() {
939
+ return this.registrations.length;
940
+ }
941
+ /** ND-18: count of admitted (handed to a handler), still-non-terminal requests — what
942
+ * ClientHealth.activeRequests.serving sums across every handle. */
943
+ get servingCount() {
944
+ let n = 0;
945
+ for (const data of this.activeStatuses.values()) if (data.admitted) n++;
946
+ return n;
947
+ }
948
+ async teardown() {
949
+ await this.sessionSub?.unsubscribe();
950
+ this.sessionSub = void 0;
951
+ }
952
+ /**
953
+ * Top-level inbound message handler for this entity's `request/+` subscription: parses and
954
+ * schema-validates the payload (rejecting/warning on failure), drops retained clears and
955
+ * already-seen duplicates, publishes RECEIVED, then routes the request — dispatch interception
956
+ * (ND-12) first, then cancelRequest resolution, then normal admission-policy handling.
957
+ */
958
+ async handleInbound(text, meta) {
959
+ if (text === "") return;
960
+ const requestUuid = meta.requestUuid;
961
+ if (!requestUuid) return;
962
+ let parsed;
963
+ try {
964
+ parsed = JSON.parse(text);
965
+ } catch {
966
+ await this.rejectOrWarn(meta.topic, text, void 0, ["invalid JSON"], requestUuid);
967
+ return;
968
+ }
969
+ const result = validateMessage("request", parsed);
970
+ if (!result.ok) {
971
+ await this.rejectOrWarn(meta.topic, text, result.value, result.errors ?? [], requestUuid);
972
+ return;
973
+ }
974
+ const request = result.value;
975
+ const dupKey = `${request.source}:${request.sequenceId}`;
976
+ if (this.seen.has(dupKey)) {
977
+ this.ctx.diagnostic("duplicate-request-ignored", { source: request.source, sequenceId: request.sequenceId });
978
+ this.requestSettledHook?.(meta.topic);
979
+ return;
980
+ }
981
+ this.seen.add(dupKey);
982
+ const req = new IncomingRequest(request, requestUuid, this.sink);
983
+ await req.publishReceived();
984
+ if (this.dispatchInterceptor && request.destination === "") {
985
+ const target = this.dispatchInterceptor(request);
986
+ if (target) {
987
+ void target.executor.run(req, target.entity).catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
988
+ } else {
989
+ this.ctx.diagnostic("dispatch-rejected", { reason: "REJECTED" });
990
+ await req.reject("REJECTED");
991
+ }
992
+ return;
993
+ }
994
+ const firstDetail = request.details[0];
995
+ if (firstDetail && firstDetail.type === "cancel") {
996
+ this.ctx.diagnostic("legacy-cancel-normalized", { source: request.source, sequenceId: request.sequenceId });
997
+ firstDetail.type = "cancelRequest";
998
+ }
999
+ const isCancelRequest = request.details.length > 0 && request.details[0].type === "cancelRequest";
1000
+ if (isCancelRequest) {
1001
+ const matching = this.registrations.filter((r) => r.filter.matches(request));
1002
+ if (matching.length > 0) {
1003
+ for (const r of matching) r.handler(req);
1004
+ } else {
1005
+ const executors = this.cancelExecutors();
1006
+ if (executors.length > 0) {
1007
+ await resolveCancelRequest(req, executors);
1008
+ } else {
1009
+ this.ctx.diagnostic("dispatch-rejected", { reason: "ACTION_NOT_IMPLEMENTED" });
1010
+ await req.reject("ACTION_NOT_IMPLEMENTED");
1011
+ }
1012
+ }
1013
+ return;
1014
+ }
1015
+ const policy = this.ctx.getExecutionPolicy();
1016
+ const decision = policy.admit(request, this.buildActiveStatuses());
1017
+ await this.applyAdmissionDecision(request, req, decision, policy);
1018
+ }
1019
+ /** Controller ruling R2: build a minimal one-detail IncomingRequest and reject it with
1020
+ * MALFORMED_REQUEST when (source, sequenceId) can still be read; otherwise surface the usual
1021
+ * 'validation-warning' event and drop, same as any other schema-routed subscription would. */
1022
+ async rejectOrWarn(topic, raw, parsed, errors, requestUuid) {
1023
+ const obj = parsed && typeof parsed === "object" ? parsed : void 0;
1024
+ const source = typeof obj?.source === "string" ? obj.source : void 0;
1025
+ const sequenceId = typeof obj?.sequenceId === "number" ? obj.sequenceId : void 0;
1026
+ if (source === void 0 || sequenceId === void 0) {
1027
+ this.ctx.session.reportValidationWarning({ topic, payload: raw, errors });
1028
+ this.requestSettledHook?.(topic);
1029
+ return;
1030
+ }
1031
+ const minimal = {
1032
+ destination: this.ctx.ref.entityUuid,
1033
+ source,
1034
+ sequenceId,
1035
+ timestamp: toTimestamp(),
1036
+ details: [{ type: this.inferDetailType(obj), version: "1.0" }]
1037
+ };
1038
+ const req = new IncomingRequest(minimal, requestUuid, this.sink);
1039
+ this.ctx.diagnostic("dispatch-rejected", { reason: "MALFORMED_REQUEST" });
1040
+ await req.reject("MALFORMED_REQUEST");
1041
+ }
1042
+ inferDetailType(obj) {
1043
+ const details = obj.details;
1044
+ if (Array.isArray(details) && details.length > 0) {
1045
+ const first = details[0];
1046
+ if (first && typeof first === "object" && typeof first.type === "string") {
1047
+ return first.type;
1048
+ }
1049
+ }
1050
+ return "unknown";
1051
+ }
1052
+ /** The StatusSink: publish the requestStatus, then republish activeRequestsStatus (point 7). */
1053
+ async publishStatus(req, status) {
1054
+ const topic = requestStatusTopic(this.ctx.ref, req.requestUuid);
1055
+ const { qos, retain } = RESOURCE_CONFIG.requestStatus;
1056
+ await this.ctx.session.publishTopic(topic, "requestStatus", status, { qos, retain });
1057
+ this.ctx.countPublish();
1058
+ if (isTerminalRequestState(status.status)) {
1059
+ this.activeStatuses.delete(req.requestUuid);
1060
+ this.requestSettledHook?.(requestTopic(this.ctx.ref, req.requestUuid));
1061
+ setImmediate(() => {
1062
+ this.reAdmitPending().catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
1063
+ });
1064
+ } else {
1065
+ this.activeStatuses.set(req.requestUuid, {
1066
+ req,
1067
+ status,
1068
+ priority: req.request.priority,
1069
+ admitted: this.activeStatuses.get(req.requestUuid)?.admitted ?? false
1070
+ });
1071
+ }
1072
+ const statusArray = [...this.activeStatuses.values()].map((data) => data.status);
1073
+ await this.ctx.session.publishResource(
1074
+ this.ctx.ref,
1075
+ "activeRequestsStatus",
1076
+ "requestStatusArray",
1077
+ statusArray
1078
+ );
1079
+ this.ctx.countPublish();
1080
+ }
1081
+ /** The admission view (R7: augmented with priority): only requests a policy decision has
1082
+ * already admitted. Buffered requests — and the pending request itself, which is entered as
1083
+ * admitted:false by its own RECEIVED — never appear here. */
1084
+ buildActiveStatuses() {
1085
+ return [...this.activeStatuses.values()].filter((data) => data.admitted).map((data) => ({
1086
+ ...data.status,
1087
+ ...data.priority !== void 0 ? { priority: data.priority } : {}
1088
+ }));
1089
+ }
1090
+ /** Apply an admission decision: accept, reject, buffer, or preempt. */
1091
+ async applyAdmissionDecision(request, req, decision, policy) {
1092
+ if (decision.action === "reject") {
1093
+ this.ctx.diagnostic("dispatch-rejected", { reason: decision.reason });
1094
+ await req.reject(decision.reason);
1095
+ } else if (decision.action === "buffer") {
1096
+ this.pendingRequests.push({ request, req });
1097
+ await this.enforceBufferLimit(policy);
1098
+ } else {
1099
+ if (decision.action === "preempt") {
1100
+ for (const key of decision.preempt) {
1101
+ for (const data of this.activeStatuses.values()) {
1102
+ if (!data.admitted) continue;
1103
+ if (data.status.destination === key.source && data.status.requestSequenceId === key.sequenceId) {
1104
+ const executorOwned = this.executor?.executor.cancel(key) ?? false;
1105
+ if (!executorOwned) await data.req.complete({ status: "CANCELED", reason: "PREEMPTED" });
1106
+ }
1107
+ }
1108
+ }
1109
+ }
1110
+ await this.handleAcceptedRequest(request, req);
1111
+ }
1112
+ }
1113
+ /** Handle an accepted request: mark as admitted, route to matching handlers. */
1114
+ async handleAcceptedRequest(request, req) {
1115
+ const existing = this.activeStatuses.get(req.requestUuid);
1116
+ if (existing) existing.admitted = true;
1117
+ const matching = this.registrations.filter((r) => r.filter.matches(request));
1118
+ if (matching.length > 0) {
1119
+ for (const r of matching) r.handler(req);
1120
+ return;
1121
+ }
1122
+ if (this.executor && this.executor.executor.hasHandlers()) {
1123
+ void this.executor.executor.run(req, this.executor.entity).catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
1124
+ return;
1125
+ }
1126
+ this.ctx.diagnostic("dispatch-rejected", { reason: "ACTION_NOT_IMPLEMENTED" });
1127
+ await req.reject("ACTION_NOT_IMPLEMENTED");
1128
+ }
1129
+ /** Every executor a cancelRequest should be resolved against: this server's own first (if any),
1130
+ * then every managed handle's (ND-12, IMRFM only). */
1131
+ cancelExecutors() {
1132
+ const list = [];
1133
+ if (this.executor) list.push(this.executor.executor);
1134
+ if (this.managedExecutorsHook) list.push(...this.managedExecutorsHook());
1135
+ return list;
1136
+ }
1137
+ /** Enforce bufferLimit: if the buffer exceeds the limit, displace the oldest request with REJECTED. */
1138
+ async enforceBufferLimit(policy) {
1139
+ const limit = policy.bufferLimit ?? Number.POSITIVE_INFINITY;
1140
+ while (this.pendingRequests.length > limit) {
1141
+ const displaced = this.pendingRequests.shift();
1142
+ this.ctx.diagnostic("dispatch-rejected", { reason: "REJECTED" });
1143
+ await displaced.req.reject("REJECTED");
1144
+ }
1145
+ }
1146
+ /** Re-admit buffered requests after a terminal transition, one at a time: each admitted request
1147
+ * is marked admitted before the next decision is taken, so the drain stops as soon as the
1148
+ * policy buffers again. Removal from the queue happens before any await, so two overlapping
1149
+ * drains can never hand the same request to a handler twice. */
1150
+ async reAdmitPending() {
1151
+ while (this.pendingRequests.length > 0) {
1152
+ const policy = this.ctx.getExecutionPolicy();
1153
+ const index = this.selectNextPending(policy);
1154
+ const pending = this.pendingRequests[index];
1155
+ const decision = policy.admit(pending.request, this.buildActiveStatuses());
1156
+ if (decision.action === "buffer") break;
1157
+ this.pendingRequests.splice(index, 1);
1158
+ await this.applyAdmissionDecision(pending.request, pending.req, decision, policy);
1159
+ }
1160
+ }
1161
+ /** Next buffered request to drain: lowest numeric priority first when the policy asks for a
1162
+ * priority drain (arrival order breaking ties), plain FIFO otherwise. */
1163
+ selectNextPending(policy) {
1164
+ if (!policy.drainByPriority) return 0;
1165
+ const pri = (i) => this.pendingRequests[i].request.priority ?? DEFAULT_PRIORITY;
1166
+ let best = 0;
1167
+ for (let i = 1; i < this.pendingRequests.length; i++) if (pri(i) < pri(best)) best = i;
1168
+ return best;
1169
+ }
1170
+ };
1171
+
1172
+ // src/core/entityHandle.ts
1173
+ import { randomUUID } from "crypto";
1174
+ var RETAINED_RESOURCES = [
1175
+ "identity",
1176
+ "batteryStatus",
1177
+ "globalPath",
1178
+ "globalPlan",
1179
+ "activeRequestsStatus",
1180
+ "disconnection"
1181
+ ];
1182
+ var EntityHandle = class {
1183
+ /** @internal — constructed by Iso21423Client.registerSelfEntity/registerManagedEntity. */
1184
+ constructor(ctx, ownershipMode, registration) {
1185
+ this.ctx = ctx;
1186
+ this.ownershipMode = ownershipMode;
1187
+ this.#identity = {
1188
+ id: registration.entityUuid,
1189
+ timestamp: toTimestamp(),
1190
+ entityType: registration.entityType,
1191
+ manufacturerName: registration.manufacturerName,
1192
+ iso21423Version: registration.iso21423Version ?? PROTOCOL_VERSION,
1193
+ capabilities: {
1194
+ provides: registration.capabilities?.provides ?? [],
1195
+ accepts: { requests: registration.capabilities?.accepts ?? [] }
1196
+ },
1197
+ details: registration.details ?? {}
1198
+ };
1199
+ this.#registrationPolicy = registration.executionPolicy;
1200
+ }
1201
+ ctx;
1202
+ ownershipMode;
1203
+ #identity;
1204
+ #states = [];
1205
+ #requestServer;
1206
+ #executor;
1207
+ #executionPolicy;
1208
+ #registrationPolicy;
1209
+ get entityUuid() {
1210
+ return this.ctx.ref.entityUuid;
1211
+ }
1212
+ get entityType() {
1213
+ return this.ctx.ref.entityType;
1214
+ }
1215
+ /** Last states this handle published — feeds the automatic INVALID_IMR_STATE_FOR_ACTION rule. */
1216
+ lastStates() {
1217
+ return this.#states;
1218
+ }
1219
+ identity() {
1220
+ return this.#identity;
1221
+ }
1222
+ async publishIdentity(identity) {
1223
+ this.#identity = { ...identity, timestamp: toTimestamp(identity.timestamp) };
1224
+ await this.publish("identity", this.#identity);
1225
+ }
1226
+ /** Shallow-merges `partial` onto the current identity (top-level fields only — e.g. a partial `capabilities` replaces the whole object) and republishes it with a fresh timestamp. */
1227
+ async updateIdentity(partial) {
1228
+ await this.publishIdentity({ ...this.#identity, ...partial, timestamp: toTimestamp() });
1229
+ }
1230
+ /** Set a per-handle execution policy override (P-2). */
1231
+ setExecutionPolicy(policy) {
1232
+ this.#executionPolicy = policy;
1233
+ }
1234
+ /** Get the resolved execution policy (per-handle > registration > client default > DEFAULT_EXECUTION_POLICY). */
1235
+ getExecutionPolicy() {
1236
+ return this.#executionPolicy ?? this.#registrationPolicy ?? this.ctx.getDefaultExecutionPolicy();
1237
+ }
1238
+ async publishStatus(update) {
1239
+ this.#states = [...update.states];
1240
+ await this.publish("status", {
1241
+ entityId: this.entityUuid,
1242
+ timestamp: toTimestamp(update.timestamp),
1243
+ states: update.states,
1244
+ ...update.disabledCapabilities ? { disabledCapabilities: update.disabledCapabilities } : {}
1245
+ });
1246
+ }
1247
+ async publishBatteryStatus(update) {
1248
+ await this.publish("batteryStatus", { ...update, timestamp: toTimestamp(update.timestamp) });
1249
+ }
1250
+ async publishOdometry(sample) {
1251
+ await this.publish("odometry", { ...sample, timestamp: toTimestamp(sample.timestamp) });
1252
+ }
1253
+ async publishLocalTrajectory(sample) {
1254
+ await this.publish("localTrajectory", {
1255
+ timestamp: toTimestamp(sample.timestamp),
1256
+ localTrajectory: sample.points
1257
+ });
1258
+ }
1259
+ async publishGlobalPath(snapshot) {
1260
+ await this.publish("globalPath", { ...snapshot, timestamp: toTimestamp(snapshot.timestamp) });
1261
+ }
1262
+ async publishGlobalPlan(snapshot) {
1263
+ await this.publish("globalPlan", { ...snapshot, timestamp: toTimestamp(snapshot.timestamp) });
1264
+ }
1265
+ /**
1266
+ * Publishes a deployment-defined resource previously declared with `registerExtensionResource`
1267
+ * (throws for an undeclared name). No schema applies: `payload` is JSON-serialized as given, so
1268
+ * include your own `timestamp` if the resource needs one.
1269
+ */
1270
+ async publishExtension(resource, payload) {
1271
+ await this.publish(resource, payload);
1272
+ }
1273
+ /**
1274
+ * Sends a request to `cmd.destination` (or resolves an empty destination via
1275
+ * {@link resolveDestRef}, R3). Unless `requireCapability: false`, checks the destination's
1276
+ * known `accepts` capability list first and throws {@link NotCapableError} for any detail type
1277
+ * it doesn't advertise — skipped entirely for an unknown (not-yet-discovered) destination.
1278
+ * Subscribes to the status topic before publishing the request, so no status can be missed.
1279
+ */
1280
+ async sendRequest(cmd) {
1281
+ const destRef = this.resolveDestRef(cmd);
1282
+ if (cmd.requireCapability !== false && cmd.destination) {
1283
+ const accepts = this.ctx.catalog.acceptsOf(cmd.destination);
1284
+ const missing = accepts && cmd.details.map((d) => d.type).filter((t) => !accepts.includes(t));
1285
+ if (missing && missing.length > 0) {
1286
+ throw new NotCapableError(
1287
+ `entity ${cmd.destination} does not accept: ${missing.join(", ")} (pass requireCapability: false to send anyway)`
1288
+ );
1289
+ }
1290
+ }
1291
+ const sequenceId = await this.ctx.sequence.next();
1292
+ const requestUuid = cmd.requestUuid ?? randomUUID();
1293
+ const request = {
1294
+ destination: cmd.destination,
1295
+ source: this.entityUuid,
1296
+ sequenceId,
1297
+ timestamp: toTimestamp(),
1298
+ ...cmd.priority !== void 0 ? { priority: cmd.priority } : {},
1299
+ ...cmd.atomic !== void 0 ? { atomic: cmd.atomic } : {},
1300
+ details: cmd.details,
1301
+ ...cmd.recoveries ? { recoveries: cmd.recoveries } : {}
1302
+ };
1303
+ const handle = new RequestHandle(
1304
+ this.ctx,
1305
+ destRef,
1306
+ requestUuid,
1307
+ this.entityUuid,
1308
+ sequenceId,
1309
+ cmd.destination,
1310
+ cmd.timeoutMs ?? this.ctx.requestTimeoutMs
1311
+ );
1312
+ const sub = await this.ctx.session.subscribeTopic(
1313
+ requestStatusTopic(destRef, requestUuid),
1314
+ "requestStatus",
1315
+ (msg) => handle.ingest(msg),
1316
+ { qos: 2 }
1317
+ );
1318
+ this.ctx.trackInFlight(handle);
1319
+ handle.armTimeout(sub);
1320
+ await this.ctx.session.publishTopic(
1321
+ requestTopic(destRef, requestUuid),
1322
+ "request",
1323
+ request,
1324
+ { qos: 2, retain: true }
1325
+ );
1326
+ this.ctx.countPublish();
1327
+ return handle;
1328
+ }
1329
+ /** Registers a low-level request handler (Task 5); Tasks 6/7 add admission and the executor
1330
+ * hand-off on top of the same `RequestServer`. */
1331
+ async acceptRequests(filter, handler) {
1332
+ const server = this.ensureRequestServer();
1333
+ await server.ensureStarted();
1334
+ const deregister = server.register(filter, handler);
1335
+ const requestFilterTopic = `${this.ctx.session.topicFor(this.ctx.ref, "request")}/+`;
1336
+ return composeSubscription([requestFilterTopic], [{
1337
+ unsubscribe: async () => {
1338
+ deregister();
1339
+ if (server.handlerCount === 0) {
1340
+ await server.teardown();
1341
+ if (this.#requestServer === server) this.#requestServer = void 0;
1342
+ }
1343
+ }
1344
+ }]);
1345
+ }
1346
+ /**
1347
+ * Registers a per-action handler (Task 7, ND-11.1): the `ActionExecutor` becomes the fallback
1348
+ * consumer on this handle's `RequestServer` — low-level `acceptRequests` filters still win when
1349
+ * they match, otherwise any request whose details this executor recognizes is driven through
1350
+ * the executor's sequencing/atomic/recovery/cancelRequest logic. Registering a second handler
1351
+ * for the same `type` without `override: true` throws.
1352
+ */
1353
+ onRequest(type, handler, opts) {
1354
+ if (!this.#executor) {
1355
+ this.#executor = new ActionExecutor();
1356
+ const server = this.ensureRequestServer();
1357
+ server.setExecutor(this.#executor, this);
1358
+ void server.ensureStarted().catch((err) => this.ctx.diagnostic("dispatch-rejected", { reason: "GENERAL_FAILURE", error: err }));
1359
+ }
1360
+ this.#executor.register(type, handler, opts);
1361
+ }
1362
+ /**
1363
+ * @internal — FleetGateway janitor seam (ND-10): `cb` fires with this handle's request topic
1364
+ * whenever its `RequestServer` publishes a terminal status, or drops a duplicate/unroutable
1365
+ * retained request. Force-creates and starts the `RequestServer` so the hook is live even
1366
+ * before any `onRequest`/`acceptRequests` call.
1367
+ */
1368
+ async onRequestSettled(cb) {
1369
+ const server = this.ensureRequestServer();
1370
+ await server.ensureStarted();
1371
+ server.setRequestSettledHook(cb);
1372
+ }
1373
+ /**
1374
+ * @internal — FleetGateway dispatch seam (ND-12): wires the empty-destination interceptor onto
1375
+ * this handle's `RequestServer` (the IMRFM handle, wired once at `FleetGateway.connect()`).
1376
+ */
1377
+ async setDispatchInterceptor(cb) {
1378
+ const server = this.ensureRequestServer();
1379
+ await server.ensureStarted();
1380
+ server.setDispatchInterceptor(cb);
1381
+ }
1382
+ /**
1383
+ * @internal — FleetGateway cancel-resolution seam (ND-12): wires the managed-handles executor
1384
+ * lookup onto this handle's `RequestServer` (the IMRFM handle, wired once at
1385
+ * `FleetGateway.connect()`) so a cancelRequest for a dispatched request can find the run in the
1386
+ * robot's executor instead of the IMRFM's own.
1387
+ */
1388
+ async setManagedExecutorsHook(cb) {
1389
+ const server = this.ensureRequestServer();
1390
+ await server.ensureStarted();
1391
+ server.setManagedExecutorsHook(cb);
1392
+ }
1393
+ /** @internal — ND-12 retarget seam: this handle's executor, if an `onRequest` handler is
1394
+ * registered on it; used to hand a dispatched request off to a managed handle. A valid,
1395
+ * registered robot with no `onRequest` handler yields `undefined` here too — the dispatch
1396
+ * callback rejects it the same as an unknown uuid (there is nothing to run the request). */
1397
+ dispatchTarget() {
1398
+ return this.#executor ? { executor: this.#executor, entity: this } : void 0;
1399
+ }
1400
+ /** ND-18: requests this handle's RequestServer is currently serving (0 if it never started). */
1401
+ servingCount() {
1402
+ return this.#requestServer?.servingCount ?? 0;
1403
+ }
1404
+ ensureRequestServer() {
1405
+ if (!this.#requestServer) this.#requestServer = new RequestServer(this.ctx);
1406
+ return this.#requestServer;
1407
+ }
1408
+ /**
1409
+ * Controller ruling R3: an empty `destination` (spec §3.1 "IMRFM picks the robot") is not a
1410
+ * literal topic segment — resolve the actual target from the identity catalog by
1411
+ * `destinationType` (default `'IMRFM'`). Exactly one match is required; the wire `Request`
1412
+ * still carries `destination: ''` (only the topic ref is resolved).
1413
+ */
1414
+ resolveDestRef(cmd) {
1415
+ if (cmd.destination !== "") {
1416
+ const destinationType = cmd.destinationType ?? this.ctx.catalog.entityTypeOf(cmd.destination) ?? "IMR";
1417
+ return { entityType: destinationType, entityUuid: cmd.destination };
1418
+ }
1419
+ const entityType = cmd.destinationType ?? "IMRFM";
1420
+ const candidates = this.ctx.catalog.entities().filter((e) => e.entityType === entityType);
1421
+ if (candidates.length !== 1) {
1422
+ throw new Iso21423Error(
1423
+ `sendRequest: cannot resolve an empty destination to exactly one "${entityType}" entity (found ${candidates.length}) \u2014 pass destinationType and ensure exactly one such entity is discoverable`
1424
+ );
1425
+ }
1426
+ return { entityType, entityUuid: candidates[0].entityUuid };
1427
+ }
1428
+ /** Final OFFLINE status stays as the tombstone; every other retained topic is cleared. */
1429
+ async unregister() {
1430
+ await this.publishStatus({ states: ["OFFLINE"] });
1431
+ for (const resource of RETAINED_RESOURCES) {
1432
+ await this.ctx.session.clearRetained(
1433
+ this.ctx.session.topicFor(this.ctx.ref, resource)
1434
+ );
1435
+ }
1436
+ }
1437
+ async publish(resource, payload) {
1438
+ await this.ctx.session.publishResource(
1439
+ this.ctx.ref,
1440
+ resource,
1441
+ messageKindFor(resource),
1442
+ payload
1443
+ );
1444
+ this.ctx.countPublish();
1445
+ }
1446
+ };
1447
+
1448
+ // src/core/selfCheck.ts
1449
+ async function publishSelfCheck(session, ref, timeoutMs = 2e3) {
1450
+ const topic = session.topicFor(ref, "identity");
1451
+ let seen = false;
1452
+ let resolveEcho = () => {
1453
+ };
1454
+ const echo = new Promise((resolve) => {
1455
+ resolveEcho = resolve;
1456
+ });
1457
+ const sub = await session.subscribeTopic(topic, null, (raw) => {
1458
+ if (typeof raw === "string" && raw.length > 0) {
1459
+ seen = true;
1460
+ resolveEcho();
1461
+ }
1462
+ }, { qos: 1 });
1463
+ try {
1464
+ const timer = new Promise((resolve) => {
1465
+ const t = setTimeout(resolve, timeoutMs);
1466
+ t.unref?.();
1467
+ });
1468
+ await Promise.race([echo, timer]);
1469
+ if (!seen) {
1470
+ throw new AuthorizationDenied(
1471
+ `publish self-check failed: no retained identity echo on ${topic} \u2014 the broker ACL probably denies write access to this namespace (ND-15)`,
1472
+ topic
1473
+ );
1474
+ }
1475
+ } finally {
1476
+ await sub.unsubscribe();
1477
+ }
1478
+ }
1479
+
1480
+ // src/core/client.ts
1481
+ import { randomUUID as randomUUID2 } from "crypto";
1482
+ var sharedSequenceStore;
1483
+ function defaultSequenceStore() {
1484
+ return sharedSequenceStore ??= new FileSequenceStore();
1485
+ }
1486
+ var Iso21423Client = class _Iso21423Client {
1487
+ transport;
1488
+ security;
1489
+ validateOutbound;
1490
+ sourceId;
1491
+ sequenceStore;
1492
+ requestTimeoutMs;
1493
+ sessionPromise;
1494
+ session;
1495
+ cache;
1496
+ pendingCatalogListeners = [];
1497
+ defaultExecutionPolicy;
1498
+ selfEntities = /* @__PURE__ */ new Map();
1499
+ managedEntities = /* @__PURE__ */ new Map();
1500
+ trackedSubs = /* @__PURE__ */ new Set();
1501
+ inFlightRequests = /* @__PURE__ */ new Set();
1502
+ since;
1503
+ lastConnectionChange;
1504
+ subscriptionCount = 0;
1505
+ closed = false;
1506
+ counters = { published: 0, received: 0, validationWarnings: 0, rejections: 0 };
1507
+ listeners = {
1508
+ connection: [],
1509
+ "validation-warning": [],
1510
+ diagnostic: []
1511
+ };
1512
+ constructor(transport, opts) {
1513
+ this.transport = transport;
1514
+ this.security = opts.security;
1515
+ this.validateOutbound = opts.validateOutbound;
1516
+ this.sourceId = opts.sourceId;
1517
+ this.sequenceStore = opts.sequenceStore === null ? null : opts.sequenceStore ?? defaultSequenceStore();
1518
+ this.requestTimeoutMs = opts.requestTimeoutMs ?? 5e3;
1519
+ }
1520
+ static async connect(opts) {
1521
+ const hasTransport = opts.transport !== void 0;
1522
+ const hasUrl = opts.url !== void 0;
1523
+ if (hasTransport === hasUrl) {
1524
+ throw new Iso21423Error('Iso21423Client.connect requires exactly one of "transport" or "url"');
1525
+ }
1526
+ const transport = opts.transport ?? createMqttTransport(opts.url, { ...opts.security });
1527
+ return new _Iso21423Client(transport, opts);
1528
+ }
1529
+ // ---- registration -------------------------------------------------------
1530
+ /**
1531
+ * Registers this process's own entity: opens the session (arming the B.4 Last Will) if it
1532
+ * isn't open yet, and publishes the resulting identity. Must be the first operation on the
1533
+ * client (P-4) — if a session is already open under a different entity, throws rather than
1534
+ * silently registering under the wrong identity/will.
1535
+ */
1536
+ async registerSelfEntity(reg) {
1537
+ const ref = { entityType: reg.entityType, entityUuid: reg.entityUuid };
1538
+ const session = await this.ensureSession(ref);
1539
+ if (session.entity.entityType !== ref.entityType || session.entity.entityUuid !== ref.entityUuid) {
1540
+ throw new Iso21423Error(
1541
+ "register the self entity before any other operation, so the B.4 Last Will can be armed at connect time (P-4)"
1542
+ );
1543
+ }
1544
+ const sequence = await this.openSequence(reg.entityUuid);
1545
+ const { ctx, bindSelf } = this.contextFor(ref, sequence);
1546
+ const handle = new EntityHandle(ctx, "self", reg);
1547
+ bindSelf(handle);
1548
+ await handle.publishIdentity(handle.identity());
1549
+ if (this.security?.selfCheck) await this.runSelfCheck(handle);
1550
+ this.selfEntities.set(reg.entityUuid, handle);
1551
+ return handle;
1552
+ }
1553
+ /**
1554
+ * Registers an entity managed on behalf of `managerUuid` (an already-registered self entity,
1555
+ * per B.5.2.4): publishes the managed entity's identity with `managedBy` set, and updates the
1556
+ * manager's own retained identity to include it in `manages`.
1557
+ */
1558
+ async registerManagedEntity(managerUuid, reg) {
1559
+ const manager = this.selfEntities.get(managerUuid);
1560
+ if (!manager) {
1561
+ throw new Iso21423Error(
1562
+ `registerManagedEntity: "${managerUuid}" is not a registered self entity`
1563
+ );
1564
+ }
1565
+ const entityType = reg.entityType ?? "IMR";
1566
+ const ref = { entityType, entityUuid: reg.entityUuid };
1567
+ const sequence = await this.openSequence(reg.entityUuid);
1568
+ const { ctx, bindSelf } = this.contextFor(ref, sequence);
1569
+ const handle = new EntityHandle(ctx, "managed", { ...reg, entityType });
1570
+ bindSelf(handle);
1571
+ const identity = handle.identity();
1572
+ identity.capabilities.managedBy = managerUuid;
1573
+ await handle.publishIdentity(identity);
1574
+ const managerIdentity = manager.identity();
1575
+ const manages = [...managerIdentity.capabilities.manages ?? [], reg.entityUuid];
1576
+ await manager.updateIdentity({ capabilities: { ...managerIdentity.capabilities, manages } });
1577
+ const list = this.managedEntities.get(managerUuid) ?? [];
1578
+ list.push(handle);
1579
+ this.managedEntities.set(managerUuid, list);
1580
+ return handle;
1581
+ }
1582
+ listManagedEntities(managerUuid) {
1583
+ return [...this.managedEntities.get(managerUuid) ?? []];
1584
+ }
1585
+ /** @internal — FleetGateway.registerImr rollback (ND-15 self-check failure): drops a managed
1586
+ * entity's handle so listManagedEntities()/health() stop reporting it. */
1587
+ removeManagedEntity(managerUuid, entityUuid) {
1588
+ const list = this.managedEntities.get(managerUuid);
1589
+ if (!list) return;
1590
+ this.managedEntities.set(managerUuid, list.filter((h) => h.entityUuid !== entityUuid));
1591
+ }
1592
+ /** Set the client-wide default execution policy (P-2), overridable per entity handle. */
1593
+ setDefaultExecutionPolicy(policy) {
1594
+ this.defaultExecutionPolicy = policy;
1595
+ }
1596
+ // ---- observation --------------------------------------------------------
1597
+ /**
1598
+ * Deliberately does NOT go through `subscribeResource('identity', ...)`: the shared
1599
+ * `EntityCache` already owns the one identity-wildcard subscription (every client needs it,
1600
+ * per decision 3). A second, independent subscribeTopic() to the same filter would make the
1601
+ * fake broker (and a real one) redeliver retained identities twice over — this taps the
1602
+ * cache's own stream instead, replaying what it already knows plus every future update.
1603
+ */
1604
+ async subscribeEntities(filter, handler) {
1605
+ await this.ensureSession();
1606
+ const cache = this.cache;
1607
+ const matches = (e) => filter.matches({ entityType: e.entityType, entityUuid: e.entityUuid });
1608
+ let active = true;
1609
+ for (const entry of cache.entities()) {
1610
+ if (matches(entry)) handler(entry.identity);
1611
+ }
1612
+ const listener = (entry) => {
1613
+ if (!active || !matches(entry)) return;
1614
+ this.counters.received++;
1615
+ handler(entry.identity);
1616
+ };
1617
+ cache.on("entity", listener);
1618
+ const topicFilters = Object.freeze(filter.topicFiltersFor("identity"));
1619
+ const sub = {
1620
+ topicFilters,
1621
+ get active() {
1622
+ return active;
1623
+ },
1624
+ async unsubscribe() {
1625
+ active = false;
1626
+ cache.off("entity", listener);
1627
+ },
1628
+ async [Symbol.asyncDispose]() {
1629
+ await sub.unsubscribe();
1630
+ }
1631
+ };
1632
+ return this.trackSubscription(sub);
1633
+ }
1634
+ /** Subscribes to a raw resource (not identity — see {@link subscribeEntities}) across every entity `filter` selects. */
1635
+ async subscribeResource(kind, filter, handler) {
1636
+ const session = await this.ensureSession();
1637
+ const topicFilters = filter.topicFiltersFor(kind);
1638
+ const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(
1639
+ f,
1640
+ messageKindFor(kind),
1641
+ (msg, meta) => {
1642
+ this.counters.received++;
1643
+ handler({
1644
+ entityType: meta.entityType,
1645
+ entityUuid: meta.entityUuid,
1646
+ kind,
1647
+ topic: meta.topic,
1648
+ message: msg
1649
+ });
1650
+ }
1651
+ )));
1652
+ return this.trackSubscription(composeSubscription(topicFilters, parts));
1653
+ }
1654
+ /** Observes inbound requests matching `filter`, without participating in serving them (no admission/status effects). */
1655
+ async subscribeRequests(filter, handler) {
1656
+ const session = await this.ensureSession();
1657
+ const topicFilters = filter.topicFilters();
1658
+ const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(
1659
+ f,
1660
+ "request",
1661
+ (msg, meta) => {
1662
+ if (!meta.requestUuid) return;
1663
+ this.counters.received++;
1664
+ handler({
1665
+ entityType: meta.entityType,
1666
+ entityUuid: meta.entityUuid,
1667
+ requestUuid: meta.requestUuid,
1668
+ request: msg,
1669
+ topic: meta.topic
1670
+ });
1671
+ }
1672
+ )));
1673
+ return this.trackSubscription(composeSubscription(topicFilters, parts));
1674
+ }
1675
+ /** Observes request status updates matching `filter`, e.g. for a fleet-wide activity dashboard. */
1676
+ async subscribeRequestStatus(filter, handler) {
1677
+ const session = await this.ensureSession();
1678
+ const topicFilters = filter.topicFilters();
1679
+ const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(
1680
+ f,
1681
+ "requestStatus",
1682
+ (msg, meta) => {
1683
+ this.counters.received++;
1684
+ handler({
1685
+ entityType: meta.entityType,
1686
+ entityUuid: meta.entityUuid,
1687
+ kind: "requestStatus",
1688
+ topic: meta.topic,
1689
+ message: msg
1690
+ });
1691
+ }
1692
+ )));
1693
+ return this.trackSubscription(composeSubscription(topicFilters, parts));
1694
+ }
1695
+ /**
1696
+ * Retained-identity-only catalog (D-18). Deliberately await-free: callers get a live handle
1697
+ * immediately, and the graph fills in as retained `identity`/`disconnection` messages arrive
1698
+ * (opening the session — identity-less if none is open yet — happens in the background).
1699
+ */
1700
+ discover() {
1701
+ void this.ensureSession().then(() => this.cache.watchDisconnections()).catch((err) => console.error("[Iso21423Client] discover(): failed to open session", err));
1702
+ return {
1703
+ entities: () => this.cache?.entities() ?? [],
1704
+ get: (uuid) => this.cache?.get(uuid),
1705
+ managedBy: (uuid) => this.cache?.managedBy(uuid) ?? [],
1706
+ on: (event, cb) => {
1707
+ if (this.cache) {
1708
+ this.cache.on(event, cb);
1709
+ } else {
1710
+ this.pendingCatalogListeners.push([event, cb]);
1711
+ }
1712
+ }
1713
+ };
1714
+ }
1715
+ // ---- misc -----------------------------------------------------------------
1716
+ /** Point-in-time snapshot of connection state, registered entities, subscription/traffic counters — see {@link ClientHealth}. */
1717
+ health() {
1718
+ return {
1719
+ connection: this.session?.connectionState ?? "closed",
1720
+ since: this.since ?? /* @__PURE__ */ new Date(0),
1721
+ lastConnectionChange: this.lastConnectionChange ?? this.since ?? /* @__PURE__ */ new Date(0),
1722
+ entities: {
1723
+ self: [...this.selfEntities.keys()],
1724
+ managed: [...this.managedEntities.values()].flat().map((h) => h.entityUuid)
1725
+ },
1726
+ subscriptions: this.subscriptionCount,
1727
+ activeRequests: { sent: this.inFlightRequests.size, serving: this.servingCount() },
1728
+ counters: { ...this.counters }
1729
+ };
1730
+ }
1731
+ on(event, cb) {
1732
+ this.listeners[event].push(cb);
1733
+ }
1734
+ /** Graceful shutdown: the will never fires (MemoryTransport.end() reports ungraceful:false). */
1735
+ async close(opts) {
1736
+ if (this.closed) return;
1737
+ this.closed = true;
1738
+ if (!this.sessionPromise) return;
1739
+ this.failAllInFlight();
1740
+ await Promise.all([...this.trackedSubs].map((s) => s.unsubscribe().catch(() => {
1741
+ })));
1742
+ const session = await this.sessionPromise;
1743
+ const timeoutMs = opts?.timeout ?? 5e3;
1744
+ await Promise.race([
1745
+ session.close(),
1746
+ new Promise((resolve) => {
1747
+ setTimeout(resolve, timeoutMs).unref?.();
1748
+ })
1749
+ ]);
1750
+ }
1751
+ // ---- internals --------------------------------------------------------
1752
+ identitylessRef() {
1753
+ return { entityType: "client", entityUuid: this.sourceId ?? randomUUID2() };
1754
+ }
1755
+ async ensureSession(self) {
1756
+ if (!this.sessionPromise) this.sessionPromise = this.openSession(self);
1757
+ return this.sessionPromise;
1758
+ }
1759
+ async openSession(self) {
1760
+ const armWill = self !== void 0;
1761
+ const entity = self ?? this.identitylessRef();
1762
+ const session = await Iso21423Session.connect({
1763
+ transport: this.transport,
1764
+ entity,
1765
+ credentials: this.security && {
1766
+ username: this.security.username,
1767
+ password: this.security.password
1768
+ },
1769
+ validateOutbound: this.validateOutbound,
1770
+ armWill
1771
+ });
1772
+ if (!armWill) this.diagnostic("will-not-armed");
1773
+ this.session = session;
1774
+ this.since = /* @__PURE__ */ new Date();
1775
+ this.lastConnectionChange = this.since;
1776
+ session.on("connection", (s) => {
1777
+ this.lastConnectionChange = /* @__PURE__ */ new Date();
1778
+ if (s === "offline") this.failAllInFlight();
1779
+ for (const cb of this.listeners.connection) cb(s);
1780
+ });
1781
+ session.on("validation-warning", (w) => {
1782
+ this.counters.validationWarnings++;
1783
+ for (const cb of this.listeners["validation-warning"]) cb(w);
1784
+ });
1785
+ this.cache = new EntityCache(session);
1786
+ await this.cache.start();
1787
+ for (const [event, cb] of this.pendingCatalogListeners) this.cache.on(event, cb);
1788
+ this.pendingCatalogListeners = [];
1789
+ return session;
1790
+ }
1791
+ async openSequence(entityUuid) {
1792
+ const store = this.sequenceStore === null ? void 0 : this.sequenceStore;
1793
+ return SequenceCounter.open(entityUuid, store, () => this.diagnostic("sequence-store-unavailable"));
1794
+ }
1795
+ /**
1796
+ * `bindSelf` must be called with the `EntityHandle` built from the returned `ctx`, right after
1797
+ * construction — `sendCancel` re-enters `EntityHandle.sendRequest` (cancel = a new request,
1798
+ * D-02) and `contextFor` necessarily runs before that `EntityHandle` exists.
1799
+ */
1800
+ contextFor(ref, sequence) {
1801
+ const box = {};
1802
+ const ctx = {
1803
+ session: this.session,
1804
+ ref,
1805
+ sequence,
1806
+ catalog: this.cache,
1807
+ diagnostic: (code, detail) => this.diagnostic(code, detail),
1808
+ countPublish: () => {
1809
+ this.counters.published++;
1810
+ },
1811
+ requestTimeoutMs: this.requestTimeoutMs,
1812
+ sendCancel: async (handle, actionId) => {
1813
+ const destRef = handle.internalDestRef();
1814
+ await box.handle.sendRequest({
1815
+ destination: destRef.entityUuid,
1816
+ destinationType: destRef.entityType,
1817
+ details: [cancelRequest({
1818
+ source: handle.sourceUuid,
1819
+ requestId: handle.sequenceId,
1820
+ ...actionId !== void 0 ? { actionId } : {}
1821
+ })],
1822
+ requireCapability: false
1823
+ });
1824
+ },
1825
+ trackInFlight: (handle) => {
1826
+ this.inFlightRequests.add(handle);
1827
+ const drop = () => {
1828
+ this.inFlightRequests.delete(handle);
1829
+ };
1830
+ handle.completion().then(drop, drop);
1831
+ },
1832
+ getDefaultExecutionPolicy: () => {
1833
+ return this.defaultExecutionPolicy ?? DEFAULT_EXECUTION_POLICY;
1834
+ },
1835
+ getExecutionPolicy: () => {
1836
+ return box.handle.getExecutionPolicy();
1837
+ }
1838
+ };
1839
+ return { ctx, bindSelf: (handle) => {
1840
+ box.handle = handle;
1841
+ } };
1842
+ }
1843
+ failAllInFlight() {
1844
+ for (const handle of [...this.inFlightRequests]) handle.failFast();
1845
+ }
1846
+ /** Identity-echo publish self-check (ND-15): confirms our own retained identity round-trips.
1847
+ * Shares its implementation with FleetGateway's self-check (default ON there, OFF here). */
1848
+ async runSelfCheck(handle) {
1849
+ await publishSelfCheck(this.session, handle.ctx.ref, this.security?.selfCheckTimeoutMs);
1850
+ }
1851
+ diagnostic(code, detail) {
1852
+ if (code === "dispatch-rejected") this.counters.rejections++;
1853
+ const event = { code, detail, at: /* @__PURE__ */ new Date() };
1854
+ for (const cb of this.listeners.diagnostic) cb(event);
1855
+ }
1856
+ /** ND-18: sum of servingCount() across every self and managed handle. */
1857
+ servingCount() {
1858
+ let n = 0;
1859
+ for (const handle of this.selfEntities.values()) n += handle.servingCount();
1860
+ for (const list of this.managedEntities.values()) for (const handle of list) n += handle.servingCount();
1861
+ return n;
1862
+ }
1863
+ /** Wraps a raw {@link Subscription} to maintain `subscriptionCount` and the tracked-subs set that `close()` drains. */
1864
+ trackSubscription(sub) {
1865
+ this.subscriptionCount += sub.topicFilters.length;
1866
+ let counted = true;
1867
+ const wrapped = {
1868
+ topicFilters: sub.topicFilters,
1869
+ get active() {
1870
+ return sub.active;
1871
+ },
1872
+ unsubscribe: async () => {
1873
+ this.trackedSubs.delete(wrapped);
1874
+ await sub.unsubscribe();
1875
+ if (counted) {
1876
+ counted = false;
1877
+ this.subscriptionCount -= sub.topicFilters.length;
1878
+ }
1879
+ },
1880
+ [Symbol.asyncDispose]: async () => {
1881
+ await wrapped.unsubscribe();
1882
+ }
1883
+ };
1884
+ this.trackedSubs.add(wrapped);
1885
+ return wrapped;
1886
+ }
1887
+ };
1888
+
1889
+ export {
1890
+ REQUEST_TRANSITIONS,
1891
+ DETAIL_TRANSITIONS,
1892
+ isTerminalRequestState,
1893
+ RequestLifecycle,
1894
+ DetailLifecycle,
1895
+ RESOURCE_MESSAGE_KIND,
1896
+ messageKindFor,
1897
+ composeSubscription,
1898
+ defaultStateDir,
1899
+ FileSequenceStore,
1900
+ SequenceCounter,
1901
+ toTimestamp,
1902
+ DEFAULT_PRIORITY,
1903
+ policies,
1904
+ DEFAULT_EXECUTION_POLICY,
1905
+ EntityCache,
1906
+ RequestHandle,
1907
+ IncomingRequest,
1908
+ ActionExecutor,
1909
+ resolveCancelRequest,
1910
+ RequestServer,
1911
+ EntityHandle,
1912
+ publishSelfCheck,
1913
+ Iso21423Client
1914
+ };
1915
+ //# sourceMappingURL=chunk-GPNR37CI.js.map