maka-agent 0.2.0-dev.15.20260902 → 0.2.0-dev.16.20260903

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 (160) hide show
  1. package/dist/cli-core.js +0 -1
  2. package/dist/pi-transcript.js +48 -0
  3. package/dist/pi-tui-form-interaction.js +497 -0
  4. package/dist/pi-tui-pickers.js +256 -55
  5. package/dist/pi-tui-runner.js +215 -12
  6. package/dist/runtime-host-cli.js +17 -42
  7. package/dist/runtime-host-lifecycle-transaction.js +31 -13
  8. package/dist/runtime-host-managed-lifecycle-manager.js +1 -1
  9. package/dist/runtime-host-onboarding.js +3 -1
  10. package/dist/runtime-host-openrc-service.js +469 -0
  11. package/dist/runtime-host-run-command.js +6 -2
  12. package/dist/runtime-host-service-command.js +3 -3
  13. package/dist/runtime-host-service-management-command.js +43 -15
  14. package/dist/runtime-host-session-channel.js +3 -0
  15. package/dist/runtime-host-session-driver.js +21 -6
  16. package/dist/runtime-host-setup-command.js +30 -31
  17. package/dist/tui-context-refresh.js +103 -0
  18. package/dist/tui-copy-catalog.js +73 -0
  19. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  20. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  21. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  22. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  23. package/node_modules/@maka/core/dist/chat-model-choice.js +4 -0
  24. package/node_modules/@maka/core/dist/computer-use.js +27 -92
  25. package/node_modules/@maka/core/dist/interaction.js +577 -3
  26. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  27. package/node_modules/@maka/core/dist/local-memory.js +2 -2
  28. package/node_modules/@maka/core/dist/model-call-usage-projection.js +3 -0
  29. package/node_modules/@maka/core/dist/model-metadata.js +26 -7
  30. package/node_modules/@maka/core/dist/model-thinking.js +17 -0
  31. package/node_modules/@maka/core/dist/provider-registry.js +1 -0
  32. package/node_modules/@maka/core/dist/runtime-event.js +23 -1
  33. package/node_modules/@maka/core/dist/scheduled-task.js +4 -0
  34. package/node_modules/@maka/core/dist/session.js +95 -2
  35. package/node_modules/@maka/core/dist/text-sanitize.js +19 -0
  36. package/node_modules/@maka/core/dist/usage-ledger-merge.js +3 -0
  37. package/node_modules/@maka/core/dist/usage-record-schema.js +11 -5
  38. package/node_modules/@maka/core/dist/workhub-creation-intent.js +75 -9
  39. package/node_modules/@maka/core/dist/workhub-session-resolver.js +50 -0
  40. package/node_modules/@maka/core/package.json +2 -0
  41. package/node_modules/@maka/eval/dist/harbor-external-subject.js +2 -1
  42. package/node_modules/@maka/eval/dist/harness-executor.js +3 -2
  43. package/node_modules/@maka/eval/dist/install-preflight.js +39 -10
  44. package/node_modules/@maka/eval/dist/process-termination.js +83 -0
  45. package/node_modules/@maka/mcp/dist/sep-2243.js +3 -3
  46. package/node_modules/@maka/runtime/dist/agent-run.js +6 -3
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +332 -118
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction-contract.js +6 -1
  49. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +171 -341
  50. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +3 -26
  51. package/node_modules/@maka/runtime/dist/bundled-skill-catalog.generated.js +1 -1
  52. package/node_modules/@maka/runtime/dist/computer-use-codec.js +1 -141
  53. package/node_modules/@maka/runtime/dist/computer-use-tools.js +23 -105
  54. package/node_modules/@maka/runtime/dist/context-budget-policy.js +20 -26
  55. package/node_modules/@maka/runtime/dist/context-budget.js +18 -20
  56. package/node_modules/@maka/runtime/dist/conversation-copy.js +23 -19
  57. package/node_modules/@maka/runtime/dist/cua-frame-state.js +1 -69
  58. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +267 -0
  59. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +6 -9
  60. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +67 -23
  61. package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +11 -18
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +66 -73
  63. package/node_modules/@maka/runtime/dist/interaction-authority.js +69 -0
  64. package/node_modules/@maka/runtime/dist/mcp-tools.js +13 -1
  65. package/node_modules/@maka/runtime/dist/memory-extraction.js +11 -11
  66. package/node_modules/@maka/runtime/dist/model-adapter.js +24 -6
  67. package/node_modules/@maka/runtime/dist/model-factory.js +14 -5
  68. package/node_modules/@maka/runtime/dist/oauth-provider-contracts.js +28 -1
  69. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +7 -6
  70. package/node_modules/@maka/runtime/dist/opencode-session-header.js +29 -0
  71. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +11 -1
  72. package/node_modules/@maka/runtime/dist/runtime-kernel.js +12 -11
  73. package/node_modules/@maka/runtime/dist/runtime-read-model.js +51 -13
  74. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +3 -0
  75. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +26 -0
  76. package/node_modules/@maka/runtime/dist/session-manager.js +1 -0
  77. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +16 -1
  78. package/node_modules/@maka/runtime/dist/stream-graph-projection.js +6 -0
  79. package/node_modules/@maka/runtime/dist/stream-graph-read-model.js +5 -0
  80. package/node_modules/@maka/runtime/dist/stream-usage-fallback-fetch.js +74 -0
  81. package/node_modules/@maka/runtime/dist/subscription-credentials.js +51 -4
  82. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +47 -3
  83. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +20 -1
  84. package/node_modules/@maka/runtime/dist/test-connection.js +18 -11
  85. package/node_modules/@maka/runtime/dist/tool-runtime.js +183 -0
  86. package/node_modules/@maka/runtime/package.json +1 -0
  87. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +14 -0
  88. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +84 -1
  89. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +68 -51
  90. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  91. package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +8 -5
  92. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +342 -36
  93. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +60 -4
  94. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +3 -3
  95. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +1 -1
  96. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +48 -60
  97. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +847 -431
  98. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +33 -74
  99. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +82 -69
  100. package/node_modules/@maka/runtime-host/dist/peer-reachability/index.js +21 -0
  101. package/node_modules/@maka/runtime-host/dist/peer-reachability/model.js +202 -0
  102. package/node_modules/@maka/runtime-host/dist/peer-reachability/owner.js +119 -0
  103. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +245 -0
  104. package/node_modules/@maka/runtime-host/dist/protocol/agent-graph.js +4 -1
  105. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +68 -0
  106. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +15 -8
  107. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +7 -23
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +47 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +25 -1
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/peer-mesh.js +14 -31
  112. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +19 -6
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +36 -1
  114. package/node_modules/@maka/runtime-host/dist/protocol/session-revision.js +11 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +16 -2
  116. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +51 -2
  117. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +35 -2
  118. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  119. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +12 -10
  120. package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +163 -30
  121. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +38 -14
  122. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +45 -22
  123. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +78 -20
  124. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +4 -2
  125. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +2 -1
  126. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +49 -28
  127. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -6
  128. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +130 -27
  129. package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +30 -1
  130. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -4
  131. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +16 -3
  132. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +66 -3
  133. package/node_modules/@maka/runtime-host/dist/server/oauth-execution-authority.js +20 -3
  134. package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +8 -21
  135. package/node_modules/@maka/runtime-host/dist/server/peer-mesh-authority.js +1 -1
  136. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -3
  137. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +72 -12
  138. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +48 -18
  139. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +43 -26
  140. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +15 -1
  141. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +229 -4
  142. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +146 -8
  143. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +32 -6
  144. package/node_modules/@maka/runtime-host/package.json +1 -0
  145. package/node_modules/@maka/storage/dist/agent-run-store.js +18 -5
  146. package/node_modules/@maka/storage/dist/codex-session-adapter.js +14 -0
  147. package/node_modules/@maka/storage/dist/execution-stores.js +5 -0
  148. package/node_modules/@maka/storage/dist/interaction-store.js +13 -1
  149. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +9 -3
  150. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +49 -19
  151. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +3 -1
  152. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +13 -5
  153. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +4 -2
  154. package/node_modules/@maka/storage/dist/session-store.js +39 -6
  155. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +16 -9
  156. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +30 -3
  157. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +117 -0
  158. package/node_modules/@maka/storage/dist/sqlite-usage-store.js +29 -6
  159. package/node_modules/@maka/storage/dist/usage-stores.js +3 -1
  160. package/package.json +1 -1
@@ -16,8 +16,18 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
+ import { authenticateSignedPeerReachabilityLease, isPeerReachabilityLeaseCurrent, isPeerReachabilityLeaseRecoverable, PEER_REACHABILITY_MAX_CLOCK_SKEW_MS, peerReachabilityLeaseReceipt, verifySignedPeerReachabilityLease, } from '../peer-reachability/index.js';
19
20
  import { normalizePeerError, RuntimeHostPeerError, signRuntimeHostPeerIdentity, startRuntimeHostPeerEndpoint, verifyRuntimeHostPeerIdentity, } from '../transport/peer-native.js';
20
21
  import { RuntimeHostPermanentReconnectError } from './reconnect-lifecycle.js';
22
+ // One Desktop endpoint can retain 32 Host profiles and 128 guest mounts.
23
+ const AUTHENTICATED_REACHABILITY_MAX_ENTRIES = 160;
24
+ export class RuntimeHostPeerReachabilityUnavailableError extends Error {
25
+ code = 'peer_reachability_needs_repair';
26
+ constructor(peerId) {
27
+ super(`Peer ${peerId} has no usable or recoverable route`);
28
+ this.name = 'RuntimeHostPeerReachabilityUnavailableError';
29
+ }
30
+ }
21
31
  export function createRuntimeHostPeerClientFromEnvironment(environment = process.env, options = {}) {
22
32
  const nativePath = environment.MAKA_RUNTIME_HOST_PEER_NATIVE_PATH;
23
33
  const keyPath = environment.MAKA_RUNTIME_HOST_PEER_KEY_PATH;
@@ -32,16 +42,20 @@ export function createRuntimeHostPeerClient(input) {
32
42
  class RuntimeHostPeerClientImpl {
33
43
  #nativePath;
34
44
  #keyPath;
45
+ #relayAnchorPath;
35
46
  #expectedPeerId;
36
47
  #listenAddresses;
37
48
  #coordinationRelays;
38
49
  #automaticRelayDiscovery;
39
50
  #webRtcStunUrls;
40
51
  #routeResolver;
41
- #authenticatedRoutes = new Map();
52
+ #routeListeners = new Map();
53
+ #routeResolverSubscriptions = new Map();
54
+ #authenticatedReachability = new Map();
42
55
  #endpoint;
43
56
  #draining;
44
57
  #meshDraining;
58
+ #connectivityDraining;
45
59
  #applicationConsumer;
46
60
  #meshConsumer;
47
61
  #terminalError;
@@ -52,21 +66,27 @@ class RuntimeHostPeerClientImpl {
52
66
  constructor(input) {
53
67
  this.#nativePath = input.nativePath;
54
68
  this.#keyPath = input.keyPath;
69
+ this.#relayAnchorPath = input.relayAnchorPath;
55
70
  this.#expectedPeerId = input.expectedPeerId;
56
71
  this.#listenAddresses = input.listenAddresses;
57
72
  this.#coordinationRelays = input.coordinationRelays;
58
73
  this.#automaticRelayDiscovery = input.automaticRelayDiscovery ?? false;
59
74
  this.#webRtcStunUrls =
60
75
  input.webRtcStunUrls === undefined ? undefined : [...input.webRtcStunUrls];
61
- this.#routeResolver = input.routeResolver;
62
76
  }
63
77
  identity() {
64
- const endpoint = this.#requireEndpoint();
65
- return Object.freeze({
66
- peerId: endpoint.peerId,
67
- listenAddresses: Object.freeze([...endpoint.listenAddresses]),
68
- coordinationRelays: Object.freeze([...endpoint.activeCoordinationRelays]),
69
- });
78
+ return Object.freeze({ peerId: this.#requireEndpoint().peerId });
79
+ }
80
+ reachability() {
81
+ return freezeReachability(this.#requireEndpoint().reachabilitySnapshot);
82
+ }
83
+ async watchReachability(afterGeneration, timeoutMs) {
84
+ try {
85
+ return freezeReachability(await this.#requireEndpoint().watchReachability(afterGeneration, timeoutMs));
86
+ }
87
+ catch (error) {
88
+ throw normalizePeerError(error);
89
+ }
70
90
  }
71
91
  signIdentity(payload) {
72
92
  const peerId = this.#requireEndpoint().peerId;
@@ -86,6 +106,9 @@ class RuntimeHostPeerClientImpl {
86
106
  signature: proof.signature,
87
107
  });
88
108
  }
109
+ isConnected(peerId) {
110
+ return this.#endpoint?.connectivitySnapshot.connectedPeerIds.includes(peerId) ?? false;
111
+ }
89
112
  transitSnapshot() {
90
113
  return Object.freeze({ ...this.#requireEndpoint().transitSnapshot });
91
114
  }
@@ -96,29 +119,130 @@ class RuntimeHostPeerClientImpl {
96
119
  throw normalizePeerError(error);
97
120
  });
98
121
  }
99
- observeAuthenticatedRoutes(input) {
100
- if (input.routeHints.length === 0 && input.coordinationRelays.length === 0)
101
- return;
102
- this.#authenticatedRoutes.set(input.peerId, Object.freeze({
103
- routeHints: Object.freeze([...input.routeHints]),
104
- coordinationRelays: Object.freeze([...input.coordinationRelays]),
105
- }));
122
+ attachRouteResolver(resolver) {
123
+ if (this.#routeResolver && this.#routeResolver !== resolver) {
124
+ throw new Error('Runtime Host peer client already has a reachability resolver');
125
+ }
126
+ if (this.#routeResolver === resolver)
127
+ return () => undefined;
128
+ this.#routeResolver = resolver;
129
+ for (const peerId of this.#routeListeners.keys()) {
130
+ this.#subscribeResolver(peerId);
131
+ this.#notifyRouteChange(peerId);
132
+ }
133
+ let attached = true;
134
+ return () => {
135
+ if (!attached)
136
+ return;
137
+ attached = false;
138
+ if (this.#routeResolver !== resolver)
139
+ return;
140
+ this.#routeResolver = undefined;
141
+ for (const unsubscribe of this.#routeResolverSubscriptions.values())
142
+ unsubscribe();
143
+ this.#routeResolverSubscriptions.clear();
144
+ for (const peerId of this.#routeListeners.keys())
145
+ this.#notifyRouteChange(peerId);
146
+ };
147
+ }
148
+ subscribeRoutes(peerId, listener) {
149
+ const listeners = this.#routeListeners.get(peerId) ?? new Set();
150
+ const first = listeners.size === 0;
151
+ listeners.add(listener);
152
+ this.#routeListeners.set(peerId, listeners);
153
+ if (first)
154
+ this.#subscribeResolver(peerId);
155
+ let subscribed = true;
156
+ return () => {
157
+ if (!subscribed)
158
+ return;
159
+ subscribed = false;
160
+ listeners.delete(listener);
161
+ if (listeners.size > 0)
162
+ return;
163
+ this.#routeListeners.delete(peerId);
164
+ this.#routeResolverSubscriptions.get(peerId)?.();
165
+ this.#routeResolverSubscriptions.delete(peerId);
166
+ };
167
+ }
168
+ observeAuthenticatedReachability(input) {
169
+ const now = Date.now();
170
+ const identity = {
171
+ value: input.value,
172
+ expectedPeerId: input.expectedPeerId,
173
+ verifyIdentity: this.verifyIdentity.bind(this),
174
+ };
175
+ const next = input.allowHistorical
176
+ ? authenticateSignedPeerReachabilityLease(identity)
177
+ : verifySignedPeerReachabilityLease({ ...identity, now });
178
+ this.#pruneAuthenticatedReachability(now);
179
+ let current = this.#authenticatedReachability.get(input.expectedPeerId);
180
+ if (!isPeerReachabilityLeaseRecoverable(next.lease, now))
181
+ return current?.signed ?? next;
182
+ if (current && current.signed.lease.revision >= next.lease.revision) {
183
+ if (current.signed.lease.revision === next.lease.revision &&
184
+ !sameReachability(current.signed, next)) {
185
+ throw new Error('Peer reachability revision contains conflicting signed facts');
186
+ }
187
+ this.#rememberAuthenticatedReachability(input.expectedPeerId, current);
188
+ return current.signed;
189
+ }
190
+ this.#rememberAuthenticatedReachability(input.expectedPeerId, {
191
+ signed: next,
192
+ ...(next.lease.issuedAt <= now + PEER_REACHABILITY_MAX_CLOCK_SKEW_MS
193
+ ? {
194
+ receipt: peerReachabilityLeaseReceipt({
195
+ signed: next,
196
+ wallNow: now,
197
+ monotonicNow: performance.now(),
198
+ }),
199
+ }
200
+ : {}),
201
+ });
202
+ this.#notifyRouteChange(input.expectedPeerId);
203
+ return next;
204
+ }
205
+ #pruneAuthenticatedReachability(now) {
206
+ for (const [peerId, authenticated] of this.#authenticatedReachability) {
207
+ if (!isPeerReachabilityLeaseRecoverable(authenticated.signed.lease, now)) {
208
+ this.#authenticatedReachability.delete(peerId);
209
+ this.#notifyRouteChange(peerId);
210
+ }
211
+ }
212
+ }
213
+ #rememberAuthenticatedReachability(peerId, authenticated) {
214
+ this.#authenticatedReachability.delete(peerId);
215
+ this.#authenticatedReachability.set(peerId, authenticated);
216
+ while (this.#authenticatedReachability.size > AUTHENTICATED_REACHABILITY_MAX_ENTRIES) {
217
+ let unobservedPeerId;
218
+ for (const candidatePeerId of this.#authenticatedReachability.keys()) {
219
+ if (this.#routeListeners.has(candidatePeerId))
220
+ continue;
221
+ unobservedPeerId = candidatePeerId;
222
+ break;
223
+ }
224
+ const evictedPeerId = unobservedPeerId ?? this.#authenticatedReachability.keys().next().value;
225
+ if (evictedPeerId === undefined)
226
+ break;
227
+ this.#authenticatedReachability.delete(evictedPeerId);
228
+ this.#notifyRouteChange(evictedPeerId);
229
+ }
106
230
  }
107
231
  async connect(input, signal, onPhase) {
108
- if (input.refreshRoutes !== false) {
232
+ if (input.refreshRoutes !== false && this.#routeResolver) {
109
233
  notifyPhase(onPhase, 'discovering');
110
- await this.#prepareRoutes(input, signal);
111
234
  }
112
235
  notifyPhase(onPhase, 'connecting');
113
236
  return this.#connect(input, signal, 'application');
114
237
  }
115
238
  async #prepareRoutes(input, signal) {
116
- if (!this.#routeResolver?.prepareRoutes)
239
+ const resolver = this.#routeResolver;
240
+ if (!resolver)
117
241
  return;
118
242
  const deadline = AbortSignal.timeout(Math.min(10_000, input.directDeadlineMs));
119
243
  const operationSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
120
244
  try {
121
- await this.#routeResolver.prepareRoutes(input.peerId, operationSignal);
245
+ await resolver.prepareRoutes(input.peerId, operationSignal);
122
246
  }
123
247
  catch {
124
248
  // Route preparation enriches an invitation/profile with fresher Mesh
@@ -202,23 +326,61 @@ class RuntimeHostPeerClientImpl {
202
326
  async #startConnect(input, signal, kind) {
203
327
  signal?.throwIfAborted();
204
328
  const endpoint = this.#requireEndpoint();
205
- const requestId = this.#allocateRequestId();
206
- const discovered = kind === 'application' ? this.#routeResolver?.resolveRoutes(input.peerId) : undefined;
207
- const authenticated = kind === 'application' ? this.#authenticatedRoutes.get(input.peerId) : undefined;
208
- const connection = endpoint[kind === 'application' ? 'connect' : 'connectMeshControl']({
209
- ...input,
210
- routeHints: mergeAddresses(discovered?.routeHints ?? [], [
211
- ...(authenticated?.routeHints ?? []),
212
- ...input.routeHints,
213
- ]),
214
- coordinationRelays: mergeAddresses(discovered?.coordinationRelays ?? [], [
215
- ...(authenticated?.coordinationRelays ?? []),
216
- ...(input.coordinationRelays ?? []),
217
- ]),
218
- transitRelayPeerIds: mergeValues(discovered?.transitRelayPeerIds ?? [], input.transitRelayPeerIds, 64),
219
- requestId,
220
- });
221
329
  let settled = false;
330
+ let preparing = Boolean(kind === 'application' && input.refreshRoutes !== false && this.#routeResolver);
331
+ const snapshot = () => this.#connectionResolution(input, kind, preparing);
332
+ let resolution = snapshot();
333
+ if (resolution.state === 'exhausted') {
334
+ throw new RuntimeHostPeerReachabilityUnavailableError(input.peerId);
335
+ }
336
+ const requestId = this.#allocateRequestId();
337
+ const attemptLifetime = new AbortController();
338
+ let reachabilityFailure;
339
+ let updateTail = Promise.resolve();
340
+ const update = () => {
341
+ if (settled)
342
+ return;
343
+ const next = snapshot();
344
+ if (sameConnectionResolution(resolution, next))
345
+ return;
346
+ const candidatesChanged = !sameCandidates(resolution, next);
347
+ resolution = next;
348
+ if (next.state === 'exhausted') {
349
+ reachabilityFailure ??= new RuntimeHostPeerReachabilityUnavailableError(input.peerId);
350
+ void cancelPeerConnect(endpoint, requestId, () => settled);
351
+ return;
352
+ }
353
+ if (!candidatesChanged)
354
+ return;
355
+ const candidates = connectCandidates(next);
356
+ updateTail = updateTail.then(() => updatePeerConnect(endpoint, requestId, candidates, () => settled), () => updatePeerConnect(endpoint, requestId, candidates, () => settled));
357
+ void updateTail.catch(() => undefined);
358
+ };
359
+ const unsubscribe = kind === 'application' ? this.subscribeRoutes(input.peerId, update) : undefined;
360
+ let connection;
361
+ try {
362
+ connection = endpoint[kind === 'application' ? 'connect' : 'connectMeshControl']({
363
+ ...input,
364
+ ...connectCandidates(resolution),
365
+ requestId,
366
+ });
367
+ }
368
+ catch (error) {
369
+ settled = true;
370
+ attemptLifetime.abort();
371
+ unsubscribe?.();
372
+ throw normalizePeerError(error);
373
+ }
374
+ if (preparing) {
375
+ const prepared = this.#prepareRoutes(input, signal ? AbortSignal.any([signal, attemptLifetime.signal]) : attemptLifetime.signal);
376
+ void prepared.then(() => {
377
+ preparing = false;
378
+ update();
379
+ }, () => {
380
+ preparing = false;
381
+ update();
382
+ });
383
+ }
222
384
  const cancel = () => {
223
385
  void cancelPeerConnect(endpoint, requestId, () => settled);
224
386
  };
@@ -227,6 +389,10 @@ class RuntimeHostPeerClientImpl {
227
389
  cancel();
228
390
  try {
229
391
  const stream = await connection;
392
+ if (reachabilityFailure) {
393
+ stream.abort();
394
+ throw reachabilityFailure;
395
+ }
230
396
  if (signal?.aborted) {
231
397
  stream.abort();
232
398
  signal.throwIfAborted();
@@ -235,13 +401,73 @@ class RuntimeHostPeerClientImpl {
235
401
  }
236
402
  catch (error) {
237
403
  signal?.throwIfAborted();
404
+ if (reachabilityFailure)
405
+ throw reachabilityFailure;
238
406
  throw normalizePeerError(error);
239
407
  }
240
408
  finally {
241
409
  settled = true;
410
+ attemptLifetime.abort();
411
+ unsubscribe?.();
242
412
  signal?.removeEventListener('abort', cancel);
243
413
  }
244
414
  }
415
+ #connectionResolution(input, kind, preparing) {
416
+ const discovered = kind === 'application' ? this.#routeResolver?.resolveRoutes(input.peerId) : undefined;
417
+ const rememberedEntry = kind === 'application' ? this.#authenticatedReachability.get(input.peerId) : undefined;
418
+ const remembered = rememberedEntry?.signed;
419
+ const authenticated = remembered && isPeerReachabilityLeaseRecoverable(remembered.lease, Date.now())
420
+ ? remembered
421
+ : undefined;
422
+ if (remembered && !authenticated)
423
+ this.#authenticatedReachability.delete(input.peerId);
424
+ const currentAuthenticated = Boolean(authenticated &&
425
+ rememberedEntry &&
426
+ isPeerReachabilityLeaseCurrent(authenticated, rememberedEntry.receipt, performance.now()));
427
+ const candidates = {
428
+ routeHints: mergeAddresses(discovered?.routeHints ?? [], [
429
+ ...(currentAuthenticated ? (authenticated?.lease.directRoutes ?? []) : []),
430
+ ...input.routeHints,
431
+ ...(!currentAuthenticated ? (authenticated?.lease.directRoutes ?? []) : []),
432
+ ]),
433
+ coordinationRelays: mergeAddresses(discovered?.coordinationRelays ?? [], [
434
+ ...(currentAuthenticated ? (authenticated?.lease.coordinationRoutes ?? []) : []),
435
+ ...(input.coordinationRelays ?? []),
436
+ ...(!currentAuthenticated ? (authenticated?.lease.coordinationRoutes ?? []) : []),
437
+ ]),
438
+ transitRelayPeerIds: mergeValues(discovered?.transitRelayPeerIds ?? [], input.transitRelayPeerIds, 64),
439
+ };
440
+ const connected = this.#endpoint?.connectivitySnapshot.connectedPeerIds.includes(input.peerId) ?? false;
441
+ return Object.freeze({
442
+ ...candidates,
443
+ state: hasConnectionCandidates(candidates) || connected
444
+ ? 'available'
445
+ : preparing
446
+ ? 'recovering'
447
+ : (discovered?.state ?? 'exhausted'),
448
+ });
449
+ }
450
+ #subscribeResolver(peerId) {
451
+ if (this.#routeResolverSubscriptions.has(peerId))
452
+ return;
453
+ const resolver = this.#routeResolver;
454
+ if (!resolver)
455
+ return;
456
+ const unsubscribe = resolver.subscribeRoutes(peerId, () => {
457
+ this.#notifyRouteChange(peerId);
458
+ });
459
+ this.#routeResolverSubscriptions.set(peerId, unsubscribe);
460
+ }
461
+ #notifyRouteChange(peerId) {
462
+ for (const listener of this.#routeListeners.get(peerId) ?? []) {
463
+ try {
464
+ listener();
465
+ }
466
+ catch {
467
+ // Reachability evidence cannot let one observer disrupt the others.
468
+ }
469
+ }
470
+ }
245
471
  close() {
246
472
  this.#closeTask ??= this.#close();
247
473
  return this.#closeTask;
@@ -258,6 +484,7 @@ class RuntimeHostPeerClientImpl {
258
484
  const endpoint = startRuntimeHostPeerEndpoint({
259
485
  nativePath: this.#nativePath,
260
486
  keyPath: this.#keyPath,
487
+ ...(this.#relayAnchorPath ? { relayAnchorPath: this.#relayAnchorPath } : {}),
261
488
  ...(this.#expectedPeerId ? { expectedPeerId: this.#expectedPeerId } : {}),
262
489
  ...(this.#listenAddresses ? { listenAddresses: this.#listenAddresses } : {}),
263
490
  ...(this.#coordinationRelays ? { coordinationRelays: this.#coordinationRelays } : {}),
@@ -267,8 +494,31 @@ class RuntimeHostPeerClientImpl {
267
494
  this.#endpoint = endpoint;
268
495
  this.#draining = this.#drainInbound(endpoint);
269
496
  this.#meshDraining = this.#drainMeshInbound(endpoint);
497
+ this.#connectivityDraining = this.#drainConnectivity(endpoint);
270
498
  return endpoint;
271
499
  }
500
+ async #drainConnectivity(endpoint) {
501
+ let current = endpoint.connectivitySnapshot;
502
+ try {
503
+ while (!this.#closed) {
504
+ const next = await endpoint.watchConnectivity(current.generation, 300_000);
505
+ const previousPeers = new Set(current.connectedPeerIds);
506
+ const nextPeers = new Set(next.connectedPeerIds);
507
+ current = next;
508
+ for (const peerId of new Set([...previousPeers, ...nextPeers])) {
509
+ if (previousPeers.has(peerId) !== nextPeers.has(peerId))
510
+ this.#notifyRouteChange(peerId);
511
+ }
512
+ }
513
+ }
514
+ catch (error) {
515
+ if (this.#closed)
516
+ return;
517
+ this.#terminalError = error instanceof Error ? error : new Error(String(error));
518
+ this.#finishConsumer('application', this.#terminalError);
519
+ this.#finishConsumer('mesh', this.#terminalError);
520
+ }
521
+ }
272
522
  async #drainInbound(endpoint) {
273
523
  try {
274
524
  while (true) {
@@ -334,6 +584,11 @@ class RuntimeHostPeerClientImpl {
334
584
  }
335
585
  async #close() {
336
586
  this.#closed = true;
587
+ for (const unsubscribe of this.#routeResolverSubscriptions.values())
588
+ unsubscribe();
589
+ this.#routeResolverSubscriptions.clear();
590
+ this.#routeListeners.clear();
591
+ this.#authenticatedReachability.clear();
337
592
  const endpoint = this.#endpoint;
338
593
  this.#endpoint = undefined;
339
594
  if (!endpoint)
@@ -347,7 +602,7 @@ class RuntimeHostPeerClientImpl {
347
602
  closeFailed = true;
348
603
  closeError = error;
349
604
  }
350
- await Promise.all([this.#draining, this.#meshDraining]);
605
+ await Promise.all([this.#draining, this.#meshDraining, this.#connectivityDraining]);
351
606
  if (closeFailed)
352
607
  throw closeError;
353
608
  }
@@ -385,9 +640,49 @@ function waitForPeerConnectTurn(previous, signal) {
385
640
  function mergeAddresses(primary, secondary) {
386
641
  return mergeValues(primary, secondary, 32);
387
642
  }
643
+ function freezeReachability(snapshot) {
644
+ return Object.freeze({
645
+ generation: snapshot.generation,
646
+ listenAddresses: Object.freeze([...snapshot.listenAddresses]),
647
+ activeCoordinationRelays: Object.freeze([...snapshot.activeCoordinationRelays]),
648
+ });
649
+ }
388
650
  function mergeValues(primary, secondary, limit) {
389
651
  return Object.freeze([...new Set([...primary, ...(secondary ?? [])])].slice(0, limit));
390
652
  }
653
+ function sameCandidates(left, right) {
654
+ return (sameValues(left.routeHints, right.routeHints) &&
655
+ sameValues(left.coordinationRelays, right.coordinationRelays) &&
656
+ sameValues(left.transitRelayPeerIds, right.transitRelayPeerIds));
657
+ }
658
+ function sameConnectionResolution(left, right) {
659
+ return left.state === right.state && sameCandidates(left, right);
660
+ }
661
+ function hasConnectionCandidates(candidates) {
662
+ return (candidates.routeHints.length > 0 ||
663
+ candidates.coordinationRelays.length > 0 ||
664
+ candidates.transitRelayPeerIds.length > 0);
665
+ }
666
+ function connectCandidates(resolution) {
667
+ return {
668
+ routeHints: resolution.routeHints,
669
+ coordinationRelays: resolution.coordinationRelays,
670
+ transitRelayPeerIds: resolution.transitRelayPeerIds,
671
+ };
672
+ }
673
+ function sameValues(left, right) {
674
+ return left.length === right.length && left.every((value, index) => value === right[index]);
675
+ }
676
+ function sameReachability(left, right) {
677
+ return (left.publicKey === right.publicKey &&
678
+ left.signature === right.signature &&
679
+ left.lease.peerId === right.lease.peerId &&
680
+ left.lease.revision === right.lease.revision &&
681
+ left.lease.issuedAt === right.lease.issuedAt &&
682
+ left.lease.expiresAt === right.lease.expiresAt &&
683
+ sameValues(left.lease.directRoutes, right.lease.directRoutes) &&
684
+ sameValues(left.lease.coordinationRoutes, right.lease.coordinationRoutes));
685
+ }
391
686
  async function cancelPeerConnect(endpoint, requestId, isSettled) {
392
687
  try {
393
688
  while (!isSettled() && !(await endpoint.cancelConnect(requestId))) {
@@ -399,3 +694,14 @@ async function cancelPeerConnect(endpoint, requestId, isSettled) {
399
694
  // The endpoint closing also settles the connect promise.
400
695
  }
401
696
  }
697
+ async function updatePeerConnect(endpoint, requestId, candidates, isSettled) {
698
+ try {
699
+ while (!isSettled() && !(await endpoint.updateConnect({ requestId, ...candidates }))) {
700
+ // N-API schedules connect and updates independently. Retry until the
701
+ // engine has observed the request or the connect promise settles.
702
+ }
703
+ }
704
+ catch {
705
+ // The active connection owns failures; route enrichment is best effort.
706
+ }
707
+ }
@@ -35,6 +35,8 @@ class RuntimeHostReconnectLifecycleImpl {
35
35
  closed;
36
36
  #initial;
37
37
  #connect;
38
+ #retryInitialFailure;
39
+ #initialSignal;
38
40
  #onReconnectError;
39
41
  #onFatalError;
40
42
  #minMs;
@@ -58,9 +60,13 @@ class RuntimeHostReconnectLifecycleImpl {
58
60
  #discardTask = Promise.resolve();
59
61
  #closeTask;
60
62
  #resolveClosed;
63
+ #wakeDelay;
64
+ #wakeGeneration = 0;
61
65
  constructor(input) {
62
66
  this.#connect = input.connect;
63
67
  this.#initial = input.initial;
68
+ this.#retryInitialFailure = input.retryInitialFailure ?? false;
69
+ this.#initialSignal = input.initialSignal;
64
70
  this.#onReconnectError = input.onReconnectError;
65
71
  this.#onFatalError = input.onFatalError;
66
72
  this.#minMs = requireDelay(input.backoff?.minMs ?? DEFAULT_BACKOFF_MIN_MS, 'minMs');
@@ -84,10 +90,29 @@ class RuntimeHostReconnectLifecycleImpl {
84
90
  }
85
91
  async start() {
86
92
  try {
87
- this.#install(this.#initial ?? (await this.#connect(this.#abort.signal)));
93
+ if (this.#initial) {
94
+ this.#install(this.#initial);
95
+ return;
96
+ }
97
+ this.#initialSignal?.throwIfAborted();
98
+ const signal = this.#initialSignal
99
+ ? AbortSignal.any([this.#abort.signal, this.#initialSignal])
100
+ : this.#abort.signal;
101
+ this.#install(await this.#connect(signal));
88
102
  }
89
103
  catch (error) {
90
- this.#failPermanently(asError(error));
104
+ const failure = asError(error);
105
+ if (this.#retryInitialFailure &&
106
+ !this.#closed &&
107
+ !this.#abort.signal.aborted &&
108
+ !this.#initialSignal?.aborted &&
109
+ !(failure instanceof RuntimeHostPermanentReconnectError)) {
110
+ this.#failureCount += 1;
111
+ notifyError(this.#onReconnectError, failure);
112
+ this.#scheduleReconnect();
113
+ return;
114
+ }
115
+ this.#failPermanently(failure);
91
116
  throw error;
92
117
  }
93
118
  }
@@ -120,6 +145,12 @@ class RuntimeHostReconnectLifecycleImpl {
120
145
  this.#listeners.add(listener);
121
146
  return () => this.#listeners.delete(listener);
122
147
  }
148
+ wake() {
149
+ this.#wakeGeneration += 1;
150
+ const wake = this.#wakeDelay;
151
+ this.#wakeDelay = undefined;
152
+ wake?.();
153
+ }
123
154
  async suspend() {
124
155
  if (this.#closed || this.#terminalError) {
125
156
  throw new Error('Runtime Host reconnect lifecycle is closed');
@@ -217,11 +248,15 @@ class RuntimeHostReconnectLifecycleImpl {
217
248
  void task.then(finalize, finalize);
218
249
  }
219
250
  async #reconnect(signal) {
251
+ let attemptedWakeGeneration = this.#wakeGeneration;
220
252
  while (!this.#closed && !this.#quiesced && !this.#terminalError && !this.#current) {
221
253
  const delayMs = reconnectDelayMs(this.#failureCount - 1, this.#minMs, this.#maxMs, this.#random, this.#unstableMaxMs);
254
+ const wakeGeneration = this.#wakeGeneration;
222
255
  try {
223
- if (delayMs > 0)
224
- await this.#wait(delayMs, signal);
256
+ if (delayMs > 0 && wakeGeneration === attemptedWakeGeneration) {
257
+ await this.#waitForReconnectDelay(delayMs, signal, wakeGeneration);
258
+ }
259
+ attemptedWakeGeneration = this.#wakeGeneration;
225
260
  const resource = await this.#connect(signal);
226
261
  this.#install(resource);
227
262
  }
@@ -238,6 +273,27 @@ class RuntimeHostReconnectLifecycleImpl {
238
273
  }
239
274
  }
240
275
  }
276
+ async #waitForReconnectDelay(delayMs, signal, observedWakeGeneration) {
277
+ if (this.#wakeGeneration !== observedWakeGeneration)
278
+ return;
279
+ let wake;
280
+ const routeAvailable = new Promise((resolve) => {
281
+ wake = resolve;
282
+ });
283
+ const delayAbort = new AbortController();
284
+ const delaySignal = AbortSignal.any([signal, delayAbort.signal]);
285
+ this.#wakeDelay = wake;
286
+ if (this.#wakeGeneration !== observedWakeGeneration)
287
+ wake();
288
+ try {
289
+ await Promise.race([this.#wait(delayMs, delaySignal), routeAvailable]);
290
+ }
291
+ finally {
292
+ if (this.#wakeDelay === wake)
293
+ this.#wakeDelay = undefined;
294
+ delayAbort.abort();
295
+ }
296
+ }
241
297
  #suspension(current) {
242
298
  let active = true;
243
299
  return {
@@ -16,7 +16,7 @@
16
16
  * specific language governing permissions and limitations
17
17
  * under the License.
18
18
  */
19
- export { decodePeerMeshInvitation } from '../protocol/peer-mesh.js';
19
+ export { decodePeerMeshInvitation, } from '../protocol/peer-mesh.js';
20
20
  export { openPeerMeshNode, } from './node.js';
21
- export { openRuntimeHostPeerMeshOwner, } from './owner.js';
22
- export { hasPeerMeshIdentityObligations, PeerMeshPostCommitError } from './store.js';
21
+ export { openRuntimeHostPeerMeshComponent, } from './owner.js';
22
+ export { hasPeerMeshIdentityObligations, PeerMeshPostCommitError, } from './store.js';
@@ -23,4 +23,4 @@ export const PEER_MESH_MAX_INVITATION_RECORDS = PEER_MESH_MAX_PENDING_INVITATION
23
23
  export const PEER_MESH_MAX_ROUTE_HINTS = 16;
24
24
  export const PEER_MESH_MAX_TRANSIT_RELAY_ADDRESSES = 256;
25
25
  export const PEER_MESH_MAX_TRANSIT_ADDRESSES_PER_RELAY = 4;
26
- export const PEER_MESH_ROUTE_RECORD_MAX_BYTES = 4 * 1024;
26
+ export const PEER_MESH_MEMBER_ADVERTISEMENT_MAX_BYTES = 2 * 1024;