@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.
package/dist/index.cjs CHANGED
@@ -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.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;
@@ -916,9 +941,9 @@ function createLogger(options) {
916
941
  function buildRedactPaths(keys) {
917
942
  const prefixes = ["", "config.", "headers.", "context.", "req.headers.", "res.headers."];
918
943
  const paths = [];
919
- for (const key of keys) {
944
+ for (const key2 of keys) {
920
945
  for (const prefix of prefixes) {
921
- paths.push(`${prefix}${key}`);
946
+ paths.push(`${prefix}${key2}`);
922
947
  }
923
948
  }
924
949
  paths.push(...keys.map((k) => `*.${k}`));
@@ -1734,7 +1759,7 @@ function normalizeGroupDeleted(frame) {
1734
1759
 
1735
1760
  // src/retry.ts
1736
1761
  function defaultSleep(ms) {
1737
- return new Promise((resolve) => setTimeout(resolve, ms));
1762
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1738
1763
  }
1739
1764
  async function retryWithPolicy(fn, policy) {
1740
1765
  const random = policy.random ?? Math.random;
@@ -1862,7 +1887,7 @@ var CircuitBreaker = class {
1862
1887
  };
1863
1888
 
1864
1889
  // src/version.ts
1865
- var PACKAGE_VERSION = "0.7.7";
1890
+ var PACKAGE_VERSION = "0.7.81";
1866
1891
 
1867
1892
  // src/outbound.ts
1868
1893
  var DEFAULT_RETRY_POLICY = {
@@ -2078,11 +2103,11 @@ var OutboundAdapter = class {
2078
2103
  `outbound queue full (${this.queue.length}) \u2014 shedding load`
2079
2104
  );
2080
2105
  }
2081
- return new Promise((resolve) => {
2106
+ return new Promise((resolve2) => {
2082
2107
  this.queue.push(() => {
2083
2108
  this.inFlight++;
2084
2109
  this.metrics.setInFlightDepth(this.inFlight);
2085
- resolve();
2110
+ resolve2();
2086
2111
  });
2087
2112
  });
2088
2113
  }
@@ -2158,10 +2183,10 @@ var AgentchatChannelRuntime = class {
2158
2183
  stop(deadlineMs) {
2159
2184
  if (this.stopPromise) return this.stopPromise;
2160
2185
  const deadline = deadlineMs ?? this.now() + 5e3;
2161
- this.stopPromise = new Promise((resolve) => {
2186
+ this.stopPromise = new Promise((resolve2) => {
2162
2187
  const off = this.ws.on("closed", () => {
2163
2188
  off();
2164
- resolve();
2189
+ resolve2();
2165
2190
  });
2166
2191
  this.ws.stop(deadline);
2167
2192
  });
@@ -2391,6 +2416,457 @@ function unregisterRuntime(accountId, deadlineMs = Date.now() + 5e3) {
2391
2416
  function getRuntime(accountId) {
2392
2417
  return registry.get(accountId)?.runtime;
2393
2418
  }
2419
+ function resolveWorkspaceDir(cfg) {
2420
+ const configured = cfg?.agents?.defaults?.workspace;
2421
+ if (typeof configured === "string" && configured.trim().length > 0) {
2422
+ return path2__namespace.resolve(configured);
2423
+ }
2424
+ const profile = readEnv_js$1.readOpenClawProfileFromEnv();
2425
+ if (profile) {
2426
+ return path2__namespace.join(os__namespace.homedir(), ".openclaw", `workspace-${profile}`);
2427
+ }
2428
+ return path2__namespace.join(os__namespace.homedir(), ".openclaw", "workspace");
2429
+ }
2430
+
2431
+ // src/binding/thread-closures.ts
2432
+ var instances = /* @__PURE__ */ new Map();
2433
+ function fallbackWorkspaceDir() {
2434
+ const profile = process.env.OPENCLAW_PROFILE?.trim();
2435
+ if (profile && profile.toLowerCase() !== "default") {
2436
+ return path2__namespace.default.join(os__namespace.default.homedir(), ".openclaw", `workspace-${profile}`);
2437
+ }
2438
+ return path2__namespace.default.join(os__namespace.default.homedir(), ".openclaw", "workspace");
2439
+ }
2440
+ function resolveStatePath(cfg, accountId) {
2441
+ const workspaceDir = typeof cfg === "object" && cfg !== null ? resolveWorkspaceDir(cfg) : fallbackWorkspaceDir();
2442
+ return path2__namespace.default.join(workspaceDir, `.agentchat-closed-threads-${accountId}.json`);
2443
+ }
2444
+ var ThreadClosures = class {
2445
+ filePath;
2446
+ closed = /* @__PURE__ */ new Map();
2447
+ constructor(filePath) {
2448
+ this.filePath = filePath;
2449
+ this.load();
2450
+ }
2451
+ isClosed(conversationId) {
2452
+ return this.closed.has(conversationId);
2453
+ }
2454
+ close(conversationId, reason) {
2455
+ const record = {
2456
+ conversationId,
2457
+ closedAt: (/* @__PURE__ */ new Date()).toISOString(),
2458
+ reason: reason?.trim() ? reason.trim() : null
2459
+ };
2460
+ this.closed.set(conversationId, record);
2461
+ this.save();
2462
+ return record;
2463
+ }
2464
+ reopen(conversationId) {
2465
+ const existed = this.closed.delete(conversationId);
2466
+ if (existed) this.save();
2467
+ return existed;
2468
+ }
2469
+ list() {
2470
+ return [...this.closed.values()].sort((a, b) => b.closedAt.localeCompare(a.closedAt));
2471
+ }
2472
+ load() {
2473
+ if (!fs2__default.default.existsSync(this.filePath)) return;
2474
+ try {
2475
+ const raw = JSON.parse(fs2__default.default.readFileSync(this.filePath, "utf8"));
2476
+ if (!Array.isArray(raw)) return;
2477
+ for (const entry of raw) {
2478
+ if (!entry || typeof entry !== "object") continue;
2479
+ const conversationId = entry.conversationId;
2480
+ const closedAt = entry.closedAt;
2481
+ const reason = entry.reason;
2482
+ if (typeof conversationId !== "string" || typeof closedAt !== "string") continue;
2483
+ this.closed.set(conversationId, {
2484
+ conversationId,
2485
+ closedAt,
2486
+ reason: typeof reason === "string" ? reason : null
2487
+ });
2488
+ }
2489
+ } catch {
2490
+ this.closed = /* @__PURE__ */ new Map();
2491
+ }
2492
+ }
2493
+ save() {
2494
+ fs2__default.default.mkdirSync(path2__namespace.default.dirname(this.filePath), { recursive: true });
2495
+ const payload = JSON.stringify(this.list(), null, 2);
2496
+ const tempPath = `${this.filePath}.tmp`;
2497
+ fs2__default.default.writeFileSync(tempPath, payload, "utf8");
2498
+ fs2__default.default.renameSync(tempPath, this.filePath);
2499
+ }
2500
+ };
2501
+ function getThreadClosures(cfg, accountId) {
2502
+ const filePath = resolveStatePath(cfg, accountId);
2503
+ const existing = instances.get(filePath);
2504
+ if (existing) return existing;
2505
+ const created = new ThreadClosures(filePath);
2506
+ instances.set(filePath, created);
2507
+ return created;
2508
+ }
2509
+ var cache = /* @__PURE__ */ new Map();
2510
+ function getClient({ accountId, config, options }) {
2511
+ const existing = cache.get(accountId);
2512
+ if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
2513
+ return existing.client;
2514
+ }
2515
+ const client = new agentchatme.AgentChatClient({
2516
+ apiKey: config.apiKey,
2517
+ baseUrl: config.apiBase,
2518
+ ...options
2519
+ });
2520
+ cache.set(accountId, {
2521
+ client,
2522
+ apiKey: config.apiKey,
2523
+ apiBase: config.apiBase
2524
+ });
2525
+ return client;
2526
+ }
2527
+ function disposeClient(accountId) {
2528
+ cache.delete(accountId);
2529
+ }
2530
+
2531
+ // src/binding/send-tracker.ts
2532
+ var lastSendByKey = /* @__PURE__ */ new Map();
2533
+ var MAX_TRACKED = 512;
2534
+ function key(accountId, conversationId) {
2535
+ return `${accountId}\0${conversationId}`;
2536
+ }
2537
+ function recordAgentSend(accountId, conversationId, atMs = Date.now()) {
2538
+ if (!conversationId) return;
2539
+ const k = key(accountId, conversationId);
2540
+ lastSendByKey.delete(k);
2541
+ lastSendByKey.set(k, atMs);
2542
+ if (lastSendByKey.size > MAX_TRACKED) {
2543
+ const oldest = lastSendByKey.keys().next().value;
2544
+ if (oldest !== void 0) lastSendByKey.delete(oldest);
2545
+ }
2546
+ }
2547
+ function hasAgentSendSince(accountId, conversationId, sinceMs) {
2548
+ const at = lastSendByKey.get(key(accountId, conversationId));
2549
+ return at !== void 0 && at >= sinceMs;
2550
+ }
2551
+
2552
+ // src/binding/reply-gate.ts
2553
+ var DEFAULT_GATE_MAX_TOKENS = 256;
2554
+ var MAX_HISTORY_TURNS = 12;
2555
+ var CADENCE_WINDOW_SECONDS = 60;
2556
+ var VALID_CATEGORIES = /* @__PURE__ */ new Set([
2557
+ "open_request",
2558
+ "new_info",
2559
+ "goal_followup",
2560
+ "closing",
2561
+ "acknowledgement",
2562
+ "not_addressed",
2563
+ "no_action_needed",
2564
+ "spam",
2565
+ "other"
2566
+ ]);
2567
+ var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "yes", "true", "respond"]);
2568
+ var NO_REPLY_TOKENS = /* @__PURE__ */ new Set([
2569
+ "no_reply",
2570
+ "no-reply",
2571
+ "noreply",
2572
+ "no",
2573
+ "false",
2574
+ "silent",
2575
+ "skip",
2576
+ "none"
2577
+ ]);
2578
+ var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
2579
+ function computeConversationSignals(messages, params) {
2580
+ const windowSeconds = params.windowSeconds ?? CADENCE_WINDOW_SECONDS;
2581
+ const own = normalizeHandle(params.ownHandle);
2582
+ const prior = messages.filter(
2583
+ (m) => isRecord(m) && m.id !== params.triggerMessageId
2584
+ );
2585
+ const firstContact = prior.length === 0;
2586
+ const youHaveSpoken = prior.some((m) => messageIsOwn(m, own));
2587
+ const timestamps = [];
2588
+ for (const m of prior) {
2589
+ const ts = parseTimestamp(m.created_at);
2590
+ if (ts !== null) timestamps.push(ts);
2591
+ }
2592
+ const cutoff = params.nowMs - windowSeconds * 1e3;
2593
+ const recentInWindow = timestamps.filter((ts) => ts >= cutoff).length;
2594
+ let secondsSincePrevious = null;
2595
+ if (timestamps.length > 0) {
2596
+ const delta = (params.nowMs - Math.max(...timestamps)) / 1e3;
2597
+ secondsSincePrevious = delta > 0 ? delta : 0;
2598
+ }
2599
+ return {
2600
+ firstContact,
2601
+ youHaveSpoken,
2602
+ messagesLastWindow: recentInWindow + 1,
2603
+ // +1 for the new message
2604
+ secondsSincePrevious
2605
+ };
2606
+ }
2607
+ function messageIsOwn(msg, ownHandleNorm) {
2608
+ if (typeof msg.is_own === "boolean") return msg.is_own;
2609
+ const sender = msg.sender ?? msg.from ?? msg.sender_handle ?? "";
2610
+ return normalizeHandle(String(sender)) === ownHandleNorm;
2611
+ }
2612
+ function parseTimestamp(raw) {
2613
+ if (typeof raw !== "string" || !raw) return null;
2614
+ const t = Date.parse(raw);
2615
+ return Number.isNaN(t) ? null : t;
2616
+ }
2617
+ function normalizeHandle(handle) {
2618
+ return handle.replace(/^@/, "").toLowerCase();
2619
+ }
2620
+ function isRecord(value) {
2621
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2622
+ }
2623
+ function systemTemplate(handle) {
2624
+ const h = `@${handle}`;
2625
+ 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.
2626
+
2627
+ "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.
2628
+
2629
+ Judge DONE-NESS, not how interesting another message could be:
2630
+
2631
+ Choose "reply" only if a further message accomplishes a concrete, still-OPEN purpose:
2632
+ - answer a substantive pending question or supply specifically requested information
2633
+ - make or respond to a decision, or unblock the peer on a real task
2634
+ - ${h} started this thread toward a goal and the peer's reply needs a substantive follow-up to reach it
2635
+ - new information genuinely requires ${h}'s input
2636
+
2637
+ Choose "no_reply" when the exchange has reached its natural end \u2014 even if another clever or friendly message is easily possible:
2638
+ - it is trading pleasantries, mutual appreciation, agreement, or open-ended tangents / "riffing" with no open objective
2639
+ - 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
2640
+ - the other side is acknowledging or closing out (thanks / ok / got it / sounds good / \u{1F44D} / bye) and replying would only prolong it
2641
+ - ${h} already answered what was asked and nothing new is on the table
2642
+ - 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.)
2643
+
2644
+ "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".
2645
+
2646
+ Respond with ONLY a JSON object \u2014 no prose, no markdown fences:
2647
+ {"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>"}`;
2648
+ }
2649
+ function buildDecisionMessages(params) {
2650
+ return [
2651
+ { role: "system", content: systemTemplate(params.handle) },
2652
+ {
2653
+ role: "user",
2654
+ content: buildUserContent({
2655
+ handle: params.handle,
2656
+ event: params.event,
2657
+ history: params.history,
2658
+ signals: params.signals ?? null,
2659
+ maxHistory: params.maxHistory ?? MAX_HISTORY_TURNS
2660
+ })
2661
+ }
2662
+ ];
2663
+ }
2664
+ function buildUserContent(params) {
2665
+ const { handle, event, history, signals, maxHistory } = params;
2666
+ const kind = event.conversationKind === "group" ? "group" : "direct";
2667
+ const lines = [`Conversation type: ${kind}`];
2668
+ if (signals) {
2669
+ lines.push(`Relationship: ${relationshipPhrase(signals)}`);
2670
+ if (signals.secondsSincePrevious !== null) {
2671
+ lines.push(
2672
+ `Pace: ${signals.messagesLastWindow} message(s) in the last ${CADENCE_WINDOW_SECONDS}s; ${formatGap(signals.secondsSincePrevious)} since the previous message`
2673
+ );
2674
+ }
2675
+ }
2676
+ lines.push(`Prior messages in this thread: ${history.length}`);
2677
+ if (kind === "group") {
2678
+ const mentioned = (event.contentText || "").toLowerCase().includes(`@${handle.toLowerCase()}`);
2679
+ lines.push(
2680
+ `Message directly addresses you: ${mentioned ? "yes" : "not explicitly"}`
2681
+ );
2682
+ }
2683
+ lines.push("");
2684
+ const rendered = renderHistory(history, maxHistory);
2685
+ if (rendered.length > 0) {
2686
+ lines.push("Recent conversation (oldest first):");
2687
+ lines.push(...rendered);
2688
+ } else {
2689
+ lines.push("Recent conversation: (none \u2014 this is first contact)");
2690
+ }
2691
+ let newText = collapseWhitespace(event.contentText || "");
2692
+ if (newText.length > 2e3) newText = `${newText.slice(0, 2e3)}\u2026`;
2693
+ lines.push("");
2694
+ lines.push(`New message from @${event.senderHandle}: ${newText}`);
2695
+ lines.push("");
2696
+ lines.push("Decide now: reply or no_reply?");
2697
+ return lines.join("\n");
2698
+ }
2699
+ function renderHistory(history, maxHistory) {
2700
+ const recent = history.length > maxHistory ? history.slice(history.length - maxHistory) : history;
2701
+ const out = [];
2702
+ for (const turn of recent) {
2703
+ if (typeof turn.content !== "string" || !turn.content.trim()) continue;
2704
+ const speaker = turn.role === "assistant" ? "you" : "peer";
2705
+ let text = collapseWhitespace(turn.content);
2706
+ if (text.length > 400) text = `${text.slice(0, 400)}\u2026`;
2707
+ out.push(`${speaker}: ${text}`);
2708
+ }
2709
+ return out;
2710
+ }
2711
+ function relationshipPhrase(signals) {
2712
+ if (signals.firstContact) return "first contact \u2014 no prior messages in this thread";
2713
+ if (signals.youHaveSpoken) return "established \u2014 you have already replied in this thread";
2714
+ return "this peer is messaging you, but you have not replied yet";
2715
+ }
2716
+ function formatGap(seconds) {
2717
+ if (seconds < 90) return `${Math.round(seconds)}s`;
2718
+ if (seconds < 5400) return `${Math.round(seconds / 60)}m`;
2719
+ return `${Math.round(seconds / 3600)}h`;
2720
+ }
2721
+ function collapseWhitespace(text) {
2722
+ return text.split(/\s+/).filter(Boolean).join(" ");
2723
+ }
2724
+ function parseDecision(text, opts = {}) {
2725
+ const raw = extractJson(text);
2726
+ if (raw === null) return null;
2727
+ let obj;
2728
+ try {
2729
+ obj = JSON.parse(raw);
2730
+ } catch {
2731
+ return null;
2732
+ }
2733
+ if (!isRecord(obj)) return null;
2734
+ const decisionRaw = obj.decision;
2735
+ if (typeof decisionRaw !== "string") return null;
2736
+ const token = decisionRaw.trim().toLowerCase();
2737
+ let reply;
2738
+ if (REPLY_TOKENS.has(token)) reply = true;
2739
+ else if (NO_REPLY_TOKENS.has(token)) reply = false;
2740
+ else return null;
2741
+ const reasonRaw = obj.reason;
2742
+ let reason = typeof reasonRaw === "string" ? reasonRaw.trim() : "";
2743
+ if (reason.length > 280) reason = reason.slice(0, 280);
2744
+ const categoryRaw = obj.category;
2745
+ let category = typeof categoryRaw === "string" ? categoryRaw.trim().toLowerCase() : "other";
2746
+ if (!VALID_CATEGORIES.has(category)) category = "other";
2747
+ return {
2748
+ reply,
2749
+ reason,
2750
+ category,
2751
+ source: opts.source ?? "llm",
2752
+ latencyMs: opts.latencyMs ?? 0
2753
+ };
2754
+ }
2755
+ function extractJson(text) {
2756
+ if (!text || !text.trim()) return null;
2757
+ let s = text.trim();
2758
+ const fence = FENCE_RE.exec(s);
2759
+ if (fence?.[1]) s = fence[1].trim();
2760
+ const start = s.indexOf("{");
2761
+ const end = s.lastIndexOf("}");
2762
+ if (start === -1 || end === -1 || end <= start) return null;
2763
+ return s.slice(start, end + 1);
2764
+ }
2765
+ function gateFallback(failOpen, reason, latencyMs) {
2766
+ return {
2767
+ reply: failOpen,
2768
+ reason,
2769
+ category: "fallback",
2770
+ source: failOpen ? "fail_open" : "fail_closed",
2771
+ latencyMs
2772
+ };
2773
+ }
2774
+
2775
+ // src/binding/gate.ts
2776
+ var DEFAULT_GATE_TIMEOUT_MS = 2e4;
2777
+ var GATE_REASONING_LEVEL = "off";
2778
+ var GateTimeoutError = class extends Error {
2779
+ };
2780
+ function withTimeout(promise, ms) {
2781
+ if (!Number.isFinite(ms) || ms <= 0) return promise;
2782
+ return new Promise((resolve2, reject) => {
2783
+ const timer = setTimeout(() => reject(new GateTimeoutError("gate decision timed out")), ms);
2784
+ promise.then(
2785
+ (value) => {
2786
+ clearTimeout(timer);
2787
+ resolve2(value);
2788
+ },
2789
+ (err3) => {
2790
+ clearTimeout(timer);
2791
+ reject(err3);
2792
+ }
2793
+ );
2794
+ });
2795
+ }
2796
+ async function decideReply(params) {
2797
+ const signals = computeConversationSignals(params.rawMessages, {
2798
+ ownHandle: params.ownHandle,
2799
+ triggerMessageId: params.triggerMessageId,
2800
+ nowMs: params.nowMs
2801
+ });
2802
+ const messages = buildDecisionMessages({
2803
+ handle: params.handle,
2804
+ event: params.event,
2805
+ history: params.history,
2806
+ signals
2807
+ });
2808
+ const systemPrompt = messages.find((m) => m.role === "system")?.content ?? "";
2809
+ const userContent = messages.find((m) => m.role === "user")?.content ?? "";
2810
+ const caller = params.caller ?? createSimpleCompletionGateCaller(params.cfg, params.agentId);
2811
+ const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
2812
+ const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
2813
+ const start = Date.now();
2814
+ let text;
2815
+ try {
2816
+ text = await withTimeout(caller({ systemPrompt, userContent, maxTokens }), timeoutMs);
2817
+ } catch (err3) {
2818
+ if (err3 instanceof GateTimeoutError) {
2819
+ return gateFallback(params.failOpen, "decision_timeout", Date.now() - start);
2820
+ }
2821
+ const detail = err3 instanceof Error ? err3.message : String(err3);
2822
+ return gateFallback(
2823
+ params.failOpen,
2824
+ `decision_call_error: ${detail}`.slice(0, 220),
2825
+ Date.now() - start
2826
+ );
2827
+ }
2828
+ const latencyMs = Date.now() - start;
2829
+ const parsed = parseDecision(text, { source: "llm", latencyMs });
2830
+ return parsed ?? gateFallback(params.failOpen, "unparseable_decision", latencyMs);
2831
+ }
2832
+ function createSimpleCompletionGateCaller(cfg, agentId) {
2833
+ return async ({ systemPrompt, userContent, maxTokens, signal }) => {
2834
+ const prepared = await simpleCompletionRuntime.prepareSimpleCompletionModelForAgent({
2835
+ cfg,
2836
+ // plugin-local OpenClawConfig alias → sdk's internal type
2837
+ agentId,
2838
+ allowMissingApiKeyModes: ["aws-sdk"],
2839
+ // Do NOT skip discovery: it loads provider model catalogs. Skipping it
2840
+ // works for providers with pure dynamic resolution (e.g. Fireworks) but
2841
+ // makes catalog-based providers (Google/Gemini, Anthropic, OpenAI, …)
2842
+ // fail with "Unknown model: <ref>" — the gate must resolve the agent's
2843
+ // own model regardless of which provider it runs on.
2844
+ skipAgentDiscovery: false
2845
+ });
2846
+ if ("error" in prepared) throw new Error(prepared.error);
2847
+ const result = await simpleCompletionRuntime.completeWithPreparedSimpleCompletionModel({
2848
+ model: prepared.model,
2849
+ auth: prepared.auth,
2850
+ cfg,
2851
+ context: {
2852
+ systemPrompt,
2853
+ messages: [{ role: "user", content: userContent }]
2854
+ },
2855
+ // temperature 0 mirrors the Hermes gate: a binary policy decision must
2856
+ // be as deterministic as the provider allows, not sampled creatively.
2857
+ options: {
2858
+ maxTokens,
2859
+ temperature: 0,
2860
+ reasoning: GATE_REASONING_LEVEL,
2861
+ ...signal ? { signal } : {}
2862
+ }
2863
+ });
2864
+ return result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("");
2865
+ };
2866
+ }
2867
+
2868
+ // src/binding/inbound-bridge.ts
2869
+ var GATE_HISTORY_LIMIT = 30;
2394
2870
  function createInboundBridge(deps) {
2395
2871
  return async function onInbound(event) {
2396
2872
  switch (event.kind) {
@@ -2427,6 +2903,17 @@ async function handleMessage(deps, event) {
2427
2903
  if (!body && !event.content.attachmentId && !event.content.data) {
2428
2904
  return;
2429
2905
  }
2906
+ const threadClosures = getThreadClosures(
2907
+ deps.gatewayCfg,
2908
+ deps.accountId
2909
+ );
2910
+ if (threadClosures.isClosed(event.conversationId)) {
2911
+ deps.logger.info(
2912
+ { conversationId: event.conversationId, messageId: event.messageId, sender: event.sender },
2913
+ "inbound skipped for locally closed thread"
2914
+ );
2915
+ return;
2916
+ }
2430
2917
  const channelRuntime = deps.channelRuntime;
2431
2918
  if (!channelRuntime || typeof channelRuntime.reply?.dispatchReplyWithBufferedBlockDispatcher !== "function") {
2432
2919
  deps.logger.error(
@@ -2441,6 +2928,7 @@ async function handleMessage(deps, event) {
2441
2928
  );
2442
2929
  return;
2443
2930
  }
2931
+ const ts = typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt);
2444
2932
  const recipientHandle = selfHandle ?? "me";
2445
2933
  const conversationLabel = event.conversationKind === "group" ? `group ${event.conversationId}` : `dm with @${senderHandle}`;
2446
2934
  const sendReply = async (replyText) => {
@@ -2453,36 +2941,107 @@ async function handleMessage(deps, event) {
2453
2941
  metadata: { reply_to: event.messageId }
2454
2942
  });
2455
2943
  };
2944
+ const turnStartMs = Date.now();
2456
2945
  const deliver2 = async (payload) => {
2457
- const replyText = payload.text ?? extractText(payload.blocks);
2458
- await sendReply(replyText);
2946
+ if (threadClosures.isClosed(event.conversationId)) {
2947
+ deps.logger.info(
2948
+ { conversationId: event.conversationId, messageId: event.messageId },
2949
+ "reply suppressed for locally closed thread"
2950
+ );
2951
+ return;
2952
+ }
2953
+ if (hasAgentSendSince(deps.accountId, event.conversationId, turnStartMs)) {
2954
+ deps.logger.info(
2955
+ { conversationId: event.conversationId, messageId: event.messageId },
2956
+ "final turn text suppressed \u2014 agent already sent its reply via a message tool this turn"
2957
+ );
2958
+ return;
2959
+ }
2960
+ await sendReply(payload.text ?? extractText(payload.blocks));
2459
2961
  };
2460
2962
  try {
2461
- if (event.conversationKind === "direct") {
2462
- await directDm.dispatchInboundDirectDmWithRuntime({
2463
- cfg: deps.gatewayCfg,
2464
- runtime: { channel: channelRuntime },
2465
- channel: "agentchat",
2466
- channelLabel: "AgentChat",
2467
- accountId: deps.accountId,
2468
- peer: { kind: "direct", id: senderHandle },
2469
- senderId: senderHandle,
2470
- senderAddress: `@${senderHandle}`,
2471
- recipientAddress: `@${recipientHandle}`,
2472
- conversationLabel,
2473
- rawBody: body,
2474
- messageId: event.messageId,
2475
- timestamp: typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt),
2476
- provider: "agentchat",
2477
- surface: "agentchat",
2478
- deliver: deliver2,
2479
- onRecordError: (err3) => {
2480
- deps.logger.error(
2481
- { err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
2482
- "recordInboundSession failed"
2483
- );
2963
+ const runtime = channelRuntime;
2964
+ const peer = event.conversationKind === "group" ? { kind: "group", id: event.conversationId } : { kind: "direct", id: senderHandle };
2965
+ const { route, buildEnvelope } = inboundEnvelope.resolveInboundRouteEnvelopeBuilderWithRuntime({
2966
+ cfg: deps.gatewayCfg,
2967
+ channel: "agentchat",
2968
+ accountId: deps.accountId,
2969
+ peer,
2970
+ runtime
2971
+ });
2972
+ if (gateEnabled()) {
2973
+ const decision = await runReplyGate({
2974
+ deps,
2975
+ event,
2976
+ body,
2977
+ agentId: route.agentId,
2978
+ selfHandle,
2979
+ senderHandle,
2980
+ nowMs: Number.isFinite(ts) ? ts : Date.now()
2981
+ });
2982
+ deps.logger.info(
2983
+ {
2984
+ conversationId: event.conversationId,
2985
+ messageId: event.messageId,
2986
+ reply: decision.reply,
2987
+ source: decision.source,
2988
+ category: decision.category,
2989
+ latencyMs: decision.latencyMs,
2990
+ reason: decision.reason
2484
2991
  },
2485
- onDispatchError: (err3, info) => {
2992
+ "reply gate decision"
2993
+ );
2994
+ if (!decision.reply) return;
2995
+ }
2996
+ const { storePath, body: envelopeBody } = buildEnvelope({
2997
+ channel: "AgentChat",
2998
+ from: conversationLabel,
2999
+ body,
3000
+ timestamp: ts
3001
+ });
3002
+ const finalize = channelRuntime.reply.finalizeInboundContext;
3003
+ const ctxPayload = finalize({
3004
+ Body: envelopeBody,
3005
+ BodyForAgent: body,
3006
+ RawBody: body,
3007
+ CommandBody: body,
3008
+ From: `@${senderHandle}`,
3009
+ To: `@${recipientHandle}`,
3010
+ SessionKey: route.sessionKey,
3011
+ AccountId: deps.accountId,
3012
+ ChatType: event.conversationKind === "group" ? "group" : "direct",
3013
+ ConversationLabel: conversationLabel,
3014
+ SenderId: senderHandle,
3015
+ Provider: "agentchat",
3016
+ Surface: "agentchat",
3017
+ MessageSid: event.messageId,
3018
+ MessageSidFull: event.messageId,
3019
+ Timestamp: ts,
3020
+ OriginatingChannel: "agentchat",
3021
+ OriginatingTo: `@${recipientHandle}`
3022
+ });
3023
+ const session = channelRuntime.session;
3024
+ await inboundReplyDispatch.dispatchChannelInboundReply({
3025
+ cfg: deps.gatewayCfg,
3026
+ channel: "agentchat",
3027
+ accountId: deps.accountId,
3028
+ agentId: route.agentId,
3029
+ routeSessionKey: route.sessionKey,
3030
+ storePath,
3031
+ ctxPayload,
3032
+ recordInboundSession: session.recordInboundSession,
3033
+ dispatchReplyWithBufferedBlockDispatcher: channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
3034
+ // Under `automatic` (the default) the framework hands the agent's final
3035
+ // turn text to this `deliver`, which sends it to the source. Under the
3036
+ // opt-in `message_tool_only` mode the turn text is suppressed and the
3037
+ // agent sends via the message tool instead, so `deliver` only fires on a
3038
+ // framework fallback. Either way a gated `no_reply` turn never runs, so
3039
+ // nothing is sent.
3040
+ delivery: {
3041
+ deliver: async (payload) => {
3042
+ await deliver2(payload);
3043
+ },
3044
+ onError: (err3, info) => {
2486
3045
  deps.logger.error(
2487
3046
  {
2488
3047
  err: err3 instanceof Error ? err3.message : String(err3),
@@ -2492,84 +3051,103 @@ async function handleMessage(deps, event) {
2492
3051
  "inbound dispatch failed"
2493
3052
  );
2494
3053
  }
2495
- });
2496
- } else {
2497
- const ts = typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt);
2498
- const runtime = channelRuntime;
2499
- const { route, buildEnvelope } = inboundEnvelope.resolveInboundRouteEnvelopeBuilderWithRuntime({
2500
- cfg: deps.gatewayCfg,
2501
- channel: "agentchat",
2502
- accountId: deps.accountId,
2503
- peer: { kind: "group", id: event.conversationId },
2504
- runtime
2505
- });
2506
- const { storePath, body: envelopeBody } = buildEnvelope({
2507
- channel: "AgentChat",
2508
- from: conversationLabel,
2509
- body,
2510
- timestamp: ts
2511
- });
2512
- const finalize = channelRuntime.reply.finalizeInboundContext;
2513
- const ctxPayload = finalize({
2514
- Body: envelopeBody,
2515
- BodyForAgent: body,
2516
- RawBody: body,
2517
- CommandBody: body,
2518
- From: `@${senderHandle}`,
2519
- To: `@${recipientHandle}`,
2520
- SessionKey: route.sessionKey,
2521
- AccountId: deps.accountId,
2522
- ChatType: "group",
2523
- ConversationLabel: conversationLabel,
2524
- SenderId: senderHandle,
2525
- Provider: "agentchat",
2526
- Surface: "agentchat",
2527
- MessageSid: event.messageId,
2528
- MessageSidFull: event.messageId,
2529
- Timestamp: ts,
2530
- OriginatingChannel: "agentchat",
2531
- OriginatingTo: `@${recipientHandle}`
2532
- });
2533
- const session = channelRuntime.session;
2534
- await inboundReplyDispatch.recordInboundSessionAndDispatchReply({
2535
- cfg: deps.gatewayCfg,
2536
- channel: "agentchat",
2537
- accountId: deps.accountId,
2538
- agentId: route.agentId,
2539
- routeSessionKey: route.sessionKey,
2540
- storePath,
2541
- ctxPayload,
2542
- recordInboundSession: session.recordInboundSession,
2543
- dispatchReplyWithBufferedBlockDispatcher: channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
2544
- deliver: deliver2,
3054
+ },
3055
+ replyOptions: { sourceReplyDeliveryMode: resolveSourceReplyMode() },
3056
+ record: {
2545
3057
  onRecordError: (err3) => {
2546
3058
  deps.logger.error(
2547
3059
  { err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
2548
- "recordInboundSession failed (group)"
2549
- );
2550
- },
2551
- onDispatchError: (err3, info) => {
2552
- deps.logger.error(
2553
- {
2554
- err: err3 instanceof Error ? err3.message : String(err3),
2555
- messageId: event.messageId,
2556
- kind: info.kind
2557
- },
2558
- "inbound dispatch failed (group)"
3060
+ "recordInboundSession failed"
2559
3061
  );
2560
3062
  }
2561
- });
2562
- }
3063
+ }
3064
+ });
2563
3065
  } catch (err3) {
2564
3066
  deps.logger.error(
2565
- {
2566
- err: err3 instanceof Error ? err3.message : String(err3),
2567
- messageId: event.messageId
2568
- },
3067
+ { err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
2569
3068
  "inbound dispatch failed"
2570
3069
  );
2571
3070
  }
2572
3071
  }
3072
+ async function runReplyGate(params) {
3073
+ const { deps, event, body, agentId, selfHandle, senderHandle, nowMs } = params;
3074
+ const ownHandle = selfHandle ?? "";
3075
+ let rawMessages = [];
3076
+ try {
3077
+ const client = getClient({ accountId: deps.accountId, config: deps.config });
3078
+ const fetched = await client.getMessages(event.conversationId, { limit: GATE_HISTORY_LIMIT });
3079
+ if (Array.isArray(fetched)) rawMessages = fetched;
3080
+ } catch (err3) {
3081
+ deps.logger.warn(
3082
+ { err: err3 instanceof Error ? err3.message : String(err3), conversationId: event.conversationId },
3083
+ "reply gate: history fetch failed \u2014 deciding on the new message alone"
3084
+ );
3085
+ }
3086
+ const gateEvent = {
3087
+ conversationKind: event.conversationKind,
3088
+ senderHandle,
3089
+ contentText: body
3090
+ };
3091
+ return decideReply({
3092
+ cfg: deps.gatewayCfg,
3093
+ agentId,
3094
+ handle: ownHandle.replace(/^@/, ""),
3095
+ event: gateEvent,
3096
+ history: translateHistory(rawMessages, ownHandle, event.conversationKind, event.messageId),
3097
+ rawMessages,
3098
+ triggerMessageId: event.messageId,
3099
+ ownHandle,
3100
+ nowMs,
3101
+ failOpen: gateFailOpen(),
3102
+ timeoutMs: gateTimeoutMs(),
3103
+ caller: deps.gateCaller
3104
+ });
3105
+ }
3106
+ function translateHistory(messages, ownHandle, conversationKind, triggerMessageId) {
3107
+ const own = ownHandle.replace(/^@/, "").toLowerCase();
3108
+ const isGroup = conversationKind === "group";
3109
+ const sorted = [...messages].filter((m) => Boolean(m) && typeof m === "object").sort((a, b) => readSeq(a) - readSeq(b));
3110
+ const out = [];
3111
+ for (const m of sorted) {
3112
+ if (m.id === triggerMessageId) continue;
3113
+ const type = typeof m.type === "string" ? m.type : "text";
3114
+ if (type !== "text") continue;
3115
+ const content = m.content;
3116
+ const text = content && typeof content === "object" ? content.text : void 0;
3117
+ if (typeof text !== "string" || !text) continue;
3118
+ const senderRaw = String(m.sender ?? m.from ?? m.sender_handle ?? "");
3119
+ const isOwn = typeof m.is_own === "boolean" ? m.is_own : senderRaw.replace(/^@/, "").toLowerCase() === own;
3120
+ if (isOwn) {
3121
+ out.push({ role: "assistant", content: text });
3122
+ } else if (isGroup) {
3123
+ out.push({ role: "user", content: `[@${senderRaw.replace(/^@/, "") || "?"}] ${text}` });
3124
+ } else {
3125
+ out.push({ role: "user", content: text });
3126
+ }
3127
+ }
3128
+ return out;
3129
+ }
3130
+ function readSeq(m) {
3131
+ const seq = m.seq;
3132
+ return typeof seq === "number" ? seq : 0;
3133
+ }
3134
+ var OFF_TOKENS = /* @__PURE__ */ new Set(["0", "false", "off", "no"]);
3135
+ var ON_TOKENS = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
3136
+ function gateEnabled() {
3137
+ return !OFF_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_ENABLED ?? "").trim().toLowerCase());
3138
+ }
3139
+ function gateFailOpen() {
3140
+ return ON_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_FAIL_OPEN ?? "").trim().toLowerCase());
3141
+ }
3142
+ function gateTimeoutMs() {
3143
+ const raw = process.env.AGENTCHAT_REPLY_GATE_TIMEOUT_MS;
3144
+ if (raw === void 0 || raw.trim() === "") return void 0;
3145
+ const n = Number(raw);
3146
+ return Number.isFinite(n) && n > 0 ? n : void 0;
3147
+ }
3148
+ function resolveSourceReplyMode() {
3149
+ return (process.env.AGENTCHAT_SOURCE_REPLY_MODE ?? "").trim().toLowerCase() === "message_tool_only" ? "message_tool_only" : "automatic";
3150
+ }
2573
3151
  function handleGroupInvite(deps, event) {
2574
3152
  deps.logger.info(
2575
3153
  {
@@ -2717,27 +3295,6 @@ var agentchatGatewayAdapter = {
2717
3295
  });
2718
3296
  }
2719
3297
  };
2720
- var cache = /* @__PURE__ */ new Map();
2721
- function getClient({ accountId, config, options }) {
2722
- const existing = cache.get(accountId);
2723
- if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
2724
- return existing.client;
2725
- }
2726
- const client = new agentchatme.AgentChatClient({
2727
- apiKey: config.apiKey,
2728
- baseUrl: config.apiBase,
2729
- ...options
2730
- });
2731
- cache.set(accountId, {
2732
- client,
2733
- apiKey: config.apiKey,
2734
- apiBase: config.apiBase
2735
- });
2736
- return client;
2737
- }
2738
- function disposeClient(accountId) {
2739
- cache.delete(accountId);
2740
- }
2741
3298
 
2742
3299
  // src/binding/outbound.ts
2743
3300
  function resolveConfig(cfg, accountId) {
@@ -2799,6 +3356,7 @@ async function deliver(ctx, attachmentId) {
2799
3356
  attachmentId
2800
3357
  );
2801
3358
  const result = await runtime.sendMessage(input);
3359
+ recordAgentSend(accountId, result.message.conversation_id);
2802
3360
  return {
2803
3361
  channel: AGENTCHAT_CHANNEL_ID,
2804
3362
  messageId: result.message.id,
@@ -2868,8 +3426,8 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
2868
3426
  let contentType;
2869
3427
  let filename = "attachment";
2870
3428
  if (mediaUrl.startsWith("file://") && ctx.mediaReadFile) {
2871
- const path = decodeURIComponent(mediaUrl.replace(/^file:\/\//, ""));
2872
- const buf = await ctx.mediaReadFile(path);
3429
+ const path3 = decodeURIComponent(mediaUrl.replace(/^file:\/\//, ""));
3430
+ const buf = await ctx.mediaReadFile(path3);
2873
3431
  if (buf.byteLength > MAX_MEDIA_BYTES) {
2874
3432
  throw new AgentChatChannelError(
2875
3433
  "terminal-user",
@@ -2879,7 +3437,7 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
2879
3437
  const copy = new Uint8Array(buf.byteLength);
2880
3438
  copy.set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
2881
3439
  bytes = copy.buffer;
2882
- filename = path.split(/[\\/]/).pop() ?? filename;
3440
+ filename = path3.split(/[\\/]/).pop() ?? filename;
2883
3441
  } else {
2884
3442
  assertMediaUrlSafe(mediaUrl);
2885
3443
  const controller = new AbortController();
@@ -3034,8 +3592,8 @@ function err(message) {
3034
3592
  details: { error: message }
3035
3593
  };
3036
3594
  }
3037
- function str(params, key) {
3038
- const v = params[key];
3595
+ function str(params, key2) {
3596
+ const v = params[key2];
3039
3597
  return typeof v === "string" ? v : void 0;
3040
3598
  }
3041
3599
  function resolveConfig2(ctx) {
@@ -3292,6 +3850,7 @@ var agentchatAgentToolsFactory = ({ cfg }) => {
3292
3850
  content: { text: p.message },
3293
3851
  ...p.replyToMessageId ? { metadata: { reply_to: p.replyToMessageId } } : {}
3294
3852
  });
3853
+ recordAgentSend(r.accountId, result.message.conversation_id);
3295
3854
  const summaryParts = [
3296
3855
  `sent to @${handle} \u2014 message ${result.message.id} in ${result.message.conversation_id}`
3297
3856
  ];
@@ -3814,6 +4373,88 @@ ${lines.join("\n")}`);
3814
4373
  }
3815
4374
  }
3816
4375
  }),
4376
+ tool({
4377
+ name: "agentchat_close_local_thread",
4378
+ 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.",
4379
+ parameters: typebox.Type.Object({
4380
+ conversationId: typebox.Type.String(),
4381
+ reason: typebox.Type.Optional(typebox.Type.String({ maxLength: 200 })),
4382
+ account: ACCOUNT_PARAM
4383
+ }),
4384
+ execute: async (_id, p) => {
4385
+ const r = clientFor(cfg, p.account);
4386
+ if ("error" in r) return err2(r.error);
4387
+ const closures = getThreadClosures(cfg, r.accountId);
4388
+ const record = closures.close(p.conversationId, p.reason);
4389
+ return {
4390
+ content: [
4391
+ {
4392
+ type: "text",
4393
+ text: `closed ${record.conversationId} locally`
4394
+ }
4395
+ ],
4396
+ details: {
4397
+ conversationId: record.conversationId,
4398
+ closedAt: record.closedAt,
4399
+ reason: record.reason,
4400
+ localOnly: true
4401
+ }
4402
+ };
4403
+ }
4404
+ }),
4405
+ tool({
4406
+ name: "agentchat_reopen_local_thread",
4407
+ description: "Re-open a previously locally closed conversation thread so new inbound on that conversation id can reach the reply pipeline again.",
4408
+ parameters: typebox.Type.Object({
4409
+ conversationId: typebox.Type.String(),
4410
+ account: ACCOUNT_PARAM
4411
+ }),
4412
+ execute: async (_id, p) => {
4413
+ const r = clientFor(cfg, p.account);
4414
+ if ("error" in r) return err2(r.error);
4415
+ const closures = getThreadClosures(cfg, r.accountId);
4416
+ const reopened = closures.reopen(p.conversationId);
4417
+ return {
4418
+ content: [
4419
+ {
4420
+ type: "text",
4421
+ text: reopened ? `re-opened ${p.conversationId} locally` : `${p.conversationId} was not locally closed`
4422
+ }
4423
+ ],
4424
+ details: {
4425
+ conversationId: p.conversationId,
4426
+ reopened,
4427
+ localOnly: true
4428
+ }
4429
+ };
4430
+ }
4431
+ }),
4432
+ tool({
4433
+ name: "agentchat_list_local_closed_threads",
4434
+ description: "List conversation threads currently closed locally for this OpenClaw AgentChat account. These are client-side only, not server-side blocks or mutes.",
4435
+ parameters: typebox.Type.Object({
4436
+ account: ACCOUNT_PARAM
4437
+ }),
4438
+ execute: async (_id, p) => {
4439
+ const r = clientFor(cfg, p.account);
4440
+ if ("error" in r) return err2(r.error);
4441
+ const closures = getThreadClosures(cfg, r.accountId);
4442
+ const closed = closures.list();
4443
+ if (closed.length === 0) {
4444
+ return {
4445
+ content: [{ type: "text", text: "no locally closed threads" }],
4446
+ details: { closedThreads: [], localOnly: true }
4447
+ };
4448
+ }
4449
+ const lines = closed.map(
4450
+ (record) => `${record.conversationId} \u2014 ${record.closedAt}${record.reason ? ` \u2014 ${record.reason}` : ""}`
4451
+ );
4452
+ return {
4453
+ content: [{ type: "text", text: lines.join("\n") }],
4454
+ details: { closedThreads: closed, localOnly: true }
4455
+ };
4456
+ }
4457
+ }),
3817
4458
  tool({
3818
4459
  name: "agentchat_get_conversation_history",
3819
4460
  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.",
@@ -4112,6 +4753,7 @@ ${lines.join("\n")}`);
4112
4753
  to: "chatfather",
4113
4754
  content: { text: p.message }
4114
4755
  });
4756
+ recordAgentSend(r.accountId, result.message.conversation_id);
4115
4757
  return ok2(
4116
4758
  `message sent to @chatfather (id: ${result.message.id}). Watch your inbox for the reply.`
4117
4759
  );
@@ -4580,8 +5222,8 @@ var agentchatSetupEntry = channelCore.defineSetupPluginEntry(agentchatPlugin);
4580
5222
  // src/configured-state.ts
4581
5223
  function hasAgentChatConfiguredState(config) {
4582
5224
  if (!config || typeof config !== "object") return false;
4583
- const key = config.apiKey;
4584
- if (typeof key !== "string" || key.length < 20) return false;
5225
+ const key2 = config.apiKey;
5226
+ if (typeof key2 !== "string" || key2.length < 20) return false;
4585
5227
  const handle = config.agentHandle;
4586
5228
  if (typeof handle !== "string" || handle.trim().length === 0) return false;
4587
5229
  return true;