@xfxstudio/claworld 2026.4.29-testing.3 → 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.3",
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.3",
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
  });
@@ -142,33 +142,6 @@ const CHAT_INBOX_FILTER_STATUSES = Object.freeze([
142
142
  'kickoff_failed',
143
143
  'ended',
144
144
  ]);
145
- const CHAT_INBOX_FILTER_KEYS = Object.freeze([
146
- 'direction',
147
- 'mode',
148
- 'status',
149
- 'worldId',
150
- 'chatRequestId',
151
- 'conversationKey',
152
- 'localSessionKey',
153
- 'counterpartyAgentId',
154
- ]);
155
- const CHAT_INBOX_FILTER_KEY_SET = new Set(CHAT_INBOX_FILTER_KEYS);
156
- const MANAGE_CONVERSATION_REQUEST_ONLY_QUERY_FIELDS = Object.freeze([
157
- 'displayName',
158
- 'agentCode',
159
- 'openingMessage',
160
- ]);
161
- const MANAGE_CONVERSATION_FILTER_ONLY_TOP_LEVEL_FIELDS = Object.freeze([
162
- 'mode',
163
- 'status',
164
- 'worldId',
165
- 'counterpartyAgentId',
166
- ]);
167
- const MANAGE_CONVERSATION_GET_STATE_TARGET_FIELDS = Object.freeze([
168
- 'chatRequestId',
169
- 'conversationKey',
170
- 'localSessionKey',
171
- ]);
172
145
 
173
146
  const TERMINAL_ACCOUNT_ACTIONS = Object.freeze([
174
147
  'view_account',
@@ -319,117 +292,6 @@ function normalizeChatInboxListFiltersInput(params = {}) {
319
292
  );
320
293
  }
321
294
 
322
- function hasProvidedToolParam(params = {}, fieldId) {
323
- if (!params || typeof params !== 'object') return false;
324
- if (!Object.prototype.hasOwnProperty.call(params, fieldId)) return false;
325
- const value = params[fieldId];
326
- if (typeof value === 'string') return normalizeText(value, null) != null;
327
- return value != null;
328
- }
329
-
330
- function buildChatInboxFiltersParam({ description, worldIdProperty } = {}) {
331
- return objectParam({
332
- description,
333
- additionalProperties: false,
334
- properties: {
335
- direction: stringParam({
336
- description: 'Filter from the current account perspective.',
337
- enumValues: CHAT_INBOX_FILTER_DIRECTIONS,
338
- examples: ['outbound'],
339
- }),
340
- mode: stringParam({
341
- description: 'Filter to direct or world-scoped chat items.',
342
- enumValues: CHAT_INBOX_FILTER_MODES,
343
- examples: ['world'],
344
- }),
345
- status: stringParam({
346
- description: 'Filter to pending or terminal requests, or to chats by current status.',
347
- enumValues: CHAT_INBOX_FILTER_STATUSES,
348
- examples: ['active'],
349
- }),
350
- worldId: worldIdProperty,
351
- chatRequestId: stringParam({
352
- description: 'Filter to one canonical chat request id.',
353
- minLength: 1,
354
- examples: ['req_demo_1'],
355
- }),
356
- conversationKey: stringParam({
357
- description: 'Filter to one canonical conversation key.',
358
- minLength: 1,
359
- examples: ['pair:agt_alice::agt_moza:world:dating-demo-world'],
360
- }),
361
- localSessionKey: stringParam({
362
- description: 'Filter to one local Claworld session reference for internal tracking, summaries, or orchestration only. Not a transport address for sending a user message to the peer.',
363
- minLength: 1,
364
- examples: ['conversation:pair:agt_alice::agt_moza:world:dating-demo-world'],
365
- }),
366
- counterpartyAgentId: stringParam({
367
- description: 'Filter to one counterparty agentId.',
368
- minLength: 1,
369
- examples: ['agt_alice'],
370
- }),
371
- },
372
- });
373
- }
374
-
375
- function validateChatInboxFilterInput(filters = {}, action) {
376
- const source = normalizeObject(filters, {}) || {};
377
- for (const key of Object.keys(source)) {
378
- if (CHAT_INBOX_FILTER_KEY_SET.has(key)) continue;
379
- requireManageWorldField(`filters.${key}`, `filters.${key} is not supported for action=${action}`);
380
- }
381
- return source;
382
- }
383
-
384
- function normalizeManageConversationInboxQuery(params = {}, action) {
385
- const normalizedAction = normalizeTerminalConversationAction(action, 'list_related');
386
- const filters = validateChatInboxFilterInput(params.filters, normalizedAction);
387
-
388
- const requestOnlyField = MANAGE_CONVERSATION_REQUEST_ONLY_QUERY_FIELDS.find((fieldId) => hasProvidedToolParam(params, fieldId));
389
- if (requestOnlyField) {
390
- requireManageWorldField(requestOnlyField, `${requestOnlyField} is only supported for action=request`);
391
- }
392
- if (hasProvidedToolParam(params, 'limit')) {
393
- requireManageWorldField('limit', `limit is not supported for action=${normalizedAction}`);
394
- }
395
-
396
- const filterOnlyField = MANAGE_CONVERSATION_FILTER_ONLY_TOP_LEVEL_FIELDS.find((fieldId) => hasProvidedToolParam(params, fieldId));
397
- if (filterOnlyField) {
398
- requireManageWorldField(
399
- filterOnlyField,
400
- `${filterOnlyField} must be passed as filters.${filterOnlyField} for action=${normalizedAction}`,
401
- );
402
- }
403
-
404
- if (normalizedAction !== 'get_state') {
405
- const getStateOnlyField = MANAGE_CONVERSATION_GET_STATE_TARGET_FIELDS.find((fieldId) => hasProvidedToolParam(params, fieldId));
406
- if (getStateOnlyField) {
407
- requireManageWorldField(
408
- getStateOnlyField,
409
- `${getStateOnlyField} must be passed as filters.${getStateOnlyField} for action=${normalizedAction}`,
410
- );
411
- }
412
- }
413
-
414
- const mergedFilters = {
415
- ...filters,
416
- ...(!Object.prototype.hasOwnProperty.call(filters, 'direction') && hasProvidedToolParam(params, 'direction')
417
- ? { direction: params.direction }
418
- : {}),
419
- ...(normalizedAction === 'get_state'
420
- ? Object.fromEntries(
421
- MANAGE_CONVERSATION_GET_STATE_TARGET_FIELDS
422
- .filter((fieldId) => (
423
- !Object.prototype.hasOwnProperty.call(filters, fieldId)
424
- && hasProvidedToolParam(params, fieldId)
425
- ))
426
- .map((fieldId) => [fieldId, params[fieldId]]),
427
- )
428
- : {}),
429
- };
430
- return normalizeChatInboxListFiltersInput({ filters: mergedFilters });
431
- }
432
-
433
295
  function parseToolResultPayload(result = null) {
434
296
  const text = result?.content?.[0]?.text;
435
297
  if (typeof text !== 'string') return null;
@@ -1062,27 +924,10 @@ function createTerminalToolAdapters(api, plugin, internalTools) {
1062
924
  agentCode: stringParam({ description: 'Target public agent code for request.', minLength: 1 }),
1063
925
  openingMessage: stringParam({ description: 'Request/re-engagement kickoff message.', minLength: 1 }),
1064
926
  worldId: worldIdProperty,
1065
- direction: stringParam({
1066
- description: 'Top-level alias for filters.direction on action=list_related/get_state.',
1067
- enumValues: CHAT_INBOX_FILTER_DIRECTIONS,
1068
- examples: ['outbound'],
1069
- }),
1070
- filters: buildChatInboxFiltersParam({
1071
- description: 'Inbox filters for action=list_related/get_state.',
1072
- worldIdProperty,
1073
- }),
1074
- chatRequestId: stringParam({
1075
- description: 'Request id for action=accept/reject, or a top-level get_state convenience target that normalizes to filters.chatRequestId.',
1076
- minLength: 1,
1077
- }),
1078
- conversationKey: stringParam({
1079
- description: 'Conversation key for action=close, or a top-level get_state convenience target that normalizes to filters.conversationKey.',
1080
- minLength: 1,
1081
- }),
1082
- localSessionKey: stringParam({
1083
- description: 'Local conversation session key for action=close, or a top-level get_state convenience target that normalizes to filters.localSessionKey.',
1084
- minLength: 1,
1085
- }),
927
+ filters: objectParam({ description: 'List filters.', additionalProperties: true }),
928
+ chatRequestId: stringParam({ description: 'Request id for accept/reject.', minLength: 1 }),
929
+ conversationKey: stringParam({ description: 'Conversation key for get_state/close.', minLength: 1 }),
930
+ localSessionKey: stringParam({ description: 'Local conversation session key for get_state/close.', minLength: 1 }),
1086
931
  },
1087
932
  }),
1088
933
  async execute(toolCallId, params = {}) {
@@ -1094,19 +939,10 @@ function createTerminalToolAdapters(api, plugin, internalTools) {
1094
939
  });
1095
940
  return rewriteToolResultName(result, manageConversationsTool, action);
1096
941
  }
1097
- if (action === 'list_related' || action === 'get_state') {
1098
- const filters = normalizeManageConversationInboxQuery(params, action);
942
+ if (['list_related', 'get_state', 'accept', 'reject'].includes(action)) {
1099
943
  const result = await requireTerminalTool(internalTools, 'claworld_chat_inbox').execute(toolCallId, {
1100
944
  ...params,
1101
- action: 'list',
1102
- ...(Object.keys(filters).length > 0 ? { filters } : {}),
1103
- });
1104
- return rewriteToolResultName(result, manageConversationsTool, action);
1105
- }
1106
- if (action === 'accept' || action === 'reject') {
1107
- const result = await requireTerminalTool(internalTools, 'claworld_chat_inbox').execute(toolCallId, {
1108
- ...params,
1109
- action,
945
+ action: ['list_related', 'get_state'].includes(action) ? 'list' : action,
1110
946
  });
1111
947
  return rewriteToolResultName(result, manageConversationsTool, action);
1112
948
  }
@@ -1854,10 +1690,45 @@ function buildRegisteredTools(api, plugin) {
1854
1690
  examples: ['list', 'accept', 'reject'],
1855
1691
  }),
1856
1692
  filters: objectParam({
1857
- ...buildChatInboxFiltersParam({
1858
- description: 'Optional list filters for query mode. Omit to review the full inbox across inbound and outbound items.',
1859
- worldIdProperty,
1860
- }),
1693
+ description: 'Optional list filters for query mode. Omit to review the full inbox across inbound and outbound items.',
1694
+ properties: {
1695
+ direction: stringParam({
1696
+ description: 'Filter from the current account perspective.',
1697
+ enumValues: CHAT_INBOX_FILTER_DIRECTIONS,
1698
+ examples: ['outbound'],
1699
+ }),
1700
+ mode: stringParam({
1701
+ description: 'Filter to direct or world-scoped chat items.',
1702
+ enumValues: CHAT_INBOX_FILTER_MODES,
1703
+ examples: ['world'],
1704
+ }),
1705
+ status: stringParam({
1706
+ description: 'Filter to pending or terminal requests, or to chats by current status.',
1707
+ enumValues: CHAT_INBOX_FILTER_STATUSES,
1708
+ examples: ['active'],
1709
+ }),
1710
+ worldId: worldIdProperty,
1711
+ chatRequestId: stringParam({
1712
+ description: 'Filter to one canonical chat request id.',
1713
+ minLength: 1,
1714
+ examples: ['req_demo_1'],
1715
+ }),
1716
+ conversationKey: stringParam({
1717
+ description: 'Filter to one canonical conversation key.',
1718
+ minLength: 1,
1719
+ examples: ['pair:agt_alice::agt_moza:world:dating-demo-world'],
1720
+ }),
1721
+ localSessionKey: stringParam({
1722
+ description: 'Filter to one local Claworld session reference for internal tracking, summaries, or orchestration only. Not a transport address for sending a user message to the peer.',
1723
+ minLength: 1,
1724
+ examples: ['conversation:pair:agt_alice::agt_moza:world:dating-demo-world'],
1725
+ }),
1726
+ counterpartyAgentId: stringParam({
1727
+ description: 'Filter to one counterparty agentId.',
1728
+ minLength: 1,
1729
+ examples: ['agt_alice'],
1730
+ }),
1731
+ },
1861
1732
  }),
1862
1733
  chatRequestId: stringParam({
1863
1734
  description: 'Canonical chat request id returned by claworld_chat_inbox pendingRequests. Required for action=accept or action=reject.',
@@ -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,