@clawling/clawchat-plugin-openclaw 2026.10.7-2 → 2026.10.8-2

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.
@@ -30,12 +30,14 @@ import { createNotifySignalObserver, createProtocolControlHandler, createReconne
30
30
  import { clawChatDbPathForStateDir, getClawChatStore, makeOwnerProfilePersister, } from "./storage.js";
31
31
  import { getClawChatGroupPrompt, getClawChatUserPrompt } from "./plugin-prompts.js";
32
32
  import { loadClawChatPromptMetadata, renderClawChatProfilePrompt, resolveSenderRelation, } from "./profile-prompt.js";
33
+ import { buildNoteMemorySection } from "./note-injection.js";
34
+ import { buildGroupCatchUp, CATCH_UP_FETCH_ROWS, DeliveredGroupMessages } from "./group-catch-up.js";
33
35
  import { refreshGroupProfile, syncFirstSeenClawChatProfiles } from "./profile-sync.js";
34
36
  import { pullGroupMetadata, pullOwnerMetadata } from "./clawchat-metadata.js";
35
37
  import { deleteClawChatMemoryFile, readClawChatMemoryFile } from "./clawchat-memory.js";
36
38
  import { registerMentionRosterResolver } from "./mention-autolink.js";
37
39
  import { clearClawChatPromptInjectionForSession, stageClawChatPromptInjection, } from "./prompt-injection.js";
38
- import { createGroupMessageCoalescer } from "./group-message-coalescer.js";
40
+ import { createGroupMessageCoalescer, relabelCoalescedGroupBody } from "./group-message-coalescer.js";
39
41
  import { openclawLlmContextDebug } from "./llm-context-debug.js";
40
42
  import { GroupSettingsCache } from "./group-settings.js";
41
43
  import { PermissionCache } from "./permissions.js";
@@ -90,7 +92,6 @@ function activationBootstrapInFlightCount(accountId) {
90
92
  // hermes plugin's GROUP_SETTINGS_READY_TIMEOUT_SECONDS (5s).
91
93
  const GROUP_SETTINGS_READY_TIMEOUT_MS = 5_000;
92
94
  /** Number of recent group messages to prepend as context when the agent is @-mentioned. */
93
- const MENTION_CONTEXT_N = 10;
94
95
  const CLAWCHAT_MEMORY_ROOT_UNAVAILABLE = "ClawChat memory root unavailable: OpenClaw workspaceDir could not be resolved";
95
96
  const OPENCLAW_CONFIRM_SLASH_COMMANDS = new Set([
96
97
  "approve",
@@ -2472,12 +2473,27 @@ export async function startOpenclawClawlingGateway(params) {
2472
2473
  ownerMetadata: promptMetadata.ownerMetadata,
2473
2474
  })
2474
2475
  : [];
2476
+ const noteMemorySection = await buildNoteMemorySection({
2477
+ memoryRoot,
2478
+ chatType: promptChatType,
2479
+ chatId: turn.peer.id,
2480
+ senderId: turn.senderId,
2481
+ senderIsOwner: senderRelation === "owner",
2482
+ selfId: account.userId,
2483
+ speakers: turn.peer.kind === "group"
2484
+ ? (turn.groupMessages && turn.groupMessages.length > 0
2485
+ ? turn.groupMessages.map((message) => ({ id: message.senderId, name: message.senderName }))
2486
+ : [{ id: turn.senderId, name: turn.senderNickName }])
2487
+ : [],
2488
+ caps: { user: account.noteCapUser, group: account.noteCapGroup, turn: account.noteCapTurn },
2489
+ });
2475
2490
  return renderClawChatProfilePrompt({
2476
2491
  basePrompt: turn.peer.kind === "group" ? getClawChatGroupPrompt() : getClawChatUserPrompt(),
2477
2492
  ...promptMetadata,
2478
2493
  ownerIdFallback: account.ownerUserId,
2479
2494
  currentAgentIdFallback: account.userId,
2480
2495
  groupParticipants,
2496
+ noteMemorySection,
2481
2497
  turn: {
2482
2498
  chatType: promptChatType,
2483
2499
  chatId: turn.peer.id,
@@ -2521,6 +2537,100 @@ export async function startOpenclawClawlingGateway(params) {
2521
2537
  // coalesced batch's transcript ("Alice:" rather than "usr_…:") without
2522
2538
  // touching disk.
2523
2539
  const knownNicknames = new Map();
2540
+ // Group message ids already handed to the agent, per chat (see group-catch-up.ts).
2541
+ const deliveredGroupMessages = new DeliveredGroupMessages();
2542
+ // One catch-up line: `Name (usr_…): text`, the name from the stored frame's
2543
+ // nick_name unless that is just the id, else the cached nickname.
2544
+ const formatCatchUpLine = (row) => {
2545
+ const text = (row.text ?? "").trim() || "(empty message)";
2546
+ let senderId = "";
2547
+ let nickName = "";
2548
+ try {
2549
+ const frame = row.raw_json ? JSON.parse(row.raw_json) : null;
2550
+ senderId = typeof frame?.sender?.id === "string" ? frame.sender.id : "";
2551
+ nickName = typeof frame?.sender?.nick_name === "string" ? frame.sender.nick_name : "";
2552
+ }
2553
+ catch {
2554
+ // A malformed stored frame still yields its text.
2555
+ }
2556
+ if (!senderId)
2557
+ return text;
2558
+ const name = (nickName && nickName !== senderId ? nickName : knownNicknames.get(senderId)) ?? "";
2559
+ return name ? `${name} (${senderId}): ${text}` : `${senderId}: ${text}`;
2560
+ };
2561
+ // The sender id of a stored row whose frame carried no real nickname (its
2562
+ // nick_name is missing or just the id), else "".
2563
+ const bareSenderIdOfRow = (row) => {
2564
+ try {
2565
+ const frame = row.raw_json
2566
+ ? JSON.parse(row.raw_json)
2567
+ : null;
2568
+ const id = typeof frame?.sender?.id === "string" ? frame.sender.id : "";
2569
+ const nick = typeof frame?.sender?.nick_name === "string" ? frame.sender.nick_name : "";
2570
+ return id && (!nick || nick === id) ? id : "";
2571
+ }
2572
+ catch {
2573
+ return "";
2574
+ }
2575
+ };
2576
+ // Last group-metadata pull made only to resolve names, per chat: a sender who
2577
+ // can never be resolved (deleted account) must not refetch on every batch.
2578
+ const nicknameRefreshAt = new Map();
2579
+ const NICKNAME_REFRESH_COOLDOWN_MS = 60_000;
2580
+ const NICKNAME_REFRESH_TIMEOUT_MS = 3_000;
2581
+ // Fill knownNicknames for `ids` from ClawChat memory; if some are still
2582
+ // missing in a group, pull the group's participants once (bounded, with a
2583
+ // cooldown) and read again. Never throws: a name is a nicety, the turn is not.
2584
+ const warmGroupNicknames = async (peer, ids) => {
2585
+ if (peer.kind !== "group")
2586
+ return;
2587
+ try {
2588
+ const memoryRoot = resolveMemoryRootForPeer(peer);
2589
+ if (!memoryRoot)
2590
+ return;
2591
+ const wanted = Array.from(new Set(Array.from(ids).filter((id) => id && id !== account.userId)));
2592
+ const missing = () => wanted.filter((id) => !knownNicknames.has(id));
2593
+ const readCached = async () => {
2594
+ for (const id of missing()) {
2595
+ const nickname = await cachedNicknameFor(memoryRoot, id);
2596
+ if (nickname && nickname !== id)
2597
+ knownNicknames.set(id, nickname);
2598
+ }
2599
+ };
2600
+ await readCached();
2601
+ if (missing().length === 0)
2602
+ return;
2603
+ const now = Date.now();
2604
+ const last = nicknameRefreshAt.get(peer.id);
2605
+ if (last !== undefined && now - last < NICKNAME_REFRESH_COOLDOWN_MS)
2606
+ return;
2607
+ nicknameRefreshAt.set(peer.id, now);
2608
+ let timer;
2609
+ await Promise.race([
2610
+ refreshGroupProfile({
2611
+ platform: "openclaw",
2612
+ accountId,
2613
+ accountUserId: account.userId,
2614
+ accountOwnerUserId: account.ownerUserId,
2615
+ conversationId: peer.id,
2616
+ api: getConversationApiClient(),
2617
+ store: {},
2618
+ memoryRoot,
2619
+ log: { error: (message) => log?.error?.(`[${accountId}] ${message}`) },
2620
+ }),
2621
+ new Promise((resolve) => {
2622
+ timer = setTimeout(resolve, NICKNAME_REFRESH_TIMEOUT_MS);
2623
+ }),
2624
+ ]).finally(() => {
2625
+ if (timer)
2626
+ clearTimeout(timer);
2627
+ });
2628
+ await readCached();
2629
+ }
2630
+ catch (err) {
2631
+ log?.error?.(`[${accountId}] clawchat-plugin-openclaw group sender name lookup failed: ${err instanceof Error ? err.message : String(err)}`);
2632
+ }
2633
+ };
2524
2634
  const withCachedGroupSenderNames = async (turn, memoryRoot) => {
2525
2635
  if (turn.peer.kind !== "group" || !memoryRoot)
2526
2636
  return turn;
@@ -2552,10 +2662,39 @@ export async function startOpenclawClawlingGateway(params) {
2552
2662
  const senderNickName = isBareId(turn.senderNickName, turn.senderId)
2553
2663
  ? (await lookup(turn.senderId)) ?? turn.senderNickName
2554
2664
  : turn.senderNickName;
2665
+ // The wire carries no sender type, so a batch message from another agent
2666
+ // (Hermes, a second OpenClaw…) would read as a person. users/<id>.md holds
2667
+ // the backend's user type; this agent is always an agent.
2668
+ const typeCache = new Map();
2669
+ const lookupProfileType = async (userId) => {
2670
+ if (userId === account.userId)
2671
+ return "agent";
2672
+ if (!typeCache.has(userId)) {
2673
+ let profileType = null;
2674
+ try {
2675
+ const userFile = await readClawChatMemoryFile(memoryRoot, { targetType: "user", targetId: userId });
2676
+ profileType = userFile.exists && userFile.metadata.profile_type ? userFile.metadata.profile_type : null;
2677
+ }
2678
+ catch {
2679
+ profileType = null;
2680
+ }
2681
+ typeCache.set(userId, profileType);
2682
+ }
2683
+ return typeCache.get(userId) ?? null;
2684
+ };
2555
2685
  const groupMessages = turn.groupMessages
2556
- ? await Promise.all(turn.groupMessages.map(async (message) => isBareId(message.senderName, message.senderId)
2557
- ? { ...message, senderName: (await lookup(message.senderId)) ?? message.senderName }
2558
- : message))
2686
+ ? await Promise.all(turn.groupMessages.map(async (message) => {
2687
+ const named = isBareId(message.senderName, message.senderId)
2688
+ ? { ...message, senderName: (await lookup(message.senderId)) ?? message.senderName }
2689
+ : message;
2690
+ const profileType = await lookupProfileType(message.senderId);
2691
+ if (!profileType || profileType === named.senderProfileType)
2692
+ return named;
2693
+ const senderRelation = profileType === "agent" && named.senderRelation === "peer_user"
2694
+ ? "peer_agent"
2695
+ : named.senderRelation;
2696
+ return { ...named, senderProfileType: profileType, senderRelation };
2697
+ }))
2559
2698
  : turn.groupMessages;
2560
2699
  return { ...turn, senderNickName, ...(groupMessages ? { groupMessages } : {}) };
2561
2700
  };
@@ -2897,32 +3036,55 @@ export async function startOpenclawClawlingGateway(params) {
2897
3036
  log?.info?.(`[${accountId}] clawchat-plugin-openclaw coalesced group batch dropped at flush (now mention-only, no mention) chat_id=${turn.peer.id} msg=${turn.messageId}`);
2898
3037
  return;
2899
3038
  }
3039
+ const chatId = turn.peer.id;
3040
+ const batchIds = new Set(turn.allMessageIds ?? [turn.messageId]);
3041
+ const catchUpRows = turn.wasMentioned && store?.listRecentGroupMessages
3042
+ ? store.listRecentGroupMessages("openclaw", accountId, chatId, CATCH_UP_FETCH_ROWS + batchIds.size) ?? []
3043
+ : [];
3044
+ // Ingest labels a batch from the in-memory nickname map, which is empty
3045
+ // after a restart, and catch-up lines read the same map: resolve every
3046
+ // sender named here before the turn goes out.
3047
+ await warmGroupNicknames(turn.peer, [
3048
+ ...(turn.groupMessages ?? [])
3049
+ .filter((message) => !message.senderName || message.senderName === message.senderId)
3050
+ .map((message) => message.senderId),
3051
+ ...(!turn.senderNickName || turn.senderNickName === turn.senderId ? [turn.senderId] : []),
3052
+ ...catchUpRows.map(bareSenderIdOfRow),
3053
+ ]);
3054
+ if (turn.groupMessages?.length) {
3055
+ turn = {
3056
+ ...turn,
3057
+ rawBody: relabelCoalescedGroupBody(turn.rawBody, turn.groupMessages, (id) => knownNicknames.get(id)),
3058
+ groupMessages: turn.groupMessages.map((message) => {
3059
+ const known = message.senderName === message.senderId ? knownNicknames.get(message.senderId) : undefined;
3060
+ return known ? { ...message, senderName: known } : message;
3061
+ }),
3062
+ };
3063
+ }
3064
+ if (turn.senderNickName === turn.senderId && knownNicknames.has(turn.senderId)) {
3065
+ turn = { ...turn, senderNickName: knownNicknames.get(turn.senderId) };
3066
+ }
3067
+ // An @-mention adds the group messages this session has not been given
3068
+ // since its last turn (e.g. ones a mention-only group held back), within
3069
+ // delta-budget-chars. Every batch handed to the agent is recorded as
3070
+ // delivered, so nothing it already has comes back. See group-catch-up.ts.
3071
+ let catchUp = null;
2900
3072
  if (turn.wasMentioned && store?.listRecentGroupMessages) {
2901
- const chatId = turn.peer.id;
2902
- // Dedupe: exclude rows whose message_id belongs to the current batch/turn.
2903
- // For a coalesced multi-message turn this covers every constituent ID,
2904
- // not just the latest one (turn.messageId), so none of the batched
2905
- // messages appear twice — once in the coalesced body and once in the
2906
- // prepended "Prior group context" block.
2907
- const batchIds = new Set(turn.allMessageIds ?? [turn.messageId]);
2908
- // Overfetch so the batch's own just-stored messages don't crowd out the
2909
- // MENTION_CONTEXT_N prior rows: fetch batch-size extra rows, drop the
2910
- // batch members, then keep the most recent MENTION_CONTEXT_N survivors.
2911
- const priorRows = store.listRecentGroupMessages("openclaw", accountId, chatId, MENTION_CONTEXT_N + batchIds.size) ?? [];
2912
- const contextRows = priorRows
2913
- .filter((row) => row.message_id != null && !batchIds.has(row.message_id))
2914
- .slice(-MENTION_CONTEXT_N);
2915
- if (contextRows.length > 0) {
2916
- const priorContextBody = [
2917
- "Prior group context:",
2918
- ...contextRows.map((row, i) => `[prior ${i + 1}] ${row.text ?? "(empty)"}`),
2919
- ].join("\n");
2920
- await dispatchTurnToAgent({
2921
- ...turn,
2922
- rawBody: `${priorContextBody}\n${turn.rawBody}`,
2923
- });
2924
- return;
2925
- }
3073
+ const fetchLimit = CATCH_UP_FETCH_ROWS + batchIds.size;
3074
+ catchUp = buildGroupCatchUp({
3075
+ chatId,
3076
+ rows: catchUpRows,
3077
+ fetchLimit,
3078
+ batchIds,
3079
+ delivered: deliveredGroupMessages,
3080
+ budgetChars: account.deltaBudgetChars,
3081
+ formatLine: formatCatchUpLine,
3082
+ });
3083
+ }
3084
+ deliveredGroupMessages.remember(chatId, batchIds);
3085
+ if (catchUp) {
3086
+ await dispatchTurnToAgent({ ...turn, rawBody: `${catchUp}\n${turn.rawBody}` });
3087
+ return;
2926
3088
  }
2927
3089
  await dispatchTurnToAgent(turn);
2928
3090
  },
@@ -3207,8 +3369,8 @@ export async function startOpenclawClawlingGateway(params) {
3207
3369
  })();
3208
3370
  });
3209
3371
  // `message.recall` — the sender withdrew a message. Erase our own ledger row
3210
- // so the "Prior group context" block above (MENTION_CONTEXT_N rows, no time
3211
- // predicate, no retention) can never read it back into a turn.
3372
+ // so the mention catch-up above (unseen group messages, no time predicate,
3373
+ // no retention) can never read it back into a turn.
3212
3374
  //
3213
3375
  // Ids only: the frame carries no content, and `payload.message_id` is the
3214
3376
  // server's `rcl:<target>` slot — the id to delete is `target_message_id`.
@@ -475,8 +475,8 @@ export class ClawChatStore {
475
475
  *
476
476
  * **The only DELETE in this store, and deliberately so.** There is no prune
477
477
  * and no retention on `clawchat_messages`: without this, a message recalled
478
- * ninety seconds after it was sent stays one @-mention away from being read
479
- * back aloud under "Prior group context" for as long as the group is quiet.
478
+ * ninety seconds after it was sent, before the agent was given it, stays
479
+ * one @-mention away from being read back in the mention catch-up.
480
480
  *
481
481
  * Scoped to `(platform, account_id)` so one account's recall cannot reach
482
482
  * another's rows, and matched on `message_id`, which seeks via the
@@ -128,6 +128,10 @@
128
128
  "awarenessNote": { "type": "boolean" },
129
129
  "friendGreeting": { "type": "boolean" },
130
130
  "livewareSample": { "type": "boolean" },
131
+ "note-cap-user": { "type": "integer" },
132
+ "note-cap-group": { "type": "integer" },
133
+ "note-cap-turn": { "type": "integer" },
134
+ "delta-budget-chars": { "type": "integer" },
131
135
  "reconnect": {
132
136
  "type": "object",
133
137
  "additionalProperties": false,
@@ -202,6 +206,10 @@
202
206
  "awarenessNote": { "type": "boolean" },
203
207
  "friendGreeting": { "type": "boolean" },
204
208
  "livewareSample": { "type": "boolean" },
209
+ "note-cap-user": { "type": "integer" },
210
+ "note-cap-group": { "type": "integer" },
211
+ "note-cap-turn": { "type": "integer" },
212
+ "delta-budget-chars": { "type": "integer" },
205
213
  "reconnect": {
206
214
  "type": "object",
207
215
  "additionalProperties": false,
@@ -282,6 +290,10 @@
282
290
  "awarenessNote": { "type": "boolean" },
283
291
  "friendGreeting": { "type": "boolean" },
284
292
  "livewareSample": { "type": "boolean" },
293
+ "note-cap-user": { "type": "integer" },
294
+ "note-cap-group": { "type": "integer" },
295
+ "note-cap-turn": { "type": "integer" },
296
+ "delta-budget-chars": { "type": "integer" },
285
297
  "reconnect": {
286
298
  "type": "object",
287
299
  "additionalProperties": false,
@@ -356,6 +368,10 @@
356
368
  "awarenessNote": { "type": "boolean" },
357
369
  "friendGreeting": { "type": "boolean" },
358
370
  "livewareSample": { "type": "boolean" },
371
+ "note-cap-user": { "type": "integer" },
372
+ "note-cap-group": { "type": "integer" },
373
+ "note-cap-turn": { "type": "integer" },
374
+ "delta-budget-chars": { "type": "integer" },
359
375
  "reconnect": {
360
376
  "type": "object",
361
377
  "additionalProperties": false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawling/clawchat-plugin-openclaw",
3
- "version": "2026.10.7-2",
3
+ "version": "2026.10.8-2",
4
4
  "description": "OpenClaw ClawChat channel plugin",
5
5
  "license": "MIT",
6
6
  "author": "CLAWLING PTE. LTD.",
@@ -293,10 +293,17 @@ export async function pullGroupMetadata(params: {
293
293
  targetType: "user",
294
294
  targetId: mapped.userId,
295
295
  });
296
- if (existing.exists) continue;
296
+ // A cached file is kept as is, except that one without profile_type
297
+ // (written before types were recorded) gets just that field filled in:
298
+ // without it the prompt lists a peer agent as a person.
299
+ if (existing.exists && existing.metadata.profile_type) continue;
297
300
  if (!getUser) throw new Error("ClawChat participant metadata pull requires getUserProfile");
298
301
  const profile = await getUser(mapped.userId);
299
- const metadata = userMetadataFromProfile(profile, mapped.userId);
302
+ const fetched = userMetadataFromProfile(profile, mapped.userId);
303
+ if (existing.exists && !fetched.profile_type) continue;
304
+ const metadata = existing.exists
305
+ ? { ...existing.metadata, profile_type: fetched.profile_type! }
306
+ : fetched;
300
307
  await writeClawChatMetadata(
301
308
  params.memoryRoot,
302
309
  { targetType: "user", targetId: mapped.userId },
package/src/config.ts CHANGED
@@ -120,6 +120,11 @@ export type OpenclawClawlingAccountConfig = {
120
120
  friendGreeting?: boolean;
121
121
  /** Auto-install the Liveware Sample demo app when no liveware app is registered (default true). */
122
122
  livewareSample?: boolean;
123
+ /** Shared ClawChat session / note keys (hyphenated; see SESSION_INT_KEYS). */
124
+ "note-cap-user"?: number;
125
+ "note-cap-group"?: number;
126
+ "note-cap-turn"?: number;
127
+ "delta-budget-chars"?: number;
123
128
  reconnect?: OpenclawClawlingReconnectConfig;
124
129
  heartbeat?: OpenclawClawlingHeartbeatConfig;
125
130
  ack?: OpenclawClawlingAckConfig;
@@ -181,6 +186,10 @@ export const openclawClawlingAccountConfigSchema = {
181
186
  awarenessNote: { type: "boolean" },
182
187
  friendGreeting: { type: "boolean" },
183
188
  livewareSample: { type: "boolean" },
189
+ "note-cap-user": { type: "integer" },
190
+ "note-cap-group": { type: "integer" },
191
+ "note-cap-turn": { type: "integer" },
192
+ "delta-budget-chars": { type: "integer" },
184
193
  reconnect: {
185
194
  type: "object",
186
195
  additionalProperties: false,
@@ -320,6 +329,14 @@ export type ResolvedOpenclawClawlingAccount = {
320
329
  awarenessNote: boolean;
321
330
  friendGreeting: boolean;
322
331
  livewareSample: boolean;
332
+ /** `note-cap-user`: characters of one person's note shown in a turn. */
333
+ noteCapUser: number;
334
+ /** `note-cap-group`: characters of the group's note shown in a group turn. */
335
+ noteCapGroup: number;
336
+ /** `note-cap-turn`: characters of all notes shown in one turn together. */
337
+ noteCapTurn: number;
338
+ /** `delta-budget-chars`: characters of unseen group messages an @-mention adds. */
339
+ deltaBudgetChars: number;
323
340
  allowFrom: string[];
324
341
  reconnect: Required<OpenclawClawlingReconnectConfig>;
325
342
  heartbeat: Required<OpenclawClawlingHeartbeatConfig>;
@@ -564,6 +581,31 @@ export function effectiveOutputVisibility(
564
581
  ?? "normal";
565
582
  }
566
583
 
584
+ /**
585
+ * Session / note keys shared with the other ClawChat agent channels (same
586
+ * hyphenated names, meaning and factory values as the Hermes plugin's
587
+ * `SESSION_INT_KEYS`). An out-of-range value is clamped to the nearest bound,
588
+ * a non-number falls back to the factory value. Every key here has a reader;
589
+ * the shared keys this plugin has no use for are listed in
590
+ * docs/clawchat-plugin-openclaw.md with the reason.
591
+ * key -> [factory, minimum, maximum]
592
+ */
593
+ export const SESSION_INT_KEYS = {
594
+ "note-cap-user": [1500, 300, 6000],
595
+ "note-cap-group": [2000, 300, 8000],
596
+ "note-cap-turn": [4000, 1000, 16000],
597
+ "delta-budget-chars": [8000, 2000, 32000],
598
+ } as const satisfies Record<string, readonly [number, number, number]>;
599
+
600
+ function readSessionInt(channel: Record<string, unknown>, key: keyof typeof SESSION_INT_KEYS): number {
601
+ const [factory, minimum, maximum] = SESSION_INT_KEYS[key];
602
+ const raw = channel[key];
603
+ const parsed =
604
+ typeof raw === "number" ? raw : typeof raw === "string" && raw.trim() ? Number(raw.trim()) : Number.NaN;
605
+ if (!Number.isFinite(parsed)) return factory;
606
+ return Math.max(minimum, Math.min(maximum, Math.trunc(parsed)));
607
+ }
608
+
567
609
  function readReconnect(raw: unknown): Required<OpenclawClawlingReconnectConfig> {
568
610
  const s = raw && typeof raw === "object" ? (raw as Record<string, unknown>) : {};
569
611
  return {
@@ -693,6 +735,10 @@ export function resolveOpenclawClawlingAccount(
693
735
  awarenessNote,
694
736
  friendGreeting,
695
737
  livewareSample,
738
+ noteCapUser: readSessionInt(channel, "note-cap-user"),
739
+ noteCapGroup: readSessionInt(channel, "note-cap-group"),
740
+ noteCapTurn: readSessionInt(channel, "note-cap-turn"),
741
+ deltaBudgetChars: readSessionInt(channel, "delta-budget-chars"),
696
742
  allowFrom: [],
697
743
  reconnect: readReconnect(channel.reconnect),
698
744
  heartbeat: readHeartbeat(channel.heartbeat),
@@ -0,0 +1,112 @@
1
+ /**
2
+ * What an @-mention adds in front of a group turn: the group messages this
3
+ * agent's session has not been given since its last turn.
4
+ *
5
+ * Every group batch the plugin hands to the host is recorded as delivered
6
+ * (per chat, bounded). On a mention, the ledger's recent group messages minus
7
+ * the delivered ones, the agent's own replies and the batch itself are the
8
+ * catch-up — e.g. messages a mention-only group held back. It is bounded by
9
+ * the shared `delta-budget-chars` key (characters, newest kept first); the
10
+ * unseen messages that do not fit are counted in one closing line, and are
11
+ * recorded as delivered with the rest, so a later mention does not bring them
12
+ * back out of order. Same rule as the Hermes plugin's shared group sessions.
13
+ *
14
+ * The delivered record is in memory: after a gateway restart the first
15
+ * mention may repeat up to that budget of messages the session already has.
16
+ */
17
+
18
+ /** How far back the ledger is read to find unseen messages (one row per message). */
19
+ export const CATCH_UP_FETCH_ROWS = 500;
20
+ /** Per group, how many delivered message ids are remembered. */
21
+ export const DELIVERED_GROUP_IDS_MAX = 500;
22
+
23
+ export const GROUP_UNSEEN_HEADER =
24
+ "[ClawChat group messages you have not seen yet, oldest first. " +
25
+ "Context only; the new messages follow.]";
26
+
27
+ export function groupUnseenLeftOutLine(count: string): string {
28
+ return (
29
+ `[${count} earlier unseen group messages were left out for length. If you ` +
30
+ "need them, ask in the group; the group's note (clawchat_memory_read) " +
31
+ "holds what was saved about it.]"
32
+ );
33
+ }
34
+
35
+ export class DeliveredGroupMessages {
36
+ private readonly byChat = new Map<string, Set<string>>();
37
+
38
+ constructor(private readonly max = DELIVERED_GROUP_IDS_MAX) {}
39
+
40
+ remember(chatId: string, messageIds: Iterable<string | null | undefined>): void {
41
+ let delivered = this.byChat.get(chatId);
42
+ if (!delivered) {
43
+ delivered = new Set();
44
+ this.byChat.set(chatId, delivered);
45
+ }
46
+ for (const id of messageIds) {
47
+ if (!id) continue;
48
+ delivered.delete(id); // re-insert at the end (most recent)
49
+ delivered.add(id);
50
+ }
51
+ while (delivered.size > this.max) {
52
+ const oldest = delivered.values().next().value as string;
53
+ delivered.delete(oldest);
54
+ }
55
+ }
56
+
57
+ has(chatId: string, messageId: string): boolean {
58
+ return this.byChat.get(chatId)?.has(messageId) ?? false;
59
+ }
60
+ }
61
+
62
+ export type CatchUpRow = {
63
+ message_id: string | null;
64
+ direction?: string | null;
65
+ text?: string | null;
66
+ };
67
+
68
+ /**
69
+ * The catch-up text (or null when nothing is unseen) for `rows` (oldest
70
+ * first, as read from the ledger with `fetchLimit`). Records every unseen row
71
+ * as delivered.
72
+ */
73
+ export function buildGroupCatchUp<Row extends CatchUpRow>(params: {
74
+ chatId: string;
75
+ rows: Row[];
76
+ fetchLimit: number;
77
+ batchIds: Set<string>;
78
+ delivered: DeliveredGroupMessages;
79
+ budgetChars: number;
80
+ formatLine: (row: Row) => string;
81
+ }): string | null {
82
+ const { chatId, rows, batchIds, delivered, budgetChars } = params;
83
+ const windowFull = rows.length >= params.fetchLimit;
84
+ const unseen = rows.filter(
85
+ (row) =>
86
+ row.message_id != null &&
87
+ row.direction !== "outbound" &&
88
+ !batchIds.has(row.message_id) &&
89
+ !delivered.has(chatId, row.message_id),
90
+ );
91
+ if (unseen.length === 0) return null;
92
+ delivered.remember(chatId, unseen.map((row) => row.message_id));
93
+ const kept: string[] = [];
94
+ let used = 0;
95
+ for (let index = unseen.length - 1; index >= 0; index -= 1) {
96
+ // newest first, so the budget keeps the latest
97
+ const line = params.formatLine(unseen[index]!);
98
+ const cost = line.length + (kept.length > 0 ? 1 : 0);
99
+ if (used + cost > budgetChars) {
100
+ if (kept.length === 0) kept.push(`${line.slice(0, Math.max(0, budgetChars - 1))}…`);
101
+ break;
102
+ }
103
+ kept.push(line);
104
+ used += cost;
105
+ }
106
+ const leftOut = unseen.length - kept.length;
107
+ const lines = [GROUP_UNSEEN_HEADER, ...kept.reverse()];
108
+ if (leftOut > 0 || windowFull) {
109
+ lines.push(groupUnseenLeftOutLine(windowFull ? `${leftOut}+` : String(leftOut)));
110
+ }
111
+ return lines.join("\n");
112
+ }
@@ -93,6 +93,38 @@ export function formatCoalescedGroupBody(
93
93
  ].join("\n");
94
94
  }
95
95
 
96
+ /**
97
+ * Relabel a coalesced body's `[message N] <sender>:` lines whose sender was
98
+ * still a bare id when the batch was built (ingest labels synchronously from
99
+ * an in-memory nickname map, which is empty right after a restart). Only the
100
+ * label line of each message, in order, is touched; bodies are never rewritten.
101
+ */
102
+ export function relabelCoalescedGroupBody(
103
+ rawBody: string,
104
+ messages: Pick<CoalescedGroupPromptMessage, "senderId" | "senderName">[],
105
+ nameFor: (senderId: string) => string | undefined,
106
+ ): string {
107
+ const lines = rawBody.split("\n");
108
+ let from = 0;
109
+ messages.forEach((message, index) => {
110
+ const prefix = `[message ${index + 1}] ${formatField(message.senderId)}:`;
111
+ let at = -1;
112
+ for (let i = from; i < lines.length; i += 1) {
113
+ if (lines[i]!.startsWith(`[message ${index + 1}] `)) {
114
+ at = i;
115
+ break;
116
+ }
117
+ }
118
+ if (at < 0) return;
119
+ from = at + 1;
120
+ if (message.senderName && message.senderName !== message.senderId) return;
121
+ const name = nameFor(message.senderId);
122
+ if (!name || name === message.senderId || !lines[at]!.startsWith(prefix)) return;
123
+ lines[at] = `[message ${index + 1}] ${formatField(name)}:${lines[at]!.slice(prefix.length)}`;
124
+ });
125
+ return lines.join("\n");
126
+ }
127
+
96
128
  function groupMessageForPrompt(turn: CoalescableGroupTurn): CoalescedGroupPromptMessage {
97
129
  return {
98
130
  messageId: turn.messageId,