@xfxstudio/claworld 2026.4.29-testing.4 → 2026.4.30-pr190-feature.1

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.
@@ -8,7 +8,7 @@
8
8
  ],
9
9
  "name": "Claworld Persona Relay",
10
10
  "description": "Claworld relay world channel plugin for OpenClaw.",
11
- "version": "2026.4.29-testing.4",
11
+ "version": "2026.4.30-pr190-feature.1",
12
12
  "configSchema": {
13
13
  "type": "object",
14
14
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xfxstudio/claworld",
3
- "version": "2026.4.29-testing.4",
3
+ "version": "2026.4.30-pr190-feature.1",
4
4
  "description": "Claworld channel plugin for OpenClaw",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -1,6 +1,8 @@
1
1
  import { createKickoffBrief } from './relay/kickoff-text.js';
2
2
  import { normalizeAcceptedChatKickoffRecord } from './relay/kickoff-progress.js';
3
3
 
4
+ export const DEFAULT_CHAT_REQUEST_TTL_MS = 30 * 24 * 60 * 60 * 1000;
5
+
4
6
  function normalizeText(value, fallback = null) {
5
7
  if (value == null) return fallback;
6
8
  const normalized = String(value).trim();
@@ -132,6 +132,35 @@ function resolveNormalizedText(value, fallback = null) {
132
132
  return normalizeClaworldText(value, fallback);
133
133
  }
134
134
 
135
+ function resolveInboundMessageId({ delivery = {}, payload = {}, metadata = {} } = {}) {
136
+ const notification = payload.notification && typeof payload.notification === 'object' && !Array.isArray(payload.notification)
137
+ ? payload.notification
138
+ : delivery.notification && typeof delivery.notification === 'object' && !Array.isArray(delivery.notification)
139
+ ? delivery.notification
140
+ : {};
141
+ const candidates = [
142
+ delivery.deliveryId,
143
+ delivery.inboxItemId,
144
+ delivery.messageId,
145
+ delivery.eventId,
146
+ delivery.notificationId,
147
+ payload.deliveryId,
148
+ payload.inboxItemId,
149
+ payload.messageId,
150
+ payload.eventId,
151
+ payload.notificationId,
152
+ metadata.messageId,
153
+ metadata.eventId,
154
+ metadata.notificationId,
155
+ notification.notificationId,
156
+ ];
157
+ for (const candidate of candidates) {
158
+ const normalized = resolveNormalizedText(candidate, null);
159
+ if (normalized) return normalized;
160
+ }
161
+ return null;
162
+ }
163
+
135
164
  function isAgentScopedSessionKey(sessionKey) {
136
165
  return /^agent:[^:]+:/i.test(String(sessionKey || ''));
137
166
  }
@@ -274,6 +303,7 @@ function parseBridgeTimestampMs(value) {
274
303
 
275
304
  function resolveBridgeDeliveryTimestampMs({ delivery = {}, metadata = {} } = {}) {
276
305
  return parseBridgeTimestampMs(delivery?.createdAt)
306
+ || parseBridgeTimestampMs(delivery?.availableAt)
277
307
  || parseBridgeTimestampMs(delivery?.turnCreatedAt)
278
308
  || parseBridgeTimestampMs(metadata?.createdAt)
279
309
  || Date.now();
@@ -1752,6 +1782,7 @@ function buildDeliveryInboundEnvelope({
1752
1782
  commandText = null,
1753
1783
  timestamp = null,
1754
1784
  deliveryId,
1785
+ eventType = 'delivery',
1755
1786
  sessionKey,
1756
1787
  localSessionKey = null,
1757
1788
  worldId = null,
@@ -1770,13 +1801,16 @@ function buildDeliveryInboundEnvelope({
1770
1801
  const normalizedCommandText = String(commandText || '').trim();
1771
1802
  const commandBody = normalizedCommandText || rawBody;
1772
1803
  const bodyForAgent = bodyText || rawBody;
1804
+ const eventLabel = normalizePluginOptionalText(eventType) === 'delivery'
1805
+ ? 'delivery'
1806
+ : `event ${normalizePluginOptionalText(eventType)}`;
1773
1807
  const contextLines = mergeUntrustedContextLines([
1774
1808
  `[claworld peer ${remoteLabel}]`,
1775
1809
  ...(worldId ? [`[claworld world ${worldId}]`] : []),
1776
1810
  ...(conversationKey ? [`[claworld conversation ${conversationKey}]`] : []),
1777
1811
  ...(localSessionKey && localSessionKey !== sessionKey ? [`[claworld local session ${localSessionKey}]`] : []),
1778
1812
  `[claworld relay session ${sessionKey}]`,
1779
- `[claworld delivery ${deliveryId}]`,
1813
+ `[claworld ${eventLabel} ${deliveryId}]`,
1780
1814
  ], untrustedContext);
1781
1815
  const envelopeTimestamp = Number.isFinite(timestamp) ? new Date(timestamp) : new Date();
1782
1816
 
@@ -2173,7 +2207,7 @@ function resolveBoundLocalAgentId({ cfg = {}, runtimeConfig = {}, relayClient }
2173
2207
  || 'main';
2174
2208
  }
2175
2209
 
2176
- async function maybeBridgeRuntimeDelivery({
2210
+ async function maybeBridgeRuntimeInboundEvent({
2177
2211
  relayClient,
2178
2212
  runtimeConfig,
2179
2213
  runtimeAccountId,
@@ -2192,36 +2226,46 @@ async function maybeBridgeRuntimeDelivery({
2192
2226
  const payload = delivery.payload && typeof delivery.payload === 'object' && !Array.isArray(delivery.payload)
2193
2227
  ? delivery.payload
2194
2228
  : {};
2195
- const deliveryId = resolveNormalizedText(delivery.deliveryId, null);
2229
+ const eventType = resolveNormalizedText(delivery.eventType, resolveNormalizedText(event?.eventType, 'delivery'));
2230
+ const deliveryId = resolveInboundMessageId({ delivery, payload, metadata });
2196
2231
  const sessionKey = resolveNormalizedText(delivery.sessionKey, null);
2197
2232
  const contextText = resolveNormalizedText(payload.contextText, null);
2198
2233
  const incomingText = resolveNormalizedText(
2199
2234
  payload.commandText,
2200
- contextText ? null : resolveNormalizedText(payload.text, null),
2235
+ contextText ? null : resolveNormalizedText(payload.text, resolveNormalizedText(payload.body, null)),
2201
2236
  );
2202
2237
  const commandText = resolveNormalizedText(payload.commandText, incomingText);
2203
2238
  const fromAgentId = resolveNormalizedText(metadata.fromAgentId, null);
2204
- const remoteIdentity = fromAgentId || 'unknown-peer';
2239
+ const routeSessionKind = resolveNormalizedText(
2240
+ event?.route?.sessionKind,
2241
+ resolveNormalizedText(delivery.sessionKind, resolveNormalizedText(payload.sessionKind, null)),
2242
+ );
2243
+ const isRelayDelivery = eventType === 'delivery';
2244
+ const allowReply = metadata.allowReply === true || (isRelayDelivery && metadata.allowReply !== false);
2245
+ const remoteIdentity = fromAgentId
2246
+ || resolveNormalizedText(metadata.source, routeSessionKind === 'management' ? 'claworld-management' : 'unknown-peer');
2205
2247
 
2206
2248
  if (
2207
2249
  !runtime?.channel?.reply?.finalizeInboundContext
2208
2250
  || !runtime?.channel?.reply?.dispatchReplyFromConfig
2209
2251
  || !runtime?.channel?.reply?.createReplyDispatcherWithTyping
2210
2252
  ) {
2211
- logger.warn?.(`[claworld:${runtimeAccountId}] skipping delivery bridge: missing runtime bridge hooks`, {
2253
+ logger.warn?.(`[claworld:${runtimeAccountId}] skipping inbound bridge: missing runtime bridge hooks`, {
2254
+ eventType,
2212
2255
  deliveryId,
2213
2256
  sessionKey,
2214
2257
  });
2215
2258
  return { skipped: true, reason: 'missing_runtime_bridge_hooks' };
2216
2259
  }
2217
2260
  if (!deliveryId || !sessionKey || (!incomingText && !contextText)) {
2218
- logger.warn?.(`[claworld:${runtimeAccountId}] skipping delivery bridge: missing delivery payload`, {
2261
+ logger.warn?.(`[claworld:${runtimeAccountId}] skipping inbound bridge: missing payload`, {
2262
+ eventType,
2219
2263
  deliveryId,
2220
2264
  sessionKey,
2221
2265
  hasIncomingText: Boolean(incomingText),
2222
2266
  hasContextText: Boolean(contextText),
2223
2267
  });
2224
- return { skipped: true, reason: 'missing_delivery_payload' };
2268
+ return { skipped: true, reason: 'missing_inbound_payload' };
2225
2269
  }
2226
2270
 
2227
2271
  const loadedCfg = await runtime.config?.loadConfig?.() || {};
@@ -2247,7 +2291,7 @@ async function maybeBridgeRuntimeDelivery({
2247
2291
  fallbackTarget: runtimeConfig.routing?.fallbackTarget,
2248
2292
  }) || null;
2249
2293
  const worldId = resolveDeliveryWorldId(delivery);
2250
- const commandAuthorized = shouldAuthorizeBridgedCommand({
2294
+ const commandAuthorized = isRelayDelivery && shouldAuthorizeBridgedCommand({
2251
2295
  runtimeConfig,
2252
2296
  incomingText: commandText || incomingText,
2253
2297
  });
@@ -2261,6 +2305,7 @@ async function maybeBridgeRuntimeDelivery({
2261
2305
  commandText,
2262
2306
  timestamp: inboundTimestamp,
2263
2307
  deliveryId,
2308
+ eventType,
2264
2309
  sessionKey,
2265
2310
  localSessionKey,
2266
2311
  worldId,
@@ -2268,6 +2313,9 @@ async function maybeBridgeRuntimeDelivery({
2268
2313
  untrustedContext: payload.untrustedContext,
2269
2314
  });
2270
2315
  const localIdentity = normalizeClaworldText(runtimeConfig.relay?.agentId, runtimeConfig.accountId);
2316
+ const isManagementSession = routeSessionKind === 'management';
2317
+ const senderName = isManagementSession ? 'Claworld' : remoteIdentity;
2318
+ const conversationLabel = isManagementSession ? 'Claworld management' : remoteIdentity;
2271
2319
  const inboundCtx = runtime.channel.reply.finalizeInboundContext({
2272
2320
  Body,
2273
2321
  RawBody,
@@ -2282,18 +2330,18 @@ async function maybeBridgeRuntimeDelivery({
2282
2330
  OriginatingChannel: 'claworld',
2283
2331
  OriginatingFrom: remoteIdentity,
2284
2332
  OriginatingTo: remoteIdentity,
2285
- ChatType: 'direct',
2286
- SenderName: remoteIdentity,
2333
+ ChatType: isManagementSession ? 'management' : 'direct',
2334
+ SenderName: senderName,
2287
2335
  SenderId: remoteIdentity,
2288
2336
  MessageId: deliveryId,
2289
2337
  Provider: 'claworld',
2290
2338
  Surface: 'claworld',
2291
- ConversationLabel: remoteIdentity,
2339
+ ConversationLabel: conversationLabel,
2292
2340
  Timestamp: inboundTimestamp,
2293
2341
  MessageSid: deliveryId,
2294
2342
  WasMentioned: false,
2295
2343
  CommandAuthorized: commandAuthorized,
2296
- RelayDeliveryId: deliveryId,
2344
+ RelayDeliveryId: isRelayDelivery ? deliveryId : null,
2297
2345
  RelayFromAgentId: fromAgentId,
2298
2346
  UntrustedContext,
2299
2347
  });
@@ -2308,6 +2356,7 @@ async function maybeBridgeRuntimeDelivery({
2308
2356
  ctx: inboundCtx,
2309
2357
  onRecordError: (error) => {
2310
2358
  logger.error?.(`[claworld:${runtimeAccountId}] failed to record inbound session`, {
2359
+ eventType,
2311
2360
  deliveryId,
2312
2361
  sessionKey,
2313
2362
  localSessionKey,
@@ -2318,7 +2367,8 @@ async function maybeBridgeRuntimeDelivery({
2318
2367
  });
2319
2368
  }
2320
2369
 
2321
- logger.info?.(`[claworld:${runtimeAccountId}] routing delivery into runtime session`, {
2370
+ logger.info?.(`[claworld:${runtimeAccountId}] ${isRelayDelivery ? 'routing delivery into runtime session' : 'routing inbound event into runtime session'}`, {
2371
+ eventType,
2322
2372
  deliveryId,
2323
2373
  sessionKey,
2324
2374
  localSessionKey,
@@ -2327,27 +2377,29 @@ async function maybeBridgeRuntimeDelivery({
2327
2377
  routeStatus: routed?.status || null,
2328
2378
  bodyPreview: String(Body || '').slice(0, 240),
2329
2379
  rawBodyPreview: String(RawBody || '').slice(0, 240),
2330
- allowReply: metadata.allowReply !== false,
2380
+ allowReply,
2331
2381
  commandAuthorized,
2332
2382
  });
2333
2383
 
2334
- try {
2335
- const acceptedResult = await relayClient.acceptDeliveryHttp({
2336
- deliveryId,
2337
- sessionKey,
2338
- source: 'runtime_dispatch',
2339
- });
2340
- if (acceptedResult.status < 200 || acceptedResult.status >= 300) {
2341
- throw new Error(`failed to submit relay delivery acceptance: ${acceptedResult.status}`);
2384
+ if (isRelayDelivery && metadata.acceptanceRequired !== false) {
2385
+ try {
2386
+ const acceptedResult = await relayClient.acceptDeliveryHttp({
2387
+ deliveryId,
2388
+ sessionKey,
2389
+ source: 'runtime_dispatch',
2390
+ });
2391
+ if (acceptedResult.status < 200 || acceptedResult.status >= 300) {
2392
+ throw new Error(`failed to submit relay delivery acceptance: ${acceptedResult.status}`);
2393
+ }
2394
+ } catch (error) {
2395
+ logger.warn?.(`[claworld:${runtimeAccountId}] delivery acceptance acknowledgement failed`, {
2396
+ deliveryId,
2397
+ sessionKey,
2398
+ localSessionKey,
2399
+ localAgentId,
2400
+ error: error?.message || String(error),
2401
+ });
2342
2402
  }
2343
- } catch (error) {
2344
- logger.warn?.(`[claworld:${runtimeAccountId}] delivery acceptance acknowledgement failed`, {
2345
- deliveryId,
2346
- sessionKey,
2347
- localSessionKey,
2348
- localAgentId,
2349
- error: error?.message || String(error),
2350
- });
2351
2403
  }
2352
2404
 
2353
2405
  let {
@@ -2362,15 +2414,16 @@ async function maybeBridgeRuntimeDelivery({
2362
2414
  deliveryId,
2363
2415
  sessionKey,
2364
2416
  localAgentId,
2365
- allowReply: metadata.allowReply !== false,
2417
+ allowReply,
2366
2418
  logger,
2367
2419
  runtimeAccountId,
2368
2420
  inboundCtx,
2369
2421
  });
2370
2422
 
2371
2423
  const shouldRetryKickoffDispatch = (
2372
- metadata.deliveryType === 'kickoff'
2373
- && metadata.allowReply !== false
2424
+ isRelayDelivery
2425
+ && metadata.deliveryType === 'kickoff'
2426
+ && allowReply
2374
2427
  && replied !== true
2375
2428
  && runtimeOutputSummary.counts.final > 0
2376
2429
  && runtimeOutputSummary.counts.nonRenderableFinal > 0
@@ -2407,14 +2460,15 @@ async function maybeBridgeRuntimeDelivery({
2407
2460
  deliveryId,
2408
2461
  sessionKey,
2409
2462
  localAgentId,
2410
- allowReply: metadata.allowReply !== false,
2463
+ allowReply,
2411
2464
  logger,
2412
2465
  runtimeAccountId,
2413
2466
  inboundCtx,
2414
2467
  }));
2415
2468
  }
2416
2469
 
2417
- logger.info?.(`[claworld:${runtimeAccountId}] delivery bridge completed`, {
2470
+ logger.info?.(`[claworld:${runtimeAccountId}] ${isRelayDelivery ? 'delivery bridge completed' : 'inbound bridge completed'}`, {
2471
+ eventType,
2418
2472
  deliveryId,
2419
2473
  sessionKey,
2420
2474
  localSessionKey,
@@ -2874,9 +2928,9 @@ export function createClaworldChannelPlugin({
2874
2928
  sessionKey: event?.delivery?.sessionKey || null,
2875
2929
  });
2876
2930
 
2877
- if (event?.eventType === 'delivery') {
2931
+ if (event?.delivery?.sessionKey) {
2878
2932
  const runtimeContext = accountRuntimeContexts.get(accountKey) || {};
2879
- maybeBridgeRuntimeDelivery({
2933
+ maybeBridgeRuntimeInboundEvent({
2880
2934
  relayClient,
2881
2935
  runtimeConfig,
2882
2936
  runtimeAccountId,
@@ -2886,7 +2940,7 @@ export function createClaworldChannelPlugin({
2886
2940
  cfg: runtimeContext.cfg,
2887
2941
  inbound,
2888
2942
  }).catch((error) => {
2889
- logger.error?.(`[claworld:${runtimeAccountId}] delivery bridge exception`, {
2943
+ logger.error?.(`[claworld:${runtimeAccountId}] inbound bridge exception`, {
2890
2944
  error: error?.message || String(error),
2891
2945
  });
2892
2946
  });
@@ -653,10 +653,7 @@ export function projectToolAccountViewResponse({
653
653
  identityPayload = null,
654
654
  } = {}) {
655
655
  const identityReady = identityPayload?.ready === true;
656
- const bindingReady = pairingPayload?.status === 'paired';
657
- const ready = bindingReady && identityReady;
658
- const relayResolved = pairingPayload?.relayAgent?.resolved ?? null;
659
- const relayOnline = pairingPayload?.relayAgent?.online ?? null;
656
+ const ready = pairingPayload?.status === 'paired' && identityReady;
660
657
  const resolvedShareCard = identityPayload && Object.prototype.hasOwnProperty.call(identityPayload, 'shareCard')
661
658
  ? projectToolShareCard(identityPayload.shareCard)
662
659
  : undefined;
@@ -671,14 +668,7 @@ export function projectToolAccountViewResponse({
671
668
  reason: normalizeText(pairingPayload?.reason, null),
672
669
  bindingSource: normalizeText(pairingPayload?.bindingSource, null),
673
670
  activation: {
674
- status: bindingReady ? 'ready' : 'pending',
675
- },
676
- diagnostics: {
677
- toolReachable: true,
678
- bindingReady,
679
- publicIdentityReady: identityReady,
680
- relayPresenceResolved: relayResolved,
681
- relayOnline,
671
+ status: pairingPayload?.status === 'paired' ? 'ready' : 'pending',
682
672
  },
683
673
  relay: {
684
674
  agentId: normalizeText(
@@ -688,9 +678,9 @@ export function projectToolAccountViewResponse({
688
678
  displayName: normalizeText(pairingPayload?.relayAgent?.displayName, null),
689
679
  discoverable: pairingPayload?.relayAgent?.discoverable ?? null,
690
680
  contactable: pairingPayload?.relayAgent?.contactable ?? null,
691
- online: relayOnline,
692
- resolved: relayResolved,
693
- bindingStatus: bindingReady ? 'bound' : 'unactivated',
681
+ online: pairingPayload?.relayAgent?.online ?? null,
682
+ resolved: pairingPayload?.relayAgent?.resolved ?? null,
683
+ bindingStatus: pairingPayload?.status === 'paired' ? 'bound' : 'unactivated',
694
684
  },
695
685
  profile: projectToolAccountProfile(identityPayload),
696
686
  ...projectToolAccountIdentityFields(identityPayload),
@@ -1968,16 +1968,7 @@ function buildRegisteredTools(api, plugin) {
1968
1968
  expiresInSeconds: params.expiresInSeconds ?? null,
1969
1969
  });
1970
1970
  const pairedAgentId = identityPayload?.agentId || runtimeConfig.relay?.agentId || null;
1971
- const pairedRuntimeConfig = pairedAgentId
1972
- ? {
1973
- ...runtimeConfig,
1974
- relay: {
1975
- ...(runtimeConfig.relay && typeof runtimeConfig.relay === 'object' ? runtimeConfig.relay : {}),
1976
- agentId: pairedAgentId,
1977
- },
1978
- }
1979
- : runtimeConfig;
1980
- const relayAgentFallback = pairedAgentId
1971
+ const relayAgent = pairedAgentId
1981
1972
  ? {
1982
1973
  agentId: pairedAgentId,
1983
1974
  displayName: normalizeText(
@@ -1998,23 +1989,6 @@ function buildRegisteredTools(api, plugin) {
1998
1989
  || runtimeConfig.relay?.appToken
1999
1990
  || runtimeConfig.relay?.credentialToken,
2000
1991
  );
2001
- let relayAgent = relayAgentFallback;
2002
- if (hasConfiguredAppToken && pairedAgentId && typeof plugin.helpers?.pairing?.resolveAgentIdentity === 'function') {
2003
- const resolvedRelayAgent = await plugin.helpers.pairing.resolveAgentIdentity({
2004
- cfg,
2005
- accountId,
2006
- runtimeConfig: pairedRuntimeConfig,
2007
- agentId: pairedAgentId,
2008
- });
2009
- if (resolvedRelayAgent && typeof resolvedRelayAgent === 'object') {
2010
- relayAgent = {
2011
- ...relayAgentFallback,
2012
- ...resolvedRelayAgent,
2013
- agentId: normalizeText(resolvedRelayAgent.agentId, pairedAgentId),
2014
- displayName: normalizeText(resolvedRelayAgent.displayName, relayAgentFallback?.displayName ?? null),
2015
- };
2016
- }
2017
- }
2018
1992
  const pairingPayload = {
2019
1993
  status: hasConfiguredAppToken ? 'paired' : 'unpaired',
2020
1994
  reason: hasConfiguredAppToken
@@ -2023,7 +1997,15 @@ function buildRegisteredTools(api, plugin) {
2023
1997
  bindingSource: hasConfiguredAppToken
2024
1998
  ? 'configured_app_token'
2025
1999
  : (runtimeConfig.registration?.enabled === true ? 'registration_pending' : 'unbound'),
2026
- runtimeConfig: pairedRuntimeConfig,
2000
+ runtimeConfig: pairedAgentId
2001
+ ? {
2002
+ ...runtimeConfig,
2003
+ relay: {
2004
+ ...(runtimeConfig.relay && typeof runtimeConfig.relay === 'object' ? runtimeConfig.relay : {}),
2005
+ agentId: pairedAgentId,
2006
+ },
2007
+ }
2008
+ : runtimeConfig,
2027
2009
  relayAgent,
2028
2010
  };
2029
2011
  return buildToolResult(projectToolAccountViewResponse({
@@ -5,6 +5,51 @@ export const STALE_CONNECTION_CLOSE_CODE = 4002;
5
5
  export const TERMINAL_CLOSE_REASONS = new Set(['duplicate_connection_replaced', 'stale_connection']);
6
6
  export const DEFAULT_REPLY_ACK_TIMEOUT_MS = 5000;
7
7
 
8
+ function cloneObject(value, fallback = {}) {
9
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return { ...fallback };
10
+ return { ...value };
11
+ }
12
+
13
+ function normalizeEnvelopeText(value, fallback = null) {
14
+ if (value == null) return fallback;
15
+ const normalized = String(value).trim();
16
+ return normalized || fallback;
17
+ }
18
+
19
+ function resolveEnvelopeMessageId(data = {}, payload = {}) {
20
+ const notification = payload.notification && typeof payload.notification === 'object' && !Array.isArray(payload.notification)
21
+ ? payload.notification
22
+ : data.notification && typeof data.notification === 'object' && !Array.isArray(data.notification)
23
+ ? data.notification
24
+ : {};
25
+ const metadata = data.metadata && typeof data.metadata === 'object' && !Array.isArray(data.metadata)
26
+ ? data.metadata
27
+ : payload.metadata && typeof payload.metadata === 'object' && !Array.isArray(payload.metadata)
28
+ ? payload.metadata
29
+ : {};
30
+ const candidates = [
31
+ data.deliveryId,
32
+ data.inboxItemId,
33
+ data.messageId,
34
+ data.eventId,
35
+ data.notificationId,
36
+ payload.deliveryId,
37
+ payload.inboxItemId,
38
+ payload.messageId,
39
+ payload.eventId,
40
+ payload.notificationId,
41
+ metadata.messageId,
42
+ metadata.eventId,
43
+ metadata.notificationId,
44
+ notification.notificationId,
45
+ ];
46
+ for (const candidate of candidates) {
47
+ const normalized = normalizeEnvelopeText(candidate, null);
48
+ if (normalized) return normalized;
49
+ }
50
+ return null;
51
+ }
52
+
8
53
  export function normalizeRelayWebSocketUrl(serverUrl) {
9
54
  const parsed = new URL(serverUrl);
10
55
  if (parsed.protocol === 'http:') parsed.protocol = 'ws:';
@@ -23,20 +68,63 @@ export function normalizeRelayWebSocketUrl(serverUrl) {
23
68
 
24
69
  export function buildInboundEnvelope(message = {}) {
25
70
  const data = message.data || {};
26
- if (message.event !== 'delivery') return null;
71
+ const directPayload = data.payload && typeof data.payload === 'object' && !Array.isArray(data.payload)
72
+ ? { ...data.payload }
73
+ : {};
27
74
  const metadata = data.metadata && typeof data.metadata === 'object' && !Array.isArray(data.metadata)
28
75
  ? { ...data.metadata }
29
- : {};
76
+ : directPayload.metadata && typeof directPayload.metadata === 'object' && !Array.isArray(directPayload.metadata)
77
+ ? { ...directPayload.metadata }
78
+ : cloneObject(data.meta, {});
79
+ const payloadEventType = normalizeEnvelopeText(directPayload.eventType, null);
80
+ const dataEventType = normalizeEnvelopeText(data.eventType, null);
81
+ const eventType = dataEventType
82
+ || payloadEventType
83
+ || (message.event === 'delivery' ? 'delivery' : normalizeEnvelopeText(message.event, null));
84
+ const payload = Object.keys(directPayload).length > 0
85
+ ? { ...directPayload }
86
+ : cloneObject(data, {});
87
+ if (Object.keys(directPayload).length > 0) {
88
+ for (const key of [
89
+ 'eventType',
90
+ 'eventName',
91
+ 'sessionKind',
92
+ 'sessionKey',
93
+ 'targetSessionKey',
94
+ 'targetAgentId',
95
+ 'text',
96
+ 'body',
97
+ 'notification',
98
+ ]) {
99
+ if (payload[key] == null && data[key] != null) payload[key] = data[key];
100
+ }
101
+ }
102
+ const targetAgentId = normalizeEnvelopeText(
103
+ data.targetAgentId,
104
+ normalizeEnvelopeText(payload.targetAgentId, null),
105
+ );
106
+ const sessionKey = normalizeEnvelopeText(
107
+ data.sessionKey,
108
+ normalizeEnvelopeText(
109
+ payload.sessionKey,
110
+ normalizeEnvelopeText(
111
+ data.targetSessionKey,
112
+ normalizeEnvelopeText(payload.targetSessionKey, null),
113
+ ),
114
+ ),
115
+ );
116
+ const isDeliveryEvent = message.event === 'delivery';
117
+ const isRoutableEvent = Boolean(eventType && sessionKey);
118
+ if (!isDeliveryEvent && !isRoutableEvent) return null;
30
119
  return {
31
- eventType: data.eventType || 'delivery',
32
- deliveryId: data.deliveryId || null,
33
- sessionKey: data.sessionKey || null,
34
- createdAt: data.createdAt || null,
120
+ eventType: eventType || 'delivery',
121
+ deliveryId: resolveEnvelopeMessageId(data, payload),
122
+ sessionKey,
123
+ targetAgentId,
124
+ createdAt: data.createdAt || data.availableAt || null,
35
125
  updatedAt: data.updatedAt || null,
36
126
  turnCreatedAt: data.turnCreatedAt || null,
37
- payload: data.payload && typeof data.payload === 'object' && !Array.isArray(data.payload)
38
- ? { ...data.payload }
39
- : {},
127
+ payload,
40
128
  metadata,
41
129
  };
42
130
  }
@@ -47,6 +47,10 @@ export function buildConversationSessionKey(conversationKey = null, fallbackSess
47
47
  export function resolveRuntimeSessionTarget(event = {}, options = {}) {
48
48
  const payload = normalizePayload(event.payload);
49
49
  const eventType = normalizeText(event.eventType || event.type || payload.eventType, null);
50
+ const providedSessionKind = normalizeText(
51
+ event.sessionKind,
52
+ normalizeText(payload.sessionKind, normalizeText(options.sessionKind, null)),
53
+ );
50
54
  const targetAgentId = normalizeText(
51
55
  event.targetAgentId,
52
56
  normalizeText(payload.targetAgentId, normalizeText(options.targetAgentId, null)),
@@ -60,15 +64,15 @@ export function resolveRuntimeSessionTarget(event = {}, options = {}) {
60
64
  normalizeText(payload.sessionKey, normalizeText(options.sessionKey, null)),
61
65
  );
62
66
 
63
- if (CLAWORLD_MANAGEMENT_EVENT_TYPES.includes(eventType)) {
67
+ if (providedSessionKind === CLAWORLD_SESSION_KINDS.management || CLAWORLD_MANAGEMENT_EVENT_TYPES.includes(eventType)) {
64
68
  const managementSessionKey = normalizeText(
65
69
  options.managementSessionKey,
66
- buildManagementSessionKey(targetAgentId),
70
+ normalizeText(providedSessionKey, buildManagementSessionKey(targetAgentId)),
67
71
  );
68
72
  return {
69
73
  sessionKind: CLAWORLD_SESSION_KINDS.management,
70
74
  target: normalizeText(options.managementTarget, 'management_session'),
71
- sessionKey: managementSessionKey || providedSessionKey,
75
+ sessionKey: providedSessionKey || managementSessionKey,
72
76
  managementSessionKey: managementSessionKey || null,
73
77
  conversationSessionKey: conversationKey ? buildConversationSessionKey(conversationKey) : null,
74
78
  targetAgentId,