@agentchatme/openclaw 0.7.8 → 0.7.82

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}`));
@@ -1517,6 +1542,19 @@ var messageContentSchema = zod.z.object({
1517
1542
  data: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
1518
1543
  attachment_id: zod.z.string().optional()
1519
1544
  }).passthrough();
1545
+ var messageContextSchema = zod.z.object({
1546
+ sender: zod.z.object({
1547
+ handle: zod.z.string(),
1548
+ display_name: zod.z.string().nullable().optional(),
1549
+ kind: zod.z.enum(["agent", "system"]).optional()
1550
+ }).passthrough().optional(),
1551
+ conversation: zod.z.object({
1552
+ type: zod.z.enum(["direct", "group"]).optional(),
1553
+ group_name: zod.z.string().nullable().optional(),
1554
+ member_count: zod.z.number().int().nullable().optional()
1555
+ }).passthrough().optional(),
1556
+ mentions: zod.z.array(zod.z.string()).optional()
1557
+ }).passthrough();
1520
1558
  var messageSchema = zod.z.object({
1521
1559
  id: zod.z.string(),
1522
1560
  conversation_id: zod.z.string(),
@@ -1526,6 +1564,7 @@ var messageSchema = zod.z.object({
1526
1564
  type: zod.z.enum(["text", "structured", "file", "system"]),
1527
1565
  content: messageContentSchema,
1528
1566
  metadata: zod.z.record(zod.z.string(), zod.z.unknown()).default({}),
1567
+ context: messageContextSchema.optional(),
1529
1568
  // Per-recipient delivery state lives in `message_deliveries` since
1530
1569
  // migration 011 — the `messages` row no longer carries `status`,
1531
1570
  // `delivered_at`, or `read_at`. Fresh-send envelopes over WS omit
@@ -1647,7 +1686,12 @@ function normalizeMessageNew(frame) {
1647
1686
  createdAt: msg.created_at,
1648
1687
  deliveredAt: msg.delivered_at ?? null,
1649
1688
  readAt: msg.read_at ?? null,
1650
- receivedAt: frame.receivedAt
1689
+ receivedAt: frame.receivedAt,
1690
+ senderDisplayName: msg.context?.sender?.display_name ?? null,
1691
+ senderKind: msg.context?.sender?.kind === "system" ? "system" : "agent",
1692
+ groupName: msg.context?.conversation?.group_name ?? null,
1693
+ memberCount: msg.context?.conversation?.member_count ?? null,
1694
+ mentions: (msg.context?.mentions ?? []).map((m) => m.toLowerCase())
1651
1695
  };
1652
1696
  }
1653
1697
  function normalizeMessageRead(frame) {
@@ -1726,7 +1770,7 @@ function normalizeGroupDeleted(frame) {
1726
1770
 
1727
1771
  // src/retry.ts
1728
1772
  function defaultSleep(ms) {
1729
- return new Promise((resolve) => setTimeout(resolve, ms));
1773
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1730
1774
  }
1731
1775
  async function retryWithPolicy(fn, policy) {
1732
1776
  const random = policy.random ?? Math.random;
@@ -1854,7 +1898,7 @@ var CircuitBreaker = class {
1854
1898
  };
1855
1899
 
1856
1900
  // src/version.ts
1857
- var PACKAGE_VERSION = "0.7.8";
1901
+ var PACKAGE_VERSION = "0.7.82";
1858
1902
 
1859
1903
  // src/outbound.ts
1860
1904
  var DEFAULT_RETRY_POLICY = {
@@ -2070,11 +2114,11 @@ var OutboundAdapter = class {
2070
2114
  `outbound queue full (${this.queue.length}) \u2014 shedding load`
2071
2115
  );
2072
2116
  }
2073
- return new Promise((resolve) => {
2117
+ return new Promise((resolve2) => {
2074
2118
  this.queue.push(() => {
2075
2119
  this.inFlight++;
2076
2120
  this.metrics.setInFlightDepth(this.inFlight);
2077
- resolve();
2121
+ resolve2();
2078
2122
  });
2079
2123
  });
2080
2124
  }
@@ -2150,10 +2194,10 @@ var AgentchatChannelRuntime = class {
2150
2194
  stop(deadlineMs) {
2151
2195
  if (this.stopPromise) return this.stopPromise;
2152
2196
  const deadline = deadlineMs ?? this.now() + 5e3;
2153
- this.stopPromise = new Promise((resolve) => {
2197
+ this.stopPromise = new Promise((resolve2) => {
2154
2198
  const off = this.ws.on("closed", () => {
2155
2199
  off();
2156
- resolve();
2200
+ resolve2();
2157
2201
  });
2158
2202
  this.ws.stop(deadline);
2159
2203
  });
@@ -2383,6 +2427,476 @@ function unregisterRuntime(accountId, deadlineMs = Date.now() + 5e3) {
2383
2427
  function getRuntime(accountId) {
2384
2428
  return registry.get(accountId)?.runtime;
2385
2429
  }
2430
+ function resolveWorkspaceDir(cfg) {
2431
+ const configured = cfg?.agents?.defaults?.workspace;
2432
+ if (typeof configured === "string" && configured.trim().length > 0) {
2433
+ return path2__namespace.resolve(configured);
2434
+ }
2435
+ const profile = readEnv_js$1.readOpenClawProfileFromEnv();
2436
+ if (profile) {
2437
+ return path2__namespace.join(os__namespace.homedir(), ".openclaw", `workspace-${profile}`);
2438
+ }
2439
+ return path2__namespace.join(os__namespace.homedir(), ".openclaw", "workspace");
2440
+ }
2441
+
2442
+ // src/binding/thread-closures.ts
2443
+ var instances = /* @__PURE__ */ new Map();
2444
+ function fallbackWorkspaceDir() {
2445
+ const profile = process.env.OPENCLAW_PROFILE?.trim();
2446
+ if (profile && profile.toLowerCase() !== "default") {
2447
+ return path2__namespace.default.join(os__namespace.default.homedir(), ".openclaw", `workspace-${profile}`);
2448
+ }
2449
+ return path2__namespace.default.join(os__namespace.default.homedir(), ".openclaw", "workspace");
2450
+ }
2451
+ function resolveStatePath(cfg, accountId) {
2452
+ const workspaceDir = typeof cfg === "object" && cfg !== null ? resolveWorkspaceDir(cfg) : fallbackWorkspaceDir();
2453
+ return path2__namespace.default.join(workspaceDir, `.agentchat-closed-threads-${accountId}.json`);
2454
+ }
2455
+ var ThreadClosures = class {
2456
+ filePath;
2457
+ closed = /* @__PURE__ */ new Map();
2458
+ constructor(filePath) {
2459
+ this.filePath = filePath;
2460
+ this.load();
2461
+ }
2462
+ isClosed(conversationId) {
2463
+ return this.closed.has(conversationId);
2464
+ }
2465
+ close(conversationId, reason) {
2466
+ const record = {
2467
+ conversationId,
2468
+ closedAt: (/* @__PURE__ */ new Date()).toISOString(),
2469
+ reason: reason?.trim() ? reason.trim() : null
2470
+ };
2471
+ this.closed.set(conversationId, record);
2472
+ this.save();
2473
+ return record;
2474
+ }
2475
+ reopen(conversationId) {
2476
+ const existed = this.closed.delete(conversationId);
2477
+ if (existed) this.save();
2478
+ return existed;
2479
+ }
2480
+ list() {
2481
+ return [...this.closed.values()].sort((a, b) => b.closedAt.localeCompare(a.closedAt));
2482
+ }
2483
+ load() {
2484
+ if (!fs2__default.default.existsSync(this.filePath)) return;
2485
+ try {
2486
+ const raw = JSON.parse(fs2__default.default.readFileSync(this.filePath, "utf8"));
2487
+ if (!Array.isArray(raw)) return;
2488
+ for (const entry of raw) {
2489
+ if (!entry || typeof entry !== "object") continue;
2490
+ const conversationId = entry.conversationId;
2491
+ const closedAt = entry.closedAt;
2492
+ const reason = entry.reason;
2493
+ if (typeof conversationId !== "string" || typeof closedAt !== "string") continue;
2494
+ this.closed.set(conversationId, {
2495
+ conversationId,
2496
+ closedAt,
2497
+ reason: typeof reason === "string" ? reason : null
2498
+ });
2499
+ }
2500
+ } catch {
2501
+ this.closed = /* @__PURE__ */ new Map();
2502
+ }
2503
+ }
2504
+ save() {
2505
+ fs2__default.default.mkdirSync(path2__namespace.default.dirname(this.filePath), { recursive: true });
2506
+ const payload = JSON.stringify(this.list(), null, 2);
2507
+ const tempPath = `${this.filePath}.tmp`;
2508
+ fs2__default.default.writeFileSync(tempPath, payload, "utf8");
2509
+ fs2__default.default.renameSync(tempPath, this.filePath);
2510
+ }
2511
+ };
2512
+ function getThreadClosures(cfg, accountId) {
2513
+ const filePath = resolveStatePath(cfg, accountId);
2514
+ const existing = instances.get(filePath);
2515
+ if (existing) return existing;
2516
+ const created = new ThreadClosures(filePath);
2517
+ instances.set(filePath, created);
2518
+ return created;
2519
+ }
2520
+ var cache = /* @__PURE__ */ new Map();
2521
+ function getClient({ accountId, config, options }) {
2522
+ const existing = cache.get(accountId);
2523
+ if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
2524
+ return existing.client;
2525
+ }
2526
+ const client = new agentchatme.AgentChatClient({
2527
+ apiKey: config.apiKey,
2528
+ baseUrl: config.apiBase,
2529
+ ...options
2530
+ });
2531
+ cache.set(accountId, {
2532
+ client,
2533
+ apiKey: config.apiKey,
2534
+ apiBase: config.apiBase
2535
+ });
2536
+ return client;
2537
+ }
2538
+ function disposeClient(accountId) {
2539
+ cache.delete(accountId);
2540
+ }
2541
+
2542
+ // src/binding/send-tracker.ts
2543
+ var lastSendByKey = /* @__PURE__ */ new Map();
2544
+ var MAX_TRACKED = 512;
2545
+ function key(accountId, conversationId) {
2546
+ return `${accountId}\0${conversationId}`;
2547
+ }
2548
+ function recordAgentSend(accountId, conversationId, atMs = Date.now()) {
2549
+ if (!conversationId) return;
2550
+ const k = key(accountId, conversationId);
2551
+ lastSendByKey.delete(k);
2552
+ lastSendByKey.set(k, atMs);
2553
+ if (lastSendByKey.size > MAX_TRACKED) {
2554
+ const oldest = lastSendByKey.keys().next().value;
2555
+ if (oldest !== void 0) lastSendByKey.delete(oldest);
2556
+ }
2557
+ }
2558
+ function hasAgentSendSince(accountId, conversationId, sinceMs) {
2559
+ const at = lastSendByKey.get(key(accountId, conversationId));
2560
+ return at !== void 0 && at >= sinceMs;
2561
+ }
2562
+
2563
+ // src/binding/reply-gate.ts
2564
+ var DEFAULT_GATE_MAX_TOKENS = 256;
2565
+ var MAX_HISTORY_TURNS = 12;
2566
+ var CADENCE_WINDOW_SECONDS = 60;
2567
+ var VALID_CATEGORIES = /* @__PURE__ */ new Set([
2568
+ "open_request",
2569
+ "new_info",
2570
+ "goal_followup",
2571
+ "closing",
2572
+ "acknowledgement",
2573
+ "not_addressed",
2574
+ "no_action_needed",
2575
+ "spam",
2576
+ "other"
2577
+ ]);
2578
+ var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "yes", "true", "respond"]);
2579
+ var NO_REPLY_TOKENS = /* @__PURE__ */ new Set([
2580
+ "no_reply",
2581
+ "no-reply",
2582
+ "noreply",
2583
+ "no",
2584
+ "false",
2585
+ "silent",
2586
+ "skip",
2587
+ "none"
2588
+ ]);
2589
+ var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
2590
+ function computeConversationSignals(messages, params) {
2591
+ const windowSeconds = params.windowSeconds ?? CADENCE_WINDOW_SECONDS;
2592
+ const own = normalizeHandle(params.ownHandle);
2593
+ const prior = messages.filter(
2594
+ (m) => isRecord(m) && m.id !== params.triggerMessageId
2595
+ );
2596
+ const firstContact = prior.length === 0;
2597
+ const youHaveSpoken = prior.some((m) => messageIsOwn(m, own));
2598
+ const timestamps = [];
2599
+ for (const m of prior) {
2600
+ const ts = parseTimestamp(m.created_at);
2601
+ if (ts !== null) timestamps.push(ts);
2602
+ }
2603
+ const cutoff = params.nowMs - windowSeconds * 1e3;
2604
+ const recentInWindow = timestamps.filter((ts) => ts >= cutoff).length;
2605
+ let secondsSincePrevious = null;
2606
+ if (timestamps.length > 0) {
2607
+ const delta = (params.nowMs - Math.max(...timestamps)) / 1e3;
2608
+ secondsSincePrevious = delta > 0 ? delta : 0;
2609
+ }
2610
+ return {
2611
+ firstContact,
2612
+ youHaveSpoken,
2613
+ messagesLastWindow: recentInWindow + 1,
2614
+ // +1 for the new message
2615
+ secondsSincePrevious
2616
+ };
2617
+ }
2618
+ function messageIsOwn(msg, ownHandleNorm) {
2619
+ if (typeof msg.is_own === "boolean") return msg.is_own;
2620
+ const sender = msg.sender ?? msg.from ?? msg.sender_handle ?? "";
2621
+ return normalizeHandle(String(sender)) === ownHandleNorm;
2622
+ }
2623
+ function parseTimestamp(raw) {
2624
+ if (typeof raw !== "string" || !raw) return null;
2625
+ const t = Date.parse(raw);
2626
+ return Number.isNaN(t) ? null : t;
2627
+ }
2628
+ function normalizeHandle(handle) {
2629
+ return handle.replace(/^@/, "").toLowerCase();
2630
+ }
2631
+ function isRecord(value) {
2632
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2633
+ }
2634
+ function systemTemplate(handle) {
2635
+ const h = `@${handle}`;
2636
+ 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.
2637
+
2638
+ "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.
2639
+
2640
+ Judge DONE-NESS, not how interesting another message could be:
2641
+
2642
+ Choose "reply" only if a further message accomplishes a concrete, still-OPEN purpose:
2643
+ - answer a substantive pending question or supply specifically requested information
2644
+ - make or respond to a decision, or unblock the peer on a real task
2645
+ - ${h} started this thread toward a goal and the peer's reply needs a substantive follow-up to reach it
2646
+ - new information genuinely requires ${h}'s input
2647
+
2648
+ Choose "no_reply" when the exchange has reached its natural end \u2014 even if another clever or friendly message is easily possible:
2649
+ - it is trading pleasantries, mutual appreciation, agreement, or open-ended tangents / "riffing" with no open objective
2650
+ - 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
2651
+ - the other side is acknowledging or closing out (thanks / ok / got it / sounds good / \u{1F44D} / bye) and replying would only prolong it
2652
+ - ${h} already answered what was asked and nothing new is on the table
2653
+ - 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.)
2654
+
2655
+ "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".
2656
+
2657
+ Respond with ONLY a JSON object \u2014 no prose, no markdown fences:
2658
+ {"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>"}`;
2659
+ }
2660
+ function buildDecisionMessages(params) {
2661
+ return [
2662
+ { role: "system", content: systemTemplate(params.handle) },
2663
+ {
2664
+ role: "user",
2665
+ content: buildUserContent({
2666
+ handle: params.handle,
2667
+ event: params.event,
2668
+ history: params.history,
2669
+ signals: params.signals ?? null,
2670
+ maxHistory: params.maxHistory ?? MAX_HISTORY_TURNS
2671
+ })
2672
+ }
2673
+ ];
2674
+ }
2675
+ function formatReceivedAt(ms) {
2676
+ if (!Number.isFinite(ms)) return "an unknown time";
2677
+ const iso = new Date(ms).toISOString();
2678
+ return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
2679
+ }
2680
+ function formatConversationContext(params) {
2681
+ const { handle, event, signals, priorCount } = params;
2682
+ const lines = [`Conversation type: ${formatConversationLabel(event)}`];
2683
+ if (signals) {
2684
+ lines.push(`Relationship: ${relationshipPhrase(signals)}`);
2685
+ if (signals.secondsSincePrevious !== null) {
2686
+ lines.push(
2687
+ `Pace: ${signals.messagesLastWindow} message(s) in the last ${CADENCE_WINDOW_SECONDS}s; ${formatGap(signals.secondsSincePrevious)} since the previous message`
2688
+ );
2689
+ }
2690
+ }
2691
+ lines.push(`Prior messages in this thread: ${priorCount}`);
2692
+ if (event.conversationKind === "group" && handle && (event.mentions ?? []).includes(handle.toLowerCase())) {
2693
+ lines.push("You were @-mentioned in this message.");
2694
+ }
2695
+ return lines;
2696
+ }
2697
+ function formatConversationLabel(event) {
2698
+ if (event.conversationKind !== "group") return "direct";
2699
+ let label = event.groupName ? `group "${event.groupName}"` : "group";
2700
+ if (event.memberCount != null) {
2701
+ label += ` (${event.memberCount} member${event.memberCount === 1 ? "" : "s"})`;
2702
+ }
2703
+ return label;
2704
+ }
2705
+ function buildUserContent(params) {
2706
+ const { handle, event, history, signals, maxHistory } = params;
2707
+ const lines = formatConversationContext({
2708
+ handle,
2709
+ event,
2710
+ signals,
2711
+ priorCount: history.length
2712
+ });
2713
+ lines.push("");
2714
+ const rendered = renderHistory(history, maxHistory);
2715
+ if (rendered.length > 0) {
2716
+ lines.push("Recent conversation (oldest first):");
2717
+ lines.push(...rendered);
2718
+ } else {
2719
+ lines.push("Recent conversation: (none \u2014 this is first contact)");
2720
+ }
2721
+ let newText = collapseWhitespace(event.contentText || "");
2722
+ if (newText.length > 2e3) newText = `${newText.slice(0, 2e3)}\u2026`;
2723
+ lines.push("");
2724
+ lines.push(`New message from @${event.senderHandle}: ${newText}`);
2725
+ lines.push("");
2726
+ lines.push("Decide now: reply or no_reply?");
2727
+ return lines.join("\n");
2728
+ }
2729
+ function renderHistory(history, maxHistory) {
2730
+ const recent = history.length > maxHistory ? history.slice(history.length - maxHistory) : history;
2731
+ const out = [];
2732
+ for (const turn of recent) {
2733
+ if (typeof turn.content !== "string" || !turn.content.trim()) continue;
2734
+ const speaker = turn.role === "assistant" ? "you" : "peer";
2735
+ let text = collapseWhitespace(turn.content);
2736
+ if (text.length > 400) text = `${text.slice(0, 400)}\u2026`;
2737
+ out.push(`${speaker}: ${text}`);
2738
+ }
2739
+ return out;
2740
+ }
2741
+ function relationshipPhrase(signals) {
2742
+ if (signals.firstContact) return "first contact \u2014 no prior messages in this thread";
2743
+ if (signals.youHaveSpoken) return "established \u2014 you have already replied in this thread";
2744
+ return "this peer is messaging you, but you have not replied yet";
2745
+ }
2746
+ function formatGap(seconds) {
2747
+ if (seconds < 90) return `${Math.round(seconds)}s`;
2748
+ if (seconds < 5400) return `${Math.round(seconds / 60)}m`;
2749
+ return `${Math.round(seconds / 3600)}h`;
2750
+ }
2751
+ function collapseWhitespace(text) {
2752
+ return text.split(/\s+/).filter(Boolean).join(" ");
2753
+ }
2754
+ function parseDecision(text, opts = {}) {
2755
+ const raw = extractJson(text);
2756
+ if (raw === null) return null;
2757
+ let obj;
2758
+ try {
2759
+ obj = JSON.parse(raw);
2760
+ } catch {
2761
+ return null;
2762
+ }
2763
+ if (!isRecord(obj)) return null;
2764
+ const decisionRaw = obj.decision;
2765
+ if (typeof decisionRaw !== "string") return null;
2766
+ const token = decisionRaw.trim().toLowerCase();
2767
+ let reply;
2768
+ if (REPLY_TOKENS.has(token)) reply = true;
2769
+ else if (NO_REPLY_TOKENS.has(token)) reply = false;
2770
+ else return null;
2771
+ const reasonRaw = obj.reason;
2772
+ let reason = typeof reasonRaw === "string" ? reasonRaw.trim() : "";
2773
+ if (reason.length > 280) reason = reason.slice(0, 280);
2774
+ const categoryRaw = obj.category;
2775
+ let category = typeof categoryRaw === "string" ? categoryRaw.trim().toLowerCase() : "other";
2776
+ if (!VALID_CATEGORIES.has(category)) category = "other";
2777
+ return {
2778
+ reply,
2779
+ reason,
2780
+ category,
2781
+ source: opts.source ?? "llm",
2782
+ latencyMs: opts.latencyMs ?? 0
2783
+ };
2784
+ }
2785
+ function extractJson(text) {
2786
+ if (!text || !text.trim()) return null;
2787
+ let s = text.trim();
2788
+ const fence = FENCE_RE.exec(s);
2789
+ if (fence?.[1]) s = fence[1].trim();
2790
+ const start = s.indexOf("{");
2791
+ const end = s.lastIndexOf("}");
2792
+ if (start === -1 || end === -1 || end <= start) return null;
2793
+ return s.slice(start, end + 1);
2794
+ }
2795
+ function gateFallback(failOpen, reason, latencyMs) {
2796
+ return {
2797
+ reply: failOpen,
2798
+ reason,
2799
+ category: "fallback",
2800
+ source: failOpen ? "fail_open" : "fail_closed",
2801
+ latencyMs
2802
+ };
2803
+ }
2804
+
2805
+ // src/binding/gate.ts
2806
+ var DEFAULT_GATE_TIMEOUT_MS = 2e4;
2807
+ var GATE_REASONING_LEVEL = "off";
2808
+ var GateTimeoutError = class extends Error {
2809
+ };
2810
+ function withTimeout(promise, ms) {
2811
+ if (!Number.isFinite(ms) || ms <= 0) return promise;
2812
+ return new Promise((resolve2, reject) => {
2813
+ const timer = setTimeout(() => reject(new GateTimeoutError("gate decision timed out")), ms);
2814
+ promise.then(
2815
+ (value) => {
2816
+ clearTimeout(timer);
2817
+ resolve2(value);
2818
+ },
2819
+ (err3) => {
2820
+ clearTimeout(timer);
2821
+ reject(err3);
2822
+ }
2823
+ );
2824
+ });
2825
+ }
2826
+ async function decideReply(params) {
2827
+ const signals = computeConversationSignals(params.rawMessages, {
2828
+ ownHandle: params.ownHandle,
2829
+ triggerMessageId: params.triggerMessageId,
2830
+ nowMs: params.nowMs
2831
+ });
2832
+ const messages = buildDecisionMessages({
2833
+ handle: params.handle,
2834
+ event: params.event,
2835
+ history: params.history,
2836
+ signals
2837
+ });
2838
+ const systemPrompt = messages.find((m) => m.role === "system")?.content ?? "";
2839
+ const userContent = messages.find((m) => m.role === "user")?.content ?? "";
2840
+ const caller = params.caller ?? createSimpleCompletionGateCaller(params.cfg, params.agentId);
2841
+ const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
2842
+ const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
2843
+ const start = Date.now();
2844
+ let text;
2845
+ try {
2846
+ text = await withTimeout(caller({ systemPrompt, userContent, maxTokens }), timeoutMs);
2847
+ } catch (err3) {
2848
+ if (err3 instanceof GateTimeoutError) {
2849
+ return gateFallback(params.failOpen, "decision_timeout", Date.now() - start);
2850
+ }
2851
+ const detail = err3 instanceof Error ? err3.message : String(err3);
2852
+ return gateFallback(
2853
+ params.failOpen,
2854
+ `decision_call_error: ${detail}`.slice(0, 220),
2855
+ Date.now() - start
2856
+ );
2857
+ }
2858
+ const latencyMs = Date.now() - start;
2859
+ const parsed = parseDecision(text, { source: "llm", latencyMs });
2860
+ return parsed ?? gateFallback(params.failOpen, "unparseable_decision", latencyMs);
2861
+ }
2862
+ function createSimpleCompletionGateCaller(cfg, agentId) {
2863
+ return async ({ systemPrompt, userContent, maxTokens, signal }) => {
2864
+ const prepared = await simpleCompletionRuntime.prepareSimpleCompletionModelForAgent({
2865
+ cfg,
2866
+ // plugin-local OpenClawConfig alias → sdk's internal type
2867
+ agentId,
2868
+ allowMissingApiKeyModes: ["aws-sdk"],
2869
+ // Do NOT skip discovery: it loads provider model catalogs. Skipping it
2870
+ // works for providers with pure dynamic resolution (e.g. Fireworks) but
2871
+ // makes catalog-based providers (Google/Gemini, Anthropic, OpenAI, …)
2872
+ // fail with "Unknown model: <ref>" — the gate must resolve the agent's
2873
+ // own model regardless of which provider it runs on.
2874
+ skipAgentDiscovery: false
2875
+ });
2876
+ if ("error" in prepared) throw new Error(prepared.error);
2877
+ const result = await simpleCompletionRuntime.completeWithPreparedSimpleCompletionModel({
2878
+ model: prepared.model,
2879
+ auth: prepared.auth,
2880
+ cfg,
2881
+ context: {
2882
+ systemPrompt,
2883
+ messages: [{ role: "user", content: userContent }]
2884
+ },
2885
+ // temperature 0 mirrors the Hermes gate: a binary policy decision must
2886
+ // be as deterministic as the provider allows, not sampled creatively.
2887
+ options: {
2888
+ maxTokens,
2889
+ temperature: 0,
2890
+ reasoning: GATE_REASONING_LEVEL,
2891
+ ...signal ? { signal } : {}
2892
+ }
2893
+ });
2894
+ return result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("");
2895
+ };
2896
+ }
2897
+
2898
+ // src/binding/inbound-bridge.ts
2899
+ var GATE_HISTORY_LIMIT = 30;
2386
2900
  function createInboundBridge(deps) {
2387
2901
  return async function onInbound(event) {
2388
2902
  switch (event.kind) {
@@ -2419,6 +2933,17 @@ async function handleMessage(deps, event) {
2419
2933
  if (!body && !event.content.attachmentId && !event.content.data) {
2420
2934
  return;
2421
2935
  }
2936
+ const threadClosures = getThreadClosures(
2937
+ deps.gatewayCfg,
2938
+ deps.accountId
2939
+ );
2940
+ if (threadClosures.isClosed(event.conversationId)) {
2941
+ deps.logger.info(
2942
+ { conversationId: event.conversationId, messageId: event.messageId, sender: event.sender },
2943
+ "inbound skipped for locally closed thread"
2944
+ );
2945
+ return;
2946
+ }
2422
2947
  const channelRuntime = deps.channelRuntime;
2423
2948
  if (!channelRuntime || typeof channelRuntime.reply?.dispatchReplyWithBufferedBlockDispatcher !== "function") {
2424
2949
  deps.logger.error(
@@ -2433,6 +2958,7 @@ async function handleMessage(deps, event) {
2433
2958
  );
2434
2959
  return;
2435
2960
  }
2961
+ const ts = typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt);
2436
2962
  const recipientHandle = selfHandle ?? "me";
2437
2963
  const conversationLabel = event.conversationKind === "group" ? `group ${event.conversationId}` : `dm with @${senderHandle}`;
2438
2964
  const sendReply = async (replyText) => {
@@ -2445,36 +2971,131 @@ async function handleMessage(deps, event) {
2445
2971
  metadata: { reply_to: event.messageId }
2446
2972
  });
2447
2973
  };
2974
+ const turnStartMs = Date.now();
2448
2975
  const deliver2 = async (payload) => {
2449
- const replyText = payload.text ?? extractText(payload.blocks);
2450
- await sendReply(replyText);
2976
+ if (threadClosures.isClosed(event.conversationId)) {
2977
+ deps.logger.info(
2978
+ { conversationId: event.conversationId, messageId: event.messageId },
2979
+ "reply suppressed for locally closed thread"
2980
+ );
2981
+ return;
2982
+ }
2983
+ if (hasAgentSendSince(deps.accountId, event.conversationId, turnStartMs)) {
2984
+ deps.logger.info(
2985
+ { conversationId: event.conversationId, messageId: event.messageId },
2986
+ "final turn text suppressed \u2014 agent already sent its reply via a message tool this turn"
2987
+ );
2988
+ return;
2989
+ }
2990
+ await sendReply(payload.text ?? extractText(payload.blocks));
2451
2991
  };
2452
2992
  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
- );
2993
+ const runtime = channelRuntime;
2994
+ const peer = event.conversationKind === "group" ? { kind: "group", id: event.conversationId } : { kind: "direct", id: senderHandle };
2995
+ const { route, buildEnvelope } = inboundEnvelope.resolveInboundRouteEnvelopeBuilderWithRuntime({
2996
+ cfg: deps.gatewayCfg,
2997
+ channel: "agentchat",
2998
+ accountId: deps.accountId,
2999
+ peer,
3000
+ runtime
3001
+ });
3002
+ let gateContext = null;
3003
+ if (gateEnabled()) {
3004
+ const { decision, context } = await runReplyGate({
3005
+ deps,
3006
+ event,
3007
+ body,
3008
+ agentId: route.agentId,
3009
+ selfHandle,
3010
+ senderHandle,
3011
+ nowMs: Number.isFinite(ts) ? ts : Date.now()
3012
+ });
3013
+ deps.logger.info(
3014
+ {
3015
+ conversationId: event.conversationId,
3016
+ messageId: event.messageId,
3017
+ reply: decision.reply,
3018
+ source: decision.source,
3019
+ category: decision.category,
3020
+ latencyMs: decision.latencyMs,
3021
+ reason: decision.reason
3022
+ },
3023
+ "reply gate decision"
3024
+ );
3025
+ if (!decision.reply) return;
3026
+ gateContext = context;
3027
+ }
3028
+ const contextHeader = [formatSenderLine(event), `Received: ${formatReceivedAt(ts)}`];
3029
+ if (gateContext) {
3030
+ contextHeader.push(...gateContext);
3031
+ } else {
3032
+ contextHeader.push(
3033
+ `Conversation type: ${formatConversationLabel({
3034
+ conversationKind: event.conversationKind,
3035
+ senderHandle,
3036
+ contentText: body,
3037
+ groupName: event.groupName,
3038
+ memberCount: event.memberCount,
3039
+ mentions: event.mentions
3040
+ })}`
3041
+ );
3042
+ const self = (selfHandle ?? "").replace(/^@/, "").toLowerCase();
3043
+ if (event.conversationKind === "group" && self && event.mentions.includes(self)) {
3044
+ contextHeader.push("You were @-mentioned in this message.");
3045
+ }
3046
+ }
3047
+ const agentBody = `${contextHeader.join("\n")}
3048
+
3049
+ ${body}`;
3050
+ const { storePath, body: envelopeBody } = buildEnvelope({
3051
+ channel: "AgentChat",
3052
+ from: conversationLabel,
3053
+ body: agentBody,
3054
+ timestamp: ts
3055
+ });
3056
+ const finalize = channelRuntime.reply.finalizeInboundContext;
3057
+ const ctxPayload = finalize({
3058
+ Body: envelopeBody,
3059
+ BodyForAgent: agentBody,
3060
+ RawBody: body,
3061
+ CommandBody: body,
3062
+ From: `@${senderHandle}`,
3063
+ To: `@${recipientHandle}`,
3064
+ SessionKey: route.sessionKey,
3065
+ AccountId: deps.accountId,
3066
+ ChatType: event.conversationKind === "group" ? "group" : "direct",
3067
+ ConversationLabel: conversationLabel,
3068
+ SenderId: senderHandle,
3069
+ Provider: "agentchat",
3070
+ Surface: "agentchat",
3071
+ MessageSid: event.messageId,
3072
+ MessageSidFull: event.messageId,
3073
+ Timestamp: ts,
3074
+ OriginatingChannel: "agentchat",
3075
+ OriginatingTo: `@${recipientHandle}`
3076
+ });
3077
+ const session = channelRuntime.session;
3078
+ await inboundReplyDispatch.dispatchChannelInboundReply({
3079
+ cfg: deps.gatewayCfg,
3080
+ channel: "agentchat",
3081
+ accountId: deps.accountId,
3082
+ agentId: route.agentId,
3083
+ routeSessionKey: route.sessionKey,
3084
+ storePath,
3085
+ ctxPayload,
3086
+ recordInboundSession: session.recordInboundSession,
3087
+ dispatchReplyWithBufferedBlockDispatcher: channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
3088
+ // Under `automatic` (the default) the framework hands the agent's final
3089
+ // turn text to this `deliver`, which sends it to the source. Under the
3090
+ // opt-in `message_tool_only` mode the turn text is suppressed and the
3091
+ // agent sends via the message tool instead, so `deliver` only fires on a
3092
+ // framework fallback. Either way a gated `no_reply` turn never runs, so
3093
+ // nothing is sent.
3094
+ delivery: {
3095
+ deliver: async (payload) => {
3096
+ await deliver2(payload);
2476
3097
  },
2477
- onDispatchError: (err3, info) => {
3098
+ onError: (err3, info) => {
2478
3099
  deps.logger.error(
2479
3100
  {
2480
3101
  err: err3 instanceof Error ? err3.message : String(err3),
@@ -2484,84 +3105,124 @@ async function handleMessage(deps, event) {
2484
3105
  "inbound dispatch failed"
2485
3106
  );
2486
3107
  }
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,
3108
+ },
3109
+ replyOptions: { sourceReplyDeliveryMode: resolveSourceReplyMode() },
3110
+ record: {
2537
3111
  onRecordError: (err3) => {
2538
3112
  deps.logger.error(
2539
3113
  { 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)"
3114
+ "recordInboundSession failed"
2551
3115
  );
2552
3116
  }
2553
- });
2554
- }
3117
+ }
3118
+ });
2555
3119
  } catch (err3) {
2556
3120
  deps.logger.error(
2557
- {
2558
- err: err3 instanceof Error ? err3.message : String(err3),
2559
- messageId: event.messageId
2560
- },
3121
+ { err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
2561
3122
  "inbound dispatch failed"
2562
3123
  );
2563
3124
  }
2564
3125
  }
3126
+ function formatSenderLine(event) {
3127
+ const who = event.senderDisplayName ? `${event.senderDisplayName} (@${event.sender})` : `@${event.sender}`;
3128
+ return `From: ${event.senderKind === "system" ? `${who}, a system agent` : who}`;
3129
+ }
3130
+ async function runReplyGate(params) {
3131
+ const { deps, event, body, agentId, selfHandle, senderHandle, nowMs } = params;
3132
+ const ownHandle = selfHandle ?? "";
3133
+ let rawMessages = [];
3134
+ try {
3135
+ const client = getClient({ accountId: deps.accountId, config: deps.config });
3136
+ const fetched = await client.getMessages(event.conversationId, { limit: GATE_HISTORY_LIMIT });
3137
+ if (Array.isArray(fetched)) rawMessages = fetched;
3138
+ } catch (err3) {
3139
+ deps.logger.warn(
3140
+ { err: err3 instanceof Error ? err3.message : String(err3), conversationId: event.conversationId },
3141
+ "reply gate: history fetch failed \u2014 deciding on the new message alone"
3142
+ );
3143
+ }
3144
+ const bareHandle = ownHandle.replace(/^@/, "");
3145
+ const gateEvent = {
3146
+ conversationKind: event.conversationKind,
3147
+ senderHandle,
3148
+ contentText: body,
3149
+ groupName: event.groupName,
3150
+ memberCount: event.memberCount,
3151
+ mentions: event.mentions
3152
+ };
3153
+ const history = translateHistory(rawMessages, ownHandle, event.conversationKind, event.messageId);
3154
+ const decision = await decideReply({
3155
+ cfg: deps.gatewayCfg,
3156
+ agentId,
3157
+ handle: bareHandle,
3158
+ event: gateEvent,
3159
+ history,
3160
+ rawMessages,
3161
+ triggerMessageId: event.messageId,
3162
+ ownHandle,
3163
+ nowMs,
3164
+ failOpen: gateFailOpen(),
3165
+ timeoutMs: gateTimeoutMs(),
3166
+ caller: deps.gateCaller
3167
+ });
3168
+ const signals = computeConversationSignals(rawMessages, {
3169
+ ownHandle,
3170
+ triggerMessageId: event.messageId,
3171
+ nowMs
3172
+ });
3173
+ const context = formatConversationContext({
3174
+ handle: bareHandle,
3175
+ event: gateEvent,
3176
+ signals,
3177
+ priorCount: history.length
3178
+ });
3179
+ return { decision, context };
3180
+ }
3181
+ function translateHistory(messages, ownHandle, conversationKind, triggerMessageId) {
3182
+ const own = ownHandle.replace(/^@/, "").toLowerCase();
3183
+ const isGroup = conversationKind === "group";
3184
+ const sorted = [...messages].filter((m) => Boolean(m) && typeof m === "object").sort((a, b) => readSeq(a) - readSeq(b));
3185
+ const out = [];
3186
+ for (const m of sorted) {
3187
+ if (m.id === triggerMessageId) continue;
3188
+ const type = typeof m.type === "string" ? m.type : "text";
3189
+ if (type !== "text") continue;
3190
+ const content = m.content;
3191
+ const text = content && typeof content === "object" ? content.text : void 0;
3192
+ if (typeof text !== "string" || !text) continue;
3193
+ const senderRaw = String(m.sender ?? m.from ?? m.sender_handle ?? "");
3194
+ const isOwn = typeof m.is_own === "boolean" ? m.is_own : senderRaw.replace(/^@/, "").toLowerCase() === own;
3195
+ if (isOwn) {
3196
+ out.push({ role: "assistant", content: text });
3197
+ } else if (isGroup) {
3198
+ out.push({ role: "user", content: `[@${senderRaw.replace(/^@/, "") || "?"}] ${text}` });
3199
+ } else {
3200
+ out.push({ role: "user", content: text });
3201
+ }
3202
+ }
3203
+ return out;
3204
+ }
3205
+ function readSeq(m) {
3206
+ const seq = m.seq;
3207
+ return typeof seq === "number" ? seq : 0;
3208
+ }
3209
+ var OFF_TOKENS = /* @__PURE__ */ new Set(["0", "false", "off", "no"]);
3210
+ var ON_TOKENS = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
3211
+ function gateEnabled() {
3212
+ return !OFF_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_ENABLED ?? "").trim().toLowerCase());
3213
+ }
3214
+ function gateFailOpen() {
3215
+ return ON_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_FAIL_OPEN ?? "").trim().toLowerCase());
3216
+ }
3217
+ function gateTimeoutMs() {
3218
+ const raw = process.env.AGENTCHAT_REPLY_GATE_TIMEOUT_MS;
3219
+ if (raw === void 0 || raw.trim() === "") return void 0;
3220
+ const n = Number(raw);
3221
+ return Number.isFinite(n) && n > 0 ? n : void 0;
3222
+ }
3223
+ function resolveSourceReplyMode() {
3224
+ return (process.env.AGENTCHAT_SOURCE_REPLY_MODE ?? "").trim().toLowerCase() === "message_tool_only" ? "message_tool_only" : "automatic";
3225
+ }
2565
3226
  function handleGroupInvite(deps, event) {
2566
3227
  deps.logger.info(
2567
3228
  {
@@ -2709,27 +3370,6 @@ var agentchatGatewayAdapter = {
2709
3370
  });
2710
3371
  }
2711
3372
  };
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
3373
 
2734
3374
  // src/binding/outbound.ts
2735
3375
  function resolveConfig(cfg, accountId) {
@@ -2791,6 +3431,7 @@ async function deliver(ctx, attachmentId) {
2791
3431
  attachmentId
2792
3432
  );
2793
3433
  const result = await runtime.sendMessage(input);
3434
+ recordAgentSend(accountId, result.message.conversation_id);
2794
3435
  return {
2795
3436
  channel: AGENTCHAT_CHANNEL_ID,
2796
3437
  messageId: result.message.id,
@@ -2860,8 +3501,8 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
2860
3501
  let contentType;
2861
3502
  let filename = "attachment";
2862
3503
  if (mediaUrl.startsWith("file://") && ctx.mediaReadFile) {
2863
- const path = decodeURIComponent(mediaUrl.replace(/^file:\/\//, ""));
2864
- const buf = await ctx.mediaReadFile(path);
3504
+ const path3 = decodeURIComponent(mediaUrl.replace(/^file:\/\//, ""));
3505
+ const buf = await ctx.mediaReadFile(path3);
2865
3506
  if (buf.byteLength > MAX_MEDIA_BYTES) {
2866
3507
  throw new AgentChatChannelError(
2867
3508
  "terminal-user",
@@ -2871,7 +3512,7 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
2871
3512
  const copy = new Uint8Array(buf.byteLength);
2872
3513
  copy.set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
2873
3514
  bytes = copy.buffer;
2874
- filename = path.split(/[\\/]/).pop() ?? filename;
3515
+ filename = path3.split(/[\\/]/).pop() ?? filename;
2875
3516
  } else {
2876
3517
  assertMediaUrlSafe(mediaUrl);
2877
3518
  const controller = new AbortController();
@@ -3026,8 +3667,8 @@ function err(message) {
3026
3667
  details: { error: message }
3027
3668
  };
3028
3669
  }
3029
- function str(params, key) {
3030
- const v = params[key];
3670
+ function str(params, key2) {
3671
+ const v = params[key2];
3031
3672
  return typeof v === "string" ? v : void 0;
3032
3673
  }
3033
3674
  function resolveConfig2(ctx) {
@@ -3284,6 +3925,7 @@ var agentchatAgentToolsFactory = ({ cfg }) => {
3284
3925
  content: { text: p.message },
3285
3926
  ...p.replyToMessageId ? { metadata: { reply_to: p.replyToMessageId } } : {}
3286
3927
  });
3928
+ recordAgentSend(r.accountId, result.message.conversation_id);
3287
3929
  const summaryParts = [
3288
3930
  `sent to @${handle} \u2014 message ${result.message.id} in ${result.message.conversation_id}`
3289
3931
  ];
@@ -3806,6 +4448,88 @@ ${lines.join("\n")}`);
3806
4448
  }
3807
4449
  }
3808
4450
  }),
4451
+ tool({
4452
+ name: "agentchat_close_local_thread",
4453
+ 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.",
4454
+ parameters: typebox.Type.Object({
4455
+ conversationId: typebox.Type.String(),
4456
+ reason: typebox.Type.Optional(typebox.Type.String({ maxLength: 200 })),
4457
+ account: ACCOUNT_PARAM
4458
+ }),
4459
+ execute: async (_id, p) => {
4460
+ const r = clientFor(cfg, p.account);
4461
+ if ("error" in r) return err2(r.error);
4462
+ const closures = getThreadClosures(cfg, r.accountId);
4463
+ const record = closures.close(p.conversationId, p.reason);
4464
+ return {
4465
+ content: [
4466
+ {
4467
+ type: "text",
4468
+ text: `closed ${record.conversationId} locally`
4469
+ }
4470
+ ],
4471
+ details: {
4472
+ conversationId: record.conversationId,
4473
+ closedAt: record.closedAt,
4474
+ reason: record.reason,
4475
+ localOnly: true
4476
+ }
4477
+ };
4478
+ }
4479
+ }),
4480
+ tool({
4481
+ name: "agentchat_reopen_local_thread",
4482
+ description: "Re-open a previously locally closed conversation thread so new inbound on that conversation id can reach the reply pipeline again.",
4483
+ parameters: typebox.Type.Object({
4484
+ conversationId: typebox.Type.String(),
4485
+ account: ACCOUNT_PARAM
4486
+ }),
4487
+ execute: async (_id, p) => {
4488
+ const r = clientFor(cfg, p.account);
4489
+ if ("error" in r) return err2(r.error);
4490
+ const closures = getThreadClosures(cfg, r.accountId);
4491
+ const reopened = closures.reopen(p.conversationId);
4492
+ return {
4493
+ content: [
4494
+ {
4495
+ type: "text",
4496
+ text: reopened ? `re-opened ${p.conversationId} locally` : `${p.conversationId} was not locally closed`
4497
+ }
4498
+ ],
4499
+ details: {
4500
+ conversationId: p.conversationId,
4501
+ reopened,
4502
+ localOnly: true
4503
+ }
4504
+ };
4505
+ }
4506
+ }),
4507
+ tool({
4508
+ name: "agentchat_list_local_closed_threads",
4509
+ description: "List conversation threads currently closed locally for this OpenClaw AgentChat account. These are client-side only, not server-side blocks or mutes.",
4510
+ parameters: typebox.Type.Object({
4511
+ account: ACCOUNT_PARAM
4512
+ }),
4513
+ execute: async (_id, p) => {
4514
+ const r = clientFor(cfg, p.account);
4515
+ if ("error" in r) return err2(r.error);
4516
+ const closures = getThreadClosures(cfg, r.accountId);
4517
+ const closed = closures.list();
4518
+ if (closed.length === 0) {
4519
+ return {
4520
+ content: [{ type: "text", text: "no locally closed threads" }],
4521
+ details: { closedThreads: [], localOnly: true }
4522
+ };
4523
+ }
4524
+ const lines = closed.map(
4525
+ (record) => `${record.conversationId} \u2014 ${record.closedAt}${record.reason ? ` \u2014 ${record.reason}` : ""}`
4526
+ );
4527
+ return {
4528
+ content: [{ type: "text", text: lines.join("\n") }],
4529
+ details: { closedThreads: closed, localOnly: true }
4530
+ };
4531
+ }
4532
+ }),
3809
4533
  tool({
3810
4534
  name: "agentchat_get_conversation_history",
3811
4535
  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 +4828,7 @@ ${lines.join("\n")}`);
4104
4828
  to: "chatfather",
4105
4829
  content: { text: p.message }
4106
4830
  });
4831
+ recordAgentSend(r.accountId, result.message.conversation_id);
4107
4832
  return ok2(
4108
4833
  `message sent to @chatfather (id: ${result.message.id}). Watch your inbox for the reply.`
4109
4834
  );