@xmoxmo/bncr 0.3.6 → 0.3.7

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 (164) hide show
  1. package/README.md +5 -0
  2. package/dist/index.js +28 -5
  3. package/index.ts +55 -721
  4. package/package.json +8 -4
  5. package/scripts/check-pack.mjs +93 -18
  6. package/scripts/check-register-drift.mjs +35 -13
  7. package/scripts/selfcheck.mjs +80 -11
  8. package/src/bootstrap/channel-plugin-runtime.ts +81 -0
  9. package/src/bootstrap/cli.ts +97 -0
  10. package/src/bootstrap/register-runtime-gateway.ts +129 -0
  11. package/src/bootstrap/register-runtime-helpers.ts +140 -0
  12. package/src/bootstrap/register-runtime-singleton.ts +137 -0
  13. package/src/bootstrap/register-runtime.ts +201 -0
  14. package/src/bootstrap/runtime-discovery.ts +187 -0
  15. package/src/bootstrap/runtime-loader.ts +54 -0
  16. package/src/channel.ts +1590 -4967
  17. package/src/core/accounts.ts +23 -4
  18. package/src/core/dead-letter-diagnostics.ts +37 -5
  19. package/src/core/diagnostics.ts +31 -15
  20. package/src/core/downlink-health.ts +3 -11
  21. package/src/core/extended-diagnostics.ts +78 -36
  22. package/src/core/file-transfer-payloads.ts +1 -1
  23. package/src/core/logging.ts +1 -0
  24. package/src/core/outbox-enqueue.ts +13 -2
  25. package/src/core/outbox-entry-builders.ts +2 -0
  26. package/src/core/outbox-summary.ts +75 -3
  27. package/src/core/permissions.ts +15 -2
  28. package/src/core/persisted-outbox-entry.ts +21 -6
  29. package/src/core/policy.ts +45 -4
  30. package/src/core/probe.ts +3 -15
  31. package/src/core/register-trace.ts +3 -3
  32. package/src/core/status.ts +43 -4
  33. package/src/core/targets.ts +216 -205
  34. package/src/core/types.ts +221 -0
  35. package/src/core/value-sanitize.ts +29 -0
  36. package/src/messaging/inbound/commands.ts +147 -172
  37. package/src/messaging/inbound/context-facts.ts +4 -2
  38. package/src/messaging/inbound/contracts.ts +70 -0
  39. package/src/messaging/inbound/dispatch-prep.ts +303 -0
  40. package/src/messaging/inbound/dispatch.ts +49 -462
  41. package/src/messaging/inbound/gate.ts +18 -5
  42. package/src/messaging/inbound/last-route.ts +10 -4
  43. package/src/messaging/inbound/media-url-download.ts +109 -0
  44. package/src/messaging/inbound/native-command-runtime.ts +225 -0
  45. package/src/messaging/inbound/parse.ts +2 -1
  46. package/src/messaging/inbound/remote-media.ts +49 -0
  47. package/src/messaging/inbound/reply-config.ts +16 -4
  48. package/src/messaging/inbound/reply-dispatch.ts +162 -0
  49. package/src/messaging/inbound/runtime-compat.ts +31 -10
  50. package/src/messaging/inbound/session-label.ts +15 -7
  51. package/src/messaging/inbound/turn-context.ts +131 -0
  52. package/src/messaging/outbound/actions.ts +24 -10
  53. package/src/messaging/outbound/diagnostics-debug-builders.ts +365 -0
  54. package/src/messaging/outbound/diagnostics.ts +31 -355
  55. package/src/messaging/outbound/durable-message-adapter.ts +20 -16
  56. package/src/messaging/outbound/durable-queue-adapter.ts +20 -7
  57. package/src/messaging/outbound/media.ts +24 -13
  58. package/src/messaging/outbound/reply-enqueue-media.ts +181 -0
  59. package/src/messaging/outbound/reply-enqueue.ts +46 -155
  60. package/src/messaging/outbound/send-params.ts +3 -0
  61. package/src/messaging/outbound/send.ts +19 -10
  62. package/src/messaging/outbound/session-route.ts +18 -3
  63. package/src/openclaw/channel-runtime-contracts.ts +76 -0
  64. package/src/openclaw/config-runtime.ts +13 -7
  65. package/src/openclaw/inbound-session-runtime.ts +7 -3
  66. package/src/openclaw/ingress-runtime.ts +17 -27
  67. package/src/openclaw/reply-runtime.ts +54 -59
  68. package/src/openclaw/routing-runtime.ts +35 -18
  69. package/src/openclaw/runtime-surface.ts +156 -12
  70. package/src/openclaw/sdk-helpers.ts +8 -1
  71. package/src/openclaw/session-route-runtime.ts +12 -12
  72. package/src/plugin/ack-outbox-runtime-group.ts +264 -0
  73. package/src/plugin/bridge-ack-facade.ts +137 -0
  74. package/src/plugin/bridge-connection-facade.ts +111 -0
  75. package/src/plugin/bridge-diagnostics-facade.ts +23 -0
  76. package/src/plugin/bridge-drain-facade.ts +98 -0
  77. package/src/plugin/bridge-extended-diagnostics-facade.ts +149 -0
  78. package/src/plugin/bridge-file-transfer-push-facade.ts +140 -0
  79. package/src/plugin/bridge-lifecycle.ts +156 -0
  80. package/src/plugin/bridge-media-facade.ts +241 -0
  81. package/src/plugin/bridge-outbox-facade.ts +182 -0
  82. package/src/plugin/bridge-runtime-helpers.ts +266 -0
  83. package/src/plugin/bridge-runtime-snapshots.ts +104 -0
  84. package/src/plugin/bridge-runtime-surface-facade.ts +8 -0
  85. package/src/plugin/bridge-status-facade.ts +76 -0
  86. package/src/plugin/bridge-status-worker-facade.ts +72 -0
  87. package/src/plugin/bridge-support-runtime.ts +137 -0
  88. package/src/plugin/bridge-surface-handlers-group.ts +242 -0
  89. package/src/plugin/bridge-surface-helpers.ts +28 -0
  90. package/src/plugin/capabilities.ts +1 -3
  91. package/src/plugin/channel-components.ts +289 -0
  92. package/src/plugin/channel-inbound-helpers.ts +149 -0
  93. package/src/plugin/channel-plugin-bridge-group.ts +129 -0
  94. package/src/plugin/channel-plugin-surface-group.ts +202 -0
  95. package/src/plugin/channel-runtime-builders-delivery.ts +513 -0
  96. package/src/plugin/channel-runtime-builders-status.ts +331 -0
  97. package/src/plugin/channel-runtime-builders.ts +25 -0
  98. package/src/plugin/channel-runtime-constants.ts +40 -0
  99. package/src/plugin/channel-runtime-types.ts +146 -0
  100. package/src/plugin/channel-send-runtime-group.ts +37 -0
  101. package/src/plugin/channel-send.ts +226 -0
  102. package/src/plugin/channel-utils.ts +102 -0
  103. package/src/plugin/config.ts +24 -3
  104. package/src/plugin/connection-handlers-helpers.ts +254 -0
  105. package/src/plugin/connection-handlers.ts +440 -0
  106. package/src/plugin/connection-state-helpers.ts +159 -0
  107. package/src/plugin/connection-state-runtime-group.ts +51 -0
  108. package/src/plugin/connection-state.ts +527 -0
  109. package/src/plugin/diagnostics-handlers.ts +211 -0
  110. package/src/plugin/error-message.ts +15 -0
  111. package/src/plugin/file-ack-runtime.ts +284 -0
  112. package/src/plugin/file-inbound-abort.ts +112 -0
  113. package/src/plugin/file-inbound-chunk.ts +146 -0
  114. package/src/plugin/file-inbound-complete.ts +153 -0
  115. package/src/plugin/file-inbound-handlers.ts +19 -0
  116. package/src/plugin/file-inbound-init.ts +122 -0
  117. package/src/plugin/file-inbound-runtime.ts +51 -0
  118. package/src/plugin/file-inbound-state.ts +62 -0
  119. package/src/plugin/file-transfer-logs.ts +227 -0
  120. package/src/plugin/file-transfer-orchestrator-chunk.ts +135 -0
  121. package/src/plugin/file-transfer-orchestrator.ts +304 -0
  122. package/src/plugin/file-transfer-runtime-group.ts +102 -0
  123. package/src/plugin/file-transfer-send.ts +89 -0
  124. package/src/plugin/file-transfer-setup.ts +206 -0
  125. package/src/plugin/gateway-event-context.ts +41 -0
  126. package/src/plugin/gateway-runtime.ts +14 -4
  127. package/src/plugin/inbound-acceptance.ts +107 -0
  128. package/src/plugin/inbound-handlers.ts +248 -0
  129. package/src/plugin/inbound-surface-handlers-group.ts +152 -0
  130. package/src/plugin/media-dedupe-runtime.ts +90 -0
  131. package/src/plugin/media-orchestrators-runtime-group.ts +316 -0
  132. package/src/plugin/message-ack-runtime.ts +284 -0
  133. package/src/plugin/message-send.ts +16 -6
  134. package/src/plugin/messaging.ts +98 -36
  135. package/src/plugin/outbound.ts +50 -8
  136. package/src/plugin/outbox-ack-logs.ts +136 -0
  137. package/src/plugin/outbox-ack-outcome.ts +128 -0
  138. package/src/plugin/outbox-drain-ack.ts +145 -0
  139. package/src/plugin/outbox-drain-failure.ts +84 -0
  140. package/src/plugin/outbox-drain-loop.ts +554 -0
  141. package/src/plugin/outbox-drain-post-push.ts +159 -0
  142. package/src/plugin/outbox-drain-runtime.ts +141 -0
  143. package/src/plugin/outbox-drain-schedule.ts +116 -0
  144. package/src/plugin/outbox-file-push-flow.ts +69 -0
  145. package/src/plugin/outbox-push-route-runtime-group.ts +81 -0
  146. package/src/plugin/outbox-push.ts +267 -0
  147. package/src/plugin/outbox-route.ts +181 -0
  148. package/src/plugin/outbox-text-push-flow.ts +90 -0
  149. package/src/plugin/runtime-diagnostics-assembler.ts +183 -0
  150. package/src/plugin/runtime-diagnostics-helpers.ts +302 -0
  151. package/src/plugin/runtime-diagnostics-payload-builders.ts +171 -0
  152. package/src/plugin/runtime-diagnostics-snapshot.ts +31 -0
  153. package/src/plugin/setup.ts +33 -6
  154. package/src/plugin/state-store.ts +249 -0
  155. package/src/plugin/state-transient-runtime-group.ts +105 -0
  156. package/src/plugin/status-runtime.ts +251 -0
  157. package/src/plugin/status.ts +33 -7
  158. package/src/plugin/target-runtime.ts +141 -0
  159. package/src/plugin/target-status-runtime-group.ts +130 -0
  160. package/src/plugin/transient-state-runtime.ts +82 -0
  161. package/src/runtime/outbound-ack-timeout.ts +5 -3
  162. package/src/runtime/outbound-flags.ts +24 -8
  163. package/src/runtime/status-snapshots.ts +36 -7
  164. package/src/runtime/status-worker.ts +34 -4
@@ -0,0 +1,149 @@
1
+ import type { buildIntegratedDiagnostics as buildIntegratedDiagnosticsFromRuntime } from '../core/status.ts';
2
+ import type {
3
+ BncrAckObservability,
4
+ BncrDeadLetterDiagnosticsSummary,
5
+ BncrOutboxQueueDiagnostics,
6
+ } from '../core/types.ts';
7
+ import type { OpenClawChannelRuntimeSurfaceDiagnostics } from '../openclaw/runtime-surface.ts';
8
+ import {
9
+ buildConnectionRuntimeSnapshot,
10
+ buildOutboundRuntimeSnapshot,
11
+ buildRegisterRuntimeSnapshot,
12
+ } from './bridge-surface-helpers.ts';
13
+ import { createBncrExtendedDiagnosticsAssembler } from './runtime-diagnostics-snapshot.ts';
14
+
15
+ type RuntimeStatusInput = Parameters<typeof buildIntegratedDiagnosticsFromRuntime>[0];
16
+ type IntegratedDiagnostics = ReturnType<typeof buildIntegratedDiagnosticsFromRuntime>;
17
+ type ExtendedDiagnosticsOptions = {
18
+ runtimeStatusInput?: RuntimeStatusInput;
19
+ integratedDiagnostics?: IntegratedDiagnostics;
20
+ };
21
+
22
+ export function createBncrBridgeExtendedDiagnosticsFacade(runtime: {
23
+ normalizeAccountId: (accountId: string) => string;
24
+ buildIntegratedDiagnostics: (
25
+ accountId: string,
26
+ runtimeStatusInput?: RuntimeStatusInput,
27
+ ) => IntegratedDiagnostics;
28
+ buildOutboxDiagnostics: (accountId: string) => BncrOutboxQueueDiagnostics;
29
+ buildRuntimeAckObservability: (accountId: string) => BncrAckObservability;
30
+ getCounter: (map: Map<string, number>, accountId: string) => number;
31
+ prePushGuardSkipCountByAccount: Map<string, number>;
32
+ lastPrePushGuardSkipAtByAccount: Map<string, number>;
33
+ lastPrePushGuardSkipReasonByAccount: Map<string, string>;
34
+ hasGatewayContext: () => boolean;
35
+ buildRuntimeSurfaceDiagnostics: () => OpenClawChannelRuntimeSurfaceDiagnostics;
36
+ getRegisterState: () => {
37
+ bridgeId: string;
38
+ gatewayPid: number;
39
+ pluginVersion: string | null;
40
+ pluginSource: string | null;
41
+ lastApiInstanceId: string | null;
42
+ lastRegistryFingerprint: string | null;
43
+ registerCount: number;
44
+ firstRegisterAt: number | null;
45
+ lastRegisterAt: number | null;
46
+ lastApiRebindAt: number | null;
47
+ apiGeneration: number;
48
+ registerTraceRecent: ReturnType<typeof buildRegisterRuntimeSnapshot>['registerTraceRecent'];
49
+ lastDriftSnapshot: ReturnType<typeof buildRegisterRuntimeSnapshot>['lastDriftSnapshot'];
50
+ };
51
+ buildRegisterTraceSummary: () => ReturnType<
52
+ typeof import('../core/register-trace.ts')['buildRegisterTraceSummary']
53
+ >;
54
+ activeConnectionCount: (accountId: string) => number;
55
+ getConnectionState: () => {
56
+ lastGatewayContextAt: number | null;
57
+ primaryLeaseId: string | null;
58
+ connectionEpoch: number;
59
+ acceptedConnections: number;
60
+ lastConnectAt: number | null;
61
+ lastDisconnectAt: number | null;
62
+ lastActivityAtGlobal: number | null;
63
+ lastInboundAtGlobal: number | null;
64
+ lastAckAtGlobal: number | null;
65
+ recentConnections: ReturnType<typeof buildConnectionRuntimeSnapshot>['recentConnections'];
66
+ };
67
+ getOutboundState: () => {
68
+ outboundEnqueueCountByAccount: Map<string, number>;
69
+ lastOutboundEnqueueAtByAccount: Map<string, number>;
70
+ };
71
+ buildDeadLetterDiagnostics: (accountId: string) => BncrDeadLetterDiagnosticsSummary;
72
+ bridgeVersion: number;
73
+ staleCounters: {
74
+ staleConnect: number;
75
+ staleInbound: number;
76
+ staleActivity: number;
77
+ staleAck: number;
78
+ staleFileInit: number;
79
+ staleFileChunk: number;
80
+ staleFileComplete: number;
81
+ staleFileAbort: number;
82
+ lastStaleAt: number | null;
83
+ };
84
+ now: () => number;
85
+ }) {
86
+ const assemble = createBncrExtendedDiagnosticsAssembler({
87
+ normalizeAccountId: runtime.normalizeAccountId,
88
+ buildIntegratedDiagnostics: runtime.buildIntegratedDiagnostics,
89
+ buildOutboxDiagnostics: runtime.buildOutboxDiagnostics,
90
+ buildRuntimeAckObservability: runtime.buildRuntimeAckObservability,
91
+ getCounter: runtime.getCounter,
92
+ prePushGuardSkipCountByAccount: runtime.prePushGuardSkipCountByAccount,
93
+ lastPrePushGuardSkipAtByAccount: runtime.lastPrePushGuardSkipAtByAccount,
94
+ lastPrePushGuardSkipReasonByAccount: runtime.lastPrePushGuardSkipReasonByAccount,
95
+ hasGatewayContext: runtime.hasGatewayContext,
96
+ buildRuntimeSurfaceDiagnostics: runtime.buildRuntimeSurfaceDiagnostics,
97
+ getRegisterRuntime: () => {
98
+ const registerState = runtime.getRegisterState();
99
+ return buildRegisterRuntimeSnapshot({
100
+ bridgeId: registerState.bridgeId,
101
+ gatewayPid: registerState.gatewayPid,
102
+ pluginVersion: registerState.pluginVersion,
103
+ pluginSource: registerState.pluginSource,
104
+ lastApiInstanceId: registerState.lastApiInstanceId,
105
+ lastRegistryFingerprint: registerState.lastRegistryFingerprint,
106
+ registerCount: registerState.registerCount,
107
+ firstRegisterAt: registerState.firstRegisterAt,
108
+ lastRegisterAt: registerState.lastRegisterAt,
109
+ lastApiRebindAt: registerState.lastApiRebindAt,
110
+ apiGeneration: registerState.apiGeneration,
111
+ registerTraceRecent: registerState.registerTraceRecent,
112
+ lastDriftSnapshot: registerState.lastDriftSnapshot ?? null,
113
+ });
114
+ },
115
+ buildRegisterTraceSummary: runtime.buildRegisterTraceSummary,
116
+ activeConnectionCount: runtime.activeConnectionCount,
117
+ getConnectionRuntime: () => {
118
+ const connectionState = runtime.getConnectionState();
119
+ return buildConnectionRuntimeSnapshot({
120
+ lastGatewayContextAt: connectionState.lastGatewayContextAt,
121
+ primaryLeaseId: connectionState.primaryLeaseId,
122
+ connectionEpoch: connectionState.connectionEpoch,
123
+ acceptedConnections: connectionState.acceptedConnections,
124
+ lastConnectAt: connectionState.lastConnectAt,
125
+ lastDisconnectAt: connectionState.lastDisconnectAt,
126
+ lastActivityAtGlobal: connectionState.lastActivityAtGlobal,
127
+ lastInboundAtGlobal: connectionState.lastInboundAtGlobal,
128
+ lastAckAtGlobal: connectionState.lastAckAtGlobal,
129
+ recentConnections: connectionState.recentConnections,
130
+ });
131
+ },
132
+ getOutboundRuntime: () => {
133
+ const outboundState = runtime.getOutboundState();
134
+ return buildOutboundRuntimeSnapshot({
135
+ outboundEnqueueCountByAccount: outboundState.outboundEnqueueCountByAccount,
136
+ lastOutboundEnqueueAtByAccount: outboundState.lastOutboundEnqueueAtByAccount,
137
+ });
138
+ },
139
+ buildDeadLetterDiagnostics: runtime.buildDeadLetterDiagnostics,
140
+ bridgeVersion: runtime.bridgeVersion,
141
+ staleCounters: runtime.staleCounters,
142
+ now: runtime.now,
143
+ });
144
+
145
+ return {
146
+ buildExtendedDiagnostics: (accountId: string, options: ExtendedDiagnosticsOptions = {}) =>
147
+ assemble(accountId, options),
148
+ };
149
+ }
@@ -0,0 +1,140 @@
1
+ import {
2
+ buildFileTransferPushOkArgs,
3
+ buildFileTransferPushSuccessArgs,
4
+ } from '../core/outbox-file-transfer-bookkeeping.ts';
5
+ import {
6
+ buildFileTransferBroadcastPayload,
7
+ buildFileTransferRouteSelectArgs,
8
+ } from '../core/outbox-file-transfer-success.ts';
9
+ import type { BncrConnection, BncrRoute, OutboxEntry } from '../core/types.ts';
10
+
11
+ export function createBncrBridgeFileTransferPushFacade(runtime: {
12
+ pushEvent: string;
13
+ getGatewayContext: () => {
14
+ broadcastToConnIds: (event: string, payload: unknown, connIds: ReadonlySet<string>) => void;
15
+ } | null;
16
+ transferMediaToBncrClient: (params: {
17
+ accountId: string;
18
+ sessionKey: string;
19
+ route: BncrRoute;
20
+ mediaUrl: string;
21
+ mediaLocalRoots?: readonly string[];
22
+ }) => Promise<{
23
+ mode: 'base64' | 'chunk';
24
+ mimeType?: string;
25
+ fileName?: string;
26
+ mediaBase64?: string;
27
+ path?: string;
28
+ }>;
29
+ buildFileTransferOutboundFrame: (params: {
30
+ entry: OutboxEntry;
31
+ meta: Record<string, unknown>;
32
+ media: { fileName?: string; mimeType?: string; path?: string; base64?: string; type?: string };
33
+ mediaUrl: string;
34
+ }) => Record<string, unknown>;
35
+ logOutboxRouteSelect: (args: {
36
+ messageId: string;
37
+ accountId: string;
38
+ kind?: 'file-transfer';
39
+ routeReason: string;
40
+ connIds: Iterable<string>;
41
+ ownerConnId: string;
42
+ ownerClientId: string;
43
+ recentInboundReachable: boolean;
44
+ event: string;
45
+ }) => void;
46
+ recordOutboxPushSuccess: (args: {
47
+ entry: OutboxEntry;
48
+ connIds: Iterable<string>;
49
+ ownerConnId?: string;
50
+ ownerClientId?: string;
51
+ clearLastError?: boolean;
52
+ }) => void;
53
+ logOutboxPushOkSummary: (messageId: string) => void;
54
+ logOutboxPushOk: (args: {
55
+ messageId: string;
56
+ accountId: string;
57
+ kind?: 'file-transfer';
58
+ connIds: Iterable<string>;
59
+ ownerConnId: string;
60
+ ownerClientId: string;
61
+ recentInboundReachable: boolean;
62
+ event: string;
63
+ }) => void;
64
+ handleFileTransferPushFailure: (args: { entry: OutboxEntry; error: unknown }) => void;
65
+ handleFileTransferPushGuardFailure: (args: {
66
+ entry: OutboxEntry;
67
+ guard: {
68
+ reason: 'media-url-missing' | 'no-gateway-context' | 'no-active-connection';
69
+ lastError: string;
70
+ recentInboundReachable?: boolean;
71
+ };
72
+ }) => void;
73
+ }) {
74
+ const pushFileTransferSuccessPath = async (args: {
75
+ entry: OutboxEntry;
76
+ meta: Record<string, unknown>;
77
+ owner: BncrConnection | null;
78
+ connIds: Iterable<string>;
79
+ recentInboundReachable: boolean;
80
+ routeReason: string;
81
+ mediaUrl: string;
82
+ }): Promise<void> => {
83
+ const media = await runtime.transferMediaToBncrClient({
84
+ accountId: args.entry.accountId,
85
+ sessionKey: args.entry.sessionKey,
86
+ route: args.entry.route,
87
+ mediaUrl: args.mediaUrl,
88
+ mediaLocalRoots: Array.isArray(args.meta.mediaLocalRoots)
89
+ ? args.meta.mediaLocalRoots.filter((v): v is string => typeof v === 'string')
90
+ : undefined,
91
+ });
92
+ const frame = runtime.buildFileTransferOutboundFrame({
93
+ entry: args.entry,
94
+ meta: args.meta,
95
+ media,
96
+ mediaUrl: args.mediaUrl,
97
+ });
98
+
99
+ runtime.getGatewayContext()!.broadcastToConnIds(
100
+ runtime.pushEvent,
101
+ buildFileTransferBroadcastPayload({
102
+ frame,
103
+ messageId: args.entry.messageId,
104
+ }),
105
+ new Set(args.connIds),
106
+ );
107
+ runtime.logOutboxRouteSelect(
108
+ buildFileTransferRouteSelectArgs({
109
+ entry: args.entry,
110
+ connIds: args.connIds,
111
+ routeReason: args.routeReason,
112
+ recentInboundReachable: args.recentInboundReachable,
113
+ owner: args.owner,
114
+ event: runtime.pushEvent,
115
+ }),
116
+ );
117
+ runtime.recordOutboxPushSuccess(
118
+ buildFileTransferPushSuccessArgs({
119
+ entry: args.entry,
120
+ connIds: args.connIds,
121
+ owner: args.owner,
122
+ }),
123
+ );
124
+ runtime.logOutboxPushOkSummary(args.entry.messageId);
125
+ runtime.logOutboxPushOk(
126
+ buildFileTransferPushOkArgs({
127
+ entry: args.entry,
128
+ connIds: args.connIds,
129
+ recentInboundReachable: args.recentInboundReachable,
130
+ event: runtime.pushEvent,
131
+ }),
132
+ );
133
+ };
134
+
135
+ return {
136
+ pushFileTransferSuccessPath,
137
+ handleFileTransferPushFailure: runtime.handleFileTransferPushFailure,
138
+ handleFileTransferPushGuardFailure: runtime.handleFileTransferPushGuardFailure,
139
+ };
140
+ }
@@ -0,0 +1,156 @@
1
+ import path from 'node:path';
2
+ import type { OpenClawPluginServiceContext } from 'openclaw/plugin-sdk/core';
3
+ import { BNCR_DEFAULT_ACCOUNT_ID } from '../core/accounts.ts';
4
+ import type { BncrChannelPolicyConfig } from '../core/policy.ts';
5
+ import { resolveBncrConfigWarnings } from '../core/policy.ts';
6
+ import type { BncrChannelConfigRoot } from './channel-runtime-types.ts';
7
+
8
+ export function buildBncrBridgeCleanupDebugInfo(args: {
9
+ bridgeId: string;
10
+ reason: string;
11
+ messageAckWaiters: number;
12
+ fileAckWaiters: number;
13
+ earlyFileAcks: number;
14
+ outbox: number;
15
+ runningDrainAccounts: number;
16
+ channelAccountWorkers: number;
17
+ hasSaveTimer: boolean;
18
+ hasPushTimer: boolean;
19
+ }) {
20
+ return {
21
+ bridge: args.bridgeId,
22
+ reason: args.reason,
23
+ messageAckWaiters: args.messageAckWaiters,
24
+ fileAckWaiters: args.fileAckWaiters,
25
+ earlyFileAcks: args.earlyFileAcks,
26
+ outbox: args.outbox,
27
+ runningDrainAccounts: args.runningDrainAccounts,
28
+ channelAccountWorkers: args.channelAccountWorkers,
29
+ hasSaveTimer: args.hasSaveTimer,
30
+ hasPushTimer: args.hasPushTimer,
31
+ };
32
+ }
33
+
34
+ export function startBncrBridgeService(
35
+ runtime: {
36
+ bridgeId: string;
37
+ setStopped: (value: boolean) => void;
38
+ setStatePath: (value: string) => void;
39
+ getRuntimeConfig: () => BncrChannelConfigRoot;
40
+ initializeCanonicalAgentId: (cfg: BncrChannelConfigRoot) => void;
41
+ logWarn: (
42
+ scope: string | undefined,
43
+ message: string,
44
+ options?: { debugOnly?: boolean },
45
+ ) => void;
46
+ loadState: () => Promise<void>;
47
+ setDebugFlag: (value: boolean) => void;
48
+ refreshDebugFlagFromConfig: (options?: { forceLog?: boolean }) => Promise<void>;
49
+ buildIntegratedDiagnostics: (accountId: string) => {
50
+ regression: { totalKnownRoutes: number; ok: boolean };
51
+ health: { pending: number; deadLetter: number };
52
+ };
53
+ logInfo: (
54
+ scope: string | undefined,
55
+ message: string,
56
+ options?: { debugOnly?: boolean },
57
+ ) => void;
58
+ getChannelConfigRoot: (
59
+ cfg: BncrChannelConfigRoot,
60
+ ) => BncrChannelPolicyConfig | null | undefined;
61
+ },
62
+ ctx: OpenClawPluginServiceContext,
63
+ debug?: boolean,
64
+ ) {
65
+ runtime.setStopped(false);
66
+ runtime.setStatePath(path.join(ctx.stateDir, 'bncr-bridge-state.json'));
67
+ return (async () => {
68
+ try {
69
+ const cfg = runtime.getRuntimeConfig();
70
+ runtime.initializeCanonicalAgentId(cfg);
71
+ for (const warning of resolveBncrConfigWarnings(runtime.getChannelConfigRoot(cfg))) {
72
+ runtime.logWarn('config', warning);
73
+ }
74
+ } catch {
75
+ // ignore startup canonical agent initialization errors
76
+ }
77
+ await runtime.loadState();
78
+ if (typeof debug === 'boolean') runtime.setDebugFlag(debug);
79
+ await runtime.refreshDebugFlagFromConfig({ forceLog: true });
80
+ const bootDiag = runtime.buildIntegratedDiagnostics(BNCR_DEFAULT_ACCOUNT_ID);
81
+ runtime.logInfo(
82
+ 'startup',
83
+ `bridge=${runtime.bridgeId} routes=${bootDiag.regression.totalKnownRoutes}`,
84
+ );
85
+ runtime.logInfo(
86
+ 'debug',
87
+ `service started bridge=${runtime.bridgeId} diag.ok=${bootDiag.regression.ok} routes=${bootDiag.regression.totalKnownRoutes} pending=${bootDiag.health.pending} dead=${bootDiag.health.deadLetter}`,
88
+ { debugOnly: true },
89
+ );
90
+ })();
91
+ }
92
+
93
+ export function cleanupBncrBridgeRuntime(
94
+ runtime: {
95
+ bridgeId: string;
96
+ logInfo: (
97
+ scope: string | undefined,
98
+ message: string,
99
+ options?: { debugOnly?: boolean },
100
+ ) => void;
101
+ setStopped: (value: boolean) => void;
102
+ clearAllChannelAccountWorkers: (reason: string) => void;
103
+ getMessageAckWaiterCount: () => number;
104
+ getFileAckWaiterCount: () => number;
105
+ getEarlyFileAckCount: () => number;
106
+ getOutboxCount: () => number;
107
+ getRunningDrainAccountCount: () => number;
108
+ getChannelAccountWorkerCount: () => number;
109
+ hasSaveTimer: () => boolean;
110
+ hasPushTimer: () => boolean;
111
+ clearSaveTimer: () => void;
112
+ clearPushTimer: () => void;
113
+ clearAllMessageAckWaiters: (result: 'timeout') => void;
114
+ clearAllFileAckWaiters: (reason: string) => void;
115
+ },
116
+ reason: string,
117
+ ) {
118
+ runtime.logInfo(
119
+ 'lifecycle',
120
+ `cleanup ${JSON.stringify(
121
+ buildBncrBridgeCleanupDebugInfo({
122
+ bridgeId: runtime.bridgeId,
123
+ reason,
124
+ messageAckWaiters: runtime.getMessageAckWaiterCount(),
125
+ fileAckWaiters: runtime.getFileAckWaiterCount(),
126
+ earlyFileAcks: runtime.getEarlyFileAckCount(),
127
+ outbox: runtime.getOutboxCount(),
128
+ runningDrainAccounts: runtime.getRunningDrainAccountCount(),
129
+ channelAccountWorkers: runtime.getChannelAccountWorkerCount(),
130
+ hasSaveTimer: runtime.hasSaveTimer(),
131
+ hasPushTimer: runtime.hasPushTimer(),
132
+ }),
133
+ )}`,
134
+ { debugOnly: true },
135
+ );
136
+ runtime.setStopped(true);
137
+ runtime.clearAllChannelAccountWorkers(reason);
138
+ runtime.clearSaveTimer();
139
+ runtime.clearPushTimer();
140
+ runtime.clearAllMessageAckWaiters('timeout');
141
+ runtime.clearAllFileAckWaiters(reason);
142
+ }
143
+
144
+ export async function stopBncrBridgeService(runtime: {
145
+ cleanupRuntime: (reason: string) => void;
146
+ flushState: () => Promise<void>;
147
+ logInfo: (scope: string | undefined, message: string, options?: { debugOnly?: boolean }) => void;
148
+ }) {
149
+ runtime.cleanupRuntime('service stopped');
150
+ await runtime.flushState();
151
+ runtime.logInfo('debug', 'service stopped', { debugOnly: true });
152
+ }
153
+
154
+ export function shutdownBncrBridgeService(runtime: { cleanupRuntime: (reason: string) => void }) {
155
+ runtime.cleanupRuntime('shutdown');
156
+ }
@@ -0,0 +1,241 @@
1
+ import type { BncrRoute, FileSendTransferState } from '../core/types.ts';
2
+ import type {
3
+ NormalizedReplyPayload,
4
+ OutboundReplyTargetPolicy,
5
+ ReplyMediaEntriesParams,
6
+ ReplyPayloadInput,
7
+ } from '../messaging/outbound/reply-enqueue.ts';
8
+ import type { OpenClawLoadedMedia } from '../openclaw/media-runtime.ts';
9
+ import { loadOpenClawWebMedia } from '../openclaw/media-runtime.ts';
10
+
11
+ type RuntimeMediaApiHolder = Parameters<typeof loadOpenClawWebMedia>[0];
12
+
13
+ export function createBncrBridgeMediaFacade(runtime: {
14
+ getApi: () => RuntimeMediaApiHolder;
15
+ resolveOutboundFileName: (args: {
16
+ mediaUrl: string;
17
+ fileName?: string;
18
+ mimeType?: string;
19
+ }) => string;
20
+ outboxRoute: {
21
+ buildTransferRouteDiagnostics: (args: {
22
+ accountId: string;
23
+ recentInboundReachable: boolean;
24
+ }) => unknown;
25
+ selectTransferConnIds: (args: {
26
+ directConnIds: Set<string>;
27
+ recentConnIds: Set<string>;
28
+ recentInboundReachable: boolean;
29
+ }) => ReadonlySet<string>;
30
+ };
31
+ fileTransferOrchestrator: {
32
+ waitChunkAck: (params: {
33
+ transferId: string;
34
+ chunkIndex: number;
35
+ timeoutMs?: number;
36
+ }) => Promise<void>;
37
+ waitCompleteAck: (params: {
38
+ transferId: string;
39
+ timeoutMs?: number;
40
+ }) => Promise<{ path: string }>;
41
+ transferMediaToBncrClient: (params: {
42
+ accountId: string;
43
+ sessionKey: string;
44
+ route: BncrRoute;
45
+ mediaUrl: string;
46
+ mediaLocalRoots?: readonly string[];
47
+ }) => Promise<{
48
+ mode: 'base64' | 'chunk';
49
+ mimeType?: string;
50
+ fileName?: string;
51
+ mediaBase64?: string;
52
+ path?: string;
53
+ }>;
54
+ };
55
+ replyMediaOrchestrator: {
56
+ enqueueFromReply: (params: {
57
+ accountId: string;
58
+ sessionKey: string;
59
+ route: BncrRoute;
60
+ payload: ReplyPayloadInput;
61
+ mediaLocalRoots?: readonly string[];
62
+ replyTargetPolicy?: OutboundReplyTargetPolicy;
63
+ }) => void;
64
+ enqueueReplyMediaEntries: (params: ReplyMediaEntriesParams) => void;
65
+ };
66
+ logInfoJson: (
67
+ scope: string | undefined,
68
+ event: string,
69
+ payload: Record<string, unknown>,
70
+ options?: { debugOnly?: boolean },
71
+ ) => void;
72
+ buildEnqueueFromReplyDebugInfo: (args: {
73
+ accountId: string;
74
+ sessionKey: string;
75
+ route: BncrRoute;
76
+ payload: NormalizedReplyPayload;
77
+ }) => Record<string, unknown>;
78
+ fileTransferLogs: {
79
+ logFileChunkDiag: (args: {
80
+ accountId: string;
81
+ sessionKey: string;
82
+ mediaUrl: string;
83
+ hasGatewayContext: boolean;
84
+ activeConnectionKey: string | null;
85
+ ownerConnId?: string;
86
+ ownerClientId?: string;
87
+ directConnIds: Iterable<string>;
88
+ recentInboundReachable: boolean;
89
+ recentConnIds: Iterable<string>;
90
+ accountConnections: Array<{
91
+ connId: string;
92
+ clientId?: string;
93
+ connectedAt: number;
94
+ lastSeenAt: number;
95
+ }>;
96
+ }) => void;
97
+ logFileTransferStart: (args: {
98
+ transferId: string;
99
+ accountId: string;
100
+ sessionKey: string;
101
+ mediaUrl: string;
102
+ fileName: string;
103
+ mimeType?: string;
104
+ fileSize: number;
105
+ chunkSize: number;
106
+ totalChunks: number;
107
+ connIds: ReadonlySet<string>;
108
+ ownerConnId?: string;
109
+ ownerClientId?: string;
110
+ }) => void;
111
+ logFileTransferChunkSend: (args: {
112
+ transferId: string;
113
+ accountId: string;
114
+ chunkIndex: number;
115
+ attempt: number;
116
+ offset: number;
117
+ size: number;
118
+ connIds: ReadonlySet<string>;
119
+ }) => void;
120
+ logFileTransferChunkAck: (args: {
121
+ transferId: string;
122
+ accountId: string;
123
+ chunkIndex: number;
124
+ attempt: number;
125
+ }) => void;
126
+ logFileTransferChunkAckFail: (args: {
127
+ transferId: string;
128
+ accountId: string;
129
+ chunkIndex: number;
130
+ attempt: number;
131
+ error: unknown;
132
+ }) => void;
133
+ logFileTransferCompleteSend: (args: {
134
+ transferId: string;
135
+ accountId: string;
136
+ connIds: ReadonlySet<string>;
137
+ }) => void;
138
+ logFileTransferCompleteAck: (args: {
139
+ transferId: string;
140
+ accountId: string;
141
+ payload: { path: string };
142
+ }) => void;
143
+ buildInitialFileSendTransferState: (args: {
144
+ transferId: string;
145
+ accountId: string;
146
+ sessionKey: string;
147
+ route: BncrRoute;
148
+ fileName: string;
149
+ mimeType?: string;
150
+ fileSize: number;
151
+ chunkSize: number;
152
+ totalChunks: number;
153
+ fileSha256: string;
154
+ ownerConnId?: string;
155
+ ownerClientId?: string;
156
+ normalizeAccountId: (accountId: string) => string;
157
+ }) => FileSendTransferState;
158
+ };
159
+ normalizeAccountId: (accountId: string) => string;
160
+ }) {
161
+ const loadOutboundTransferMedia = async (params: {
162
+ mediaUrl: string;
163
+ mediaLocalRoots?: readonly string[];
164
+ }): Promise<{
165
+ loaded: OpenClawLoadedMedia;
166
+ size: number;
167
+ mimeType?: string;
168
+ fileName: string;
169
+ }> => {
170
+ const loaded = await loadOpenClawWebMedia(runtime.getApi(), params.mediaUrl, {
171
+ localRoots: params.mediaLocalRoots,
172
+ maxBytes: 50 * 1024 * 1024,
173
+ });
174
+ const size = loaded.buffer.byteLength;
175
+ const mimeType = loaded.contentType;
176
+ const fileName = runtime.resolveOutboundFileName({
177
+ mediaUrl: params.mediaUrl,
178
+ fileName: loaded.fileName,
179
+ mimeType,
180
+ });
181
+ return { loaded, size, mimeType, fileName };
182
+ };
183
+
184
+ const logEnqueueFromReply = (args: {
185
+ accountId: string;
186
+ sessionKey: string;
187
+ route: BncrRoute;
188
+ payload: NormalizedReplyPayload;
189
+ }) => {
190
+ runtime.logInfoJson(
191
+ 'outbound',
192
+ 'enqueue-from-reply',
193
+ runtime.buildEnqueueFromReplyDebugInfo(args),
194
+ {
195
+ debugOnly: true,
196
+ },
197
+ );
198
+ };
199
+
200
+ return {
201
+ loadOutboundTransferMedia,
202
+ buildTransferRouteDiagnostics: (args: { accountId: string; recentInboundReachable: boolean }) =>
203
+ runtime.outboxRoute.buildTransferRouteDiagnostics(args),
204
+ selectTransferConnIds: (args: {
205
+ directConnIds: Set<string>;
206
+ recentConnIds: Set<string>;
207
+ recentInboundReachable: boolean;
208
+ }) => runtime.outboxRoute.selectTransferConnIds(args),
209
+ waitChunkAck: runtime.fileTransferOrchestrator.waitChunkAck,
210
+ waitCompleteAck: runtime.fileTransferOrchestrator.waitCompleteAck,
211
+ transferMediaToBncrClient: runtime.fileTransferOrchestrator.transferMediaToBncrClient,
212
+ enqueueFromReply: runtime.replyMediaOrchestrator.enqueueFromReply,
213
+ enqueueReplyMediaEntries: runtime.replyMediaOrchestrator.enqueueReplyMediaEntries,
214
+ logEnqueueFromReply,
215
+ logFileChunkDiag: runtime.fileTransferLogs.logFileChunkDiag,
216
+ logFileTransferStart: runtime.fileTransferLogs.logFileTransferStart,
217
+ logFileTransferChunkSend: runtime.fileTransferLogs.logFileTransferChunkSend,
218
+ logFileTransferChunkAck: runtime.fileTransferLogs.logFileTransferChunkAck,
219
+ logFileTransferChunkAckFail: runtime.fileTransferLogs.logFileTransferChunkAckFail,
220
+ logFileTransferCompleteSend: runtime.fileTransferLogs.logFileTransferCompleteSend,
221
+ logFileTransferCompleteAck: runtime.fileTransferLogs.logFileTransferCompleteAck,
222
+ buildInitialFileSendTransferState: (args: {
223
+ transferId: string;
224
+ accountId: string;
225
+ sessionKey: string;
226
+ route: BncrRoute;
227
+ fileName: string;
228
+ mimeType?: string;
229
+ fileSize: number;
230
+ chunkSize: number;
231
+ totalChunks: number;
232
+ fileSha256: string;
233
+ ownerConnId?: string;
234
+ ownerClientId?: string;
235
+ }) =>
236
+ runtime.fileTransferLogs.buildInitialFileSendTransferState({
237
+ ...args,
238
+ normalizeAccountId: runtime.normalizeAccountId,
239
+ }),
240
+ };
241
+ }