@agentchatme/openclaw 0.7.7 → 0.7.81

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.
@@ -10,15 +10,40 @@ var zod = require('zod');
10
10
  var channelLifecycle = require('openclaw/plugin-sdk/channel-lifecycle');
11
11
  var pino = require('pino');
12
12
  var ws = require('ws');
13
- var directDm = require('openclaw/plugin-sdk/direct-dm');
14
13
  var inboundEnvelope = require('openclaw/plugin-sdk/inbound-envelope');
15
14
  var inboundReplyDispatch = require('openclaw/plugin-sdk/inbound-reply-dispatch');
15
+ var fs2 = require('fs');
16
+ var os = require('os');
17
+ var path2 = require('path');
18
+ var readEnv_js$1 = require('./credentials/read-env.cjs');
16
19
  var agentchatme = require('agentchatme');
20
+ var simpleCompletionRuntime = require('openclaw/plugin-sdk/simple-completion-runtime');
17
21
  var typebox = require('@sinclair/typebox');
18
22
 
19
23
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
20
24
 
25
+ function _interopNamespace(e) {
26
+ if (e && e.__esModule) return e;
27
+ var n = Object.create(null);
28
+ if (e) {
29
+ Object.keys(e).forEach(function (k) {
30
+ if (k !== 'default') {
31
+ var d = Object.getOwnPropertyDescriptor(e, k);
32
+ Object.defineProperty(n, k, d.get ? d : {
33
+ enumerable: true,
34
+ get: function () { return e[k]; }
35
+ });
36
+ }
37
+ });
38
+ }
39
+ n.default = e;
40
+ return Object.freeze(n);
41
+ }
42
+
21
43
  var pino__default = /*#__PURE__*/_interopDefault(pino);
44
+ var fs2__default = /*#__PURE__*/_interopDefault(fs2);
45
+ var os__namespace = /*#__PURE__*/_interopNamespace(os);
46
+ var path2__namespace = /*#__PURE__*/_interopNamespace(path2);
22
47
 
23
48
  // src/channel.setup.ts
24
49
 
@@ -271,9 +296,9 @@ async function registerAgentVerify(input, opts = {}) {
271
296
  }
272
297
  return { ok: false, reason: "server-error", status: res.status, message };
273
298
  }
274
- async function post(path, body, opts) {
299
+ async function post(path3, body, opts) {
275
300
  const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
276
- const url = `${base}${path}`;
301
+ const url = `${base}${path3}`;
277
302
  const controller = new AbortController();
278
303
  const fetchImpl = opts.fetch ?? fetch;
279
304
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -908,9 +933,9 @@ function createLogger(options) {
908
933
  function buildRedactPaths(keys) {
909
934
  const prefixes = ["", "config.", "headers.", "context.", "req.headers.", "res.headers."];
910
935
  const paths = [];
911
- for (const key of keys) {
936
+ for (const key2 of keys) {
912
937
  for (const prefix of prefixes) {
913
- paths.push(`${prefix}${key}`);
938
+ paths.push(`${prefix}${key2}`);
914
939
  }
915
940
  }
916
941
  paths.push(...keys.map((k) => `*.${k}`));
@@ -1726,7 +1751,7 @@ function normalizeGroupDeleted(frame) {
1726
1751
 
1727
1752
  // src/retry.ts
1728
1753
  function defaultSleep(ms) {
1729
- return new Promise((resolve) => setTimeout(resolve, ms));
1754
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1730
1755
  }
1731
1756
  async function retryWithPolicy(fn, policy) {
1732
1757
  const random = policy.random ?? Math.random;
@@ -1854,7 +1879,7 @@ var CircuitBreaker = class {
1854
1879
  };
1855
1880
 
1856
1881
  // src/version.ts
1857
- var PACKAGE_VERSION = "0.7.7";
1882
+ var PACKAGE_VERSION = "0.7.81";
1858
1883
 
1859
1884
  // src/outbound.ts
1860
1885
  var DEFAULT_RETRY_POLICY = {
@@ -2070,11 +2095,11 @@ var OutboundAdapter = class {
2070
2095
  `outbound queue full (${this.queue.length}) \u2014 shedding load`
2071
2096
  );
2072
2097
  }
2073
- return new Promise((resolve) => {
2098
+ return new Promise((resolve2) => {
2074
2099
  this.queue.push(() => {
2075
2100
  this.inFlight++;
2076
2101
  this.metrics.setInFlightDepth(this.inFlight);
2077
- resolve();
2102
+ resolve2();
2078
2103
  });
2079
2104
  });
2080
2105
  }
@@ -2150,10 +2175,10 @@ var AgentchatChannelRuntime = class {
2150
2175
  stop(deadlineMs) {
2151
2176
  if (this.stopPromise) return this.stopPromise;
2152
2177
  const deadline = deadlineMs ?? this.now() + 5e3;
2153
- this.stopPromise = new Promise((resolve) => {
2178
+ this.stopPromise = new Promise((resolve2) => {
2154
2179
  const off = this.ws.on("closed", () => {
2155
2180
  off();
2156
- resolve();
2181
+ resolve2();
2157
2182
  });
2158
2183
  this.ws.stop(deadline);
2159
2184
  });
@@ -2383,6 +2408,457 @@ function unregisterRuntime(accountId, deadlineMs = Date.now() + 5e3) {
2383
2408
  function getRuntime(accountId) {
2384
2409
  return registry.get(accountId)?.runtime;
2385
2410
  }
2411
+ function resolveWorkspaceDir(cfg) {
2412
+ const configured = cfg?.agents?.defaults?.workspace;
2413
+ if (typeof configured === "string" && configured.trim().length > 0) {
2414
+ return path2__namespace.resolve(configured);
2415
+ }
2416
+ const profile = readEnv_js$1.readOpenClawProfileFromEnv();
2417
+ if (profile) {
2418
+ return path2__namespace.join(os__namespace.homedir(), ".openclaw", `workspace-${profile}`);
2419
+ }
2420
+ return path2__namespace.join(os__namespace.homedir(), ".openclaw", "workspace");
2421
+ }
2422
+
2423
+ // src/binding/thread-closures.ts
2424
+ var instances = /* @__PURE__ */ new Map();
2425
+ function fallbackWorkspaceDir() {
2426
+ const profile = process.env.OPENCLAW_PROFILE?.trim();
2427
+ if (profile && profile.toLowerCase() !== "default") {
2428
+ return path2__namespace.default.join(os__namespace.default.homedir(), ".openclaw", `workspace-${profile}`);
2429
+ }
2430
+ return path2__namespace.default.join(os__namespace.default.homedir(), ".openclaw", "workspace");
2431
+ }
2432
+ function resolveStatePath(cfg, accountId) {
2433
+ const workspaceDir = typeof cfg === "object" && cfg !== null ? resolveWorkspaceDir(cfg) : fallbackWorkspaceDir();
2434
+ return path2__namespace.default.join(workspaceDir, `.agentchat-closed-threads-${accountId}.json`);
2435
+ }
2436
+ var ThreadClosures = class {
2437
+ filePath;
2438
+ closed = /* @__PURE__ */ new Map();
2439
+ constructor(filePath) {
2440
+ this.filePath = filePath;
2441
+ this.load();
2442
+ }
2443
+ isClosed(conversationId) {
2444
+ return this.closed.has(conversationId);
2445
+ }
2446
+ close(conversationId, reason) {
2447
+ const record = {
2448
+ conversationId,
2449
+ closedAt: (/* @__PURE__ */ new Date()).toISOString(),
2450
+ reason: reason?.trim() ? reason.trim() : null
2451
+ };
2452
+ this.closed.set(conversationId, record);
2453
+ this.save();
2454
+ return record;
2455
+ }
2456
+ reopen(conversationId) {
2457
+ const existed = this.closed.delete(conversationId);
2458
+ if (existed) this.save();
2459
+ return existed;
2460
+ }
2461
+ list() {
2462
+ return [...this.closed.values()].sort((a, b) => b.closedAt.localeCompare(a.closedAt));
2463
+ }
2464
+ load() {
2465
+ if (!fs2__default.default.existsSync(this.filePath)) return;
2466
+ try {
2467
+ const raw = JSON.parse(fs2__default.default.readFileSync(this.filePath, "utf8"));
2468
+ if (!Array.isArray(raw)) return;
2469
+ for (const entry of raw) {
2470
+ if (!entry || typeof entry !== "object") continue;
2471
+ const conversationId = entry.conversationId;
2472
+ const closedAt = entry.closedAt;
2473
+ const reason = entry.reason;
2474
+ if (typeof conversationId !== "string" || typeof closedAt !== "string") continue;
2475
+ this.closed.set(conversationId, {
2476
+ conversationId,
2477
+ closedAt,
2478
+ reason: typeof reason === "string" ? reason : null
2479
+ });
2480
+ }
2481
+ } catch {
2482
+ this.closed = /* @__PURE__ */ new Map();
2483
+ }
2484
+ }
2485
+ save() {
2486
+ fs2__default.default.mkdirSync(path2__namespace.default.dirname(this.filePath), { recursive: true });
2487
+ const payload = JSON.stringify(this.list(), null, 2);
2488
+ const tempPath = `${this.filePath}.tmp`;
2489
+ fs2__default.default.writeFileSync(tempPath, payload, "utf8");
2490
+ fs2__default.default.renameSync(tempPath, this.filePath);
2491
+ }
2492
+ };
2493
+ function getThreadClosures(cfg, accountId) {
2494
+ const filePath = resolveStatePath(cfg, accountId);
2495
+ const existing = instances.get(filePath);
2496
+ if (existing) return existing;
2497
+ const created = new ThreadClosures(filePath);
2498
+ instances.set(filePath, created);
2499
+ return created;
2500
+ }
2501
+ var cache = /* @__PURE__ */ new Map();
2502
+ function getClient({ accountId, config, options }) {
2503
+ const existing = cache.get(accountId);
2504
+ if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
2505
+ return existing.client;
2506
+ }
2507
+ const client = new agentchatme.AgentChatClient({
2508
+ apiKey: config.apiKey,
2509
+ baseUrl: config.apiBase,
2510
+ ...options
2511
+ });
2512
+ cache.set(accountId, {
2513
+ client,
2514
+ apiKey: config.apiKey,
2515
+ apiBase: config.apiBase
2516
+ });
2517
+ return client;
2518
+ }
2519
+ function disposeClient(accountId) {
2520
+ cache.delete(accountId);
2521
+ }
2522
+
2523
+ // src/binding/send-tracker.ts
2524
+ var lastSendByKey = /* @__PURE__ */ new Map();
2525
+ var MAX_TRACKED = 512;
2526
+ function key(accountId, conversationId) {
2527
+ return `${accountId}\0${conversationId}`;
2528
+ }
2529
+ function recordAgentSend(accountId, conversationId, atMs = Date.now()) {
2530
+ if (!conversationId) return;
2531
+ const k = key(accountId, conversationId);
2532
+ lastSendByKey.delete(k);
2533
+ lastSendByKey.set(k, atMs);
2534
+ if (lastSendByKey.size > MAX_TRACKED) {
2535
+ const oldest = lastSendByKey.keys().next().value;
2536
+ if (oldest !== void 0) lastSendByKey.delete(oldest);
2537
+ }
2538
+ }
2539
+ function hasAgentSendSince(accountId, conversationId, sinceMs) {
2540
+ const at = lastSendByKey.get(key(accountId, conversationId));
2541
+ return at !== void 0 && at >= sinceMs;
2542
+ }
2543
+
2544
+ // src/binding/reply-gate.ts
2545
+ var DEFAULT_GATE_MAX_TOKENS = 256;
2546
+ var MAX_HISTORY_TURNS = 12;
2547
+ var CADENCE_WINDOW_SECONDS = 60;
2548
+ var VALID_CATEGORIES = /* @__PURE__ */ new Set([
2549
+ "open_request",
2550
+ "new_info",
2551
+ "goal_followup",
2552
+ "closing",
2553
+ "acknowledgement",
2554
+ "not_addressed",
2555
+ "no_action_needed",
2556
+ "spam",
2557
+ "other"
2558
+ ]);
2559
+ var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "yes", "true", "respond"]);
2560
+ var NO_REPLY_TOKENS = /* @__PURE__ */ new Set([
2561
+ "no_reply",
2562
+ "no-reply",
2563
+ "noreply",
2564
+ "no",
2565
+ "false",
2566
+ "silent",
2567
+ "skip",
2568
+ "none"
2569
+ ]);
2570
+ var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
2571
+ function computeConversationSignals(messages, params) {
2572
+ const windowSeconds = params.windowSeconds ?? CADENCE_WINDOW_SECONDS;
2573
+ const own = normalizeHandle(params.ownHandle);
2574
+ const prior = messages.filter(
2575
+ (m) => isRecord(m) && m.id !== params.triggerMessageId
2576
+ );
2577
+ const firstContact = prior.length === 0;
2578
+ const youHaveSpoken = prior.some((m) => messageIsOwn(m, own));
2579
+ const timestamps = [];
2580
+ for (const m of prior) {
2581
+ const ts = parseTimestamp(m.created_at);
2582
+ if (ts !== null) timestamps.push(ts);
2583
+ }
2584
+ const cutoff = params.nowMs - windowSeconds * 1e3;
2585
+ const recentInWindow = timestamps.filter((ts) => ts >= cutoff).length;
2586
+ let secondsSincePrevious = null;
2587
+ if (timestamps.length > 0) {
2588
+ const delta = (params.nowMs - Math.max(...timestamps)) / 1e3;
2589
+ secondsSincePrevious = delta > 0 ? delta : 0;
2590
+ }
2591
+ return {
2592
+ firstContact,
2593
+ youHaveSpoken,
2594
+ messagesLastWindow: recentInWindow + 1,
2595
+ // +1 for the new message
2596
+ secondsSincePrevious
2597
+ };
2598
+ }
2599
+ function messageIsOwn(msg, ownHandleNorm) {
2600
+ if (typeof msg.is_own === "boolean") return msg.is_own;
2601
+ const sender = msg.sender ?? msg.from ?? msg.sender_handle ?? "";
2602
+ return normalizeHandle(String(sender)) === ownHandleNorm;
2603
+ }
2604
+ function parseTimestamp(raw) {
2605
+ if (typeof raw !== "string" || !raw) return null;
2606
+ const t = Date.parse(raw);
2607
+ return Number.isNaN(t) ? null : t;
2608
+ }
2609
+ function normalizeHandle(handle) {
2610
+ return handle.replace(/^@/, "").toLowerCase();
2611
+ }
2612
+ function isRecord(value) {
2613
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2614
+ }
2615
+ function systemTemplate(handle) {
2616
+ const h = `@${handle}`;
2617
+ return `You are the reply gate for ${h}, an autonomous agent on AgentChat (a peer-to-peer messaging network for AI agents). A message just arrived. Your only job is to decide whether ${h} should reply to it now. You do NOT write the reply \u2014 you output one decision.
2618
+
2619
+ "no_reply" is a SUCCESS, not a failure. Most healthy conversations are SUPPOSED to end; going quiet is the normal, correct outcome and is never rude here \u2014 on this network silence IS the acknowledgement.
2620
+
2621
+ Judge DONE-NESS, not how interesting another message could be:
2622
+
2623
+ Choose "reply" only if a further message accomplishes a concrete, still-OPEN purpose:
2624
+ - answer a substantive pending question or supply specifically requested information
2625
+ - make or respond to a decision, or unblock the peer on a real task
2626
+ - ${h} started this thread toward a goal and the peer's reply needs a substantive follow-up to reach it
2627
+ - new information genuinely requires ${h}'s input
2628
+
2629
+ Choose "no_reply" when the exchange has reached its natural end \u2014 even if another clever or friendly message is easily possible:
2630
+ - it is trading pleasantries, mutual appreciation, agreement, or open-ended tangents / "riffing" with no open objective
2631
+ - a courtesy question that merely mirrors the exchange back ("and you?", "what are you working on?", "what tools are you using?") after the substantive part has run its course is part of the pleasantry, not an open task \u2014 it does not oblige a reply
2632
+ - the other side is acknowledging or closing out (thanks / ok / got it / sounds good / \u{1F44D} / bye) and replying would only prolong it
2633
+ - ${h} already answered what was asked and nothing new is on the table
2634
+ - in a group, the message is not addressed to ${h} and does not need it. (Groups only \u2014 in a direct conversation every message is addressed to ${h} by definition, so "not_addressed" never applies there.)
2635
+
2636
+ "I could add something" is NOT a reason to reply. "Something concrete is unresolved and my reply resolves it" IS. Two agents keeping a chat alive by each politely asking the next question is the exact failure you exist to prevent \u2014 the thread being pleasant does not make it open. If the Pace line shows messages flying back and forth with each turn only restating, appreciating, or re-asking a mirrored question, that IS the loop \u2014 choose "no_reply". When unsure, prefer "no_reply".
2637
+
2638
+ Respond with ONLY a JSON object \u2014 no prose, no markdown fences:
2639
+ {"decision": "reply" or "no_reply", "reason": "<one short sentence>", "category": "<one of: open_request, new_info, goal_followup, closing, acknowledgement, not_addressed, no_action_needed, spam, other>"}`;
2640
+ }
2641
+ function buildDecisionMessages(params) {
2642
+ return [
2643
+ { role: "system", content: systemTemplate(params.handle) },
2644
+ {
2645
+ role: "user",
2646
+ content: buildUserContent({
2647
+ handle: params.handle,
2648
+ event: params.event,
2649
+ history: params.history,
2650
+ signals: params.signals ?? null,
2651
+ maxHistory: params.maxHistory ?? MAX_HISTORY_TURNS
2652
+ })
2653
+ }
2654
+ ];
2655
+ }
2656
+ function buildUserContent(params) {
2657
+ const { handle, event, history, signals, maxHistory } = params;
2658
+ const kind = event.conversationKind === "group" ? "group" : "direct";
2659
+ const lines = [`Conversation type: ${kind}`];
2660
+ if (signals) {
2661
+ lines.push(`Relationship: ${relationshipPhrase(signals)}`);
2662
+ if (signals.secondsSincePrevious !== null) {
2663
+ lines.push(
2664
+ `Pace: ${signals.messagesLastWindow} message(s) in the last ${CADENCE_WINDOW_SECONDS}s; ${formatGap(signals.secondsSincePrevious)} since the previous message`
2665
+ );
2666
+ }
2667
+ }
2668
+ lines.push(`Prior messages in this thread: ${history.length}`);
2669
+ if (kind === "group") {
2670
+ const mentioned = (event.contentText || "").toLowerCase().includes(`@${handle.toLowerCase()}`);
2671
+ lines.push(
2672
+ `Message directly addresses you: ${mentioned ? "yes" : "not explicitly"}`
2673
+ );
2674
+ }
2675
+ lines.push("");
2676
+ const rendered = renderHistory(history, maxHistory);
2677
+ if (rendered.length > 0) {
2678
+ lines.push("Recent conversation (oldest first):");
2679
+ lines.push(...rendered);
2680
+ } else {
2681
+ lines.push("Recent conversation: (none \u2014 this is first contact)");
2682
+ }
2683
+ let newText = collapseWhitespace(event.contentText || "");
2684
+ if (newText.length > 2e3) newText = `${newText.slice(0, 2e3)}\u2026`;
2685
+ lines.push("");
2686
+ lines.push(`New message from @${event.senderHandle}: ${newText}`);
2687
+ lines.push("");
2688
+ lines.push("Decide now: reply or no_reply?");
2689
+ return lines.join("\n");
2690
+ }
2691
+ function renderHistory(history, maxHistory) {
2692
+ const recent = history.length > maxHistory ? history.slice(history.length - maxHistory) : history;
2693
+ const out = [];
2694
+ for (const turn of recent) {
2695
+ if (typeof turn.content !== "string" || !turn.content.trim()) continue;
2696
+ const speaker = turn.role === "assistant" ? "you" : "peer";
2697
+ let text = collapseWhitespace(turn.content);
2698
+ if (text.length > 400) text = `${text.slice(0, 400)}\u2026`;
2699
+ out.push(`${speaker}: ${text}`);
2700
+ }
2701
+ return out;
2702
+ }
2703
+ function relationshipPhrase(signals) {
2704
+ if (signals.firstContact) return "first contact \u2014 no prior messages in this thread";
2705
+ if (signals.youHaveSpoken) return "established \u2014 you have already replied in this thread";
2706
+ return "this peer is messaging you, but you have not replied yet";
2707
+ }
2708
+ function formatGap(seconds) {
2709
+ if (seconds < 90) return `${Math.round(seconds)}s`;
2710
+ if (seconds < 5400) return `${Math.round(seconds / 60)}m`;
2711
+ return `${Math.round(seconds / 3600)}h`;
2712
+ }
2713
+ function collapseWhitespace(text) {
2714
+ return text.split(/\s+/).filter(Boolean).join(" ");
2715
+ }
2716
+ function parseDecision(text, opts = {}) {
2717
+ const raw = extractJson(text);
2718
+ if (raw === null) return null;
2719
+ let obj;
2720
+ try {
2721
+ obj = JSON.parse(raw);
2722
+ } catch {
2723
+ return null;
2724
+ }
2725
+ if (!isRecord(obj)) return null;
2726
+ const decisionRaw = obj.decision;
2727
+ if (typeof decisionRaw !== "string") return null;
2728
+ const token = decisionRaw.trim().toLowerCase();
2729
+ let reply;
2730
+ if (REPLY_TOKENS.has(token)) reply = true;
2731
+ else if (NO_REPLY_TOKENS.has(token)) reply = false;
2732
+ else return null;
2733
+ const reasonRaw = obj.reason;
2734
+ let reason = typeof reasonRaw === "string" ? reasonRaw.trim() : "";
2735
+ if (reason.length > 280) reason = reason.slice(0, 280);
2736
+ const categoryRaw = obj.category;
2737
+ let category = typeof categoryRaw === "string" ? categoryRaw.trim().toLowerCase() : "other";
2738
+ if (!VALID_CATEGORIES.has(category)) category = "other";
2739
+ return {
2740
+ reply,
2741
+ reason,
2742
+ category,
2743
+ source: opts.source ?? "llm",
2744
+ latencyMs: opts.latencyMs ?? 0
2745
+ };
2746
+ }
2747
+ function extractJson(text) {
2748
+ if (!text || !text.trim()) return null;
2749
+ let s = text.trim();
2750
+ const fence = FENCE_RE.exec(s);
2751
+ if (fence?.[1]) s = fence[1].trim();
2752
+ const start = s.indexOf("{");
2753
+ const end = s.lastIndexOf("}");
2754
+ if (start === -1 || end === -1 || end <= start) return null;
2755
+ return s.slice(start, end + 1);
2756
+ }
2757
+ function gateFallback(failOpen, reason, latencyMs) {
2758
+ return {
2759
+ reply: failOpen,
2760
+ reason,
2761
+ category: "fallback",
2762
+ source: failOpen ? "fail_open" : "fail_closed",
2763
+ latencyMs
2764
+ };
2765
+ }
2766
+
2767
+ // src/binding/gate.ts
2768
+ var DEFAULT_GATE_TIMEOUT_MS = 2e4;
2769
+ var GATE_REASONING_LEVEL = "off";
2770
+ var GateTimeoutError = class extends Error {
2771
+ };
2772
+ function withTimeout(promise, ms) {
2773
+ if (!Number.isFinite(ms) || ms <= 0) return promise;
2774
+ return new Promise((resolve2, reject) => {
2775
+ const timer = setTimeout(() => reject(new GateTimeoutError("gate decision timed out")), ms);
2776
+ promise.then(
2777
+ (value) => {
2778
+ clearTimeout(timer);
2779
+ resolve2(value);
2780
+ },
2781
+ (err3) => {
2782
+ clearTimeout(timer);
2783
+ reject(err3);
2784
+ }
2785
+ );
2786
+ });
2787
+ }
2788
+ async function decideReply(params) {
2789
+ const signals = computeConversationSignals(params.rawMessages, {
2790
+ ownHandle: params.ownHandle,
2791
+ triggerMessageId: params.triggerMessageId,
2792
+ nowMs: params.nowMs
2793
+ });
2794
+ const messages = buildDecisionMessages({
2795
+ handle: params.handle,
2796
+ event: params.event,
2797
+ history: params.history,
2798
+ signals
2799
+ });
2800
+ const systemPrompt = messages.find((m) => m.role === "system")?.content ?? "";
2801
+ const userContent = messages.find((m) => m.role === "user")?.content ?? "";
2802
+ const caller = params.caller ?? createSimpleCompletionGateCaller(params.cfg, params.agentId);
2803
+ const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
2804
+ const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
2805
+ const start = Date.now();
2806
+ let text;
2807
+ try {
2808
+ text = await withTimeout(caller({ systemPrompt, userContent, maxTokens }), timeoutMs);
2809
+ } catch (err3) {
2810
+ if (err3 instanceof GateTimeoutError) {
2811
+ return gateFallback(params.failOpen, "decision_timeout", Date.now() - start);
2812
+ }
2813
+ const detail = err3 instanceof Error ? err3.message : String(err3);
2814
+ return gateFallback(
2815
+ params.failOpen,
2816
+ `decision_call_error: ${detail}`.slice(0, 220),
2817
+ Date.now() - start
2818
+ );
2819
+ }
2820
+ const latencyMs = Date.now() - start;
2821
+ const parsed = parseDecision(text, { source: "llm", latencyMs });
2822
+ return parsed ?? gateFallback(params.failOpen, "unparseable_decision", latencyMs);
2823
+ }
2824
+ function createSimpleCompletionGateCaller(cfg, agentId) {
2825
+ return async ({ systemPrompt, userContent, maxTokens, signal }) => {
2826
+ const prepared = await simpleCompletionRuntime.prepareSimpleCompletionModelForAgent({
2827
+ cfg,
2828
+ // plugin-local OpenClawConfig alias → sdk's internal type
2829
+ agentId,
2830
+ allowMissingApiKeyModes: ["aws-sdk"],
2831
+ // Do NOT skip discovery: it loads provider model catalogs. Skipping it
2832
+ // works for providers with pure dynamic resolution (e.g. Fireworks) but
2833
+ // makes catalog-based providers (Google/Gemini, Anthropic, OpenAI, …)
2834
+ // fail with "Unknown model: <ref>" — the gate must resolve the agent's
2835
+ // own model regardless of which provider it runs on.
2836
+ skipAgentDiscovery: false
2837
+ });
2838
+ if ("error" in prepared) throw new Error(prepared.error);
2839
+ const result = await simpleCompletionRuntime.completeWithPreparedSimpleCompletionModel({
2840
+ model: prepared.model,
2841
+ auth: prepared.auth,
2842
+ cfg,
2843
+ context: {
2844
+ systemPrompt,
2845
+ messages: [{ role: "user", content: userContent }]
2846
+ },
2847
+ // temperature 0 mirrors the Hermes gate: a binary policy decision must
2848
+ // be as deterministic as the provider allows, not sampled creatively.
2849
+ options: {
2850
+ maxTokens,
2851
+ temperature: 0,
2852
+ reasoning: GATE_REASONING_LEVEL,
2853
+ ...signal ? { signal } : {}
2854
+ }
2855
+ });
2856
+ return result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("");
2857
+ };
2858
+ }
2859
+
2860
+ // src/binding/inbound-bridge.ts
2861
+ var GATE_HISTORY_LIMIT = 30;
2386
2862
  function createInboundBridge(deps) {
2387
2863
  return async function onInbound(event) {
2388
2864
  switch (event.kind) {
@@ -2419,6 +2895,17 @@ async function handleMessage(deps, event) {
2419
2895
  if (!body && !event.content.attachmentId && !event.content.data) {
2420
2896
  return;
2421
2897
  }
2898
+ const threadClosures = getThreadClosures(
2899
+ deps.gatewayCfg,
2900
+ deps.accountId
2901
+ );
2902
+ if (threadClosures.isClosed(event.conversationId)) {
2903
+ deps.logger.info(
2904
+ { conversationId: event.conversationId, messageId: event.messageId, sender: event.sender },
2905
+ "inbound skipped for locally closed thread"
2906
+ );
2907
+ return;
2908
+ }
2422
2909
  const channelRuntime = deps.channelRuntime;
2423
2910
  if (!channelRuntime || typeof channelRuntime.reply?.dispatchReplyWithBufferedBlockDispatcher !== "function") {
2424
2911
  deps.logger.error(
@@ -2433,6 +2920,7 @@ async function handleMessage(deps, event) {
2433
2920
  );
2434
2921
  return;
2435
2922
  }
2923
+ const ts = typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt);
2436
2924
  const recipientHandle = selfHandle ?? "me";
2437
2925
  const conversationLabel = event.conversationKind === "group" ? `group ${event.conversationId}` : `dm with @${senderHandle}`;
2438
2926
  const sendReply = async (replyText) => {
@@ -2445,36 +2933,107 @@ async function handleMessage(deps, event) {
2445
2933
  metadata: { reply_to: event.messageId }
2446
2934
  });
2447
2935
  };
2936
+ const turnStartMs = Date.now();
2448
2937
  const deliver2 = async (payload) => {
2449
- const replyText = payload.text ?? extractText(payload.blocks);
2450
- await sendReply(replyText);
2938
+ if (threadClosures.isClosed(event.conversationId)) {
2939
+ deps.logger.info(
2940
+ { conversationId: event.conversationId, messageId: event.messageId },
2941
+ "reply suppressed for locally closed thread"
2942
+ );
2943
+ return;
2944
+ }
2945
+ if (hasAgentSendSince(deps.accountId, event.conversationId, turnStartMs)) {
2946
+ deps.logger.info(
2947
+ { conversationId: event.conversationId, messageId: event.messageId },
2948
+ "final turn text suppressed \u2014 agent already sent its reply via a message tool this turn"
2949
+ );
2950
+ return;
2951
+ }
2952
+ await sendReply(payload.text ?? extractText(payload.blocks));
2451
2953
  };
2452
2954
  try {
2453
- if (event.conversationKind === "direct") {
2454
- await directDm.dispatchInboundDirectDmWithRuntime({
2455
- cfg: deps.gatewayCfg,
2456
- runtime: { channel: channelRuntime },
2457
- channel: "agentchat",
2458
- channelLabel: "AgentChat",
2459
- accountId: deps.accountId,
2460
- peer: { kind: "direct", id: senderHandle },
2461
- senderId: senderHandle,
2462
- senderAddress: `@${senderHandle}`,
2463
- recipientAddress: `@${recipientHandle}`,
2464
- conversationLabel,
2465
- rawBody: body,
2466
- messageId: event.messageId,
2467
- timestamp: typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt),
2468
- provider: "agentchat",
2469
- surface: "agentchat",
2470
- deliver: deliver2,
2471
- onRecordError: (err3) => {
2472
- deps.logger.error(
2473
- { err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
2474
- "recordInboundSession failed"
2475
- );
2955
+ const runtime = channelRuntime;
2956
+ const peer = event.conversationKind === "group" ? { kind: "group", id: event.conversationId } : { kind: "direct", id: senderHandle };
2957
+ const { route, buildEnvelope } = inboundEnvelope.resolveInboundRouteEnvelopeBuilderWithRuntime({
2958
+ cfg: deps.gatewayCfg,
2959
+ channel: "agentchat",
2960
+ accountId: deps.accountId,
2961
+ peer,
2962
+ runtime
2963
+ });
2964
+ if (gateEnabled()) {
2965
+ const decision = await runReplyGate({
2966
+ deps,
2967
+ event,
2968
+ body,
2969
+ agentId: route.agentId,
2970
+ selfHandle,
2971
+ senderHandle,
2972
+ nowMs: Number.isFinite(ts) ? ts : Date.now()
2973
+ });
2974
+ deps.logger.info(
2975
+ {
2976
+ conversationId: event.conversationId,
2977
+ messageId: event.messageId,
2978
+ reply: decision.reply,
2979
+ source: decision.source,
2980
+ category: decision.category,
2981
+ latencyMs: decision.latencyMs,
2982
+ reason: decision.reason
2476
2983
  },
2477
- onDispatchError: (err3, info) => {
2984
+ "reply gate decision"
2985
+ );
2986
+ if (!decision.reply) return;
2987
+ }
2988
+ const { storePath, body: envelopeBody } = buildEnvelope({
2989
+ channel: "AgentChat",
2990
+ from: conversationLabel,
2991
+ body,
2992
+ timestamp: ts
2993
+ });
2994
+ const finalize = channelRuntime.reply.finalizeInboundContext;
2995
+ const ctxPayload = finalize({
2996
+ Body: envelopeBody,
2997
+ BodyForAgent: body,
2998
+ RawBody: body,
2999
+ CommandBody: body,
3000
+ From: `@${senderHandle}`,
3001
+ To: `@${recipientHandle}`,
3002
+ SessionKey: route.sessionKey,
3003
+ AccountId: deps.accountId,
3004
+ ChatType: event.conversationKind === "group" ? "group" : "direct",
3005
+ ConversationLabel: conversationLabel,
3006
+ SenderId: senderHandle,
3007
+ Provider: "agentchat",
3008
+ Surface: "agentchat",
3009
+ MessageSid: event.messageId,
3010
+ MessageSidFull: event.messageId,
3011
+ Timestamp: ts,
3012
+ OriginatingChannel: "agentchat",
3013
+ OriginatingTo: `@${recipientHandle}`
3014
+ });
3015
+ const session = channelRuntime.session;
3016
+ await inboundReplyDispatch.dispatchChannelInboundReply({
3017
+ cfg: deps.gatewayCfg,
3018
+ channel: "agentchat",
3019
+ accountId: deps.accountId,
3020
+ agentId: route.agentId,
3021
+ routeSessionKey: route.sessionKey,
3022
+ storePath,
3023
+ ctxPayload,
3024
+ recordInboundSession: session.recordInboundSession,
3025
+ dispatchReplyWithBufferedBlockDispatcher: channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
3026
+ // Under `automatic` (the default) the framework hands the agent's final
3027
+ // turn text to this `deliver`, which sends it to the source. Under the
3028
+ // opt-in `message_tool_only` mode the turn text is suppressed and the
3029
+ // agent sends via the message tool instead, so `deliver` only fires on a
3030
+ // framework fallback. Either way a gated `no_reply` turn never runs, so
3031
+ // nothing is sent.
3032
+ delivery: {
3033
+ deliver: async (payload) => {
3034
+ await deliver2(payload);
3035
+ },
3036
+ onError: (err3, info) => {
2478
3037
  deps.logger.error(
2479
3038
  {
2480
3039
  err: err3 instanceof Error ? err3.message : String(err3),
@@ -2484,84 +3043,103 @@ async function handleMessage(deps, event) {
2484
3043
  "inbound dispatch failed"
2485
3044
  );
2486
3045
  }
2487
- });
2488
- } else {
2489
- const ts = typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt);
2490
- const runtime = channelRuntime;
2491
- const { route, buildEnvelope } = inboundEnvelope.resolveInboundRouteEnvelopeBuilderWithRuntime({
2492
- cfg: deps.gatewayCfg,
2493
- channel: "agentchat",
2494
- accountId: deps.accountId,
2495
- peer: { kind: "group", id: event.conversationId },
2496
- runtime
2497
- });
2498
- const { storePath, body: envelopeBody } = buildEnvelope({
2499
- channel: "AgentChat",
2500
- from: conversationLabel,
2501
- body,
2502
- timestamp: ts
2503
- });
2504
- const finalize = channelRuntime.reply.finalizeInboundContext;
2505
- const ctxPayload = finalize({
2506
- Body: envelopeBody,
2507
- BodyForAgent: body,
2508
- RawBody: body,
2509
- CommandBody: body,
2510
- From: `@${senderHandle}`,
2511
- To: `@${recipientHandle}`,
2512
- SessionKey: route.sessionKey,
2513
- AccountId: deps.accountId,
2514
- ChatType: "group",
2515
- ConversationLabel: conversationLabel,
2516
- SenderId: senderHandle,
2517
- Provider: "agentchat",
2518
- Surface: "agentchat",
2519
- MessageSid: event.messageId,
2520
- MessageSidFull: event.messageId,
2521
- Timestamp: ts,
2522
- OriginatingChannel: "agentchat",
2523
- OriginatingTo: `@${recipientHandle}`
2524
- });
2525
- const session = channelRuntime.session;
2526
- await inboundReplyDispatch.recordInboundSessionAndDispatchReply({
2527
- cfg: deps.gatewayCfg,
2528
- channel: "agentchat",
2529
- accountId: deps.accountId,
2530
- agentId: route.agentId,
2531
- routeSessionKey: route.sessionKey,
2532
- storePath,
2533
- ctxPayload,
2534
- recordInboundSession: session.recordInboundSession,
2535
- dispatchReplyWithBufferedBlockDispatcher: channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
2536
- deliver: deliver2,
3046
+ },
3047
+ replyOptions: { sourceReplyDeliveryMode: resolveSourceReplyMode() },
3048
+ record: {
2537
3049
  onRecordError: (err3) => {
2538
3050
  deps.logger.error(
2539
3051
  { err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
2540
- "recordInboundSession failed (group)"
2541
- );
2542
- },
2543
- onDispatchError: (err3, info) => {
2544
- deps.logger.error(
2545
- {
2546
- err: err3 instanceof Error ? err3.message : String(err3),
2547
- messageId: event.messageId,
2548
- kind: info.kind
2549
- },
2550
- "inbound dispatch failed (group)"
3052
+ "recordInboundSession failed"
2551
3053
  );
2552
3054
  }
2553
- });
2554
- }
3055
+ }
3056
+ });
2555
3057
  } catch (err3) {
2556
3058
  deps.logger.error(
2557
- {
2558
- err: err3 instanceof Error ? err3.message : String(err3),
2559
- messageId: event.messageId
2560
- },
3059
+ { err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
2561
3060
  "inbound dispatch failed"
2562
3061
  );
2563
3062
  }
2564
3063
  }
3064
+ async function runReplyGate(params) {
3065
+ const { deps, event, body, agentId, selfHandle, senderHandle, nowMs } = params;
3066
+ const ownHandle = selfHandle ?? "";
3067
+ let rawMessages = [];
3068
+ try {
3069
+ const client = getClient({ accountId: deps.accountId, config: deps.config });
3070
+ const fetched = await client.getMessages(event.conversationId, { limit: GATE_HISTORY_LIMIT });
3071
+ if (Array.isArray(fetched)) rawMessages = fetched;
3072
+ } catch (err3) {
3073
+ deps.logger.warn(
3074
+ { err: err3 instanceof Error ? err3.message : String(err3), conversationId: event.conversationId },
3075
+ "reply gate: history fetch failed \u2014 deciding on the new message alone"
3076
+ );
3077
+ }
3078
+ const gateEvent = {
3079
+ conversationKind: event.conversationKind,
3080
+ senderHandle,
3081
+ contentText: body
3082
+ };
3083
+ return decideReply({
3084
+ cfg: deps.gatewayCfg,
3085
+ agentId,
3086
+ handle: ownHandle.replace(/^@/, ""),
3087
+ event: gateEvent,
3088
+ history: translateHistory(rawMessages, ownHandle, event.conversationKind, event.messageId),
3089
+ rawMessages,
3090
+ triggerMessageId: event.messageId,
3091
+ ownHandle,
3092
+ nowMs,
3093
+ failOpen: gateFailOpen(),
3094
+ timeoutMs: gateTimeoutMs(),
3095
+ caller: deps.gateCaller
3096
+ });
3097
+ }
3098
+ function translateHistory(messages, ownHandle, conversationKind, triggerMessageId) {
3099
+ const own = ownHandle.replace(/^@/, "").toLowerCase();
3100
+ const isGroup = conversationKind === "group";
3101
+ const sorted = [...messages].filter((m) => Boolean(m) && typeof m === "object").sort((a, b) => readSeq(a) - readSeq(b));
3102
+ const out = [];
3103
+ for (const m of sorted) {
3104
+ if (m.id === triggerMessageId) continue;
3105
+ const type = typeof m.type === "string" ? m.type : "text";
3106
+ if (type !== "text") continue;
3107
+ const content = m.content;
3108
+ const text = content && typeof content === "object" ? content.text : void 0;
3109
+ if (typeof text !== "string" || !text) continue;
3110
+ const senderRaw = String(m.sender ?? m.from ?? m.sender_handle ?? "");
3111
+ const isOwn = typeof m.is_own === "boolean" ? m.is_own : senderRaw.replace(/^@/, "").toLowerCase() === own;
3112
+ if (isOwn) {
3113
+ out.push({ role: "assistant", content: text });
3114
+ } else if (isGroup) {
3115
+ out.push({ role: "user", content: `[@${senderRaw.replace(/^@/, "") || "?"}] ${text}` });
3116
+ } else {
3117
+ out.push({ role: "user", content: text });
3118
+ }
3119
+ }
3120
+ return out;
3121
+ }
3122
+ function readSeq(m) {
3123
+ const seq = m.seq;
3124
+ return typeof seq === "number" ? seq : 0;
3125
+ }
3126
+ var OFF_TOKENS = /* @__PURE__ */ new Set(["0", "false", "off", "no"]);
3127
+ var ON_TOKENS = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
3128
+ function gateEnabled() {
3129
+ return !OFF_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_ENABLED ?? "").trim().toLowerCase());
3130
+ }
3131
+ function gateFailOpen() {
3132
+ return ON_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_FAIL_OPEN ?? "").trim().toLowerCase());
3133
+ }
3134
+ function gateTimeoutMs() {
3135
+ const raw = process.env.AGENTCHAT_REPLY_GATE_TIMEOUT_MS;
3136
+ if (raw === void 0 || raw.trim() === "") return void 0;
3137
+ const n = Number(raw);
3138
+ return Number.isFinite(n) && n > 0 ? n : void 0;
3139
+ }
3140
+ function resolveSourceReplyMode() {
3141
+ return (process.env.AGENTCHAT_SOURCE_REPLY_MODE ?? "").trim().toLowerCase() === "message_tool_only" ? "message_tool_only" : "automatic";
3142
+ }
2565
3143
  function handleGroupInvite(deps, event) {
2566
3144
  deps.logger.info(
2567
3145
  {
@@ -2709,27 +3287,6 @@ var agentchatGatewayAdapter = {
2709
3287
  });
2710
3288
  }
2711
3289
  };
2712
- var cache = /* @__PURE__ */ new Map();
2713
- function getClient({ accountId, config, options }) {
2714
- const existing = cache.get(accountId);
2715
- if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
2716
- return existing.client;
2717
- }
2718
- const client = new agentchatme.AgentChatClient({
2719
- apiKey: config.apiKey,
2720
- baseUrl: config.apiBase,
2721
- ...options
2722
- });
2723
- cache.set(accountId, {
2724
- client,
2725
- apiKey: config.apiKey,
2726
- apiBase: config.apiBase
2727
- });
2728
- return client;
2729
- }
2730
- function disposeClient(accountId) {
2731
- cache.delete(accountId);
2732
- }
2733
3290
 
2734
3291
  // src/binding/outbound.ts
2735
3292
  function resolveConfig(cfg, accountId) {
@@ -2791,6 +3348,7 @@ async function deliver(ctx, attachmentId) {
2791
3348
  attachmentId
2792
3349
  );
2793
3350
  const result = await runtime.sendMessage(input);
3351
+ recordAgentSend(accountId, result.message.conversation_id);
2794
3352
  return {
2795
3353
  channel: AGENTCHAT_CHANNEL_ID,
2796
3354
  messageId: result.message.id,
@@ -2860,8 +3418,8 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
2860
3418
  let contentType;
2861
3419
  let filename = "attachment";
2862
3420
  if (mediaUrl.startsWith("file://") && ctx.mediaReadFile) {
2863
- const path = decodeURIComponent(mediaUrl.replace(/^file:\/\//, ""));
2864
- const buf = await ctx.mediaReadFile(path);
3421
+ const path3 = decodeURIComponent(mediaUrl.replace(/^file:\/\//, ""));
3422
+ const buf = await ctx.mediaReadFile(path3);
2865
3423
  if (buf.byteLength > MAX_MEDIA_BYTES) {
2866
3424
  throw new AgentChatChannelError(
2867
3425
  "terminal-user",
@@ -2871,7 +3429,7 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
2871
3429
  const copy = new Uint8Array(buf.byteLength);
2872
3430
  copy.set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
2873
3431
  bytes = copy.buffer;
2874
- filename = path.split(/[\\/]/).pop() ?? filename;
3432
+ filename = path3.split(/[\\/]/).pop() ?? filename;
2875
3433
  } else {
2876
3434
  assertMediaUrlSafe(mediaUrl);
2877
3435
  const controller = new AbortController();
@@ -3026,8 +3584,8 @@ function err(message) {
3026
3584
  details: { error: message }
3027
3585
  };
3028
3586
  }
3029
- function str(params, key) {
3030
- const v = params[key];
3587
+ function str(params, key2) {
3588
+ const v = params[key2];
3031
3589
  return typeof v === "string" ? v : void 0;
3032
3590
  }
3033
3591
  function resolveConfig2(ctx) {
@@ -3284,6 +3842,7 @@ var agentchatAgentToolsFactory = ({ cfg }) => {
3284
3842
  content: { text: p.message },
3285
3843
  ...p.replyToMessageId ? { metadata: { reply_to: p.replyToMessageId } } : {}
3286
3844
  });
3845
+ recordAgentSend(r.accountId, result.message.conversation_id);
3287
3846
  const summaryParts = [
3288
3847
  `sent to @${handle} \u2014 message ${result.message.id} in ${result.message.conversation_id}`
3289
3848
  ];
@@ -3806,6 +4365,88 @@ ${lines.join("\n")}`);
3806
4365
  }
3807
4366
  }
3808
4367
  }),
4368
+ tool({
4369
+ name: "agentchat_close_local_thread",
4370
+ description: "Locally close a conversation thread for this OpenClaw AgentChat account. Future inbound on this exact conversation id will not enter the reply pipeline here, but this does not block the peer and either side can still start a brand-new thread later.",
4371
+ parameters: typebox.Type.Object({
4372
+ conversationId: typebox.Type.String(),
4373
+ reason: typebox.Type.Optional(typebox.Type.String({ maxLength: 200 })),
4374
+ account: ACCOUNT_PARAM
4375
+ }),
4376
+ execute: async (_id, p) => {
4377
+ const r = clientFor(cfg, p.account);
4378
+ if ("error" in r) return err2(r.error);
4379
+ const closures = getThreadClosures(cfg, r.accountId);
4380
+ const record = closures.close(p.conversationId, p.reason);
4381
+ return {
4382
+ content: [
4383
+ {
4384
+ type: "text",
4385
+ text: `closed ${record.conversationId} locally`
4386
+ }
4387
+ ],
4388
+ details: {
4389
+ conversationId: record.conversationId,
4390
+ closedAt: record.closedAt,
4391
+ reason: record.reason,
4392
+ localOnly: true
4393
+ }
4394
+ };
4395
+ }
4396
+ }),
4397
+ tool({
4398
+ name: "agentchat_reopen_local_thread",
4399
+ description: "Re-open a previously locally closed conversation thread so new inbound on that conversation id can reach the reply pipeline again.",
4400
+ parameters: typebox.Type.Object({
4401
+ conversationId: typebox.Type.String(),
4402
+ account: ACCOUNT_PARAM
4403
+ }),
4404
+ execute: async (_id, p) => {
4405
+ const r = clientFor(cfg, p.account);
4406
+ if ("error" in r) return err2(r.error);
4407
+ const closures = getThreadClosures(cfg, r.accountId);
4408
+ const reopened = closures.reopen(p.conversationId);
4409
+ return {
4410
+ content: [
4411
+ {
4412
+ type: "text",
4413
+ text: reopened ? `re-opened ${p.conversationId} locally` : `${p.conversationId} was not locally closed`
4414
+ }
4415
+ ],
4416
+ details: {
4417
+ conversationId: p.conversationId,
4418
+ reopened,
4419
+ localOnly: true
4420
+ }
4421
+ };
4422
+ }
4423
+ }),
4424
+ tool({
4425
+ name: "agentchat_list_local_closed_threads",
4426
+ description: "List conversation threads currently closed locally for this OpenClaw AgentChat account. These are client-side only, not server-side blocks or mutes.",
4427
+ parameters: typebox.Type.Object({
4428
+ account: ACCOUNT_PARAM
4429
+ }),
4430
+ execute: async (_id, p) => {
4431
+ const r = clientFor(cfg, p.account);
4432
+ if ("error" in r) return err2(r.error);
4433
+ const closures = getThreadClosures(cfg, r.accountId);
4434
+ const closed = closures.list();
4435
+ if (closed.length === 0) {
4436
+ return {
4437
+ content: [{ type: "text", text: "no locally closed threads" }],
4438
+ details: { closedThreads: [], localOnly: true }
4439
+ };
4440
+ }
4441
+ const lines = closed.map(
4442
+ (record) => `${record.conversationId} \u2014 ${record.closedAt}${record.reason ? ` \u2014 ${record.reason}` : ""}`
4443
+ );
4444
+ return {
4445
+ content: [{ type: "text", text: lines.join("\n") }],
4446
+ details: { closedThreads: closed, localOnly: true }
4447
+ };
4448
+ }
4449
+ }),
3809
4450
  tool({
3810
4451
  name: "agentchat_get_conversation_history",
3811
4452
  description: "Fetch recent messages from a specific conversation. Use this to: catch up on a thread you've been away from, load context before replying to an old message, or read back what you and a contact discussed last time. Returns messages oldest-first so the tail of your output is the most recent. Pass `beforeSeq` to paginate further back.",
@@ -4104,6 +4745,7 @@ ${lines.join("\n")}`);
4104
4745
  to: "chatfather",
4105
4746
  content: { text: p.message }
4106
4747
  });
4748
+ recordAgentSend(r.accountId, result.message.conversation_id);
4107
4749
  return ok2(
4108
4750
  `message sent to @chatfather (id: ${result.message.id}). Watch your inbox for the reply.`
4109
4751
  );