@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 @@
1
+ {"version":3,"sources":["../src/gateway/index.ts","../src/errors.ts","../src/core/client.ts","../src/session/mqttTransport.ts","../src/session/rateGate.ts","../src/topics/resources.ts","../src/types/constants.ts","../src/topics/topics.ts","../src/types/common.ts","../src/schema/validators.ts","../src/schema/iso21423.schema.json","../src/schema/normalize.ts","../src/session/session.ts","../src/core/sequence.ts","../src/core/entityCache.ts","../src/core/entityHandle.ts","../src/core/resources.ts","../src/core/types.ts","../src/requests/stateMachine.ts","../src/core/subscription.ts","../src/core/requestHandle.ts","../src/core/incomingRequest.ts","../src/core/policies.ts","../src/core/executor.ts","../src/core/requestServer.ts","../src/types/actions.ts","../src/core/selfCheck.ts","../src/gateway/janitor.ts","../src/gateway/fleetGateway.ts"],"sourcesContent":["/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './fleetGateway.js';\nexport { publishSelfCheck } from './selfCheck.js';\nexport { RetainedRequestJanitor } from './janitor.js';\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Base class for all errors this SDK throws; `name` is set to the concrete subclass name so it survives serialization. */\nexport class Iso21423Error extends Error {\n constructor(message: string) {\n super(message);\n this.name = new.target.name;\n }\n}\n\n/** Thrown when a payload fails ISO 21423 JSON Schema validation; `errors` holds the raw Ajv error list. */\nexport class ValidationError extends Iso21423Error {\n constructor(message: string, public readonly errors: unknown[]) {\n super(message);\n }\n}\n\n/** Thrown when a request/detail reaches a terminal failure state; `finalStatus` carries the last status received. */\nexport class RequestFailed extends Iso21423Error {\n constructor(message: string, public readonly finalStatus: unknown) {\n super(message);\n }\n}\n\nexport class RequestTimeout extends Iso21423Error {}\nexport class BrokerUnavailable extends Iso21423Error {}\n\n/** Thrown when a broker/ACL rejects a publish or subscribe; `topic` names the topic that was denied. */\nexport class AuthorizationDenied extends Iso21423Error {\n constructor(message: string, public readonly topic: string) {\n super(message);\n }\n}\n\nexport class NotCapableError extends Iso21423Error {}\n/** Thrown by {@link Lifecycle.transition} when the requested state change isn't allowed from the current state. */\nexport class IllegalTransition extends Iso21423Error {}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { MqttTransport, ConnectionState } from '../session/transport.js';\nimport { createMqttTransport } from '../session/mqttTransport.js';\nimport { Iso21423Session, type ValidationWarningEvent } from '../session/session.js';\nimport type { EntityRef } from '../topics/topics.js';\nimport type { Uuid } from '../types/common.js';\nimport type { EntityIdentity } from '../types/identity.js';\nimport type { Request, RequestStatus } from '../types/requests.js';\nimport { Iso21423Error } from '../errors.js';\nimport { SequenceCounter, FileSequenceStore, type SequenceStore } from './sequence.js';\nimport { EntityCache, type EntityCatalog, type EntityCatalogEntry } from './entityCache.js';\nimport { EntityHandle, type EntityContext } from './entityHandle.js';\nimport { RequestHandle } from './requestHandle.js';\nimport { EntityFilter, RequestFilter, RequestStatusFilter } from './filters.js';\nimport { composeSubscription, type Subscription } from './subscription.js';\nimport { messageKindFor, type ResourceKind } from './resources.js';\nimport { cancelRequest } from '../types/actions.js';\nimport type {\n ClientHealth, DiagnosticCode, DiagnosticEvent, EntityRegistration, ExecutionPolicy,\n ManagedEntityRegistration, RequestEvent, ResourceEvent, SecurityOptions,\n} from './types.js';\nimport { DEFAULT_EXECUTION_POLICY } from './policies.js';\nimport { publishSelfCheck } from './selfCheck.js';\n\n// Lazy module-level singleton (brief: \"a shared FileSequenceStore()\") — two clients in one\n// process share the same write queue instead of racing separate ones against the same file.\nlet sharedSequenceStore: FileSequenceStore | undefined;\nfunction defaultSequenceStore(): FileSequenceStore {\n return sharedSequenceStore ??= new FileSequenceStore();\n}\n\n/** Options for {@link Iso21423Client.connect}. */\nexport interface ClientOptions {\n transport?: MqttTransport;\n url?: string;\n security?: SecurityOptions;\n validateOutbound?: boolean;\n sourceId?: Uuid;\n sequenceStore?: SequenceStore | null;\n requestTimeoutMs?: number;\n}\n\ntype ClientEvents = {\n connection: (s: ConnectionState) => void;\n 'validation-warning': (w: ValidationWarningEvent) => void;\n diagnostic: (e: DiagnosticEvent) => void;\n};\n\ntype CatalogListener = Parameters<EntityCatalog['on']>;\n\n/**\n * Entry point for the ISO 21423 SDK (nodejs_api.md §6). Owns exactly one MQTT session,\n * opened lazily (decision 1) so a client can be constructed without picking an identity\n * up front — `registerSelfEntity` is what arms the B.4 Last Will.\n */\nexport class Iso21423Client {\n private readonly transport: MqttTransport;\n private readonly security?: SecurityOptions;\n private readonly validateOutbound?: boolean;\n private readonly sourceId?: Uuid;\n private readonly sequenceStore: SequenceStore | null;\n private readonly requestTimeoutMs: number;\n\n private sessionPromise?: Promise<Iso21423Session>;\n private session?: Iso21423Session;\n private cache?: EntityCache;\n private pendingCatalogListeners: CatalogListener[] = [];\n private defaultExecutionPolicy?: ExecutionPolicy;\n\n private readonly selfEntities = new Map<Uuid, EntityHandle>();\n private readonly managedEntities = new Map<Uuid, EntityHandle[]>();\n private readonly trackedSubs = new Set<Subscription>();\n private readonly inFlightRequests = new Set<RequestHandle>();\n\n private since?: Date;\n private lastConnectionChange?: Date;\n private subscriptionCount = 0;\n private closed = false;\n private readonly counters = { published: 0, received: 0, validationWarnings: 0, rejections: 0 };\n\n private readonly listeners: { [K in keyof ClientEvents]: Array<ClientEvents[K]> } = {\n connection: [], 'validation-warning': [], diagnostic: [],\n };\n\n private constructor(transport: MqttTransport, opts: ClientOptions) {\n this.transport = transport;\n this.security = opts.security;\n this.validateOutbound = opts.validateOutbound;\n this.sourceId = opts.sourceId;\n this.sequenceStore = opts.sequenceStore === null ? null : (opts.sequenceStore ?? defaultSequenceStore());\n this.requestTimeoutMs = opts.requestTimeoutMs ?? 5000;\n }\n\n static async connect(opts: ClientOptions): Promise<Iso21423Client> {\n const hasTransport = opts.transport !== undefined;\n const hasUrl = opts.url !== undefined;\n if (hasTransport === hasUrl) {\n throw new Iso21423Error('Iso21423Client.connect requires exactly one of \"transport\" or \"url\"');\n }\n const transport = opts.transport ?? createMqttTransport(opts.url!, { ...opts.security });\n // Do not open the session here (decision 1) — the first registerSelfEntity/subscribe/discover\n // call picks the entity (or falls back to an identity-less one) and arms the will accordingly.\n return new Iso21423Client(transport, opts);\n }\n\n // ---- registration -------------------------------------------------------\n\n /**\n * Registers this process's own entity: opens the session (arming the B.4 Last Will) if it\n * isn't open yet, and publishes the resulting identity. Must be the first operation on the\n * client (P-4) — if a session is already open under a different entity, throws rather than\n * silently registering under the wrong identity/will.\n */\n async registerSelfEntity(reg: EntityRegistration): Promise<EntityHandle> {\n const ref: EntityRef = { entityType: reg.entityType, entityUuid: reg.entityUuid };\n const session = await this.ensureSession(ref);\n if (session.entity.entityType !== ref.entityType || session.entity.entityUuid !== ref.entityUuid) {\n throw new Iso21423Error(\n 'register the self entity before any other operation, so the B.4 Last Will can be armed ' +\n 'at connect time (P-4)');\n }\n const sequence = await this.openSequence(reg.entityUuid);\n const { ctx, bindSelf } = this.contextFor(ref, sequence);\n const handle = new EntityHandle(ctx, 'self', reg);\n bindSelf(handle);\n await handle.publishIdentity(handle.identity());\n if (this.security?.selfCheck) await this.runSelfCheck(handle);\n this.selfEntities.set(reg.entityUuid, handle);\n return handle;\n }\n\n /**\n * Registers an entity managed on behalf of `managerUuid` (an already-registered self entity,\n * per B.5.2.4): publishes the managed entity's identity with `managedBy` set, and updates the\n * manager's own retained identity to include it in `manages`.\n */\n async registerManagedEntity(managerUuid: Uuid, reg: ManagedEntityRegistration): Promise<EntityHandle> {\n const manager = this.selfEntities.get(managerUuid);\n if (!manager) {\n throw new Iso21423Error(\n `registerManagedEntity: \"${managerUuid}\" is not a registered self entity`);\n }\n const entityType = reg.entityType ?? 'IMR';\n const ref: EntityRef = { entityType, entityUuid: reg.entityUuid };\n const sequence = await this.openSequence(reg.entityUuid);\n const { ctx, bindSelf } = this.contextFor(ref, sequence);\n const handle = new EntityHandle(ctx, 'managed', { ...reg, entityType });\n bindSelf(handle);\n const identity = handle.identity();\n identity.capabilities.managedBy = managerUuid;\n await handle.publishIdentity(identity);\n\n // B.5.2.4 link maintenance: keep the manager's retained identity in sync.\n const managerIdentity = manager.identity();\n const manages = [...(managerIdentity.capabilities.manages ?? []), reg.entityUuid];\n await manager.updateIdentity({ capabilities: { ...managerIdentity.capabilities, manages } });\n\n const list = this.managedEntities.get(managerUuid) ?? [];\n list.push(handle);\n this.managedEntities.set(managerUuid, list);\n return handle;\n }\n\n listManagedEntities(managerUuid: Uuid): EntityHandle[] {\n return [...(this.managedEntities.get(managerUuid) ?? [])];\n }\n\n /** @internal — FleetGateway.registerImr rollback (ND-15 self-check failure): drops a managed\n * entity's handle so listManagedEntities()/health() stop reporting it. */\n removeManagedEntity(managerUuid: Uuid, entityUuid: Uuid): void {\n const list = this.managedEntities.get(managerUuid);\n if (!list) return;\n this.managedEntities.set(managerUuid, list.filter((h) => h.entityUuid !== entityUuid));\n }\n\n /** Set the client-wide default execution policy (P-2), overridable per entity handle. */\n setDefaultExecutionPolicy(policy: ExecutionPolicy): void {\n this.defaultExecutionPolicy = policy;\n }\n\n // ---- observation --------------------------------------------------------\n\n /**\n * Deliberately does NOT go through `subscribeResource('identity', ...)`: the shared\n * `EntityCache` already owns the one identity-wildcard subscription (every client needs it,\n * per decision 3). A second, independent subscribeTopic() to the same filter would make the\n * fake broker (and a real one) redeliver retained identities twice over — this taps the\n * cache's own stream instead, replaying what it already knows plus every future update.\n */\n async subscribeEntities(\n filter: EntityFilter, handler: (identity: EntityIdentity) => void,\n ): Promise<Subscription> {\n await this.ensureSession();\n const cache = this.cache!;\n const matches = (e: EntityCatalogEntry) =>\n filter.matches({ entityType: e.entityType, entityUuid: e.entityUuid });\n\n let active = true;\n for (const entry of cache.entities()) {\n if (matches(entry)) handler(entry.identity);\n }\n const listener = (entry: EntityCatalogEntry): void => {\n if (!active || !matches(entry)) return;\n this.counters.received++;\n handler(entry.identity);\n };\n cache.on('entity', listener);\n\n const topicFilters = Object.freeze(filter.topicFiltersFor('identity'));\n const sub: Subscription = {\n topicFilters,\n get active() { return active; },\n async unsubscribe() {\n active = false;\n cache.off('entity', listener);\n },\n async [Symbol.asyncDispose]() { await sub.unsubscribe(); },\n };\n return this.trackSubscription(sub);\n }\n\n /** Subscribes to a raw resource (not identity — see {@link subscribeEntities}) across every entity `filter` selects. */\n async subscribeResource<T = unknown>(\n kind: ResourceKind, filter: EntityFilter, handler: (ev: ResourceEvent<T>) => void,\n ): Promise<Subscription> {\n const session = await this.ensureSession();\n const topicFilters = filter.topicFiltersFor(kind);\n const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(\n f, messageKindFor(kind),\n (msg, meta) => {\n this.counters.received++;\n handler({\n entityType: meta.entityType, entityUuid: meta.entityUuid,\n kind, topic: meta.topic, message: msg as T,\n });\n },\n )));\n return this.trackSubscription(composeSubscription(topicFilters, parts));\n }\n\n /** Observes inbound requests matching `filter`, without participating in serving them (no admission/status effects). */\n async subscribeRequests(\n filter: RequestFilter, handler: (ev: RequestEvent) => void,\n ): Promise<Subscription> {\n const session = await this.ensureSession();\n const topicFilters = filter.topicFilters();\n const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(\n f, 'request',\n (msg, meta) => {\n if (!meta.requestUuid) return;\n this.counters.received++;\n handler({\n entityType: meta.entityType, entityUuid: meta.entityUuid,\n requestUuid: meta.requestUuid, request: msg as Request, topic: meta.topic,\n });\n },\n )));\n return this.trackSubscription(composeSubscription(topicFilters, parts));\n }\n\n /** Observes request status updates matching `filter`, e.g. for a fleet-wide activity dashboard. */\n async subscribeRequestStatus(\n filter: RequestStatusFilter, handler: (ev: ResourceEvent<RequestStatus>) => void,\n ): Promise<Subscription> {\n const session = await this.ensureSession();\n const topicFilters = filter.topicFilters();\n const parts = await Promise.all(topicFilters.map((f) => session.subscribeTopic(\n f, 'requestStatus',\n (msg, meta) => {\n this.counters.received++;\n handler({\n entityType: meta.entityType, entityUuid: meta.entityUuid,\n kind: 'requestStatus', topic: meta.topic, message: msg as RequestStatus,\n });\n },\n )));\n return this.trackSubscription(composeSubscription(topicFilters, parts));\n }\n\n /**\n * Retained-identity-only catalog (D-18). Deliberately await-free: callers get a live handle\n * immediately, and the graph fills in as retained `identity`/`disconnection` messages arrive\n * (opening the session — identity-less if none is open yet — happens in the background).\n */\n discover(): EntityCatalog {\n // ensureSession() is idempotent — reuses the already-open session if registerSelfEntity ran\n // first, else opens an identity-less one. `this.cache` always exists once it resolves.\n void this.ensureSession().then(() => this.cache!.watchDisconnections())\n // No fitting DiagnosticCode for \"the session itself never opened\" — console.error, same\n // fallback convention as Iso21423Session.emitError with no error listeners.\n .catch((err) => console.error('[Iso21423Client] discover(): failed to open session', err));\n\n return {\n entities: () => this.cache?.entities() ?? [],\n get: (uuid: Uuid): EntityCatalogEntry | undefined => this.cache?.get(uuid),\n managedBy: (uuid: Uuid) => this.cache?.managedBy(uuid) ?? [],\n on: (event, cb) => {\n if (this.cache) {\n this.cache.on(event, cb);\n } else {\n this.pendingCatalogListeners.push([event, cb]);\n }\n },\n };\n }\n\n // ---- misc -----------------------------------------------------------------\n\n /** Point-in-time snapshot of connection state, registered entities, subscription/traffic counters — see {@link ClientHealth}. */\n health(): ClientHealth {\n return {\n connection: this.session?.connectionState ?? 'closed',\n since: this.since ?? new Date(0),\n lastConnectionChange: this.lastConnectionChange ?? this.since ?? new Date(0),\n entities: {\n self: [...this.selfEntities.keys()],\n managed: [...this.managedEntities.values()].flat().map((h) => h.entityUuid),\n },\n subscriptions: this.subscriptionCount,\n activeRequests: { sent: this.inFlightRequests.size, serving: this.servingCount() },\n counters: { ...this.counters },\n };\n }\n\n on<K extends keyof ClientEvents>(event: K, cb: ClientEvents[K]): void {\n this.listeners[event].push(cb);\n }\n\n /** Graceful shutdown: the will never fires (MemoryTransport.end() reports ungraceful:false). */\n async close(opts?: { timeout?: number }): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n if (!this.sessionPromise) return; // never connected: no-op\n this.failAllInFlight();\n await Promise.all([...this.trackedSubs].map((s) => s.unsubscribe().catch(() => {})));\n const session = await this.sessionPromise;\n const timeoutMs = opts?.timeout ?? 5000;\n await Promise.race([\n session.close(),\n new Promise<void>((resolve) => { setTimeout(resolve, timeoutMs).unref?.(); }),\n ]);\n }\n\n // ---- internals --------------------------------------------------------\n\n private identitylessRef(): EntityRef {\n return { entityType: 'client', entityUuid: this.sourceId ?? randomUUID() };\n }\n\n private async ensureSession(self?: EntityRef): Promise<Iso21423Session> {\n if (!this.sessionPromise) this.sessionPromise = this.openSession(self);\n return this.sessionPromise;\n }\n\n private async openSession(self?: EntityRef): Promise<Iso21423Session> {\n const armWill = self !== undefined;\n const entity = self ?? this.identitylessRef();\n const session = await Iso21423Session.connect({\n transport: this.transport,\n entity,\n credentials: this.security && {\n username: this.security.username, password: this.security.password,\n },\n validateOutbound: this.validateOutbound,\n armWill,\n });\n if (!armWill) this.diagnostic('will-not-armed');\n\n this.session = session;\n this.since = new Date();\n this.lastConnectionChange = this.since;\n session.on('connection', (s) => {\n this.lastConnectionChange = new Date();\n // nodejs_api.md §12: an offline broker fails every in-flight request instead of hanging.\n if (s === 'offline') this.failAllInFlight();\n for (const cb of this.listeners.connection) cb(s);\n });\n session.on('validation-warning', (w) => {\n this.counters.validationWarnings++;\n for (const cb of this.listeners['validation-warning']) cb(w);\n });\n\n this.cache = new EntityCache(session);\n await this.cache.start();\n for (const [event, cb] of this.pendingCatalogListeners) this.cache.on(event, cb);\n this.pendingCatalogListeners = [];\n return session;\n }\n\n private async openSequence(entityUuid: Uuid): Promise<SequenceCounter> {\n const store = this.sequenceStore === null ? undefined : this.sequenceStore;\n return SequenceCounter.open(entityUuid, store, () => this.diagnostic('sequence-store-unavailable'));\n }\n\n /**\n * `bindSelf` must be called with the `EntityHandle` built from the returned `ctx`, right after\n * construction — `sendCancel` re-enters `EntityHandle.sendRequest` (cancel = a new request,\n * D-02) and `contextFor` necessarily runs before that `EntityHandle` exists.\n */\n private contextFor(\n ref: EntityRef, sequence: SequenceCounter,\n ): { ctx: EntityContext; bindSelf: (handle: EntityHandle) => void } {\n const box: { handle?: EntityHandle } = {};\n const ctx: EntityContext = {\n session: this.session!,\n ref,\n sequence,\n catalog: this.cache!,\n diagnostic: (code, detail) => this.diagnostic(code, detail),\n countPublish: () => { this.counters.published++; },\n requestTimeoutMs: this.requestTimeoutMs,\n sendCancel: async (handle, actionId) => {\n const destRef = handle.internalDestRef();\n await box.handle!.sendRequest({\n destination: destRef.entityUuid,\n destinationType: destRef.entityType,\n details: [cancelRequest({\n source: handle.sourceUuid, requestId: handle.sequenceId,\n ...(actionId !== undefined ? { actionId } : {}),\n })],\n requireCapability: false,\n });\n },\n trackInFlight: (handle) => {\n this.inFlightRequests.add(handle);\n const drop = () => { this.inFlightRequests.delete(handle); };\n handle.completion().then(drop, drop);\n },\n getDefaultExecutionPolicy: () => {\n return this.defaultExecutionPolicy ?? DEFAULT_EXECUTION_POLICY;\n },\n getExecutionPolicy: () => {\n // Resolution order: per-handle override > registration seed > client default > DEFAULT_EXECUTION_POLICY\n return box.handle!.getExecutionPolicy();\n },\n };\n return { ctx, bindSelf: (handle) => { box.handle = handle; } };\n }\n\n private failAllInFlight(): void {\n for (const handle of [...this.inFlightRequests]) handle.failFast();\n }\n\n /** Identity-echo publish self-check (ND-15): confirms our own retained identity round-trips.\n * Shares its implementation with FleetGateway's self-check (default ON there, OFF here). */\n private async runSelfCheck(handle: EntityHandle): Promise<void> {\n await publishSelfCheck(this.session!, handle.ctx.ref, this.security?.selfCheckTimeoutMs);\n }\n\n private diagnostic(code: DiagnosticCode, detail?: unknown): void {\n if (code === 'dispatch-rejected') this.counters.rejections++;\n const event: DiagnosticEvent = { code, detail, at: new Date() };\n for (const cb of this.listeners.diagnostic) cb(event);\n }\n\n /** ND-18: sum of servingCount() across every self and managed handle. */\n private servingCount(): number {\n let n = 0;\n for (const handle of this.selfEntities.values()) n += handle.servingCount();\n for (const list of this.managedEntities.values()) for (const handle of list) n += handle.servingCount();\n return n;\n }\n\n /** Wraps a raw {@link Subscription} to maintain `subscriptionCount` and the tracked-subs set that `close()` drains. */\n private trackSubscription(sub: Subscription): Subscription {\n this.subscriptionCount += sub.topicFilters.length;\n let counted = true;\n const wrapped: Subscription = {\n topicFilters: sub.topicFilters,\n get active() { return sub.active; },\n unsubscribe: async () => {\n this.trackedSubs.delete(wrapped);\n await sub.unsubscribe();\n if (counted) {\n counted = false;\n this.subscriptionCount -= sub.topicFilters.length;\n }\n },\n [Symbol.asyncDispose]: async () => { await wrapped.unsubscribe(); },\n };\n // Track the wrapped subscription (not the raw one) — close() calls unsubscribe() on every\n // tracked entry, and only the wrapper's unsubscribe() does the counter/set bookkeeping.\n this.trackedSubs.add(wrapped);\n return wrapped;\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n ConnectionState, MqttTransport, TransportConnectOptions, TransportMessage,\n} from './transport.js';\nimport { BrokerUnavailable, Iso21423Error } from '../errors.js';\n\n/** The minimal mqtt@5 surface the adapter uses — keeps `mqtt` out of the public types. */\nexport interface MqttClientLike {\n options?: { will?: { topic?: string }; clean?: boolean };\n connected: boolean;\n on(event: string, cb: (...args: never[]) => void): void;\n publishAsync(\n topic: string, payload: string | Buffer, opts: { qos: 0 | 1 | 2; retain: boolean },\n ): Promise<unknown>;\n subscribeAsync(filter: string, opts: { qos: 0 | 1 | 2 }): Promise<Array<{ topic: string; qos: number }>>;\n unsubscribeAsync(filter: string): Promise<unknown>;\n endAsync(force?: boolean): Promise<void>;\n}\n\n/** Options for {@link createMqttTransport}. */\nexport interface MqttTransportOptions {\n username?: string;\n password?: string;\n /** TLS / socket options passed straight through to mqtt.connect (ND-15). */\n tls?: Record<string, unknown>;\n reconnectPeriod?: number;\n}\n\n/** {@link MqttTransport} implementation over mqtt@5, either owning its own client ({@link createMqttTransport}) or wrapping a caller-supplied one ({@link wrapMqttClient}). */\nclass MqttAdapter implements MqttTransport {\n private client?: MqttClientLike;\n private ended = false;\n private wired = false;\n private readonly messageCbs: Array<(m: TransportMessage) => void> = [];\n private readonly stateCbs: Array<(s: ConnectionState) => void> = [];\n\n constructor(\n private readonly acquire: (opts: TransportConnectOptions) => Promise<MqttClientLike>,\n private readonly checkWill: boolean,\n private readonly ownsClient: boolean,\n ) {}\n\n /**\n * Acquires the underlying mqtt client (via the constructor-supplied `acquire`) and wires\n * message/connection-state listeners exactly once per adapter instance, so repeated `connect()`\n * calls (e.g. reconnect flows) don't accumulate duplicate listeners. For a caller-constructed\n * client whose will doesn't match `opts.will`, throws (P-4) rather than silently diverging.\n */\n async connect(opts: TransportConnectOptions): Promise<void> {\n const client = await this.acquire(opts);\n if (this.checkWill && opts.will && client.options?.will?.topic !== opts.will.topic) {\n throw new Iso21423Error(\n `caller-constructed mqtt client must be created with will { topic: \"${opts.will.topic}\", ` +\n `payload: '${opts.will.payload}', qos: ${opts.will.qos}, retain: ${opts.will.retain} } (P-4)`,\n );\n }\n\n // Wire message/state listeners only once per adapter\n if (!this.wired) {\n this.wired = true;\n client.on('message', ((topic: string, payload: Buffer, packet: { qos?: 0 | 1 | 2; retain?: boolean }) => {\n const msg: TransportMessage = {\n topic, payload, qos: packet?.qos ?? 0, retain: packet?.retain ?? false,\n };\n for (const cb of this.messageCbs) cb(msg);\n }) as never);\n client.on('reconnect', (() => this.emitState('reconnecting')) as never);\n client.on('offline', (() => this.emitState('offline')) as never);\n client.on('close', (() => this.emitState('closed')) as never);\n // Persistent 'connect' listener: mqtt.js re-emits 'connect' after every auto-reconnect, not\n // just the initial handshake. This is the ONLY place that emits 'connected' — the initial\n // connect's own onConnect (below) fires after this one (registered later, same event) and\n // only settles the promise/records `this.client`, so each 'connect' event still produces\n // exactly one 'connected' state, initial or reconnect alike.\n client.on('connect', (() => this.emitState('connected')) as never);\n }\n\n if (client.connected) {\n // Already connected (e.g. a caller-constructed client via wrapMqttClient): no 'connect'\n // event will fire for this state, so emit it directly — the persistent listener above only\n // covers events, not the already-there case.\n this.client = client;\n this.emitState('connected');\n return;\n }\n\n // Local settled flag ensures onConnect/onError fires at most once per promise\n let settled = false;\n const resolveReject = { resolve: null as unknown as (v: void) => void, reject: null as unknown as (r: unknown) => void };\n\n const onConnect = (() => {\n if (settled) return;\n settled = true;\n // 'connected' itself is emitted by the persistent listener registered above (same event) —\n // this only needs to record the live client and settle the connect() promise.\n this.client = client;\n resolveReject.resolve();\n }) as (...args: never[]) => void;\n\n const onError = ((err: Error) => {\n if (settled) return;\n settled = true;\n // Clean up owned clients (createMqttTransport path)\n if (this.ownsClient) {\n client.endAsync(true).catch(() => {}); // fire-and-forget\n }\n resolveReject.reject(new BrokerUnavailable(`mqtt connect failed: ${err.message}`));\n }) as (...args: never[]) => void;\n\n try {\n await new Promise<void>((resolve, reject) => {\n resolveReject.resolve = resolve;\n resolveReject.reject = reject;\n client.on('connect', onConnect);\n client.on('error', onError);\n });\n } finally {\n // Clean up settled listeners to prevent accumulation on retry\n try {\n const clientWithRemoval = client as { off?: (ev: string, cb: unknown) => void; removeListener?: (ev: string, cb: unknown) => void };\n (clientWithRemoval.off ?? clientWithRemoval.removeListener)?.('connect', onConnect);\n (clientWithRemoval.off ?? clientWithRemoval.removeListener)?.('error', onError);\n } catch {\n // Ignore cleanup errors (client might be disconnected/destroyed)\n }\n }\n }\n\n async publish(\n topic: string, payload: string | Buffer, opts: { qos: 0 | 1 | 2; retain: boolean },\n ): Promise<void> {\n await this.live().publishAsync(topic, payload, opts);\n }\n\n /** Subscribes and reports whether the broker granted it — false if any SUBACK return code was a refusal (>= 0x80, ND-15) or no grants came back. */\n async subscribe(filter: string, opts: { qos: 0 | 1 | 2 }): Promise<{ granted: boolean }> {\n const grants = await this.live().subscribeAsync(filter, opts);\n // MQTT 3.1.1 SUBACK: return code >= 0x80 means the broker refused the filter (ND-15).\n const granted = grants.length > 0 && grants.every((g) => g.qos < 128);\n return { granted };\n }\n\n async unsubscribe(filter: string): Promise<void> {\n await this.live().unsubscribeAsync(filter);\n }\n\n onMessage(cb: (m: TransportMessage) => void): void {\n this.messageCbs.push(cb);\n }\n\n onConnectionState(cb: (s: ConnectionState) => void): void {\n this.stateCbs.push(cb);\n }\n\n async end(): Promise<void> {\n this.ended = true;\n if (this.client) await this.client.endAsync();\n this.emitState('closed');\n }\n\n /** Returns the connected client or throws {@link BrokerUnavailable} if `end()` was called or `connect()` hasn't completed. */\n private live(): MqttClientLike {\n if (this.ended || !this.client) throw new BrokerUnavailable('mqtt transport is not connected');\n return this.client;\n }\n\n private emitState(s: ConnectionState): void {\n for (const cb of this.stateCbs) cb(s);\n }\n}\n\n/** Adapt a caller-constructed mqtt client (D-07). Its will must match the SDK's (P-4). */\nexport function wrapMqttClient(client: MqttClientLike): MqttTransport {\n return new MqttAdapter(async () => client, true, false);\n}\n\n/**\n * Default adapter. `mqtt` is a peer dependency and is imported lazily inside connect(),\n * so importing this module never pulls mqtt into the graph (no top-level await, ND-19).\n */\nexport function createMqttTransport(url: string, opts: MqttTransportOptions = {}): MqttTransport {\n return new MqttAdapter(async (connectOpts) => {\n let mod: { connect: (url: string, o: Record<string, unknown>) => MqttClientLike };\n try {\n mod = (await import('mqtt')) as never;\n } catch (err) {\n throw new BrokerUnavailable(\n `the \"mqtt\" peer dependency is not installed: ${(err as Error).message}`,\n );\n }\n return mod.connect(url, {\n ...opts.tls,\n clientId: connectOpts.clientId,\n clean: connectOpts.cleanSession,\n keepalive: connectOpts.keepalive,\n username: connectOpts.username ?? opts.username,\n password: connectOpts.password ?? opts.password,\n reconnectPeriod: opts.reconnectPeriod,\n will: connectOpts.will,\n });\n }, false, true);\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Iso21423Error } from '../errors.js';\n\n/**\n * Latest-wins rate limiter for streaming telemetry (Table B.1 bounds).\n * Emits immediately when the minimum interval has elapsed; otherwise keeps\n * only the newest value and flushes it when the interval expires.\n */\nexport class RateGate {\n private readonly intervalMs: number;\n private lastEmit = -Infinity;\n private pending?: { value: unknown; emit: (v: never) => void };\n private timer?: ReturnType<typeof setTimeout>;\n\n constructor(maxHz: number) {\n if (!(maxHz > 0) || !Number.isFinite(maxHz)) {\n throw new Iso21423Error(`RateGate requires a finite maxHz > 0, got ${maxHz}`);\n }\n this.intervalMs = 1000 / maxHz;\n }\n\n /** Offers a value for emission; emits now if the interval has elapsed, else schedules a trailing emit and discards any previously-pending value. */\n offer<T>(value: T, emit: (v: T) => void): void {\n const now = Date.now();\n if (now - this.lastEmit >= this.intervalMs) {\n this.lastEmit = now;\n emit(value);\n return;\n }\n this.pending = { value, emit: emit as (v: never) => void };\n if (this.timer === undefined) {\n const wait = this.intervalMs - (now - this.lastEmit);\n this.timer = setTimeout(() => {\n this.timer = undefined;\n const p = this.pending;\n this.pending = undefined;\n if (p) {\n this.lastEmit = Date.now();\n (p.emit as (v: unknown) => void)(p.value);\n }\n }, wait);\n }\n }\n\n /** Cancels any pending trailing emit. The pending value is dropped, not flushed. */\n dispose(): void {\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n this.pending = undefined;\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Iso21423Error } from '../errors.js';\n\n/** Normative publish settings for a resource; `minHz`/`maxHz` bound the allowed publish rate where the spec constrains it. */\nexport interface ResourceConfig { qos: 0 | 1 | 2; retain: boolean; minHz?: number; maxHz?: number }\n\n/** Table B.1 — resources and their normative QoS / retain / rate configuration. */\nexport const RESOURCE_CONFIG: Record<string, ResourceConfig> = {\n identity: { qos: 1, retain: true },\n status: { qos: 1, retain: true },\n batteryStatus: { qos: 0, retain: true },\n footprint: { qos: 1, retain: true },\n odometry: { qos: 0, retain: false, minHz: 0.5, maxHz: 30 },\n localTrajectory: { qos: 0, retain: false, minHz: 1, maxHz: 10 },\n globalPath: { qos: 1, retain: true },\n globalPlan: { qos: 1, retain: true },\n request: { qos: 2, retain: true },\n requestStatus: { qos: 2, retain: true },\n activeRequestsStatus: { qos: 1, retain: true },\n disconnection: { qos: 1, retain: true }, // B.4 LWT parameters\n};\n\nconst STANDARD_RESOURCES: ReadonlySet<string> = new Set(Object.keys(RESOURCE_CONFIG));\n\n/** True for the resources Table B.1 defines; false for deployment-defined extension resources. */\nexport function isStandardResource(name: string): boolean {\n return STANDARD_RESOURCES.has(name);\n}\n\n/**\n * Registers a deployment-defined resource (ISO 21423 leaves the resource catalog open — see the\n * standard's extension clause) so entities can publish it via `EntityHandle.publishExtension` and\n * clients can `subscribeResource` to it. Extension resources carry no schema: subscribers receive\n * the raw payload text, exactly like `footprint`.\n *\n * Process-wide (the resource table is a module singleton): both ends of a deployment must\n * register the same name with the same config. Re-registering with an identical config is a\n * no-op; a different config throws, as does a name that collides with a standard resource.\n */\nexport function registerExtensionResource(name: string, config: ResourceConfig): void {\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(name)) {\n throw new Iso21423Error(`invalid extension resource name \"${name}\"`);\n }\n if (STANDARD_RESOURCES.has(name)) {\n throw new Iso21423Error(`\"${name}\" is a standard ISO 21423 resource and cannot be redefined`);\n }\n const existing = RESOURCE_CONFIG[name];\n if (existing && (existing.qos !== config.qos || existing.retain !== config.retain\n || existing.minHz !== config.minHz || existing.maxHz !== config.maxHz)) {\n throw new Iso21423Error(`extension resource \"${name}\" is already registered with a different config`);\n }\n RESOURCE_CONFIG[name] = { ...config };\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const ROOT_NAMESPACE = '/ISO_21423/v1';\nexport const PROTOCOL_VERSION = '1.0';\n\nexport const ENTITY_TYPES = ['IMR', 'IMRFM'] as const;\nexport type KnownEntityType = (typeof ENTITY_TYPES)[number];\n/** Widened to allow vendor-defined entity types beyond the two the spec names, while still autocompleting the known ones. */\nexport type EntityType = KnownEntityType | (string & {});\n\n/** All operating states the spec defines: stop categories, motion states, and MODE_* (mutually-exclusive mode markers) mixed together. */\nexport const KNOWN_OPERATING_STATES = [\n 'STOP_CATEGORY_0', 'STOP_CATEGORY_1', 'STOP_CATEGORY_2',\n 'PAUSED', 'WAIT_FOR_RESET', 'MAPPING', 'LOST',\n 'WAIT_FOR_ATTACHMENT', 'WAIT_FOR_EVENT', 'BLOCKED', 'ATTACHMENT_ACTIVE',\n 'STOPPED', 'DOCKING', 'SLOWING', 'ACCELERATING',\n 'LEFT_TURN', 'RIGHT_TURN', 'REVERSE', 'FORWARD', 'LINE_FOLLOWING',\n 'CHARGING', 'LOW_BATTERY', 'IDLE', 'PARKED', 'OFFLINE',\n 'READY', 'NOT_READY',\n 'MODE_AUTO', 'MODE_SEMIAUTO', 'MODE_TELEOP', 'MODE_MANUAL', 'MODE_MAINTENANCE',\n] as const;\nexport type KnownOperatingState = (typeof KNOWN_OPERATING_STATES)[number];\nexport type OperatingState = KnownOperatingState | (string & {});\n\n/** Subset of {@link KNOWN_OPERATING_STATES} that are the mutually-exclusive MODE_* markers. */\nexport const OPERATING_MODES = [\n 'MODE_AUTO', 'MODE_SEMIAUTO', 'MODE_TELEOP', 'MODE_MANUAL', 'MODE_MAINTENANCE',\n] as const;\n\n/** LWT state published by the broker on ungraceful disconnect (B.4). */\nexport const LOST_CONNECTION_STATE = 'LOST_CONNECTION';\n\n/** Overall lifecycle states for a whole {@link Request} (its `RECOVERY` state has no per-detail equivalent — see {@link DetailState}). */\nexport const REQUEST_STATES = [\n 'RECEIVED', 'ACCEPTED', 'EXECUTING', 'CANCELED', 'SUCCEEDED', 'ABORTED', 'RECOVERY',\n] as const;\nexport type RequestState = (typeof REQUEST_STATES)[number];\n\n/** Lifecycle states for a single detail/action within a request. */\nexport const DETAIL_STATES = [\n 'RECEIVED', 'ACCEPTED', 'EXECUTING', 'CANCELED', 'SUCCEEDED', 'ABORTED',\n] as const;\nexport type DetailState = (typeof DETAIL_STATES)[number];\n\nexport const KNOWN_REASON_CODES = [\n 'OK', 'GENERAL_FAILURE', 'TIMEOUT', 'VERSION_NOT_SUPPORTED', 'FORMAT_NOT_SUPPORTED',\n 'ACTION_NOT_IMPLEMENTED', 'REJECTED', 'MALFORMED_REQUEST', 'INVALID_IMR_STATE_FOR_ACTION',\n] as const;\nexport type ReasonCode = (typeof KNOWN_REASON_CODES)[number] | (string & {});\n\nexport const BATTERY_HEALTH = [\n 'UNKNOWN', 'HEALTHY', 'OVERHEAT', 'DEAD', 'OVERVOLTAGE', 'FAILURE', 'COLD',\n] as const;\nexport type BatteryHealth = (typeof BATTERY_HEALTH)[number] | (string & {});\n\n/** Charging state as distinct from {@link BatteryHealth} — this is about current/direction of charge flow, not battery condition. */\nexport const CHARGING_STATES = [\n 'UNKNOWN', 'CHARGING', 'DISCHARGING', 'NOT_CHARGING', 'FULL',\n] as const;\nexport type ChargingState = (typeof CHARGING_STATES)[number] | (string & {});\n\nexport const DOCK_ACTIONS = ['CHARGE', 'DUMP', 'FILL', 'LOAD', 'UNLOAD', 'PICK', 'DROP'] as const;\nexport type DockAction = (typeof DOCK_ACTIONS)[number] | (string & {});\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ROOT_NAMESPACE } from '../types/constants.js';\n\n/** Identifies an entity for topic-building purposes: its ISO type (\"IMR\"/\"IMRFM\") and its uuid. */\nexport interface EntityRef { entityType: string; entityUuid: string }\n\n/** Decomposed form of an ISO 21423 topic string, as produced by {@link parseTopic}. */\nexport interface ParsedTopic {\n entityType: string;\n entityUuid: string;\n resource: string;\n requestUuid?: string;\n isRequestStatus: boolean;\n}\n\nexport function topicFor(ref: EntityRef, resource: string): string {\n return `${ROOT_NAMESPACE}/${ref.entityType}/${ref.entityUuid}/${resource}`;\n}\n\nexport function requestTopic(ref: EntityRef, requestUuid: string): string {\n return `${topicFor(ref, 'request')}/${requestUuid}`;\n}\n\nexport function requestStatusTopic(ref: EntityRef, requestUuid: string): string {\n return `${requestTopic(ref, requestUuid)}/status`;\n}\n\nexport function disconnectionTopic(ref: EntityRef): string {\n return topicFor(ref, 'disconnection');\n}\n\n/** MQTT wildcard subscription matching every entity's identity topic, used to build the fleet-wide entity cache. */\nexport function identityWildcard(): string {\n return `${ROOT_NAMESPACE}/+/+/identity`;\n}\n\n/**\n * Splits a concrete topic string into its parts, or returns `null` if it doesn't\n * live under {@link ROOT_NAMESPACE} or has an unrecognized shape (e.g. extra path segments).\n */\nexport function parseTopic(topic: string): ParsedTopic | null {\n if (!topic.startsWith(`${ROOT_NAMESPACE}/`)) return null;\n const rest = topic.slice(ROOT_NAMESPACE.length + 1).split('/');\n const [entityType, entityUuid, resource, ...tail] = rest;\n if (!entityType || !entityUuid || !resource) return null;\n if (resource === 'request' && tail.length >= 1) {\n const [requestUuid, maybeStatus] = tail;\n if (!requestUuid || (maybeStatus !== undefined && maybeStatus !== 'status') || tail.length > 2) return null;\n return { entityType, entityUuid, resource, requestUuid, isRequestStatus: maybeStatus === 'status' };\n }\n if (tail.length > 0) return null;\n return { entityType, entityUuid, resource, isRequestStatus: false };\n}\n\n/** MQTT 3.1.1 topic filter matching (+ single level, # multi level). */\nexport function topicFilterMatches(filter: string, topic: string): boolean {\n const f = filter.split('/');\n const t = topic.split('/');\n for (let i = 0; i < f.length; i++) {\n const seg = f[i];\n if (seg === '#') return true;\n if (i >= t.length) return false;\n if (seg !== '+' && seg !== t[i]) return false;\n }\n return f.length === t.length;\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type Uuid = string;\n/** ISO 8601-1 timestamp string, dot-decimal milliseconds, UTC. */\nexport type IsoTimestamp = string;\n\nexport function nowTimestamp(date: Date = new Date()): IsoTimestamp {\n return date.toISOString();\n}\n\n/** Accepts both dot and comma decimal separators (spec §3.1). */\nexport function parseTimestamp(ts: string): Date {\n return new Date(ts.replace(',', '.'));\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Ajv2020 } from 'ajv/dist/2020.js';\nimport addFormats from 'ajv-formats';\nimport schema from './iso21423.schema.json' with { type: 'json' };\nimport { KNOWN_OPERATING_STATES } from '../types/constants.js';\nimport { ValidationError } from '../errors.js';\nimport { normalizeInbound } from './normalize.js';\n\nexport type MessageKind =\n | 'entityIdentity' | 'entityStatus' | 'batteryStatus' | 'odometry'\n | 'localTrajectory' | 'globalPath' | 'globalPlan'\n | 'request' | 'requestStatus' | 'requestStatusArray';\n\n/** Result of {@link validateMessage}: `value` is the normalized payload (present whether or not it validated). */\nexport interface ValidationResult {\n ok: boolean;\n value?: unknown;\n warnings: string[];\n errors?: unknown[];\n}\n\nconst ajv = new Ajv2020({ allErrors: true, strict: false });\n(addFormats as unknown as (ajv: Ajv2020) => void)(ajv);\najv.addSchema(schema);\n\nconst KNOWN_STATES = new Set<string>(KNOWN_OPERATING_STATES);\n\n/** Appends a warning (mutating `warnings`) for each `entityStatus.states` entry not in {@link KNOWN_OPERATING_STATES} — schema-valid but possibly a deployment-specific extension. */\nfunction collectWarnings(kind: MessageKind, value: unknown, warnings: string[]): void {\n if (kind !== 'entityStatus') return;\n const states = (value as { states?: unknown })?.states;\n if (!Array.isArray(states)) return;\n for (const s of states) {\n if (typeof s === 'string' && !KNOWN_STATES.has(s)) {\n warnings.push(`entityStatus: unknown operating state \"${s}\" (deployment extension?)`);\n }\n }\n}\n\n/** Normalizes then validates a raw wire payload against the ISO 21423 JSON Schema for `kind`. Throws if `kind` has no registered schema. */\nexport function validateMessage(kind: MessageKind, raw: unknown): ValidationResult {\n const { value, warnings } = normalizeInbound(kind, raw);\n const validate = ajv.getSchema(`https://openrobops.org/schemas/iso21423/v1.json#/$defs/${kind}`);\n if (!validate) throw new Error(`No schema for message kind: ${kind}`);\n const ok = validate(value) as boolean;\n collectWarnings(kind, value, warnings);\n return ok\n ? { ok: true, value, warnings }\n : { ok: false, value, warnings, errors: validate.errors ?? [] };\n}\n\n/** Egress guard: throws on non-conformant outbound payloads. */\nexport function assertValid(kind: MessageKind, value: unknown): void {\n const r = validateMessage(kind, value);\n if (!r.ok) {\n throw new ValidationError(`outbound ${kind} message is not ISO 21423 conformant`, r.errors ?? []);\n }\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://openrobops.org/schemas/iso21423/v1.json\",\n \"$defs\": {\n \"uuid\": { \"type\": \"string\", \"pattern\": \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$\" },\n \"timestamp\": { \"type\": \"string\", \"format\": \"date-time\" },\n \"point\": {\n \"type\": \"object\", \"required\": [\"x\", \"y\"],\n \"properties\": { \"x\": { \"type\": \"number\" }, \"y\": { \"type\": \"number\" } }\n },\n \"locationPoint\": {\n \"type\": \"object\", \"required\": [\"ccsId\", \"x\", \"y\", \"z\"],\n \"properties\": {\n \"ccsId\": { \"$ref\": \"#/$defs/uuid\" },\n \"x\": { \"type\": \"number\" }, \"y\": { \"type\": \"number\" }, \"z\": { \"type\": \"number\" }\n }\n },\n \"orientation\": {\n \"type\": \"object\", \"required\": [\"yaw\", \"pitch\", \"roll\"],\n \"properties\": { \"yaw\": { \"type\": \"number\" }, \"pitch\": { \"type\": \"number\" }, \"roll\": { \"type\": \"number\" } }\n },\n \"capabilities\": {\n \"type\": \"object\", \"required\": [\"provides\", \"accepts\"],\n \"properties\": {\n \"provides\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } },\n \"accepts\": {\n \"type\": \"object\", \"required\": [\"requests\"],\n \"properties\": { \"requests\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } } }\n },\n \"manages\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/uuid\" } },\n \"managedBy\": { \"$ref\": \"#/$defs/uuid\" }\n }\n },\n \"softwareVersion\": {\n \"type\": \"object\", \"required\": [\"moduleName\", \"moduleVersion\"],\n \"properties\": { \"moduleName\": { \"type\": \"string\" }, \"moduleVersion\": { \"type\": \"string\" } }\n },\n \"locationPointStamped\": {\n \"type\": \"object\", \"required\": [\"timestamp\", \"locationPoint\"],\n \"properties\": {\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"locationPoint\": { \"$ref\": \"#/$defs/locationPoint\" }\n }\n },\n \"requestDetail\": {\n \"type\": \"object\", \"required\": [\"type\", \"version\"],\n \"properties\": {\n \"type\": { \"type\": \"string\" },\n \"version\": { \"type\": \"string\" },\n \"format\": { \"type\": \"string\" },\n \"blocking\": { \"type\": \"boolean\" },\n \"atomic\": { \"type\": \"boolean\" },\n \"properties\": { \"type\": \"object\" }\n }\n },\n \"requestDetailStatus\": {\n \"type\": \"object\", \"required\": [\"type\", \"version\", \"status\"],\n \"properties\": {\n \"type\": { \"type\": \"string\" },\n \"version\": { \"type\": \"string\" },\n \"blocking\": { \"type\": \"boolean\" },\n \"status\": {\n \"type\": \"object\", \"required\": [\"code\"],\n \"properties\": {\n \"code\": { \"enum\": [\"RECEIVED\", \"ACCEPTED\", \"EXECUTING\", \"CANCELED\", \"SUCCEEDED\", \"ABORTED\"] },\n \"reason\": { \"type\": \"string\" },\n \"message\": { \"type\": \"string\" }\n }\n },\n \"properties\": { \"type\": \"object\" }\n }\n },\n \"entityIdentity\": {\n \"type\": \"object\",\n \"required\": [\"id\", \"timestamp\", \"entityType\", \"manufacturerName\", \"capabilities\", \"details\"],\n \"properties\": {\n \"id\": { \"$ref\": \"#/$defs/uuid\" },\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"entityType\": { \"type\": \"string\" },\n \"manufacturerName\": { \"type\": \"string\" },\n \"iso21423Version\": { \"type\": \"string\" },\n \"capabilities\": { \"$ref\": \"#/$defs/capabilities\" },\n \"details\": { \"type\": \"object\" }\n }\n },\n \"entityStatus\": {\n \"type\": \"object\", \"required\": [\"entityId\", \"timestamp\", \"states\"],\n \"properties\": {\n \"entityId\": { \"$ref\": \"#/$defs/uuid\" },\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"states\": { \"type\": \"array\", \"items\": { \"type\": \"string\", \"pattern\": \"^[A-Z0-9_]+$\" } },\n \"disabledCapabilities\": { \"$ref\": \"#/$defs/capabilities\" }\n }\n },\n \"batteryStatus\": {\n \"type\": \"object\", \"required\": [\"timestamp\", \"batterySoc\"],\n \"properties\": {\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"batterySoc\": { \"type\": \"number\", \"minimum\": 0, \"maximum\": 1 },\n \"batteryHealth\": { \"type\": \"string\" },\n \"batteryTemperature\": { \"type\": \"number\" },\n \"batteryVoltage\": { \"type\": \"number\" },\n \"batteryCurrent\": { \"type\": \"number\" },\n \"batteryChargingState\": { \"type\": \"string\" }\n }\n },\n \"odometry\": {\n \"type\": \"object\", \"required\": [\"timestamp\", \"pose\", \"velocity\"],\n \"properties\": {\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"pose\": {\n \"type\": \"object\", \"required\": [\"locationPoint\", \"orientation\"],\n \"properties\": {\n \"locationPoint\": { \"$ref\": \"#/$defs/locationPoint\" },\n \"orientation\": { \"$ref\": \"#/$defs/orientation\" }\n }\n },\n \"velocity\": {\n \"type\": \"object\", \"required\": [\"linear\", \"angular\"],\n \"properties\": { \"linear\": { \"type\": \"number\" }, \"angular\": { \"type\": \"number\" } }\n }\n }\n },\n \"localTrajectory\": {\n \"type\": \"object\", \"required\": [\"timestamp\", \"localTrajectory\"],\n \"properties\": {\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"localTrajectory\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/locationPointStamped\" } }\n }\n },\n \"globalPath\": {\n \"type\": \"object\", \"required\": [\"timestamp\", \"globalPath\"],\n \"properties\": {\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"globalPath\": {\n \"type\": \"object\", \"required\": [\"degree\", \"controlPoints\", \"knots\"],\n \"properties\": {\n \"degree\": { \"type\": \"integer\", \"minimum\": 1 },\n \"controlPoints\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\", \"required\": [\"locationPoint\"],\n \"properties\": {\n \"locationPoint\": { \"$ref\": \"#/$defs/locationPoint\" },\n \"weight\": { \"type\": \"number\" }\n }\n }\n },\n \"knots\": { \"type\": \"array\", \"items\": { \"type\": \"number\" }, \"minItems\": 4 }\n }\n }\n }\n },\n \"globalPlan\": {\n \"type\": \"object\", \"required\": [\"timestamp\", \"globalPlan\"],\n \"properties\": {\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"globalPlan\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/locationPointStamped\" } }\n }\n },\n \"request\": {\n \"type\": \"object\",\n \"required\": [\"destination\", \"source\", \"sequenceId\", \"timestamp\", \"details\"],\n \"properties\": {\n \"destination\": { \"anyOf\": [{ \"$ref\": \"#/$defs/uuid\" }, { \"const\": \"\" }] },\n \"source\": { \"$ref\": \"#/$defs/uuid\" },\n \"sequenceId\": { \"type\": \"integer\", \"minimum\": 0 },\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"priority\": { \"type\": \"integer\", \"minimum\": 0, \"maximum\": 255 },\n \"atomic\": { \"type\": \"boolean\" },\n \"details\": { \"type\": \"array\", \"minItems\": 1, \"items\": { \"$ref\": \"#/$defs/requestDetail\" } },\n \"recoveries\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/requestDetail\" } }\n }\n },\n \"requestStatus\": {\n \"type\": \"object\",\n \"required\": [\"source\", \"destination\", \"sequenceId\", \"requestSequenceId\", \"timestamp\", \"status\", \"detailStatuses\"],\n \"properties\": {\n \"source\": { \"$ref\": \"#/$defs/uuid\" },\n \"destination\": { \"$ref\": \"#/$defs/uuid\" },\n \"sequenceId\": { \"type\": \"integer\", \"minimum\": 0 },\n \"requestSequenceId\": { \"type\": \"integer\", \"minimum\": 0 },\n \"timestamp\": { \"$ref\": \"#/$defs/timestamp\" },\n \"status\": { \"enum\": [\"RECEIVED\", \"ACCEPTED\", \"EXECUTING\", \"CANCELED\", \"SUCCEEDED\", \"ABORTED\", \"RECOVERY\"] },\n \"detailStatuses\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/requestDetailStatus\" } },\n \"recoveryStatuses\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/requestDetailStatus\" } }\n }\n },\n \"requestStatusArray\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/$defs/requestStatus\" } }\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst TIMESTAMP_KEYS = new Set(['timestamp', 'arrivalTime']);\nconst COMMA_TS = /^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}),(\\d+)(Z|[+-]\\d{2}:?\\d{2})$/;\n\n/** Recursively rewrites comma-decimal timestamps (e.g. \"12:00:00,500Z\") to dot-decimal form, recording a warning per fix. */\nfunction fixTimestamps(value: unknown, warnings: string[], path: string): unknown {\n if (Array.isArray(value)) return value.map((v, i) => fixTimestamps(v, warnings, `${path}[${i}]`));\n if (value === null || typeof value !== 'object') return value;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (TIMESTAMP_KEYS.has(k) && typeof v === 'string' && COMMA_TS.test(v)) {\n out[k] = v.replace(COMMA_TS, '$1.$2$3');\n warnings.push(`${path}.${k}: comma-decimal timestamp normalized to dot form`);\n } else {\n out[k] = fixTimestamps(v, warnings, `${path}.${k}`);\n }\n }\n return out;\n}\n\n/**\n * Best-effort cleanup of inbound wire payloads before schema validation: fixes comma-decimal\n * timestamps and, for `entityStatus`, renames the legacy `id` field to `entityId` (spec §3.1).\n * Never throws; returns the corrected value plus human-readable warnings for anything it touched.\n */\nexport function normalizeInbound(kind: string, value: unknown): { value: unknown; warnings: string[] } {\n const warnings: string[] = [];\n let v = fixTimestamps(value, warnings, kind);\n if (kind === 'entityStatus' && v !== null && typeof v === 'object' && !Array.isArray(v)) {\n const o = v as Record<string, unknown>;\n if (o.entityId === undefined && typeof o.id === 'string') {\n const { id, ...rest } = o;\n v = { ...rest, entityId: id };\n warnings.push('entityStatus: legacy field \"id\" renamed to \"entityId\" (spec §3.1)');\n }\n }\n return { value: v, warnings };\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { MqttTransport, ConnectionState } from './transport.js';\nimport { RateGate } from './rateGate.js';\nimport { RESOURCE_CONFIG } from '../topics/resources.js';\nimport {\n topicFor, disconnectionTopic, parseTopic, topicFilterMatches, type EntityRef,\n} from '../topics/topics.js';\nimport { ROOT_NAMESPACE, LOST_CONNECTION_STATE } from '../types/constants.js';\nimport { nowTimestamp } from '../types/common.js';\nimport { validateMessage, assertValid, type MessageKind } from '../schema/validators.js';\nimport { AuthorizationDenied, Iso21423Error } from '../errors.js';\n\n/** Options for {@link Iso21423Session.connect}. */\nexport interface SessionOptions {\n transport: MqttTransport;\n entity: EntityRef;\n credentials?: { username?: string; password?: string };\n validateOutbound?: boolean;\n /** Arm the B.4 Last Will at connect time. Default true; false for identity-less sessions (R1). */\n armWill?: boolean;\n}\n\n/** Returned by `subscribeTopic` / `subscribeResource`: stop receiving on that filter. */\nexport interface SessionSubscription {\n unsubscribe(): Promise<void>;\n}\n\n/** Topic-derived metadata handed to subscription handlers alongside the parsed payload. */\nexport interface TopicMeta {\n topic: string;\n entityType: string;\n entityUuid: string;\n resource: string;\n requestUuid?: string;\n isRequestStatus: boolean;\n}\n\n/** Emitted on the `'validation-warning'` event when an inbound message fails schema validation or JSON parsing. */\nexport interface ValidationWarningEvent {\n topic: string;\n payload: string;\n errors: unknown[];\n}\n\ntype SessionEvents = {\n connection: (s: ConnectionState) => void;\n 'validation-warning': (w: ValidationWarningEvent) => void;\n error: (err: unknown) => void;\n};\n\ninterface TopicSub {\n filter: string;\n kind: MessageKind | null;\n handler: (msg: unknown, meta: TopicMeta) => void;\n}\n\n/**\n * Owns one MQTT connection for a single entity: topic-scoped subscribe/publish, retained-resource\n * dedup and republish-on-reconnect, streaming-resource rate gating, LWT arming, and inbound schema\n * validation. This is the layer `/core` builds its request/response semantics on top of.\n */\nexport class Iso21423Session {\n private retainedOwned = new Map<string, { payload: string; qos: 0 | 1 | 2 }>();\n private rateGates = new Map<string, RateGate>();\n private topicSubs: TopicSub[] = [];\n private listeners: { [K in keyof SessionEvents]: Array<SessionEvents[K]> } = {\n connection: [], 'validation-warning': [], error: [],\n };\n private wasConnected = false;\n private state: ConnectionState = 'closed';\n\n private constructor(\n private readonly transport: MqttTransport,\n readonly entity: EntityRef,\n private readonly validateOutbound: boolean,\n private readonly armWill: boolean,\n ) {}\n\n /**\n * Connects the transport and, unless `armWill` is false, arms the B.4 Last Will and clears any\n * stale retained LOST_CONNECTION left over from a prior ungraceful disconnect (spec §4).\n */\n static async connect(opts: SessionOptions): Promise<Iso21423Session> {\n const armWill = opts.armWill ?? true;\n const session = new Iso21423Session(opts.transport, opts.entity, opts.validateOutbound ?? true, armWill);\n opts.transport.onMessage((m) => session.dispatch(m.topic, m.payload));\n opts.transport.onConnectionState((s) => session.handleConnectionState(s));\n await opts.transport.connect({\n clientId: `iso21423-${opts.entity.entityType}-${opts.entity.entityUuid}`,\n cleanSession: false,\n keepalive: 60,\n username: opts.credentials?.username,\n password: opts.credentials?.password,\n will: armWill ? {\n topic: disconnectionTopic(opts.entity),\n payload: JSON.stringify({ states: [LOST_CONNECTION_STATE] }),\n qos: 1,\n retain: true,\n } : undefined,\n });\n // Clear stale retained LOST_CONNECTION from a prior crash (spec §4). Skipped when no will was\n // armed: an identity-less session never owns a disconnection topic, so there is nothing stale\n // to clear (R1 — implementer's choice).\n if (armWill) await session.clearRetained(disconnectionTopic(opts.entity));\n return session;\n }\n\n /** Passthrough so `/core` never rebuilds topics itself (Task 3 implementer note). */\n topicFor(ref: EntityRef, resource: string): string {\n return topicFor(ref, resource);\n }\n\n on<K extends keyof SessionEvents>(event: K, cb: SessionEvents[K]): void {\n this.listeners[event].push(cb);\n }\n\n /**\n * Publishes a known resource (looked up in {@link RESOURCE_CONFIG} for its QoS/retain/rate).\n * Retained resources are deduped on-change (a re-publish with identical body is a no-op) and\n * rolled back from the dedup cache if the publish itself fails. Rate-limited (streaming)\n * resources go through a per-topic {@link RateGate} and are fire-and-forget: publish failures\n * there are reported via the `error` event, not thrown.\n */\n async publishResource(ref: EntityRef, resource: string, kind: MessageKind | null, payload: unknown): Promise<void> {\n const config = RESOURCE_CONFIG[resource];\n if (!config) throw new Iso21423Error(`unknown resource \"${resource}\"`);\n if (kind && this.validateOutbound) assertValid(kind, payload);\n const topic = topicFor(ref, resource);\n const body = JSON.stringify(payload);\n\n if (config.retain) {\n if (this.retainedOwned.get(topic)?.payload === body) return; // on-change rule\n this.retainedOwned.set(topic, { payload: body, qos: config.qos });\n try {\n await this.transport.publish(topic, body, { qos: config.qos, retain: true });\n } catch (err) {\n this.retainedOwned.delete(topic);\n throw err;\n }\n return;\n }\n if (config.maxHz !== undefined) {\n let gate = this.rateGates.get(topic);\n if (!gate) {\n gate = new RateGate(config.maxHz);\n this.rateGates.set(topic, gate);\n }\n gate.offer(body, (b) => {\n this.transport.publish(topic, b, { qos: config.qos, retain: false })\n .catch((err) => this.emitError(err));\n });\n return;\n }\n await this.transport.publish(topic, body, { qos: config.qos, retain: false });\n }\n\n /** Last non-wildcard resource segment → Table B.1 QoS, defaulting to QoS 1 when unknown. */\n private qosForFilter(filter: string): 0 | 1 | 2 {\n const parsed = parseTopic(filter);\n if (!parsed) return 1;\n const key = parsed.isRequestStatus ? 'requestStatus' : parsed.resource;\n return RESOURCE_CONFIG[key]?.qos ?? 1;\n }\n\n /**\n * Always issues a broker SUBSCRIBE (a real broker redelivers retained messages on every\n * SUBSCRIBE, so a late second handler must see the current retained value); the broker-side\n * unsubscribe still only fires once the last local listener on the filter leaves (ND-17).\n */\n async subscribeTopic(\n topicFilter: string,\n kind: MessageKind | null,\n handler: (msg: unknown, meta: TopicMeta) => void,\n opts: { qos?: 0 | 1 | 2 } = {},\n ): Promise<SessionSubscription> {\n const qos = opts.qos ?? this.qosForFilter(topicFilter);\n const { granted } = await this.transport.subscribe(topicFilter, { qos });\n if (!granted) {\n throw new AuthorizationDenied(`subscription denied by broker: ${topicFilter}`, topicFilter);\n }\n const sub: TopicSub = { filter: topicFilter, kind, handler };\n this.topicSubs.push(sub);\n return {\n unsubscribe: async () => {\n this.topicSubs = this.topicSubs.filter((s) => s !== sub);\n if (!this.topicSubs.some((s) => s.filter === topicFilter)) {\n await this.transport.unsubscribe(topicFilter);\n }\n },\n };\n }\n\n /** Publish to an exact topic (request / requestStatus topics are not plain resources). */\n async publishTopic(\n topic: string,\n kind: MessageKind | null,\n payload: unknown,\n opts: { qos: 0 | 1 | 2; retain: boolean },\n ): Promise<void> {\n if (kind && this.validateOutbound) assertValid(kind, payload);\n await this.transport.publish(topic, JSON.stringify(payload), opts);\n }\n\n get connectionState(): ConnectionState {\n return this.state;\n }\n\n /**\n * Subscribe to a resource topic with optional validation.\n * When kind is null, handler receives raw payload text without parsing or validation.\n */\n async subscribeResource(\n filter: { entityType?: string; entityUuid?: string },\n resource: string,\n kind: MessageKind | null,\n handler: (msg: unknown, meta: TopicMeta) => void,\n ): Promise<SessionSubscription & { [Symbol.asyncDispose](): Promise<void> }> {\n const config = RESOURCE_CONFIG[resource];\n if (!config) throw new Iso21423Error(`unknown resource \"${resource}\"`);\n const topicFilter = `${ROOT_NAMESPACE}/${filter.entityType ?? '+'}/${filter.entityUuid ?? '+'}/${resource}`;\n const sub = await this.subscribeTopic(topicFilter, kind, handler, { qos: config.qos });\n return { unsubscribe: sub.unsubscribe, [Symbol.asyncDispose]: sub.unsubscribe };\n }\n\n /** For subscribers that opt out of schema routing (kind: null) but still want to surface a\n * malformed payload as the usual 'validation-warning' event (D-13's RequestServer). */\n reportValidationWarning(w: ValidationWarningEvent): void {\n this.emitWarning(w);\n }\n\n async publishRaw(topic: string, payload: string, opts: { qos: 0 | 1 | 2; retain: boolean }): Promise<void> {\n await this.transport.publish(topic, payload, opts);\n }\n\n /** Clears a retained topic by publishing an empty retained payload, and drops it from the owned-retained dedup cache. */\n async clearRetained(topic: string): Promise<void> {\n this.retainedOwned.delete(topic);\n await this.transport.publish(topic, '', { qos: 1, retain: true });\n }\n\n /** Optionally publishes a final status, disposes all rate gates, then ends the transport. */\n async close(finalStates?: string[]): Promise<void> {\n if (finalStates) {\n await this.publishResource(this.entity, 'status', 'entityStatus', {\n entityId: this.entity.entityUuid,\n timestamp: nowTimestamp(),\n states: finalStates,\n });\n }\n for (const gate of this.rateGates.values()) gate.dispose();\n await this.transport.end();\n }\n\n /**\n * Routes an inbound message to every registered {@link TopicSub} whose filter matches the\n * topic. `kind: null` subscribers get the raw text with no parsing; typed subscribers get an\n * empty payload treated as a retained-clear (skipped silently) and malformed/non-conformant\n * payloads reported via `emitWarning` rather than delivered to the handler.\n */\n private dispatch(topic: string, payload: Buffer): void {\n const parsed = parseTopic(topic);\n if (!parsed) return;\n const text = payload.toString();\n const meta: TopicMeta = {\n topic,\n entityType: parsed.entityType,\n entityUuid: parsed.entityUuid,\n resource: parsed.resource,\n requestUuid: parsed.requestUuid,\n isRequestStatus: parsed.isRequestStatus,\n };\n for (const sub of this.topicSubs) {\n if (!topicFilterMatches(sub.filter, topic)) continue;\n if (!sub.kind) {\n sub.handler(text, meta);\n continue;\n }\n // An empty payload on a validated subscription is a retained-clear, not malformed input.\n if (text === '') continue;\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch {\n this.emitWarning({ topic, payload: text, errors: ['invalid JSON'] });\n continue;\n }\n const result = validateMessage(sub.kind, value);\n if (!result.ok) {\n this.emitWarning({ topic, payload: text, errors: result.errors ?? [] });\n continue;\n }\n sub.handler(result.value, meta);\n }\n }\n\n private handleConnectionState(s: ConnectionState): void {\n this.state = s;\n for (const cb of this.listeners.connection) cb(s);\n if (s === 'connected' && this.wasConnected) {\n // Reconnect: republish owned retained resources (broker may have lost them).\n for (const [topic, { payload, qos }] of this.retainedOwned) {\n this.transport.publish(topic, payload, { qos, retain: true })\n .catch((err) => this.emitError(err));\n }\n // The LWT we armed at connect time has now fired (stale): clear it, same as the\n // stale-crash clear at initial connect (spec §4).\n if (this.armWill) {\n this.clearRetained(disconnectionTopic(this.entity)).catch((err) => this.emitError(err));\n }\n }\n if (s === 'connected') this.wasConnected = true;\n }\n\n private emitWarning(w: ValidationWarningEvent): void {\n for (const cb of this.listeners['validation-warning']) cb(w);\n }\n\n private emitError(err: unknown): void {\n const errorListeners = this.listeners.error;\n if (errorListeners.length > 0) {\n for (const cb of errorListeners) cb(err);\n } else {\n console.error('[Iso21423Session] async publish failed:', err);\n }\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport type { Uuid } from '../types/common.js';\n\n/** Pluggable persistence for the per-entity sequenceId seed (ND-09). */\nexport interface SequenceStore {\n load(entityUuid: Uuid): Promise<number | undefined>;\n save(entityUuid: Uuid, value: number): Promise<void>;\n}\n\nexport function defaultStateDir(): string {\n return process.env.ISO21423_STATE_DIR ?? join(homedir(), '.iso21423');\n}\n\n/** Default store: one JSON map per state directory, written atomically. */\nexport class FileSequenceStore implements SequenceStore {\n private readonly file: string;\n // ponytail: in-process serialization only; use a per-file lock if multiple processes share ISO21423_STATE_DIR\n #queue: Promise<void> = Promise.resolve();\n\n constructor(private readonly dir: string = defaultStateDir()) {\n this.file = join(this.dir, 'sequence.json');\n }\n\n private async read(): Promise<Record<string, number>> {\n try {\n return JSON.parse(await readFile(this.file, 'utf8')) as Record<string, number>;\n } catch {\n // ponytail: corrupted/unreadable file resets seeds to empty; acceptable because\n // SequenceCounter.open() re-reserves a fresh block above any ids already retained on the broker.\n return {};\n }\n }\n\n async load(entityUuid: Uuid): Promise<number | undefined> {\n return (await this.read())[entityUuid];\n }\n\n /** Queued so concurrent saves in one process read-modify-write the file one at a time. */\n save(entityUuid: Uuid, value: number): Promise<void> {\n const result = this.#queue.then(() => this.writeOne(entityUuid, value));\n // A failed write must not wedge the queue: later saves still run, only this caller sees the error.\n this.#queue = result.then(() => undefined, () => undefined);\n return result;\n }\n\n private async writeOne(entityUuid: Uuid, value: number): Promise<void> {\n const all = await this.read();\n all[entityUuid] = value;\n await mkdir(this.dir, { recursive: true });\n const tmp = `${this.file}.${process.pid}.tmp`;\n await writeFile(tmp, JSON.stringify(all), 'utf8');\n await rename(tmp, this.file);\n }\n}\n\nconst BLOCK = 1000;\n\n/**\n * Monotonic sequenceId source owned by an EntityHandle (D-15).\n * Reserves BLOCK ids per persisted write, so a crash can waste ids but never reuse them.\n */\nexport class SequenceCounter {\n private constructor(\n private readonly entityUuid: Uuid,\n private readonly store: SequenceStore | undefined,\n private counter: number,\n private reservedThrough: number,\n ) {}\n\n static async open(\n entityUuid: Uuid,\n store?: SequenceStore,\n onFallback?: (err: unknown) => void,\n ): Promise<SequenceCounter> {\n if (!store) return new SequenceCounter(entityUuid, undefined, 0, Number.MAX_SAFE_INTEGER);\n try {\n const seed = (await store.load(entityUuid)) ?? 0;\n await store.save(entityUuid, seed + BLOCK);\n return new SequenceCounter(entityUuid, store, seed, seed + BLOCK);\n } catch (err) {\n // Persistence unavailable: seed from epoch milliseconds so restarts cannot collide\n // with requests still retained on the broker (ND-09).\n onFallback?.(err);\n return new SequenceCounter(entityUuid, undefined, Date.now(), Number.MAX_SAFE_INTEGER);\n }\n }\n\n /** Returns the next sequenceId, persisting a fresh reservation block when the current one is exhausted. */\n async next(): Promise<number> {\n this.counter += 1;\n if (this.counter > this.reservedThrough && this.store) {\n this.reservedThrough = this.counter + BLOCK;\n await this.store.save(this.entityUuid, this.reservedThrough);\n }\n return this.counter;\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Uuid } from '../types/common.js';\nimport type { EntityIdentity } from '../types/identity.js';\nimport type { Iso21423Session, TopicMeta } from '../session/session.js';\nimport { validateMessage } from '../schema/validators.js';\nimport { ROOT_NAMESPACE, LOST_CONNECTION_STATE } from '../types/constants.js';\n\n/** One entity's known-state snapshot in the {@link EntityCache}. */\nexport interface EntityCatalogEntry {\n entityUuid: Uuid;\n entityType: string;\n identity: EntityIdentity;\n manages: readonly Uuid[];\n managedBy?: Uuid;\n lost: boolean;\n firstSeen: Date;\n lastSeen: Date;\n}\n\n/** Public read/observe surface over the discovered-entity catalog. */\nexport interface EntityCatalog {\n entities(): EntityCatalogEntry[];\n get(uuid: Uuid): EntityCatalogEntry | undefined;\n managedBy(uuid: Uuid): EntityCatalogEntry[];\n on(event: 'entity' | 'lost' | 'gone', cb: (e: EntityCatalogEntry) => void): void;\n}\n\n/**\n * Best-effort local catalog built purely from retained `identity` messages (D-18) —\n * never a broker query. Also backs destination-type resolution and capability checks.\n */\nexport class EntityCache implements EntityCatalog {\n private readonly byUuid = new Map<Uuid, EntityCatalogEntry>();\n private readonly listeners: Record<'entity' | 'lost' | 'gone', Array<(e: EntityCatalogEntry) => void>> =\n { entity: [], lost: [], gone: [] };\n private disconnectionSubscribed = false;\n\n constructor(private readonly session: Iso21423Session) {}\n\n /** Subscribed once per client session (decision 3): identities are cheap and always needed. */\n async start(): Promise<void> {\n // kind: null — a zero-byte retained clear must be seen as a removal, not a warning.\n await this.session.subscribeTopic(\n `${ROOT_NAMESPACE}/+/+/identity`, null, (raw, meta) => this.onIdentity(raw, meta),\n { qos: 1 });\n }\n\n /** Disconnection tracking is only wired when someone actually calls discover(). */\n async watchDisconnections(): Promise<void> {\n if (this.disconnectionSubscribed) return;\n this.disconnectionSubscribed = true;\n await this.session.subscribeTopic(\n `${ROOT_NAMESPACE}/+/+/disconnection`, null, (raw, meta) => this.onDisconnection(raw, meta),\n { qos: 1 });\n }\n\n entities(): EntityCatalogEntry[] { return [...this.byUuid.values()]; }\n get(uuid: Uuid): EntityCatalogEntry | undefined { return this.byUuid.get(uuid); }\n managedBy(uuid: Uuid): EntityCatalogEntry[] {\n return this.entities().filter((e) => e.managedBy === uuid);\n }\n\n on(event: 'entity' | 'lost' | 'gone', cb: (e: EntityCatalogEntry) => void): void {\n this.listeners[event].push(cb);\n }\n\n /** Removal path for `on()` — not part of the public `EntityCatalog` interface (D-18 consumers\n * never unsubscribe from discovery), but used internally so per-call listeners don't leak. */\n off(event: 'entity' | 'lost' | 'gone', cb: (e: EntityCatalogEntry) => void): void {\n const arr = this.listeners[event];\n const i = arr.indexOf(cb);\n if (i !== -1) arr.splice(i, 1);\n }\n\n /** Destination entityType resolution for request topics (decision 2). */\n entityTypeOf(uuid: Uuid): string | undefined { return this.byUuid.get(uuid)?.entityType; }\n\n /** Known-accepts lookup for NotCapableError (decision 4); undefined = unknown entity. */\n acceptsOf(uuid: Uuid): string[] | undefined {\n const entry = this.byUuid.get(uuid);\n if (!entry) return undefined;\n return entry.identity.capabilities?.accepts?.requests;\n }\n\n private onIdentity(raw: unknown, meta: TopicMeta): void {\n const text = typeof raw === 'string' ? raw : '';\n if (text.length === 0) {\n const gone = this.byUuid.get(meta.entityUuid);\n if (gone) {\n this.byUuid.delete(meta.entityUuid);\n this.emit('gone', gone);\n }\n return;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return; // third-party noise never breaks the catalog\n }\n const result = validateMessage('entityIdentity', parsed);\n if (!result.ok) return;\n const identity = result.value as EntityIdentity;\n const now = new Date();\n const prev = this.byUuid.get(meta.entityUuid);\n const entry: EntityCatalogEntry = {\n entityUuid: meta.entityUuid,\n entityType: identity.entityType ?? meta.entityType,\n identity,\n manages: identity.capabilities?.manages ?? [],\n managedBy: identity.capabilities?.managedBy,\n // Preserve connectivity status across an identity re-publish (e.g. an owned-retained\n // resend after the transport reconnects, session.ts's handleConnectionState): only a\n // disconnection message (onDisconnection) or a real reconnect-clear should change this.\n lost: prev?.lost ?? false,\n firstSeen: prev?.firstSeen ?? now,\n lastSeen: now,\n };\n this.byUuid.set(entry.entityUuid, entry);\n this.emit('entity', entry);\n }\n\n private onDisconnection(raw: unknown, meta: TopicMeta): void {\n const entry = this.byUuid.get(meta.entityUuid);\n if (!entry) return;\n const text = typeof raw === 'string' ? raw : '';\n const lost = text.length > 0 && text.includes(LOST_CONNECTION_STATE);\n if (lost === entry.lost) return;\n const updated = { ...entry, lost, lastSeen: new Date() };\n this.byUuid.set(entry.entityUuid, updated);\n if (lost) this.emit('lost', updated);\n }\n\n private emit(event: 'entity' | 'lost' | 'gone', e: EntityCatalogEntry): void {\n for (const cb of this.listeners[event]) cb(e);\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { Iso21423Session } from '../session/session.js';\nimport type { EntityRef } from '../topics/topics.js';\nimport { requestStatusTopic, requestTopic } from '../topics/topics.js';\nimport type { Uuid } from '../types/common.js';\nimport type { OperatingState } from '../types/constants.js';\nimport type { BatteryStatus, GlobalPath, GlobalPlan, Odometry } from '../types/telemetry.js';\nimport type { EntityIdentity } from '../types/identity.js';\nimport type { Request, RequestStatus } from '../types/requests.js';\nimport { PROTOCOL_VERSION } from '../types/constants.js';\nimport { Iso21423Error, NotCapableError } from '../errors.js';\nimport { messageKindFor } from './resources.js';\nimport {\n toTimestamp, type EntityRegistration, type LocalTrajectoryUpdate, type RequestCommand,\n type StatusUpdate, type WithOptionalTimestamp, type ExecutionPolicy,\n type ActionHandler,\n} from './types.js';\nimport type { SequenceCounter } from './sequence.js';\nimport type { EntityCache } from './entityCache.js';\nimport type { DiagnosticCode } from './types.js';\nimport { RequestHandle } from './requestHandle.js';\nimport { RequestServer, type DispatchInterceptor, type DispatchTarget } from './requestServer.js';\nimport type { IncomingRequest } from './incomingRequest.js';\nimport type { RequestAcceptanceFilter } from './filters.js';\nimport { composeSubscription, type Subscription } from './subscription.js';\nimport { ActionExecutor } from './executor.js';\n\n/**\n * Internal seam shared by the publication, requester and executor mixins (Tasks 4–7): the shared\n * dependencies (`session`, `sequence`, `catalog`) plus callbacks up into the owning `Iso21423Client`.\n */\nexport interface EntityContext {\n session: Iso21423Session;\n ref: EntityRef;\n sequence: SequenceCounter;\n catalog: EntityCache;\n diagnostic(code: DiagnosticCode, detail?: unknown): void;\n countPublish(): void;\n requestTimeoutMs: number;\n /** Cancel = a new request naming (source, requestId) — D-02, Table C.4. */\n sendCancel(handle: RequestHandle, actionId?: number): Promise<void>;\n /** Registers a sent request so close()/an offline connection can failFast() it and\n * health().activeRequests.sent stays accurate; the client drops it once it settles. */\n trackInFlight(handle: RequestHandle): void;\n /** Get the client's default execution policy. */\n getDefaultExecutionPolicy(): ExecutionPolicy;\n /** Get the resolved execution policy for this entity (per-handle > registration > client default > DEFAULT_EXECUTION_POLICY). */\n getExecutionPolicy(): ExecutionPolicy;\n}\n\nconst RETAINED_RESOURCES = [\n 'identity', 'batteryStatus', 'globalPath', 'globalPlan', 'activeRequestsStatus', 'disconnection',\n] as const;\n\n/**\n * Per-entity facade over a {@link Iso21423Session}: publishes identity/status/telemetry resources,\n * sends outbound requests (as a requester) and, once `onRequest`/`acceptRequests` is called,\n * serves inbound ones (as a `RequestServer` + `ActionExecutor` pair). One handle per entity uuid,\n * whether it's the client's own entity (`ownershipMode: 'self'`) or one it manages on behalf of\n * a fleet manager (`'managed'`).\n */\nexport class EntityHandle {\n #identity: EntityIdentity;\n #states: OperatingState[] = [];\n #requestServer?: RequestServer;\n #executor?: ActionExecutor;\n #executionPolicy?: ExecutionPolicy;\n #registrationPolicy?: ExecutionPolicy;\n\n /** @internal — constructed by Iso21423Client.registerSelfEntity/registerManagedEntity. */\n constructor(\n readonly ctx: EntityContext,\n readonly ownershipMode: 'self' | 'managed',\n registration: EntityRegistration,\n ) {\n this.#identity = {\n id: registration.entityUuid,\n timestamp: toTimestamp(),\n entityType: registration.entityType,\n manufacturerName: registration.manufacturerName,\n iso21423Version: registration.iso21423Version ?? PROTOCOL_VERSION,\n capabilities: {\n provides: registration.capabilities?.provides ?? [],\n accepts: { requests: registration.capabilities?.accepts ?? [] },\n },\n details: registration.details ?? {},\n };\n this.#registrationPolicy = registration.executionPolicy;\n }\n\n get entityUuid(): Uuid { return this.ctx.ref.entityUuid; }\n get entityType(): string { return this.ctx.ref.entityType; }\n /** Last states this handle published — feeds the automatic INVALID_IMR_STATE_FOR_ACTION rule. */\n lastStates(): readonly OperatingState[] { return this.#states; }\n identity(): EntityIdentity { return this.#identity; }\n\n async publishIdentity(identity: EntityIdentity): Promise<void> {\n this.#identity = { ...identity, timestamp: toTimestamp(identity.timestamp) };\n await this.publish('identity', this.#identity);\n }\n\n /** 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. */\n async updateIdentity(partial: Partial<EntityIdentity>): Promise<void> {\n await this.publishIdentity({ ...this.#identity, ...partial, timestamp: toTimestamp() });\n }\n\n /** Set a per-handle execution policy override (P-2). */\n setExecutionPolicy(policy: ExecutionPolicy): void {\n this.#executionPolicy = policy;\n }\n\n /** Get the resolved execution policy (per-handle > registration > client default > DEFAULT_EXECUTION_POLICY). */\n getExecutionPolicy(): ExecutionPolicy {\n return this.#executionPolicy ?? this.#registrationPolicy ?? this.ctx.getDefaultExecutionPolicy();\n }\n\n async publishStatus(update: StatusUpdate): Promise<void> {\n this.#states = [...update.states];\n await this.publish('status', {\n entityId: this.entityUuid,\n timestamp: toTimestamp(update.timestamp),\n states: update.states,\n ...(update.disabledCapabilities ? { disabledCapabilities: update.disabledCapabilities } : {}),\n });\n }\n\n async publishBatteryStatus(update: WithOptionalTimestamp<BatteryStatus>): Promise<void> {\n await this.publish('batteryStatus', { ...update, timestamp: toTimestamp(update.timestamp) });\n }\n\n async publishOdometry(sample: WithOptionalTimestamp<Odometry>): Promise<void> {\n await this.publish('odometry', { ...sample, timestamp: toTimestamp(sample.timestamp) });\n }\n\n async publishLocalTrajectory(sample: LocalTrajectoryUpdate): Promise<void> {\n await this.publish('localTrajectory', {\n timestamp: toTimestamp(sample.timestamp),\n localTrajectory: sample.points,\n });\n }\n\n async publishGlobalPath(snapshot: WithOptionalTimestamp<GlobalPath>): Promise<void> {\n await this.publish('globalPath', { ...snapshot, timestamp: toTimestamp(snapshot.timestamp) });\n }\n\n async publishGlobalPlan(snapshot: WithOptionalTimestamp<GlobalPlan>): Promise<void> {\n await this.publish('globalPlan', { ...snapshot, timestamp: toTimestamp(snapshot.timestamp) });\n }\n\n /**\n * Publishes a deployment-defined resource previously declared with `registerExtensionResource`\n * (throws for an undeclared name). No schema applies: `payload` is JSON-serialized as given, so\n * include your own `timestamp` if the resource needs one.\n */\n async publishExtension(resource: string, payload: unknown): Promise<void> {\n await this.publish(resource, payload);\n }\n\n /**\n * Sends a request to `cmd.destination` (or resolves an empty destination via\n * {@link resolveDestRef}, R3). Unless `requireCapability: false`, checks the destination's\n * known `accepts` capability list first and throws {@link NotCapableError} for any detail type\n * it doesn't advertise — skipped entirely for an unknown (not-yet-discovered) destination.\n * Subscribes to the status topic before publishing the request, so no status can be missed.\n */\n async sendRequest(cmd: RequestCommand): Promise<RequestHandle> {\n const destRef = this.resolveDestRef(cmd);\n\n if (cmd.requireCapability !== false && cmd.destination) {\n const accepts = this.ctx.catalog.acceptsOf(cmd.destination); // undefined = unknown\n const missing = accepts && cmd.details\n .map((d) => d.type)\n .filter((t) => !accepts.includes(t));\n if (missing && missing.length > 0) {\n throw new NotCapableError(\n `entity ${cmd.destination} does not accept: ${missing.join(', ')} ` +\n `(pass requireCapability: false to send anyway)`);\n }\n }\n\n const sequenceId = await this.ctx.sequence.next();\n const requestUuid = cmd.requestUuid ?? randomUUID();\n const request: Request = {\n destination: cmd.destination,\n source: this.entityUuid,\n sequenceId,\n timestamp: toTimestamp(),\n ...(cmd.priority !== undefined ? { priority: cmd.priority } : {}),\n ...(cmd.atomic !== undefined ? { atomic: cmd.atomic } : {}),\n details: cmd.details,\n ...(cmd.recoveries ? { recoveries: cmd.recoveries } : {}),\n };\n\n const handle = new RequestHandle(\n this.ctx, destRef, requestUuid, this.entityUuid, sequenceId, cmd.destination,\n cmd.timeoutMs ?? this.ctx.requestTimeoutMs);\n\n // Subscribe to the status stream BEFORE publishing, so no status can be missed.\n const sub = await this.ctx.session.subscribeTopic(\n requestStatusTopic(destRef, requestUuid), 'requestStatus',\n (msg) => handle.ingest(msg as RequestStatus), { qos: 2 });\n this.ctx.trackInFlight(handle);\n handle.armTimeout(sub);\n\n await this.ctx.session.publishTopic(\n requestTopic(destRef, requestUuid), 'request', request, { qos: 2, retain: true });\n this.ctx.countPublish();\n return handle;\n }\n\n /** Registers a low-level request handler (Task 5); Tasks 6/7 add admission and the executor\n * hand-off on top of the same `RequestServer`. */\n async acceptRequests(\n filter: RequestAcceptanceFilter, handler: (req: IncomingRequest) => void,\n ): Promise<Subscription> {\n const server = this.ensureRequestServer();\n await server.ensureStarted();\n const deregister = server.register(filter, handler);\n const requestFilterTopic = `${this.ctx.session.topicFor(this.ctx.ref, 'request')}/+`;\n return composeSubscription([requestFilterTopic], [{\n unsubscribe: async () => {\n deregister();\n if (server.handlerCount === 0) {\n await server.teardown();\n // Drop the instance too (not just its subscription): a later acceptRequests() then\n // builds a fresh RequestServer, so its `seen`/activeStatuses maps start empty instead\n // of carrying stale state from this handle's previous run.\n if (this.#requestServer === server) this.#requestServer = undefined;\n }\n },\n }]);\n }\n\n /**\n * Registers a per-action handler (Task 7, ND-11.1): the `ActionExecutor` becomes the fallback\n * consumer on this handle's `RequestServer` — low-level `acceptRequests` filters still win when\n * they match, otherwise any request whose details this executor recognizes is driven through\n * the executor's sequencing/atomic/recovery/cancelRequest logic. Registering a second handler\n * for the same `type` without `override: true` throws.\n */\n onRequest<P = Record<string, unknown>>(\n type: string, handler: ActionHandler<P>, opts?: { override?: true },\n ): void {\n if (!this.#executor) {\n this.#executor = new ActionExecutor();\n const server = this.ensureRequestServer();\n server.setExecutor(this.#executor, this);\n void server.ensureStarted()\n .catch((err) => this.ctx.diagnostic('dispatch-rejected', { reason: 'GENERAL_FAILURE', error: err }));\n }\n this.#executor.register(type, handler as ActionHandler, opts);\n }\n\n /**\n * @internal — FleetGateway janitor seam (ND-10): `cb` fires with this handle's request topic\n * whenever its `RequestServer` publishes a terminal status, or drops a duplicate/unroutable\n * retained request. Force-creates and starts the `RequestServer` so the hook is live even\n * before any `onRequest`/`acceptRequests` call.\n */\n async onRequestSettled(cb: (requestTopic: string) => void): Promise<void> {\n const server = this.ensureRequestServer();\n await server.ensureStarted();\n server.setRequestSettledHook(cb);\n }\n\n /**\n * @internal — FleetGateway dispatch seam (ND-12): wires the empty-destination interceptor onto\n * this handle's `RequestServer` (the IMRFM handle, wired once at `FleetGateway.connect()`).\n */\n async setDispatchInterceptor(cb: DispatchInterceptor): Promise<void> {\n const server = this.ensureRequestServer();\n await server.ensureStarted();\n server.setDispatchInterceptor(cb);\n }\n\n /**\n * @internal — FleetGateway cancel-resolution seam (ND-12): wires the managed-handles executor\n * lookup onto this handle's `RequestServer` (the IMRFM handle, wired once at\n * `FleetGateway.connect()`) so a cancelRequest for a dispatched request can find the run in the\n * robot's executor instead of the IMRFM's own.\n */\n async setManagedExecutorsHook(cb: () => Iterable<ActionExecutor>): Promise<void> {\n const server = this.ensureRequestServer();\n await server.ensureStarted();\n server.setManagedExecutorsHook(cb);\n }\n\n /** @internal — ND-12 retarget seam: this handle's executor, if an `onRequest` handler is\n * registered on it; used to hand a dispatched request off to a managed handle. A valid,\n * registered robot with no `onRequest` handler yields `undefined` here too — the dispatch\n * callback rejects it the same as an unknown uuid (there is nothing to run the request). */\n dispatchTarget(): DispatchTarget | undefined {\n return this.#executor ? { executor: this.#executor, entity: this } : undefined;\n }\n\n /** ND-18: requests this handle's RequestServer is currently serving (0 if it never started). */\n servingCount(): number {\n return this.#requestServer?.servingCount ?? 0;\n }\n\n private ensureRequestServer(): RequestServer {\n if (!this.#requestServer) this.#requestServer = new RequestServer(this.ctx);\n return this.#requestServer;\n }\n\n /**\n * Controller ruling R3: an empty `destination` (spec §3.1 \"IMRFM picks the robot\") is not a\n * literal topic segment — resolve the actual target from the identity catalog by\n * `destinationType` (default `'IMRFM'`). Exactly one match is required; the wire `Request`\n * still carries `destination: ''` (only the topic ref is resolved).\n */\n private resolveDestRef(cmd: RequestCommand): EntityRef {\n if (cmd.destination !== '') {\n const destinationType = cmd.destinationType\n ?? this.ctx.catalog.entityTypeOf(cmd.destination)\n ?? 'IMR'; // decision 2\n return { entityType: destinationType, entityUuid: cmd.destination };\n }\n const entityType = cmd.destinationType ?? 'IMRFM';\n const candidates = this.ctx.catalog.entities().filter((e) => e.entityType === entityType);\n if (candidates.length !== 1) {\n throw new Iso21423Error(\n `sendRequest: cannot resolve an empty destination to exactly one \"${entityType}\" ` +\n `entity (found ${candidates.length}) — pass destinationType and ensure exactly one ` +\n `such entity is discoverable`);\n }\n return { entityType, entityUuid: candidates[0]!.entityUuid };\n }\n\n /** Final OFFLINE status stays as the tombstone; every other retained topic is cleared. */\n async unregister(): Promise<void> {\n await this.publishStatus({ states: ['OFFLINE'] });\n for (const resource of RETAINED_RESOURCES) {\n await this.ctx.session.clearRetained(\n this.ctx.session.topicFor(this.ctx.ref, resource));\n }\n }\n\n private async publish(resource: string, payload: unknown): Promise<void> {\n await this.ctx.session.publishResource(\n this.ctx.ref, resource, messageKindFor(resource), payload);\n this.ctx.countPublish();\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { MessageKind } from '../schema/validators.js';\n\nexport type ResourceKind =\n | 'identity' | 'status' | 'batteryStatus' | 'odometry' | 'localTrajectory'\n | 'globalPath' | 'globalPlan' | 'activeRequestsStatus' | 'disconnection'\n | (string & {});\n\n/** Resource name → schema message kind; `null` means \"no schema, raw text\" (ND-04). */\nexport const RESOURCE_MESSAGE_KIND: Record<string, MessageKind | null> = {\n identity: 'entityIdentity',\n status: 'entityStatus',\n batteryStatus: 'batteryStatus',\n odometry: 'odometry',\n localTrajectory: 'localTrajectory',\n globalPath: 'globalPath',\n globalPlan: 'globalPlan',\n request: 'request',\n requestStatus: 'requestStatus',\n activeRequestsStatus: 'requestStatusArray',\n disconnection: null,\n footprint: null,\n};\n\n/** Looks up a resource's schema message kind; unknown resources are treated as \"no schema\" rather than throwing. */\nexport function messageKindFor(resource: string): MessageKind | null {\n return RESOURCE_MESSAGE_KIND[resource] ?? null;\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { IsoTimestamp, Uuid } from '../types/common.js';\nimport type { ConnectionState } from '../session/transport.js';\nimport type { OperatingState, ReasonCode, RequestState, DetailState } from '../types/constants.js';\nimport type { Capabilities, EntityIdentity } from '../types/identity.js';\nimport type { LocationPointStamped } from '../types/telemetry.js';\nimport type { Request, RequestDetail } from '../types/requests.js';\nimport { nowTimestamp } from '../types/common.js';\nimport type { ResourceKind } from './resources.js';\nimport type { ExecutionPolicy } from './policies.js';\n\n/** nodejs_api.md calls the wire enum StatusReason; Plan 1 named it ReasonCode (decision 9). */\nexport type StatusReason = ReasonCode;\n\nexport type WithOptionalTimestamp<T> = Omit<T, 'timestamp'> & { timestamp?: Date | IsoTimestamp };\n\n/** Accept Date or string at API boundaries; always emit dot-decimal ISO 8601 (ND-07). */\nexport function toTimestamp(t?: Date | IsoTimestamp): IsoTimestamp {\n if (typeof t === 'string') return t;\n return nowTimestamp(t ?? new Date());\n}\n\nexport type { ExecutionPolicy };\n\n/** Options for registering an entity's identity via `Iso21423Client.registerSelfEntity`/`registerManagedEntity`. */\nexport interface EntityRegistration {\n entityUuid: Uuid;\n entityType: string;\n manufacturerName: string;\n iso21423Version?: string;\n details?: Record<string, unknown>;\n /** `accepts` are action type names; the SDK wraps them into `{ requests: [...] }` (schema shape). */\n capabilities?: { provides?: string[]; accepts?: string[] };\n executionPolicy?: ExecutionPolicy;\n}\n\nexport type ManagedEntityRegistration = EntityRegistration;\n\n/** Input to publish a new {@link EntityStatus} snapshot. */\nexport interface StatusUpdate {\n states: OperatingState[];\n disabledCapabilities?: Capabilities;\n timestamp?: Date | IsoTimestamp;\n}\n\n/** Wire field is `localTrajectory` (schema); the API takes `points` (example_imr.md §2). */\nexport interface LocalTrajectoryUpdate {\n points: LocationPointStamped[];\n timestamp?: Date | IsoTimestamp;\n}\n\n/** Payload delivered to a resource observer callback: the validated/parsed message plus its origin. */\nexport interface ResourceEvent<T = unknown> {\n entityType: string;\n entityUuid: Uuid;\n kind: ResourceKind;\n topic: string;\n message: T;\n}\n\n/** Payload delivered to a request observer callback. */\nexport interface RequestEvent {\n entityType: string;\n entityUuid: Uuid;\n requestUuid: Uuid;\n request: Request;\n topic: string;\n}\n\nexport interface SecurityOptions {\n username?: string;\n password?: string;\n /** Passed through to the transport (TLS/mTLS material) — ND-15. */\n tls?: Record<string, unknown>;\n /** Identity-echo publish self-check: default off for clients, on for FleetGateway. */\n selfCheck?: boolean;\n selfCheckTimeoutMs?: number;\n}\n\n/** Internal, non-fatal conditions the client surfaces via a diagnostics event rather than throwing or logging directly. */\nexport type DiagnosticCode =\n | 'sequence-store-unavailable' | 'legacy-cancel-normalized' | 'inbound-illegal-transition'\n | 'self-check-failed' | 'janitor-cleared' | 'duplicate-request-ignored'\n | 'dispatch-rejected' | 'will-not-armed';\n\nexport interface DiagnosticEvent { code: DiagnosticCode; detail?: unknown; at: Date }\n\n/** Point-in-time snapshot of client connection/entity/subscription/traffic state. */\nexport interface ClientHealth {\n connection: ConnectionState;\n since: Date;\n lastConnectionChange: Date;\n entities: { self: Uuid[]; managed: Uuid[] };\n subscriptions: number;\n activeRequests: { sent: number; serving: number };\n counters: { published: number; received: number; validationWarnings: number; rejections: number };\n}\n\n/** Requester-side command (Task 4). */\nexport interface RequestCommand {\n destination: Uuid | '';\n /** Destination namespace type; resolved from the identity catalog, else 'IMR' (decision 2). */\n destinationType?: string;\n details: RequestDetail[];\n recoveries?: RequestDetail[];\n priority?: number;\n atomic?: boolean;\n requestUuid?: Uuid;\n /** Local-only RECEIVED deadline (D-14); default from ClientOptions.requestTimeoutMs. */\n timeoutMs?: number;\n /** Set false to skip the discovered-capability check (decision 4). */\n requireCapability?: boolean;\n}\n\n/** Executor-side updates (Tasks 5–7). */\n/** Publishes a new overall status for the whole request. */\nexport interface RequestStatusUpdate { status: RequestState; reason?: StatusReason; message?: string }\n/** Publishes a new status for one detail by its index in the request's `details` array. */\nexport interface RequestDetailStatusUpdate {\n index: number;\n status: DetailState;\n reason?: StatusReason;\n message?: string;\n properties?: Record<string, unknown>;\n}\n/** Marks the request finished; `status` is restricted to the actual terminal states (no `RECOVERY`, which is not itself terminal). */\nexport interface RequestTerminalUpdate {\n status: Extract<RequestState, 'SUCCEEDED' | 'ABORTED' | 'CANCELED'>;\n reason?: StatusReason;\n message?: string;\n}\n\n/** A {@link RequestDetail} with its `properties` narrowed to the action's own payload shape `P`. */\nexport type TypedRequestDetail<P = Record<string, unknown>> =\n Omit<RequestDetail, 'properties'> & { properties: P };\n\n/** Terminal outcome an {@link ActionHandler} returns (via `ctx.succeeded`/`ctx.aborted`) for one action. */\nexport type ActionResult =\n | { outcome: 'succeeded'; properties?: Record<string, unknown> }\n | { outcome: 'aborted'; reason: StatusReason; message?: string };\n\n/** Handed to an {@link ActionHandler}: the executing entity, the request being served, a cancellation signal, and helpers to report progress/finish the action. */\nexport interface ActionContext {\n readonly entity: import('./entityHandle.js').EntityHandle;\n readonly request: Request;\n readonly signal: AbortSignal;\n /** Publishes an EXECUTING detail-status update carrying arbitrary vendor properties, without changing lifecycle state. */\n progress(properties: Record<string, unknown>): void;\n succeeded(properties?: Record<string, unknown>): ActionResult;\n aborted(reason: StatusReason, message?: string): ActionResult;\n}\n\n/** User-supplied implementation of one action type, registered via `EntityHandle.onRequest`. */\nexport type ActionHandler<P = Record<string, unknown>> =\n (action: TypedRequestDetail<P>, ctx: ActionContext) => Promise<ActionResult>;\n\nexport type { EntityIdentity };\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { RequestState, DetailState } from '../types/constants.js';\nimport { IllegalTransition } from '../errors.js';\n\n/** Figure C.3 — request message state transitions. */\nexport const REQUEST_TRANSITIONS: Record<RequestState, readonly RequestState[]> = {\n RECEIVED: [\n 'ACCEPTED',\n 'CANCELED', // NP-2: RECEIVED→CANCELED disputed vs shared interaction model (Figure C.3 final artwork may differ)\n 'ABORTED',\n ],\n ACCEPTED: [\n 'EXECUTING',\n 'CANCELED',\n 'ABORTED', // NP-2: ACCEPTED→ABORTED disputed vs shared interaction model (Figure C.3 final artwork may differ)\n 'RECOVERY', // NP-2: ACCEPTED→RECOVERY disputed vs shared interaction model (Figure C.3 final artwork may differ)\n ],\n EXECUTING: ['SUCCEEDED', 'CANCELED', 'ABORTED', 'RECOVERY'],\n RECOVERY: ['CANCELED', 'ABORTED'], // NP-2: no RECOVERY→SUCCEEDED (disputed vs shared interaction model, Figure C.3 final artwork may differ)\n CANCELED: [],\n SUCCEEDED: [],\n ABORTED: [],\n};\n\n/** Figure C.4 — requestDetail state transitions (no RECOVERY at detail level). */\nexport const DETAIL_TRANSITIONS: Record<DetailState, readonly DetailState[]> = {\n RECEIVED: ['ACCEPTED', 'CANCELED', 'ABORTED'],\n ACCEPTED: ['EXECUTING', 'CANCELED', 'ABORTED'],\n EXECUTING: ['SUCCEEDED', 'CANCELED', 'ABORTED'],\n CANCELED: [],\n SUCCEEDED: [],\n ABORTED: [],\n};\n\nexport function isTerminalRequestState(s: RequestState): boolean {\n return REQUEST_TRANSITIONS[s].length === 0;\n}\n\n/** Generic state machine driven by a transition table; starts at `initial` and rejects any move not listed for the current state. */\nclass Lifecycle<S extends string> {\n #state: S;\n constructor(private readonly table: Record<S, readonly S[]>, initial: S) {\n this.#state = initial;\n }\n get state(): S {\n return this.#state;\n }\n canTransition(to: S): boolean {\n return this.table[this.#state].includes(to);\n }\n /** Moves to `to` if legal; throws {@link IllegalTransition} otherwise. */\n transition(to: S): void {\n if (!this.canTransition(to)) {\n throw new IllegalTransition(`illegal transition ${this.#state} → ${to}`);\n }\n this.#state = to;\n }\n isTerminal(): boolean {\n return this.table[this.#state].length === 0;\n }\n}\n\n/** Tracks a {@link Request}'s overall lifecycle per {@link REQUEST_TRANSITIONS}, starting at RECEIVED. */\nexport class RequestLifecycle extends Lifecycle<RequestState> {\n constructor() { super(REQUEST_TRANSITIONS, 'RECEIVED'); }\n}\n\n/** Tracks a single request detail's lifecycle per {@link DETAIL_TRANSITIONS}, starting at RECEIVED. */\nexport class DetailLifecycle extends Lifecycle<DetailState> {\n constructor() { super(DETAIL_TRANSITIONS, 'RECEIVED'); }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Lifetime token: `unsubscribe()` or `await using` (D-19). */\nexport interface Subscription extends AsyncDisposable {\n unsubscribe(): Promise<void>;\n readonly active: boolean;\n readonly topicFilters: readonly string[];\n}\n\n/** Bundle N session subscriptions (one per compiled MQTT filter) into one token. */\nexport function composeSubscription(\n topicFilters: string[],\n parts: Array<{ unsubscribe(): Promise<void> }>,\n): Subscription {\n let live = true;\n const sub: Subscription = {\n topicFilters: Object.freeze([...topicFilters]),\n get active() { return live; },\n async unsubscribe() {\n if (!live) return; // idempotent\n live = false;\n await Promise.all(parts.map((p) => p.unsubscribe()));\n },\n async [Symbol.asyncDispose]() {\n await sub.unsubscribe();\n },\n };\n return sub;\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Uuid } from '../types/common.js';\nimport type { RequestStatus } from '../types/requests.js';\nimport type { EntityRef } from '../topics/topics.js';\nimport { requestStatusTopic, requestTopic } from '../topics/topics.js';\nimport { isTerminalRequestState } from '../requests/stateMachine.js';\nimport { BrokerUnavailable, RequestFailed, RequestTimeout } from '../errors.js';\nimport { composeSubscription, type Subscription } from './subscription.js';\nimport type { EntityContext } from './entityHandle.js';\n\n/**\n * Requester-side lifecycle for one outbound {@link Request}: subscribes to its status topic,\n * resolves `completion()` on a terminal status (or rejects on timeout/broker loss), and owns the\n * sender-side ND-10 duty of clearing the retained request once it's terminal.\n */\nexport class RequestHandle {\n readonly createdAt = new Date();\n #latest?: RequestStatus;\n #listeners: Array<(s: RequestStatus) => void> = [];\n #settled = false;\n #resolve!: (s: RequestStatus) => void;\n #reject!: (e: Error) => void;\n #completion: Promise<RequestStatus>;\n #timer?: ReturnType<typeof setTimeout>;\n #statusSub?: { unsubscribe(): Promise<void> };\n\n /** @internal */\n constructor(\n private readonly ctx: EntityContext,\n private readonly destRef: EntityRef,\n readonly requestUuid: Uuid,\n readonly sourceUuid: Uuid,\n readonly sequenceId: number,\n readonly destination: Uuid | '',\n private readonly timeoutMs: number,\n ) {\n this.#completion = new Promise<RequestStatus>((resolve, reject) => {\n this.#resolve = resolve;\n this.#reject = reject;\n });\n // Never surfaces as an unhandled rejection if the caller only uses onStatus().\n this.#completion.catch(() => undefined);\n }\n\n /** @internal — called by sendRequest once the status subscription is live. */\n armTimeout(sub: { unsubscribe(): Promise<void> }): void {\n this.#statusSub = sub;\n this.#timer = setTimeout(() => {\n this.settle(new RequestTimeout(\n `no RECEIVED for request ${this.requestUuid} within ${this.timeoutMs} ms`));\n }, this.timeoutMs);\n this.#timer.unref?.();\n }\n\n /** @internal — one inbound requestStatus message. */\n ingest(status: RequestStatus): void {\n // Correlate by requestSequenceId (decision 5), not arrival timing: a retained status from a\n // prior use of this requestUuid (or a foreign one) must never drive this handle.\n if (status.requestSequenceId !== this.sequenceId) return;\n this.#latest = status;\n if (this.#timer) { clearTimeout(this.#timer); this.#timer = undefined; }\n for (const cb of this.#listeners) cb(status);\n if (!isTerminalRequestState(status.status)) return;\n void this.clearRetainedRequest();\n if (status.status === 'SUCCEEDED') this.settle(undefined, status);\n else this.settle(new RequestFailed(`request ${this.requestUuid} ended ${status.status}`, status));\n }\n\n /** @internal — connection lost while in flight (nodejs_api.md §12). */\n failFast(): void {\n this.settle(new BrokerUnavailable(`broker unavailable during request ${this.requestUuid}`));\n }\n\n latestStatus(): RequestStatus | undefined { return this.#latest; }\n\n /** @internal — the resolved topic ref (post R3 empty-destination resolution), for sendCancel. */\n internalDestRef(): EntityRef { return this.destRef; }\n\n /** Registers a callback for every inbound status update on this request (not just the terminal one); returns a token to stop receiving them. */\n onStatus(handler: (s: RequestStatus) => void): Subscription {\n this.#listeners.push(handler);\n return composeSubscription([requestStatusTopic(this.destRef, this.requestUuid)], [{\n unsubscribe: async () => {\n this.#listeners = this.#listeners.filter((h) => h !== handler);\n },\n }]);\n }\n\n /** Resolves with the terminal SUCCEEDED status, or rejects with {@link RequestFailed}/{@link RequestTimeout}/{@link BrokerUnavailable} — never both. */\n completion(): Promise<RequestStatus> { return this.#completion; }\n\n /** Sends a cancelRequest for this request (or one action within it, via `actionId`); a no-op once the request has already settled. */\n async cancel(opts: { actionId?: number } = {}): Promise<void> {\n if (this.#settled) return; // no-op: nothing left to cancel\n await this.ctx.sendCancel(this, opts.actionId);\n }\n\n private settle(error?: Error, status?: RequestStatus): void {\n if (this.#settled) return;\n this.#settled = true;\n if (this.#timer) { clearTimeout(this.#timer); this.#timer = undefined; }\n // Drop the status subscription on every outcome (success, failure, timeout, failFast) —\n // only ingest()'s terminal path used to do this, leaking it on timeout/failFast. The\n // retained request itself is untouched here: on timeout/failFast the true outcome is\n // unknown to us, so ND-10's janitor (Task 8) or the other party owns clearing it.\n // unsubscribe() is idempotent, so a prior clearRetainedRequest() call racing this is fine.\n void this.#statusSub?.unsubscribe().catch(() => {});\n if (error) this.#reject(error);\n else this.#resolve(status!);\n }\n\n /** Sender duty: clear the retained request on a terminal status (ND-10). Never throws — if the\n * broker publish fails, Task 8's janitor is the backstop that eventually clears stale\n * retained requests. */\n private async clearRetainedRequest(): Promise<void> {\n try {\n await this.ctx.session.clearRetained(requestTopic(this.destRef, this.requestUuid));\n } catch {\n // swallow — see comment above\n }\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Uuid } from '../types/common.js';\nimport type { Request, RequestDetail, RequestDetailStatus, RequestStatus } from '../types/requests.js';\nimport type { DetailState, RequestState } from '../types/constants.js';\nimport { DetailLifecycle, RequestLifecycle } from '../requests/stateMachine.js';\nimport { IllegalTransition } from '../errors.js';\nimport { toTimestamp, type RequestDetailStatusUpdate, type RequestStatusUpdate,\n type RequestTerminalUpdate, type StatusReason } from './types.js';\n\n/** What an {@link IncomingRequest} publishes status through; implemented by `RequestServer`. */\nexport interface StatusSink {\n /** Publishes one requestStatus message (QoS 2, retained) and refreshes activeRequestsStatus. */\n publishStatus(req: IncomingRequest, status: RequestStatus): Promise<void>;\n ownerUuid: Uuid;\n nextStatusSequenceId(): Promise<number>;\n}\n\n/**\n * Server-side lifecycle for one received {@link Request}: tracks the overall request state and\n * each detail's state via {@link RequestLifecycle}/{@link DetailLifecycle}, and publishes a\n * requestStatus message on every change. A request-level transition cascades onto any\n * still-in-flight details that legally admit it (see `cascadeDetails`), so callers don't have to\n * individually resolve every detail before completing the request.\n */\nexport class IncomingRequest {\n readonly #lifecycle = new RequestLifecycle();\n readonly #details: DetailLifecycle[];\n readonly #detailStatuses: RequestDetailStatus[];\n #recoveries?: DetailLifecycle[];\n #recoveryStatuses?: RequestDetailStatus[];\n\n /** @internal */\n constructor(\n readonly request: Request,\n readonly requestUuid: Uuid,\n private readonly sink: StatusSink,\n ) {\n this.#details = request.details.map(() => new DetailLifecycle());\n this.#detailStatuses = request.details.map((d) => ({\n type: d.type,\n version: d.version,\n ...(d.blocking !== undefined ? { blocking: d.blocking } : {}),\n status: { code: 'RECEIVED' as DetailState },\n }));\n }\n\n get source(): Uuid { return this.request.source; }\n get sequenceId(): number { return this.request.sequenceId; }\n get state(): RequestState { return this.#lifecycle.state; }\n get isTerminal(): boolean { return this.#lifecycle.isTerminal(); }\n\n /** @internal — D-12: RECEIVED is published by the server before the handler sees this. */\n async publishReceived(): Promise<void> { await this.emit(); }\n\n async accept(): Promise<void> { await this.transitionTo('ACCEPTED'); }\n\n /** Transitions straight to ABORTED with the given reason (e.g. for pre-flight rejections that never reach ACCEPTED). */\n async reject(reason: StatusReason): Promise<void> {\n await this.transitionTo('ABORTED', reason);\n }\n\n async updateStatus(update: RequestStatusUpdate): Promise<void> {\n await this.transitionTo(update.status, update.reason, update.message);\n }\n\n async updateDetailStatus(update: RequestDetailStatusUpdate): Promise<void> {\n const lifecycle = this.#details[update.index];\n const entry = this.#detailStatuses[update.index];\n if (!lifecycle || !entry) {\n throw new IllegalTransition(`no request detail at index ${update.index}`);\n }\n // A cascade (see cascadeDetails below) may already have legally advanced this detail to\n // `update.status` — an explicit call agreeing with that is accepted as a no-op, never\n // re-thrown as illegal; only a genuine mismatch goes through the FSM guard.\n if (lifecycle.state !== update.status) lifecycle.transition(update.status);\n entry.status = {\n code: update.status,\n ...(update.reason ? { reason: update.reason } : {}),\n ...(update.message ? { message: update.message } : {}),\n };\n if (update.properties) entry.properties = { ...entry.properties, ...update.properties };\n await this.emit();\n }\n\n async complete(terminal: RequestTerminalUpdate): Promise<void> {\n await this.transitionTo(terminal.status, terminal.reason, terminal.message);\n }\n\n /** @internal — used by the executor for the RECOVERY phase: transitions the request to\n * RECOVERY and seeds `recoveryStatuses` from the request's declared `recoveries`, mirroring\n * how the constructor seeds `detailStatuses` from `request.details`. */\n async enterRecovery(recoveries: RequestDetail[], reason?: StatusReason): Promise<void> {\n this.#recoveries = recoveries.map(() => new DetailLifecycle());\n this.#recoveryStatuses = recoveries.map((d) => ({\n type: d.type,\n version: d.version,\n ...(d.blocking !== undefined ? { blocking: d.blocking } : {}),\n status: { code: 'RECEIVED' as DetailState },\n }));\n await this.transitionTo('RECOVERY', reason);\n }\n\n /** @internal — used by the executor to report a recovery detail's progress/outcome. Unlike\n * `updateDetailStatus`, recovery entries are never cascaded by a terminal request transition\n * (RECOVERY has no detail-level equivalent — see cascadeDetails), so the executor must call\n * this for every recovery detail as it finishes, not just the non-last ones. */\n async updateRecoveryStatus(update: RequestDetailStatusUpdate): Promise<void> {\n const lifecycle = this.#recoveries?.[update.index];\n const entry = this.#recoveryStatuses?.[update.index];\n if (!lifecycle || !entry) {\n throw new IllegalTransition(`no recovery detail at index ${update.index}`);\n }\n // Recovery lifecycles are never cascaded by the request (see enterRecovery), so — unlike\n // main details, which arrive at EXECUTING already advanced through ACCEPTED by the cascade —\n // the executor's first update (EXECUTING, starting the recovery detail) must step through\n // ACCEPTED itself here.\n if (update.status === 'EXECUTING' && lifecycle.state === 'RECEIVED') lifecycle.transition('ACCEPTED');\n if (lifecycle.state !== update.status) lifecycle.transition(update.status);\n entry.status = {\n code: update.status,\n ...(update.reason ? { reason: update.reason } : {}),\n ...(update.message ? { message: update.message } : {}),\n };\n if (update.properties) entry.properties = { ...entry.properties, ...update.properties };\n await this.emit();\n }\n\n private async transitionTo(\n to: RequestState, reason?: StatusReason, message?: string,\n ): Promise<void> {\n this.#lifecycle.transition(to); // throws IllegalTransition\n this.cascadeDetails(to);\n await this.emit(reason, message);\n }\n\n // ponytail: a request-level transition implies at least that much progress on every detail\n // still in flight — an app that only calls accept()/updateStatus()/complete() and never\n // updateDetailStatus() for a given detail shouldn't leave it stuck at RECEIVED (or, worse,\n // publish a dead request with a still-live detail underneath it). Details already at or past\n // `to`, already terminal, or for which `to` has no detail-level equivalent (RECOVERY) are left\n // untouched; explicit updateDetailStatus() calls after this are then no-ops state-wise. Mirrors\n // onto the wire-visible #detailStatuses entry too (preserving any reason/message already set),\n // not just the internal DetailLifecycle guard.\n private cascadeDetails(to: RequestState): void {\n const target = to as unknown as DetailState;\n this.#details.forEach((lifecycle, i) => {\n if (lifecycle.isTerminal() || lifecycle.state === target) return;\n if (!lifecycle.canTransition(target)) return;\n lifecycle.transition(target);\n const entry = this.#detailStatuses[i]!;\n entry.status = { ...entry.status, code: target };\n });\n }\n\n /**\n * Builds and publishes the current requestStatus snapshot. A `reason`/`message` passed here\n * (from a request-level transition) is attached to the first detail status entry, not stored\n * at the request level — the wire schema carries reason/message per-detail, not on the request.\n */\n private async emit(reason?: StatusReason, message?: string): Promise<void> {\n const status: RequestStatus = {\n source: this.sink.ownerUuid, // decision 5\n destination: this.request.source,\n sequenceId: await this.sink.nextStatusSequenceId(),\n requestSequenceId: this.request.sequenceId,\n timestamp: toTimestamp(),\n status: this.#lifecycle.state,\n detailStatuses: this.#detailStatuses.map((d) => ({ ...d })),\n ...(this.#recoveryStatuses\n ? { recoveryStatuses: this.#recoveryStatuses.map((d) => ({ ...d })) }\n : {}),\n };\n if (reason || message) {\n const first = status.detailStatuses[0];\n if (first) {\n first.status = {\n ...first.status,\n ...(reason ? { reason } : {}),\n ...(message ? { message } : {}),\n };\n }\n }\n await this.sink.publishStatus(this, status);\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Uuid } from '../types/common.js';\nimport type { Request, RequestStatus } from '../types/requests.js';\nimport type { StatusReason } from './types.js';\n\n/** Identifies one in-flight request by its ORIGINAL sender (Uuid) and that sender's own\n * sequenceId — the same (source, sequenceId) pair a cancelRequest names (Table C.4, D-02). Never\n * the serving entity's own uuid: two different senders may coincidentally share a sequenceId, so\n * the sender is what actually disambiguates. */\nexport interface RequestKey { source: Uuid; sequenceId: number }\n\n/** What an {@link ExecutionPolicy} decides to do with a newly-arrived request against the currently-active ones. */\nexport type AdmissionDecision =\n | { action: 'accept' }\n | { action: 'reject'; reason: StatusReason }\n | { action: 'buffer' }\n | { action: 'preempt'; preempt: readonly RequestKey[] };\n\n/** Runtime admission strategy (D-17). Named C.2.2 strategies ship as presets below. */\nexport interface ExecutionPolicy {\n admit(pending: Request, active: readonly RequestStatus[]): AdmissionDecision;\n /** Optional hint: how many buffered requests to hold before displacing the oldest. */\n readonly bufferLimit?: number;\n /** Optional hint: if true, drain buffered requests by priority; else FIFO. */\n readonly drainByPriority?: boolean;\n}\n\n/** Table C.1: 0 = highest … 255 = lowest; an omitted priority is mid-scale. */\nexport const DEFAULT_PRIORITY = 100;\nconst priorityOf = (r: { priority?: number }): number => r.priority ?? DEFAULT_PRIORITY;\n// `s.source` is the SERVING entity's own uuid (constant across every active request on this\n// handle) — the sender that a cancel/preempt must name is `s.destination` (Request.source\n// mirrored back, decision 5).\nconst keyOf = (s: RequestStatus): RequestKey => ({ source: s.destination, sequenceId: s.requestSequenceId });\n\n/** Named C.2.2 execution policy presets. */\nexport const policies = {\n /** Only one active request at a time; any new request while one is active is rejected outright (no buffering). */\n abortNew(): ExecutionPolicy {\n return {\n admit: (_pending, active) =>\n active.length === 0 ? { action: 'accept' } : { action: 'reject', reason: 'REJECTED' },\n };\n },\n\n /** One active + one queued slot; the server aborts the displaced queue entry with REJECTED. */\n queueReplace(): ExecutionPolicy {\n const policy: ExecutionPolicy = {\n admit: (_pending, active) => (active.length === 0 ? { action: 'accept' } : { action: 'buffer' }),\n };\n Object.assign(policy, { bufferLimit: 1 });\n return policy;\n },\n\n /** One active request; unlimited FIFO queueing behind it. */\n queueAfter(): ExecutionPolicy {\n const policy: ExecutionPolicy = {\n admit: (_pending, active) => (active.length === 0 ? { action: 'accept' } : { action: 'buffer' }),\n };\n Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY });\n return policy;\n },\n\n /** Up to `max` concurrently active requests (unbounded by default); beyond that, buffer FIFO. */\n parallel(max = Number.POSITIVE_INFINITY): ExecutionPolicy {\n const policy: ExecutionPolicy = {\n admit: (_pending, active) => (active.length < max ? { action: 'accept' } : { action: 'buffer' }),\n };\n Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY });\n return policy;\n },\n\n /** 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. */\n priority(): ExecutionPolicy {\n const policy: ExecutionPolicy = {\n admit: (pending, active) => {\n if (active.length === 0) return { action: 'accept' };\n const mine = priorityOf(pending);\n const beatsAll = active.every(\n (s) => mine < priorityOf(s as RequestStatus & { priority?: number }));\n return beatsAll\n ? { action: 'preempt', preempt: active.map(keyOf) }\n : { action: 'buffer' };\n },\n };\n Object.assign(policy, { bufferLimit: Number.POSITIVE_INFINITY, drainByPriority: true });\n return policy;\n },\n};\n\n/** Parallel-capable default (D-17); overridable per client (P-2) and per handle. */\nexport const DEFAULT_EXECUTION_POLICY: ExecutionPolicy = policies.parallel();\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Iso21423Error } from '../errors.js';\nimport { PROTOCOL_VERSION } from '../types/constants.js';\nimport type { DetailState } from '../types/constants.js';\nimport type { Request, RequestDetail } from '../types/requests.js';\nimport { IncomingRequest } from './incomingRequest.js';\nimport type { EntityHandle } from './entityHandle.js';\nimport type { RequestKey } from './policies.js';\nimport {\n type ActionContext, type ActionHandler, type ActionResult, type StatusReason,\n type TypedRequestDetail,\n} from './types.js';\n\n/** States that block ordinary actions until cleared (decision 7). */\nconst BLOCKING_STATES = ['STOP_CATEGORY_0', 'STOP_CATEGORY_1', 'STOP_CATEGORY_2', 'WAIT_FOR_RESET'];\n/** Action types exempt from the blocking-state check (decision 7) and from ACTION_NOT_IMPLEMENTED\n * (cancelRequest is resolved by the executor itself, never dispatched to a handler). */\nconst STATE_EXEMPT_TYPES = new Set(['cancelRequest', 'pauseImr', 'resumeImr']);\n\nconst majorOf = (version: string): string => version.split('.')[0] ?? version;\n\n/** Bookkeeping for one in-flight `run()`, keyed by (source, sequenceId) so a later cancelRequest can find it. */\ninterface ActiveRun {\n controller: AbortController;\n /** Set when a cancelRequest arrived while an atomic detail was executing (or otherwise). */\n cancelRequested: boolean;\n}\n\ntype StepOutcome = { trigger: 'success' } | { trigger: 'abort' | 'cancel'; reason?: StatusReason; message?: string };\n\n/** Groups detail indices into sequencing steps: a run of consecutive `blocking: false` details\n * is one concurrent step; every `blocking: true` (default) detail is its own step. */\nfunction groupSteps(details: readonly RequestDetail[]): number[][] {\n const steps: number[][] = [];\n let i = 0;\n while (i < details.length) {\n if (details[i]!.blocking === false) {\n const group: number[] = [];\n while (i < details.length && details[i]!.blocking === false) { group.push(i); i++; }\n steps.push(group);\n } else {\n steps.push([i]);\n i++;\n }\n }\n return steps;\n}\n\n/**\n * The per-action executor (ND-11.1): runs `EntityHandle.onRequest` handlers against admitted\n * requests, driving detail sequencing, atomic protection, cancelRequest resolution and recovery.\n * See task-7-brief.md for the exact behavior list.\n */\nexport class ActionExecutor {\n private readonly handlers = new Map<string, ActionHandler>();\n private readonly runs = new Map<string, ActiveRun>();\n\n /** Registers a handler for `type`; throws if one is already registered unless `override: true`. */\n register(type: string, handler: ActionHandler, opts?: { override?: true }): void {\n if (this.handlers.has(type) && !opts?.override) {\n throw new Iso21423Error(\n `onRequest: a handler for \"${type}\" is already registered — pass { override: true } to replace it`);\n }\n this.handlers.set(type, handler as ActionHandler);\n }\n\n hasHandlers(): boolean { return this.handlers.size > 0; }\n\n private runKey(source: string, sequenceId: number): string { return `${source}:${sequenceId}`; }\n\n /** Fires the AbortController for an admitted request the policy is preempting (Task 7 seam). */\n cancel(key: RequestKey): boolean {\n const run = this.runs.get(this.runKey(key.source, key.sequenceId));\n if (!run) return false;\n run.cancelRequested = true;\n run.controller.abort();\n return true;\n }\n\n /** Entry point called once a request is admitted (RequestServer step 6 fallback). The run stays\n * registered in `this.runs` (so a cancelRequest can still find it) until the request is fully\n * terminal — including through the RECOVERY phase (controller ruling: RECOVERY→CANCELED is\n * legal, so a cancel arriving mid-recovery must still resolve). */\n async run(incoming: IncomingRequest, entity: EntityHandle): Promise<void> {\n const request = incoming.request;\n\n const preflight = this.preflightReject(request, entity);\n if (preflight) {\n await incoming.reject(preflight);\n return;\n }\n\n await incoming.accept();\n await incoming.updateStatus({ status: 'EXECUTING' });\n\n const key = this.runKey(request.source, request.sequenceId);\n const run: ActiveRun = { controller: new AbortController(), cancelRequested: false };\n this.runs.set(key, run);\n try {\n const outcome = await this.runSequence(request.details, request, entity, run, true, false,\n (index, patch) => incoming.updateDetailStatus({ index, ...patch }));\n\n if (outcome.trigger === 'success') {\n await incoming.complete({ status: 'SUCCEEDED' });\n return;\n }\n\n let trigger = outcome.trigger;\n let reason = outcome.reason;\n let message = outcome.message;\n if (request.recoveries && request.recoveries.length > 0) {\n await incoming.enterRecovery(request.recoveries, reason);\n // Controller ruling: recoveries are cleanup FOR the trigger, not a continuation of it —\n // the recovery phase starts with fresh cancel tracking (a new AbortController, and\n // cancelRequested reset) so only a *new* cancelRequest arriving during RECOVERY can stop\n // it early; the cancel/abort that got us into recovery must not immediately truncate it.\n run.controller = new AbortController();\n run.cancelRequested = false;\n const recoveryOutcome = await this.runSequence(\n request.recoveries, request, entity, run, false, true,\n (index, patch) => incoming.updateRecoveryStatus({ index, ...patch }));\n if (recoveryOutcome.trigger !== 'success') {\n // A new cancel during recovery reclassifies the final state to CANCELED even if the\n // original trigger was a plain abort; a recovery detail's own failure does not\n // reclassify a cancel-triggered run back to ABORTED (decision 8 unchanged).\n if (recoveryOutcome.trigger === 'cancel') trigger = 'cancel';\n reason = recoveryOutcome.reason ?? reason;\n message = recoveryOutcome.message ?? message;\n }\n }\n\n const finalStatus = trigger === 'cancel' ? 'CANCELED' : 'ABORTED';\n await incoming.complete({ status: finalStatus, reason, message });\n } finally {\n this.runs.delete(key);\n }\n }\n\n /** Runs one detail array (main details or recoveries) under the shared sequencing rules\n * (item 3), atomic protection (item 4) and outcome mapping (item 5).\n * - `allowSkipLastSuccess` lets the caller rely on the request-level terminal cascade for the\n * very last detail of a clean success run (main details only).\n * - `markRemainingCanceled`: recoveryStatuses is never cascaded by the request's terminal\n * transition (unlike detailStatuses), so when the sequence stops early the caller must ask\n * us to explicitly mark every not-yet-started item CANCELED (main details rely on the\n * cascade instead and pass false here). */\n private async runSequence(\n items: readonly RequestDetail[], request: Request, entity: EntityHandle,\n run: ActiveRun, allowSkipLastSuccess: boolean, markRemainingCanceled: boolean,\n update: (index: number, patch: {\n status: DetailState; reason?: StatusReason; message?: string; properties?: Record<string, unknown>;\n }) => Promise<void>,\n ): Promise<StepOutcome> {\n const steps = groupSteps(items);\n for (let s = 0; s < steps.length; s++) {\n const group = steps[s]!;\n const results = await Promise.all(\n group.map((index) => this.runOneDetail(index, items[index]!, request, entity, run, update)));\n const batchHasAbort = results.some((r) => r.outcome === 'aborted');\n const cancelledNow = run.controller.signal.aborted || run.cancelRequested;\n for (let k = 0; k < group.length; k++) {\n const index = group[k]!;\n const result = results[k]!;\n const isLastOverall = index === items.length - 1;\n if (result.outcome === 'succeeded') {\n const skip = allowSkipLastSuccess && isLastOverall && !batchHasAbort && !cancelledNow;\n if (!skip) {\n await update(index, { status: 'SUCCEEDED', ...(result.properties ? { properties: result.properties } : {}) });\n }\n } else {\n await update(index, { status: 'ABORTED', reason: result.reason, ...(result.message ? { message: result.message } : {}) });\n }\n }\n if (batchHasAbort || cancelledNow) {\n if (markRemainingCanceled) {\n for (const index of steps.slice(s + 1).flat()) {\n await update(index, { status: 'CANCELED' });\n }\n }\n const aborted = results.find((r) => r.outcome === 'aborted');\n return cancelledNow\n ? { trigger: 'cancel', reason: aborted?.reason, message: aborted?.message }\n : { trigger: 'abort', reason: aborted?.reason, message: aborted?.message };\n }\n }\n return { trigger: 'success' };\n }\n\n /**\n * Runs a single detail's handler: publishes an EXECUTING status first, then invokes the\n * registered handler (or produces an ACTION_NOT_IMPLEMENTED result if none exists), catching any\n * thrown error as a GENERAL_FAILURE abort. Waits for any `ctx.progress()` updates issued during\n * the handler call to finish publishing before returning.\n */\n private async runOneDetail(\n index: number, detail: RequestDetail, request: Request, entity: EntityHandle,\n run: ActiveRun,\n update: (index: number, patch: {\n status: DetailState; reason?: StatusReason; message?: string; properties?: Record<string, unknown>;\n }) => Promise<void>,\n ): Promise<ActionResult> {\n const atomic = (detail.atomic ?? false) || (request.atomic ?? false);\n const signal = atomic ? new AbortController().signal : run.controller.signal;\n\n await update(index, { status: 'EXECUTING' });\n\n const pending: Promise<void>[] = [];\n const ctx: ActionContext = {\n entity, request, signal,\n progress: (properties) => { pending.push(update(index, { status: 'EXECUTING', properties })); },\n succeeded: (properties) => (properties !== undefined ? { outcome: 'succeeded', properties } : { outcome: 'succeeded' }),\n aborted: (reason, message) => (message !== undefined ? { outcome: 'aborted', reason, message } : { outcome: 'aborted', reason }),\n };\n\n const typed: TypedRequestDetail = { ...detail, properties: detail.properties ?? {} };\n const handler = this.handlers.get(detail.type);\n let result: ActionResult;\n try {\n if (!handler) {\n result = { outcome: 'aborted', reason: 'ACTION_NOT_IMPLEMENTED' };\n } else {\n result = await handler(typed, ctx);\n }\n } catch (err) {\n result = { outcome: 'aborted', reason: 'GENERAL_FAILURE', message: err instanceof Error ? err.message : String(err) };\n }\n await Promise.all(pending);\n return result;\n }\n\n /** Item 1: pre-flight rejection, first match wins across the four rule categories, each\n * scanned over every detail in order. */\n private preflightReject(request: Request, entity: EntityHandle): StatusReason | undefined {\n for (const d of request.details) {\n if (d.format !== undefined && d.format !== 'ISO-21423') return 'FORMAT_NOT_SUPPORTED';\n }\n for (const d of request.details) {\n if (majorOf(d.version) !== majorOf(PROTOCOL_VERSION)) return 'VERSION_NOT_SUPPORTED';\n }\n for (const d of request.details) {\n if (d.type !== 'cancelRequest' && !this.handlers.has(d.type)) return 'ACTION_NOT_IMPLEMENTED';\n }\n const states = entity.lastStates();\n if (BLOCKING_STATES.some((s) => states.includes(s))) {\n for (const d of request.details) {\n if (!STATE_EXEMPT_TYPES.has(d.type)) return 'INVALID_IMR_STATE_FOR_ACTION';\n }\n }\n return undefined;\n }\n}\n\n/**\n * ND-11.1 / ND-12: cancelRequest is resolved by searching for the named (source, requestId) run\n * across a list of executors — never dispatched to an app handler. A plain client passes just its\n * own executor; the IMRFM's RequestServer additionally passes every managed handle's executor,\n * because a request it dispatched (ND-12) actually runs there, not in its own `runs` map.\n */\nexport async function resolveCancelRequest(\n cancelReq: IncomingRequest, executors: Iterable<ActionExecutor>,\n): Promise<void> {\n const props = cancelReq.request.details[0]?.properties as\n { source?: string; requestId?: number } | undefined;\n const key = props?.source !== undefined && props.requestId !== undefined\n ? { source: props.source, sequenceId: props.requestId } : undefined;\n const found = key !== undefined && [...executors].some((ex) => ex.cancel(key));\n if (found) {\n // SUCCEEDED is only reachable from EXECUTING (Figure C.3) — the cancel op has no detail\n // work of its own to run, so step straight through ACCEPTED/EXECUTING.\n await cancelReq.accept();\n await cancelReq.updateStatus({ status: 'EXECUTING' });\n await cancelReq.complete({ status: 'SUCCEEDED' });\n } else {\n await cancelReq.reject('REJECTED');\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { EntityContext } from './entityHandle.js';\nimport { requestStatusTopic, requestTopic } from '../topics/topics.js';\nimport { RESOURCE_CONFIG } from '../topics/resources.js';\nimport type { TopicMeta, SessionSubscription } from '../session/session.js';\nimport type { Request, RequestStatus } from '../types/requests.js';\nimport { validateMessage } from '../schema/validators.js';\nimport { isTerminalRequestState } from '../requests/stateMachine.js';\nimport { toTimestamp } from './types.js';\nimport { IncomingRequest, type StatusSink } from './incomingRequest.js';\nimport type { RequestAcceptanceFilter } from './filters.js';\nimport { DEFAULT_PRIORITY, type ExecutionPolicy } from './policies.js';\nimport { resolveCancelRequest, type ActionExecutor } from './executor.js';\nimport type { EntityHandle } from './entityHandle.js';\n\ninterface Registration { filter: RequestAcceptanceFilter; handler: (req: IncomingRequest) => void }\n\n/** @internal — FleetGateway dispatch seam (ND-12): resolves an empty-destination request to a\n * managed handle's executor, or null to reject it. */\nexport interface DispatchTarget { executor: ActionExecutor; entity: EntityHandle }\nexport type DispatchInterceptor = (request: Request) => DispatchTarget | null;\n\ninterface PendingRequest {\n request: Request;\n req: IncomingRequest;\n}\n\ninterface ActiveRequestData {\n req: IncomingRequest;\n status: RequestStatus;\n priority?: number;\n /** true = admitted (handed to handler); false = buffered/pending (admission gate only).\n * Admission logic sees only admitted=true; wire activeRequestsStatus includes all non-terminal.\n * (Distinction: admission control vs. protocol observation.) */\n admitted: boolean;\n}\n\n/**\n * One `RequestServer` per `EntityHandle`, created lazily on the first `acceptRequests` call.\n * Owns the `request/+` subscription, D-12/D-13 handling, duplicate suppression and the\n * `activeRequestsStatus` aggregation. See task-5-brief.md Step 4 for the 8-point behavior spec.\n */\nexport class RequestServer {\n private sessionSub?: SessionSubscription;\n private registrations: Registration[] = [];\n // ponytail: in-memory only — a process restart re-executes requests still retained on the\n // broker; persist the key set alongside the sequence seed if that ever bites.\n private readonly seen = new Set<string>();\n private readonly activeStatuses = new Map<string, ActiveRequestData>();\n private readonly pendingRequests: PendingRequest[] = [];\n private readonly sink: StatusSink;\n // Task 7: the executor is the fallback consumer once no acceptRequests filter matches — see\n // handleAcceptedRequest / the cancelRequest branch of handleInbound below.\n private executor?: { executor: ActionExecutor; entity: EntityHandle };\n // Task 8 (FleetGateway) seams — both optional, set only by EntityHandle.setDispatchInterceptor /\n // onRequestSettled when a gateway wires them; a plain client never touches either.\n private dispatchInterceptor?: DispatchInterceptor;\n private requestSettledHook?: (requestTopic: string) => void;\n // ND-12 cancel-resolution seam: every managed handle's executor, consulted when a cancelRequest\n // doesn't name a run in this server's own executor — a dispatched request actually runs in the\n // target robot's executor, not the IMRFM's own.\n private managedExecutorsHook?: () => Iterable<ActionExecutor>;\n\n constructor(private readonly ctx: EntityContext) {\n this.sink = {\n ownerUuid: ctx.ref.entityUuid,\n nextStatusSequenceId: () => ctx.sequence.next(), // D-15: same SequenceCounter as sendRequest\n publishStatus: (req, status) => this.publishStatus(req, status),\n };\n }\n\n /** Idempotent: a second acceptRequests() on the same handle reuses the live subscription. */\n async ensureStarted(): Promise<void> {\n if (this.sessionSub) return;\n const filter = `${this.ctx.session.topicFor(this.ctx.ref, 'request')}/+`;\n // kind: null (point 1) — a schema-routed subscription would divert malformed payloads to\n // 'validation-warning' and no rejection would ever be published (D-13).\n this.sessionSub = await this.ctx.session.subscribeTopic(\n filter, null, (msg, meta) => {\n this.handleInbound(msg as string, meta)\n .catch((err) => this.ctx.diagnostic('dispatch-rejected', { reason: 'GENERAL_FAILURE', error: err }));\n }, { qos: 2 });\n }\n\n /** @internal — EntityHandle.onRequest wires the executor in here once, the first time it's used. */\n setExecutor(executor: ActionExecutor, entity: EntityHandle): void {\n this.executor = { executor, entity };\n }\n\n /** @internal — EntityHandle.setDispatchInterceptor (ND-12, IMRFM handle only). */\n setDispatchInterceptor(cb: DispatchInterceptor): void {\n this.dispatchInterceptor = cb;\n }\n\n /** @internal — EntityHandle.setManagedExecutorsHook (ND-12 cancel resolution, IMRFM handle\n * only). */\n setManagedExecutorsHook(cb: () => Iterable<ActionExecutor>): void {\n this.managedExecutorsHook = cb;\n }\n\n /** @internal — EntityHandle.onRequestSettled (ND-10 janitor feed). */\n setRequestSettledHook(cb: (requestTopic: string) => void): void {\n this.requestSettledHook = cb;\n }\n\n /** Adds a low-level request handler for `filter`; returns a deregistration function (not itself async — callers unsubscribe/teardown separately once `handlerCount` hits 0). */\n register(filter: RequestAcceptanceFilter, handler: (req: IncomingRequest) => void): () => void {\n const reg: Registration = { filter, handler };\n this.registrations.push(reg);\n return () => { this.registrations = this.registrations.filter((r) => r !== reg); };\n }\n\n get handlerCount(): number { return this.registrations.length; }\n\n /** ND-18: count of admitted (handed to a handler), still-non-terminal requests — what\n * ClientHealth.activeRequests.serving sums across every handle. */\n get servingCount(): number {\n let n = 0;\n for (const data of this.activeStatuses.values()) if (data.admitted) n++;\n return n;\n }\n\n async teardown(): Promise<void> {\n await this.sessionSub?.unsubscribe();\n this.sessionSub = undefined;\n }\n\n /**\n * Top-level inbound message handler for this entity's `request/+` subscription: parses and\n * schema-validates the payload (rejecting/warning on failure), drops retained clears and\n * already-seen duplicates, publishes RECEIVED, then routes the request — dispatch interception\n * (ND-12) first, then cancelRequest resolution, then normal admission-policy handling.\n */\n private async handleInbound(text: string, meta: TopicMeta): Promise<void> {\n if (text === '') return; // point 2: retained clear, ignore\n const requestUuid = meta.requestUuid;\n if (!requestUuid) return; // filter guarantees this, but be safe\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n await this.rejectOrWarn(meta.topic, text, undefined, ['invalid JSON'], requestUuid);\n return;\n }\n const result = validateMessage('request', parsed);\n if (!result.ok) {\n await this.rejectOrWarn(meta.topic, text, result.value, result.errors ?? [], requestUuid);\n return; // point 3: never call the app handler\n }\n\n const request = result.value as Request;\n const dupKey = `${request.source}:${request.sequenceId}`;\n if (this.seen.has(dupKey)) {\n this.ctx.diagnostic('duplicate-request-ignored', { source: request.source, sequenceId: request.sequenceId });\n this.requestSettledHook?.(meta.topic); // ND-10: this retained topic will\n return; // never terminate on its own — point 4\n }\n this.seen.add(dupKey);\n\n const req = new IncomingRequest(request, requestUuid, this.sink);\n await req.publishReceived(); // point 5 — D-12, before any handler\n\n // publishReceived() has already entered this request in activeStatuses (admitted: false), so\n // it is on the wire in activeRequestsStatus but invisible to the admission view below — a\n // request never sees itself, or any other buffered request, as active.\n\n // ND-12: the IMRFM's dispatch callback intercepts an empty-destination request before\n // admission/cancellation semantics ever apply — a dispatched request is either handed\n // straight to a managed handle's executor, or rejected outright.\n if (this.dispatchInterceptor && request.destination === '') {\n const target = this.dispatchInterceptor(request);\n if (target) {\n void target.executor.run(req, target.entity)\n .catch((err) => this.ctx.diagnostic('dispatch-rejected', { reason: 'GENERAL_FAILURE', error: err }));\n } else {\n this.ctx.diagnostic('dispatch-rejected', { reason: 'REJECTED' });\n await req.reject('REJECTED');\n }\n return;\n }\n\n // D-02: a legacy `type: 'cancel'` detail is normalized to `cancelRequest` before anything\n // else inspects it.\n const firstDetail = request.details[0];\n if (firstDetail && firstDetail.type === 'cancel') {\n this.ctx.diagnostic('legacy-cancel-normalized', { source: request.source, sequenceId: request.sequenceId });\n firstDetail.type = 'cancelRequest';\n }\n\n // Task 6: apply the execution policy. A cancelRequest bypasses admission entirely: the whole\n // point of a cancel is to reach a busy entity. Only the *first* detail is inspected — bundled\n // cancels (a cancel riding along with other details) go through normal admission by design.\n const isCancelRequest = request.details.length > 0 && request.details[0]!.type === 'cancelRequest';\n if (isCancelRequest) {\n // Handed straight to the handlers, and left admitted:false — a cancel is not work, so it\n // must not block or preempt anything through a later admission check either.\n const matching = this.registrations.filter((r) => r.filter.matches(request));\n if (matching.length > 0) {\n for (const r of matching) r.handler(req);\n } else {\n const executors = this.cancelExecutors();\n if (executors.length > 0) {\n // ND-11.1/ND-12: the executor resolves cancelRequest itself, never an app handler — a\n // dispatched request may have run in a managed handle's executor instead of this\n // server's own, so every candidate is searched before giving up.\n await resolveCancelRequest(req, executors);\n } else {\n this.ctx.diagnostic('dispatch-rejected', { reason: 'ACTION_NOT_IMPLEMENTED' });\n await req.reject('ACTION_NOT_IMPLEMENTED');\n }\n }\n return;\n }\n\n const policy = this.ctx.getExecutionPolicy();\n const decision = policy.admit(request, this.buildActiveStatuses());\n\n await this.applyAdmissionDecision(request, req, decision, policy);\n }\n\n /** Controller ruling R2: build a minimal one-detail IncomingRequest and reject it with\n * MALFORMED_REQUEST when (source, sequenceId) can still be read; otherwise surface the usual\n * 'validation-warning' event and drop, same as any other schema-routed subscription would. */\n private async rejectOrWarn(\n topic: string, raw: string, parsed: unknown, errors: unknown[], requestUuid: string,\n ): Promise<void> {\n const obj = parsed && typeof parsed === 'object' ? parsed as Record<string, unknown> : undefined;\n const source = typeof obj?.source === 'string' ? obj.source : undefined;\n const sequenceId = typeof obj?.sequenceId === 'number' ? obj.sequenceId : undefined;\n if (source === undefined || sequenceId === undefined) {\n this.ctx.session.reportValidationWarning({ topic, payload: raw, errors });\n this.requestSettledHook?.(topic); // ND-10: an unroutable retained\n return; // request can never terminate either\n }\n const minimal: Request = {\n destination: this.ctx.ref.entityUuid,\n source,\n sequenceId,\n timestamp: toTimestamp(),\n details: [{ type: this.inferDetailType(obj!), version: '1.0' }],\n };\n const req = new IncomingRequest(minimal, requestUuid, this.sink);\n this.ctx.diagnostic('dispatch-rejected', { reason: 'MALFORMED_REQUEST' });\n await req.reject('MALFORMED_REQUEST');\n }\n\n private inferDetailType(obj: Record<string, unknown>): string {\n const details = obj.details;\n if (Array.isArray(details) && details.length > 0) {\n const first = details[0] as unknown;\n if (first && typeof first === 'object' && typeof (first as Record<string, unknown>).type === 'string') {\n return (first as Record<string, unknown>).type as string;\n }\n }\n return 'unknown';\n }\n\n /** The StatusSink: publish the requestStatus, then republish activeRequestsStatus (point 7). */\n private async publishStatus(req: IncomingRequest, status: RequestStatus): Promise<void> {\n const topic = requestStatusTopic(this.ctx.ref, req.requestUuid);\n const { qos, retain } = RESOURCE_CONFIG.requestStatus!;\n await this.ctx.session.publishTopic(topic, 'requestStatus', status, { qos, retain });\n this.ctx.countPublish();\n // Terminal requests leave the active map first, then the array is republished.\n if (isTerminalRequestState(status.status)) {\n this.activeStatuses.delete(req.requestUuid);\n this.requestSettledHook?.(requestTopic(this.ctx.ref, req.requestUuid));\n // Re-admit pending requests after a terminal transition (async to avoid blocking publishStatus)\n // ponytail: async re-admit means buffered requests may see slight delay before handling;\n // upgrade to sync if buffering causes QoS issues under load.\n setImmediate(() => {\n this.reAdmitPending()\n .catch((err) => this.ctx.diagnostic('dispatch-rejected', { reason: 'GENERAL_FAILURE', error: err }));\n });\n } else {\n // Priority is recorded from the validated Request itself, so it is fixed at RECEIVED time.\n this.activeStatuses.set(req.requestUuid, {\n req, status, priority: req.request.priority,\n admitted: this.activeStatuses.get(req.requestUuid)?.admitted ?? false,\n });\n }\n // Protocol view: activeRequestsStatus carries EVERY non-terminal request, buffered ones\n // included — it is what the entity is serving, not what the policy currently admits.\n const statusArray = [...this.activeStatuses.values()].map((data) => data.status);\n await this.ctx.session.publishResource(\n this.ctx.ref, 'activeRequestsStatus', 'requestStatusArray', statusArray);\n this.ctx.countPublish();\n }\n\n /** The admission view (R7: augmented with priority): only requests a policy decision has\n * already admitted. Buffered requests — and the pending request itself, which is entered as\n * admitted:false by its own RECEIVED — never appear here. */\n private buildActiveStatuses(): (RequestStatus & { priority?: number })[] {\n return [...this.activeStatuses.values()]\n .filter((data) => data.admitted)\n .map((data) => ({\n ...data.status,\n ...(data.priority !== undefined ? { priority: data.priority } : {}),\n }));\n }\n\n /** Apply an admission decision: accept, reject, buffer, or preempt. */\n private async applyAdmissionDecision(\n request: Request, req: IncomingRequest,\n decision: ReturnType<ExecutionPolicy['admit']>, policy: ExecutionPolicy,\n ): Promise<void> {\n if (decision.action === 'reject') {\n this.ctx.diagnostic('dispatch-rejected', { reason: decision.reason });\n await req.reject(decision.reason);\n } else if (decision.action === 'buffer') {\n this.pendingRequests.push({ request, req });\n await this.enforceBufferLimit(policy);\n } else {\n if (decision.action === 'preempt') {\n for (const key of decision.preempt) {\n for (const data of this.activeStatuses.values()) {\n // admitted-only: the keys came from the admission view, and a buffered request must\n // never be cancelled by a preemption aimed at running work.\n if (!data.admitted) continue;\n // key.source names the ORIGINAL sender (RequestKey convention, policies.ts) —\n // data.status.destination is that same sender mirrored back onto this request's\n // own status, not data.status.source (this handle's own uuid, constant here).\n if (data.status.destination === key.source && data.status.requestSequenceId === key.sequenceId) {\n // Task 7 seam: an executor-run request owns its own completion once its\n // AbortSignal fires (run() detects cancelRequested and ends it CANCELED itself);\n // ending it directly here too would race a second, illegal transition. A\n // low-level acceptRequests handler gets no such signal, so it is still ended here.\n const executorOwned = this.executor?.executor.cancel(key) ?? false;\n if (!executorOwned) await data.req.complete({ status: 'CANCELED', reason: 'PREEMPTED' });\n }\n }\n }\n }\n await this.handleAcceptedRequest(request, req);\n }\n }\n\n /** Handle an accepted request: mark as admitted, route to matching handlers. */\n private async handleAcceptedRequest(request: Request, req: IncomingRequest): Promise<void> {\n // Admitted from here on: this is what makes the request visible to later admission checks.\n const existing = this.activeStatuses.get(req.requestUuid);\n if (existing) existing.admitted = true;\n\n const matching = this.registrations.filter((r) => r.filter.matches(request));\n if (matching.length > 0) {\n for (const r of matching) r.handler(req);\n return;\n }\n // Task 7: low-level acceptRequests handlers win when their filter matches; otherwise, if any\n // onRequest handler is registered, the executor runs the request.\n if (this.executor && this.executor.executor.hasHandlers()) {\n void this.executor.executor.run(req, this.executor.entity)\n .catch((err) => this.ctx.diagnostic('dispatch-rejected', { reason: 'GENERAL_FAILURE', error: err }));\n return;\n }\n this.ctx.diagnostic('dispatch-rejected', { reason: 'ACTION_NOT_IMPLEMENTED' });\n await req.reject('ACTION_NOT_IMPLEMENTED');\n }\n\n /** Every executor a cancelRequest should be resolved against: this server's own first (if any),\n * then every managed handle's (ND-12, IMRFM only). */\n private cancelExecutors(): ActionExecutor[] {\n const list: ActionExecutor[] = [];\n if (this.executor) list.push(this.executor.executor);\n if (this.managedExecutorsHook) list.push(...this.managedExecutorsHook());\n return list;\n }\n\n /** Enforce bufferLimit: if the buffer exceeds the limit, displace the oldest request with REJECTED. */\n private async enforceBufferLimit(policy: ExecutionPolicy): Promise<void> {\n const limit = policy.bufferLimit ?? Number.POSITIVE_INFINITY;\n while (this.pendingRequests.length > limit) {\n const displaced = this.pendingRequests.shift()!;\n this.ctx.diagnostic('dispatch-rejected', { reason: 'REJECTED' });\n await displaced.req.reject('REJECTED');\n }\n }\n\n /** Re-admit buffered requests after a terminal transition, one at a time: each admitted request\n * is marked admitted before the next decision is taken, so the drain stops as soon as the\n * policy buffers again. Removal from the queue happens before any await, so two overlapping\n * drains can never hand the same request to a handler twice. */\n private async reAdmitPending(): Promise<void> {\n while (this.pendingRequests.length > 0) {\n const policy = this.ctx.getExecutionPolicy();\n const index = this.selectNextPending(policy);\n const pending = this.pendingRequests[index]!;\n const decision = policy.admit(pending.request, this.buildActiveStatuses());\n if (decision.action === 'buffer') break; // still blocked: leave the queue as is\n this.pendingRequests.splice(index, 1);\n await this.applyAdmissionDecision(pending.request, pending.req, decision, policy);\n }\n }\n\n /** Next buffered request to drain: lowest numeric priority first when the policy asks for a\n * priority drain (arrival order breaking ties), plain FIFO otherwise. */\n private selectNextPending(policy: ExecutionPolicy): number {\n if (!policy.drainByPriority) return 0;\n const pri = (i: number): number => this.pendingRequests[i]!.request.priority ?? DEFAULT_PRIORITY;\n let best = 0;\n for (let i = 1; i < this.pendingRequests.length; i++) if (pri(i) < pri(best)) best = i;\n return best;\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PROTOCOL_VERSION, type DockAction } from './constants.js';\nimport type { Uuid } from './common.js';\nimport type { LocationPoint, Orientation } from './ccs.js';\nimport type { RequestDetail } from './requests.js';\n\nexport interface OrientationTolerance { yaw: number; pitch: number; roll: number }\n\nexport interface MoveProps {\n location: LocationPoint;\n orientation?: Orientation; // in examples but not Table C.3 (spec §3.1)\n toleranceRadius?: number;\n orientationTolerance?: OrientationTolerance;\n arrivalTime?: string;\n}\n\nexport interface CancelProps { source: Uuid; requestId: number; actionId?: number }\n\nexport interface DockProps {\n dockLocation: LocationPoint;\n dockId?: Uuid;\n dockActions?: DockAction[];\n toleranceRadius?: number;\n orientationTolerance?: OrientationTolerance;\n}\n\ninterface BuilderOpts { blocking?: boolean; atomic?: boolean; version?: string }\n\n/** Assembles a {@link RequestDetail}, filling in `format`/`version`/`blocking`/`atomic` defaults. */\nfunction detail(type: string, properties: Record<string, unknown>, opts: BuilderOpts = {}): RequestDetail {\n return {\n type,\n version: opts.version ?? PROTOCOL_VERSION,\n format: 'ISO-21423',\n blocking: opts.blocking ?? true,\n atomic: opts.atomic ?? false,\n properties,\n };\n}\n\nexport const move = (props: MoveProps, opts?: BuilderOpts): RequestDetail =>\n detail('move', { ...props }, opts);\nexport const pauseImr = (opts?: BuilderOpts): RequestDetail => detail('pauseImr', {}, opts);\nexport const resumeImr = (opts?: BuilderOpts): RequestDetail => detail('resumeImr', {}, opts);\n/** Builds a `cancelRequest` action detail targeting a previously-sent request/action by id. */\nexport const cancelRequest = (props: CancelProps, opts?: BuilderOpts): RequestDetail =>\n detail('cancelRequest', { ...props }, opts);\nexport const dock = (props: DockProps, opts?: BuilderOpts): RequestDetail =>\n detail('dock', { ...props }, opts);\nexport const undock = (opts?: BuilderOpts): RequestDetail => detail('undock', {}, opts);\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Iso21423Session } from '../session/session.js';\nimport type { EntityRef } from '../topics/topics.js';\nimport { AuthorizationDenied } from '../errors.js';\n\n/**\n * ND-15: MQTT 3.1.1 gives no negative acknowledgement for a denied publish, so the only way to\n * detect a missing write grant is to read our own retained identity back.\n */\nexport async function publishSelfCheck(\n session: Iso21423Session, ref: EntityRef, timeoutMs = 2000,\n): Promise<void> {\n const topic = session.topicFor(ref, 'identity');\n let seen = false;\n let resolveEcho: () => void = () => {};\n const echo = new Promise<void>((resolve) => { resolveEcho = resolve; });\n const sub = await session.subscribeTopic(topic, null, (raw) => {\n if (typeof raw === 'string' && raw.length > 0) { seen = true; resolveEcho(); }\n }, { qos: 1 });\n try {\n const timer = new Promise<void>((resolve) => {\n const t = setTimeout(resolve, timeoutMs);\n t.unref?.();\n });\n await Promise.race([echo, timer]);\n if (!seen) {\n throw new AuthorizationDenied(\n `publish self-check failed: no retained identity echo on ${topic} — the broker ACL ` +\n `probably denies write access to this namespace (ND-15)`, topic);\n }\n } finally {\n await sub.unsubscribe();\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Iso21423Session } from '../session/session.js';\n\n/**\n * ND-10: the sender clears its own retained request at terminal state. The gateway additionally\n * clears requests in its own namespaces that are still retained a grace period after the terminal\n * status it published — protection against crashed senders. Clearing an already-cleared topic is a\n * harmless no-op, so no \"is it still retained?\" probe is needed.\n */\nexport class RetainedRequestJanitor {\n private readonly timers = new Set<ReturnType<typeof setTimeout>>();\n\n constructor(\n private readonly session: Iso21423Session,\n private readonly graceMs: number,\n private readonly onCleared: (topic: string) => void,\n ) {}\n\n /** Schedules `requestTopic` to be force-cleared after the grace period; the clear itself is idempotent, so overlapping/duplicate `note()` calls are harmless. */\n note(requestTopic: string): void {\n const timer = setTimeout(() => {\n this.timers.delete(timer);\n void this.session.clearRetained(requestTopic).then(() => this.onCleared(requestTopic))\n // Idempotent retry: the next note() (or the sender's own ND-10 clear) will catch it up,\n // so a failed clear here is silently swallowed rather than an unhandled rejection.\n .catch(() => {});\n }, this.graceMs);\n timer.unref?.();\n this.timers.add(timer);\n }\n\n dispose(): void {\n for (const t of this.timers) clearTimeout(t);\n this.timers.clear();\n }\n}\n","/**\n * Copyright 2026 InOrbit, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { MqttTransport } from '../session/transport.js';\nimport type { Uuid } from '../types/common.js';\nimport type { Request } from '../types/requests.js';\nimport { Iso21423Error } from '../errors.js';\nimport { Iso21423Client } from '../core/client.js';\nimport { EntityHandle } from '../core/entityHandle.js';\nimport type { ActionExecutor } from '../core/executor.js';\nimport type { DispatchTarget } from '../core/requestServer.js';\nimport type { ActionHandler, ExecutionPolicy, SecurityOptions } from '../core/types.js';\nimport type { SequenceStore } from '../core/sequence.js';\nimport { publishSelfCheck } from './selfCheck.js';\nimport { RetainedRequestJanitor } from './janitor.js';\n\nconst DEFAULT_JANITOR_GRACE_MS = 30_000;\n\n/** Options for {@link FleetGateway.connect}. */\nexport interface FleetGatewayOptions {\n transport?: MqttTransport;\n url?: string;\n security?: SecurityOptions;\n imrfm: {\n id: Uuid;\n manufacturerName: string;\n details?: Record<string, unknown>;\n accepts?: string[];\n provides?: string[];\n };\n janitor?: { enabled?: boolean; graceMs?: number };\n validateOutbound?: boolean;\n sequenceStore?: SequenceStore | null;\n requestTimeoutMs?: number;\n}\n\n/** Options for {@link FleetGateway.registerImr}. */\nexport interface ImrRegistration {\n id: Uuid;\n identity?: Record<string, unknown>;\n manufacturerName?: string;\n accepts?: string[];\n provides?: string[];\n executionPolicy?: ExecutionPolicy;\n}\n\n/**\n * Fleet-wide facade (ISO 21423 IMRFM role): owns one `Iso21423Client`, the IMRFM's own\n * `EntityHandle`, and every managed IMR's handle. Adds three things on top of `/core`: fleet-wide\n * `onRequest` handlers replayed onto current/future robots (controller ruling R6), the\n * empty-destination dispatch callback (ND-12), and a retained-request janitor + publish\n * self-check that both default ON (ND-10, ND-15).\n */\nexport class FleetGateway {\n private readonly imrHandles = new Map<Uuid, EntityHandle>();\n // Provenance tracking for R6: the core-level ActionExecutor only knows \"a handler for this type\n // exists or not\" — it has no notion of \"fleet-wide\" vs \"per-imr\" scope. These two maps let the\n // gateway apply its own override rule (same-scope re-registration needs override:true; a\n // per-imr registration shadowing a fleet-wide one never does) while always calling the\n // underlying `EntityHandle.onRequest` with `override: true` so the core-level guard never trips\n // on the gateway's own layering.\n private readonly fleetHandlers = new Map<string, ActionHandler>();\n private readonly perImrHandlerTypes = new Set<string>();\n private janitor?: RetainedRequestJanitor;\n private dispatchCb?: (request: Request, imrs: EntityHandle[]) => Uuid | null;\n\n private constructor(\n readonly client: Iso21423Client,\n readonly imrfm: EntityHandle,\n private readonly selfCheckEnabled: boolean,\n private readonly selfCheckTimeoutMs: number | undefined,\n ) {}\n\n /**\n * Connects the underlying client, registers the IMRFM's own identity (arming its Last Will,\n * decision 1), runs the gateway's own publish self-check (default on, ND-15) unless\n * `security.selfCheck` is false, and — unless `janitor.enabled` is false — starts the\n * retained-request janitor and wires the empty-destination dispatch interceptor (ND-12).\n */\n static async connect(opts: FleetGatewayOptions): Promise<FleetGateway> {\n const client = await Iso21423Client.connect({\n transport: opts.transport,\n url: opts.url,\n // Deliberately NOT forwarding security.selfCheck/selfCheckTimeoutMs: the gateway runs its\n // own self-check below (default ON) instead of the client's own (default OFF) — running\n // both would just double the identity-echo round trip.\n security: opts.security && {\n username: opts.security.username, password: opts.security.password, tls: opts.security.tls,\n },\n validateOutbound: opts.validateOutbound,\n sequenceStore: opts.sequenceStore,\n requestTimeoutMs: opts.requestTimeoutMs,\n });\n\n // First operation on the client (decision 1): arms the B.4 Last Will.\n const imrfm = await client.registerSelfEntity({\n entityUuid: opts.imrfm.id,\n entityType: 'IMRFM',\n manufacturerName: opts.imrfm.manufacturerName,\n details: opts.imrfm.details,\n capabilities: { provides: opts.imrfm.provides ?? [], accepts: opts.imrfm.accepts ?? [] },\n });\n\n const gateway = new FleetGateway(\n client, imrfm, opts.security?.selfCheck !== false, opts.security?.selfCheckTimeoutMs);\n\n if (gateway.selfCheckEnabled) {\n await publishSelfCheck(imrfm.ctx.session, imrfm.ctx.ref, gateway.selfCheckTimeoutMs);\n }\n\n if (opts.janitor?.enabled !== false) {\n const graceMs = opts.janitor?.graceMs ?? DEFAULT_JANITOR_GRACE_MS;\n gateway.janitor = new RetainedRequestJanitor(\n imrfm.ctx.session, graceMs,\n (topic) => imrfm.ctx.diagnostic('janitor-cleared', { topic }));\n await imrfm.onRequestSettled((topic) => gateway.janitor!.note(topic));\n }\n\n await imrfm.setDispatchInterceptor((request) => gateway.resolveDispatch(request));\n // ND-12: a dispatched request runs in the target robot's executor, not the IMRFM's own — a\n // cancelRequest for it must be resolvable there too (controller ruling).\n await imrfm.setManagedExecutorsHook(() => gateway.imrs()\n .map((h) => h.dispatchTarget()?.executor)\n .filter((e): e is ActionExecutor => e !== undefined));\n\n return gateway;\n }\n\n /**\n * Registers a new managed IMR under this IMRFM: creates its `EntityHandle`, wires it into the\n * janitor, replays every fleet-wide `onRequest` handler onto it, and (if the gateway's self-check\n * is enabled) publishes a self-check for it. On self-check failure, rolls back the local\n * bookkeeping (handle map and the manager's `manages` list) before rethrowing — nothing is\n * retained on the broker to undo, since a denied publish never lands there (ND-15).\n */\n async registerImr(reg: ImrRegistration): Promise<EntityHandle> {\n const handle = await this.client.registerManagedEntity(this.imrfm.entityUuid, {\n entityUuid: reg.id,\n entityType: 'IMR',\n manufacturerName: reg.manufacturerName ?? this.imrfm.identity().manufacturerName,\n details: reg.identity,\n capabilities: { accepts: reg.accepts ?? [], provides: reg.provides ?? [] },\n executionPolicy: reg.executionPolicy,\n });\n\n if (this.janitor) await handle.onRequestSettled((topic) => this.janitor!.note(topic));\n\n for (const [type, handler] of this.fleetHandlers) handle.onRequest(type, handler, { override: true });\n\n this.imrHandles.set(reg.id, handle);\n\n if (this.selfCheckEnabled) {\n try {\n await publishSelfCheck(handle.ctx.session, handle.ctx.ref, this.selfCheckTimeoutMs);\n } catch (err) {\n // Rollback (best-effort, local only): nothing is retained on the broker to clean up — a\n // denied publish never lands there in the first place (that's the whole point of ND-15)\n // — so undoing our own bookkeeping (the handle list and the manager's manages array) is\n // all there is to do before rethrowing.\n this.imrHandles.delete(reg.id);\n this.client.removeManagedEntity(this.imrfm.entityUuid, reg.id);\n const identity = this.imrfm.identity();\n const manages = (identity.capabilities.manages ?? []).filter((uuid) => uuid !== reg.id);\n await this.imrfm.updateIdentity({ capabilities: { ...identity.capabilities, manages } });\n throw err;\n }\n }\n\n return handle;\n }\n\n /** Unregisters and removes a managed IMR (no-op if unknown), and drops it from the IMRFM's `manages` list. */\n async unregisterImr(id: Uuid): Promise<void> {\n const handle = this.imrHandles.get(id);\n if (!handle) return;\n await handle.unregister();\n this.imrHandles.delete(id);\n const identity = this.imrfm.identity();\n const manages = (identity.capabilities.manages ?? []).filter((uuid) => uuid !== id);\n await this.imrfm.updateIdentity({ capabilities: { ...identity.capabilities, manages } });\n }\n\n imrs(): EntityHandle[] {\n return [...this.imrHandles.values()];\n }\n\n /**\n * Registers an action handler either fleet-wide (default: applied to every current and future\n * IMR, R6) or scoped to one `imr`, where it shadows a fleet-wide handler for the same type.\n * Re-registering the same scope for the same type throws unless `override: true` is passed.\n */\n onRequest<P = Record<string, unknown>>(\n type: string, handler: ActionHandler<P>, opts?: { imr?: Uuid; override?: true },\n ): void {\n const asHandler = handler as ActionHandler;\n if (opts?.imr) {\n const handle = this.imrHandles.get(opts.imr);\n if (!handle) throw new Iso21423Error(`FleetGateway.onRequest: unknown imr \"${opts.imr}\"`);\n const key = `${opts.imr}:${type}`;\n if (this.perImrHandlerTypes.has(key) && !opts.override) {\n throw new Iso21423Error(\n `FleetGateway.onRequest: a per-imr handler for \"${type}\" on \"${opts.imr}\" is already ` +\n `registered — pass { override: true } to replace it`);\n }\n this.perImrHandlerTypes.add(key);\n // Always override at the core level: this may be shadowing a fleet-wide handler already\n // registered on this same handle (R6) — the gateway's own provenance check above is the\n // real guard against a genuine same-scope duplicate registration.\n handle.onRequest(type, asHandler, { override: true });\n return;\n }\n if (this.fleetHandlers.has(type) && !opts?.override) {\n throw new Iso21423Error(\n `FleetGateway.onRequest: a fleet-wide handler for \"${type}\" is already registered — ` +\n `pass { override: true } to replace it`);\n }\n this.fleetHandlers.set(type, asHandler);\n this.imrfm.onRequest(type, asHandler, { override: true });\n // Registration order matters: this replay always uses override:true, so a fleet-wide\n // registration made AFTER a per-imr override for the same type replaces that override on\n // every current robot (a later per-imr call would still win back on that one robot).\n for (const handle of this.imrHandles.values()) handle.onRequest(type, asHandler, { override: true });\n }\n\n /** Sets the callback used to pick a target IMR for a request with an empty `destination` (ND-12); return `null` to decline dispatch. */\n onDispatch(cb: (request: Request, imrs: EntityHandle[]) => Uuid | null): void {\n this.dispatchCb = cb;\n }\n\n /** Graceful shutdown: managed handles are NOT unregistered — a fleet restart should not erase\n * the fleet's retained state; call `unregisterImr` explicitly for that. */\n async close(opts?: { timeout?: number }): Promise<void> {\n this.janitor?.dispose();\n await this.client.close(opts);\n }\n\n /** Invokes the `onDispatch` callback (if set) and resolves its chosen uuid to a live IMR's dispatch target. */\n private resolveDispatch(request: Request): DispatchTarget | null {\n if (!this.dispatchCb) return null;\n const uuid = this.dispatchCb(request, this.imrs());\n if (!uuid) return null;\n const handle = this.imrHandles.get(uuid);\n return handle?.dispatchTarget() ?? null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO,WAAW;AAAA,EACzB;AACF;AAGO,IAAM,kBAAN,cAA8B,cAAc;AAAA,EACjD,YAAY,SAAiC,QAAmB;AAC9D,UAAM,OAAO;AAD8B;AAAA,EAE7C;AAAA,EAF6C;AAG/C;AAGO,IAAM,gBAAN,cAA4B,cAAc;AAAA,EAC/C,YAAY,SAAiC,aAAsB;AACjE,UAAM,OAAO;AAD8B;AAAA,EAE7C;AAAA,EAF6C;AAG/C;AAEO,IAAM,iBAAN,cAA6B,cAAc;AAAC;AAC5C,IAAM,oBAAN,cAAgC,cAAc;AAAC;AAG/C,IAAM,sBAAN,cAAkC,cAAc;AAAA,EACrD,YAAY,SAAiC,OAAe;AAC1D,UAAM,OAAO;AAD8B;AAAA,EAE7C;AAAA,EAF6C;AAG/C;AAEO,IAAM,kBAAN,cAA8B,cAAc;AAAC;AAE7C,IAAM,oBAAN,cAAgC,cAA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