@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/CHANGELOG.md +232 -169
- package/README.md +11 -0
- package/dist/binding/agents-anchor.cjs.map +1 -1
- package/dist/binding/agents-anchor.d.cts +1 -1
- package/dist/binding/agents-anchor.d.ts +1 -1
- package/dist/binding/agents-anchor.js.map +1 -1
- package/dist/index.cjs +774 -132
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +756 -133
- package/dist/index.js.map +1 -1
- package/dist/setup-entry.cjs +772 -130
- package/dist/setup-entry.cjs.map +1 -1
- package/dist/setup-entry.js +754 -131
- package/dist/setup-entry.js.map +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +20 -16
- package/skills/agentchat/SKILL.md +3 -1
package/dist/setup-entry.js
CHANGED
|
@@ -6,10 +6,16 @@ import { z } from 'zod';
|
|
|
6
6
|
import { waitUntilAbort } from 'openclaw/plugin-sdk/channel-lifecycle';
|
|
7
7
|
import pino from 'pino';
|
|
8
8
|
import { WebSocket } from 'ws';
|
|
9
|
-
import { dispatchInboundDirectDmWithRuntime } from 'openclaw/plugin-sdk/direct-dm';
|
|
10
9
|
import { resolveInboundRouteEnvelopeBuilderWithRuntime } from 'openclaw/plugin-sdk/inbound-envelope';
|
|
11
|
-
import {
|
|
10
|
+
import { dispatchChannelInboundReply } from 'openclaw/plugin-sdk/inbound-reply-dispatch';
|
|
11
|
+
import fs2 from 'fs';
|
|
12
|
+
import * as os from 'os';
|
|
13
|
+
import os__default from 'os';
|
|
14
|
+
import * as path2 from 'path';
|
|
15
|
+
import path2__default from 'path';
|
|
16
|
+
import { readOpenClawProfileFromEnv } from './credentials/read-env.js';
|
|
12
17
|
import { AgentChatClient } from 'agentchatme';
|
|
18
|
+
import { prepareSimpleCompletionModelForAgent, completeWithPreparedSimpleCompletionModel } from 'openclaw/plugin-sdk/simple-completion-runtime';
|
|
13
19
|
import { Type } from '@sinclair/typebox';
|
|
14
20
|
|
|
15
21
|
// src/channel.setup.ts
|
|
@@ -263,9 +269,9 @@ async function registerAgentVerify(input, opts = {}) {
|
|
|
263
269
|
}
|
|
264
270
|
return { ok: false, reason: "server-error", status: res.status, message };
|
|
265
271
|
}
|
|
266
|
-
async function post(
|
|
272
|
+
async function post(path3, body, opts) {
|
|
267
273
|
const base = (opts.apiBase ?? DEFAULT_API_BASE).replace(/\/+$/, "");
|
|
268
|
-
const url = `${base}${
|
|
274
|
+
const url = `${base}${path3}`;
|
|
269
275
|
const controller = new AbortController();
|
|
270
276
|
const fetchImpl = opts.fetch ?? fetch;
|
|
271
277
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
@@ -900,9 +906,9 @@ function createLogger(options) {
|
|
|
900
906
|
function buildRedactPaths(keys) {
|
|
901
907
|
const prefixes = ["", "config.", "headers.", "context.", "req.headers.", "res.headers."];
|
|
902
908
|
const paths = [];
|
|
903
|
-
for (const
|
|
909
|
+
for (const key2 of keys) {
|
|
904
910
|
for (const prefix of prefixes) {
|
|
905
|
-
paths.push(`${prefix}${
|
|
911
|
+
paths.push(`${prefix}${key2}`);
|
|
906
912
|
}
|
|
907
913
|
}
|
|
908
914
|
paths.push(...keys.map((k) => `*.${k}`));
|
|
@@ -1718,7 +1724,7 @@ function normalizeGroupDeleted(frame) {
|
|
|
1718
1724
|
|
|
1719
1725
|
// src/retry.ts
|
|
1720
1726
|
function defaultSleep(ms) {
|
|
1721
|
-
return new Promise((
|
|
1727
|
+
return new Promise((resolve2) => setTimeout(resolve2, ms));
|
|
1722
1728
|
}
|
|
1723
1729
|
async function retryWithPolicy(fn, policy) {
|
|
1724
1730
|
const random = policy.random ?? Math.random;
|
|
@@ -1846,7 +1852,7 @@ var CircuitBreaker = class {
|
|
|
1846
1852
|
};
|
|
1847
1853
|
|
|
1848
1854
|
// src/version.ts
|
|
1849
|
-
var PACKAGE_VERSION = "0.7.
|
|
1855
|
+
var PACKAGE_VERSION = "0.7.81";
|
|
1850
1856
|
|
|
1851
1857
|
// src/outbound.ts
|
|
1852
1858
|
var DEFAULT_RETRY_POLICY = {
|
|
@@ -2062,11 +2068,11 @@ var OutboundAdapter = class {
|
|
|
2062
2068
|
`outbound queue full (${this.queue.length}) \u2014 shedding load`
|
|
2063
2069
|
);
|
|
2064
2070
|
}
|
|
2065
|
-
return new Promise((
|
|
2071
|
+
return new Promise((resolve2) => {
|
|
2066
2072
|
this.queue.push(() => {
|
|
2067
2073
|
this.inFlight++;
|
|
2068
2074
|
this.metrics.setInFlightDepth(this.inFlight);
|
|
2069
|
-
|
|
2075
|
+
resolve2();
|
|
2070
2076
|
});
|
|
2071
2077
|
});
|
|
2072
2078
|
}
|
|
@@ -2142,10 +2148,10 @@ var AgentchatChannelRuntime = class {
|
|
|
2142
2148
|
stop(deadlineMs) {
|
|
2143
2149
|
if (this.stopPromise) return this.stopPromise;
|
|
2144
2150
|
const deadline = deadlineMs ?? this.now() + 5e3;
|
|
2145
|
-
this.stopPromise = new Promise((
|
|
2151
|
+
this.stopPromise = new Promise((resolve2) => {
|
|
2146
2152
|
const off = this.ws.on("closed", () => {
|
|
2147
2153
|
off();
|
|
2148
|
-
|
|
2154
|
+
resolve2();
|
|
2149
2155
|
});
|
|
2150
2156
|
this.ws.stop(deadline);
|
|
2151
2157
|
});
|
|
@@ -2375,6 +2381,457 @@ function unregisterRuntime(accountId, deadlineMs = Date.now() + 5e3) {
|
|
|
2375
2381
|
function getRuntime(accountId) {
|
|
2376
2382
|
return registry.get(accountId)?.runtime;
|
|
2377
2383
|
}
|
|
2384
|
+
function resolveWorkspaceDir(cfg) {
|
|
2385
|
+
const configured = cfg?.agents?.defaults?.workspace;
|
|
2386
|
+
if (typeof configured === "string" && configured.trim().length > 0) {
|
|
2387
|
+
return path2.resolve(configured);
|
|
2388
|
+
}
|
|
2389
|
+
const profile = readOpenClawProfileFromEnv();
|
|
2390
|
+
if (profile) {
|
|
2391
|
+
return path2.join(os.homedir(), ".openclaw", `workspace-${profile}`);
|
|
2392
|
+
}
|
|
2393
|
+
return path2.join(os.homedir(), ".openclaw", "workspace");
|
|
2394
|
+
}
|
|
2395
|
+
|
|
2396
|
+
// src/binding/thread-closures.ts
|
|
2397
|
+
var instances = /* @__PURE__ */ new Map();
|
|
2398
|
+
function fallbackWorkspaceDir() {
|
|
2399
|
+
const profile = process.env.OPENCLAW_PROFILE?.trim();
|
|
2400
|
+
if (profile && profile.toLowerCase() !== "default") {
|
|
2401
|
+
return path2__default.join(os__default.homedir(), ".openclaw", `workspace-${profile}`);
|
|
2402
|
+
}
|
|
2403
|
+
return path2__default.join(os__default.homedir(), ".openclaw", "workspace");
|
|
2404
|
+
}
|
|
2405
|
+
function resolveStatePath(cfg, accountId) {
|
|
2406
|
+
const workspaceDir = typeof cfg === "object" && cfg !== null ? resolveWorkspaceDir(cfg) : fallbackWorkspaceDir();
|
|
2407
|
+
return path2__default.join(workspaceDir, `.agentchat-closed-threads-${accountId}.json`);
|
|
2408
|
+
}
|
|
2409
|
+
var ThreadClosures = class {
|
|
2410
|
+
filePath;
|
|
2411
|
+
closed = /* @__PURE__ */ new Map();
|
|
2412
|
+
constructor(filePath) {
|
|
2413
|
+
this.filePath = filePath;
|
|
2414
|
+
this.load();
|
|
2415
|
+
}
|
|
2416
|
+
isClosed(conversationId) {
|
|
2417
|
+
return this.closed.has(conversationId);
|
|
2418
|
+
}
|
|
2419
|
+
close(conversationId, reason) {
|
|
2420
|
+
const record = {
|
|
2421
|
+
conversationId,
|
|
2422
|
+
closedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2423
|
+
reason: reason?.trim() ? reason.trim() : null
|
|
2424
|
+
};
|
|
2425
|
+
this.closed.set(conversationId, record);
|
|
2426
|
+
this.save();
|
|
2427
|
+
return record;
|
|
2428
|
+
}
|
|
2429
|
+
reopen(conversationId) {
|
|
2430
|
+
const existed = this.closed.delete(conversationId);
|
|
2431
|
+
if (existed) this.save();
|
|
2432
|
+
return existed;
|
|
2433
|
+
}
|
|
2434
|
+
list() {
|
|
2435
|
+
return [...this.closed.values()].sort((a, b) => b.closedAt.localeCompare(a.closedAt));
|
|
2436
|
+
}
|
|
2437
|
+
load() {
|
|
2438
|
+
if (!fs2.existsSync(this.filePath)) return;
|
|
2439
|
+
try {
|
|
2440
|
+
const raw = JSON.parse(fs2.readFileSync(this.filePath, "utf8"));
|
|
2441
|
+
if (!Array.isArray(raw)) return;
|
|
2442
|
+
for (const entry of raw) {
|
|
2443
|
+
if (!entry || typeof entry !== "object") continue;
|
|
2444
|
+
const conversationId = entry.conversationId;
|
|
2445
|
+
const closedAt = entry.closedAt;
|
|
2446
|
+
const reason = entry.reason;
|
|
2447
|
+
if (typeof conversationId !== "string" || typeof closedAt !== "string") continue;
|
|
2448
|
+
this.closed.set(conversationId, {
|
|
2449
|
+
conversationId,
|
|
2450
|
+
closedAt,
|
|
2451
|
+
reason: typeof reason === "string" ? reason : null
|
|
2452
|
+
});
|
|
2453
|
+
}
|
|
2454
|
+
} catch {
|
|
2455
|
+
this.closed = /* @__PURE__ */ new Map();
|
|
2456
|
+
}
|
|
2457
|
+
}
|
|
2458
|
+
save() {
|
|
2459
|
+
fs2.mkdirSync(path2__default.dirname(this.filePath), { recursive: true });
|
|
2460
|
+
const payload = JSON.stringify(this.list(), null, 2);
|
|
2461
|
+
const tempPath = `${this.filePath}.tmp`;
|
|
2462
|
+
fs2.writeFileSync(tempPath, payload, "utf8");
|
|
2463
|
+
fs2.renameSync(tempPath, this.filePath);
|
|
2464
|
+
}
|
|
2465
|
+
};
|
|
2466
|
+
function getThreadClosures(cfg, accountId) {
|
|
2467
|
+
const filePath = resolveStatePath(cfg, accountId);
|
|
2468
|
+
const existing = instances.get(filePath);
|
|
2469
|
+
if (existing) return existing;
|
|
2470
|
+
const created = new ThreadClosures(filePath);
|
|
2471
|
+
instances.set(filePath, created);
|
|
2472
|
+
return created;
|
|
2473
|
+
}
|
|
2474
|
+
var cache = /* @__PURE__ */ new Map();
|
|
2475
|
+
function getClient({ accountId, config, options }) {
|
|
2476
|
+
const existing = cache.get(accountId);
|
|
2477
|
+
if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
|
|
2478
|
+
return existing.client;
|
|
2479
|
+
}
|
|
2480
|
+
const client = new AgentChatClient({
|
|
2481
|
+
apiKey: config.apiKey,
|
|
2482
|
+
baseUrl: config.apiBase,
|
|
2483
|
+
...options
|
|
2484
|
+
});
|
|
2485
|
+
cache.set(accountId, {
|
|
2486
|
+
client,
|
|
2487
|
+
apiKey: config.apiKey,
|
|
2488
|
+
apiBase: config.apiBase
|
|
2489
|
+
});
|
|
2490
|
+
return client;
|
|
2491
|
+
}
|
|
2492
|
+
function disposeClient(accountId) {
|
|
2493
|
+
cache.delete(accountId);
|
|
2494
|
+
}
|
|
2495
|
+
|
|
2496
|
+
// src/binding/send-tracker.ts
|
|
2497
|
+
var lastSendByKey = /* @__PURE__ */ new Map();
|
|
2498
|
+
var MAX_TRACKED = 512;
|
|
2499
|
+
function key(accountId, conversationId) {
|
|
2500
|
+
return `${accountId}\0${conversationId}`;
|
|
2501
|
+
}
|
|
2502
|
+
function recordAgentSend(accountId, conversationId, atMs = Date.now()) {
|
|
2503
|
+
if (!conversationId) return;
|
|
2504
|
+
const k = key(accountId, conversationId);
|
|
2505
|
+
lastSendByKey.delete(k);
|
|
2506
|
+
lastSendByKey.set(k, atMs);
|
|
2507
|
+
if (lastSendByKey.size > MAX_TRACKED) {
|
|
2508
|
+
const oldest = lastSendByKey.keys().next().value;
|
|
2509
|
+
if (oldest !== void 0) lastSendByKey.delete(oldest);
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
function hasAgentSendSince(accountId, conversationId, sinceMs) {
|
|
2513
|
+
const at = lastSendByKey.get(key(accountId, conversationId));
|
|
2514
|
+
return at !== void 0 && at >= sinceMs;
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
// src/binding/reply-gate.ts
|
|
2518
|
+
var DEFAULT_GATE_MAX_TOKENS = 256;
|
|
2519
|
+
var MAX_HISTORY_TURNS = 12;
|
|
2520
|
+
var CADENCE_WINDOW_SECONDS = 60;
|
|
2521
|
+
var VALID_CATEGORIES = /* @__PURE__ */ new Set([
|
|
2522
|
+
"open_request",
|
|
2523
|
+
"new_info",
|
|
2524
|
+
"goal_followup",
|
|
2525
|
+
"closing",
|
|
2526
|
+
"acknowledgement",
|
|
2527
|
+
"not_addressed",
|
|
2528
|
+
"no_action_needed",
|
|
2529
|
+
"spam",
|
|
2530
|
+
"other"
|
|
2531
|
+
]);
|
|
2532
|
+
var REPLY_TOKENS = /* @__PURE__ */ new Set(["reply", "yes", "true", "respond"]);
|
|
2533
|
+
var NO_REPLY_TOKENS = /* @__PURE__ */ new Set([
|
|
2534
|
+
"no_reply",
|
|
2535
|
+
"no-reply",
|
|
2536
|
+
"noreply",
|
|
2537
|
+
"no",
|
|
2538
|
+
"false",
|
|
2539
|
+
"silent",
|
|
2540
|
+
"skip",
|
|
2541
|
+
"none"
|
|
2542
|
+
]);
|
|
2543
|
+
var FENCE_RE = /```(?:json)?\s*([\s\S]+?)```/i;
|
|
2544
|
+
function computeConversationSignals(messages, params) {
|
|
2545
|
+
const windowSeconds = params.windowSeconds ?? CADENCE_WINDOW_SECONDS;
|
|
2546
|
+
const own = normalizeHandle(params.ownHandle);
|
|
2547
|
+
const prior = messages.filter(
|
|
2548
|
+
(m) => isRecord(m) && m.id !== params.triggerMessageId
|
|
2549
|
+
);
|
|
2550
|
+
const firstContact = prior.length === 0;
|
|
2551
|
+
const youHaveSpoken = prior.some((m) => messageIsOwn(m, own));
|
|
2552
|
+
const timestamps = [];
|
|
2553
|
+
for (const m of prior) {
|
|
2554
|
+
const ts = parseTimestamp(m.created_at);
|
|
2555
|
+
if (ts !== null) timestamps.push(ts);
|
|
2556
|
+
}
|
|
2557
|
+
const cutoff = params.nowMs - windowSeconds * 1e3;
|
|
2558
|
+
const recentInWindow = timestamps.filter((ts) => ts >= cutoff).length;
|
|
2559
|
+
let secondsSincePrevious = null;
|
|
2560
|
+
if (timestamps.length > 0) {
|
|
2561
|
+
const delta = (params.nowMs - Math.max(...timestamps)) / 1e3;
|
|
2562
|
+
secondsSincePrevious = delta > 0 ? delta : 0;
|
|
2563
|
+
}
|
|
2564
|
+
return {
|
|
2565
|
+
firstContact,
|
|
2566
|
+
youHaveSpoken,
|
|
2567
|
+
messagesLastWindow: recentInWindow + 1,
|
|
2568
|
+
// +1 for the new message
|
|
2569
|
+
secondsSincePrevious
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
function messageIsOwn(msg, ownHandleNorm) {
|
|
2573
|
+
if (typeof msg.is_own === "boolean") return msg.is_own;
|
|
2574
|
+
const sender = msg.sender ?? msg.from ?? msg.sender_handle ?? "";
|
|
2575
|
+
return normalizeHandle(String(sender)) === ownHandleNorm;
|
|
2576
|
+
}
|
|
2577
|
+
function parseTimestamp(raw) {
|
|
2578
|
+
if (typeof raw !== "string" || !raw) return null;
|
|
2579
|
+
const t = Date.parse(raw);
|
|
2580
|
+
return Number.isNaN(t) ? null : t;
|
|
2581
|
+
}
|
|
2582
|
+
function normalizeHandle(handle) {
|
|
2583
|
+
return handle.replace(/^@/, "").toLowerCase();
|
|
2584
|
+
}
|
|
2585
|
+
function isRecord(value) {
|
|
2586
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
2587
|
+
}
|
|
2588
|
+
function systemTemplate(handle) {
|
|
2589
|
+
const h = `@${handle}`;
|
|
2590
|
+
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.
|
|
2591
|
+
|
|
2592
|
+
"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.
|
|
2593
|
+
|
|
2594
|
+
Judge DONE-NESS, not how interesting another message could be:
|
|
2595
|
+
|
|
2596
|
+
Choose "reply" only if a further message accomplishes a concrete, still-OPEN purpose:
|
|
2597
|
+
- answer a substantive pending question or supply specifically requested information
|
|
2598
|
+
- make or respond to a decision, or unblock the peer on a real task
|
|
2599
|
+
- ${h} started this thread toward a goal and the peer's reply needs a substantive follow-up to reach it
|
|
2600
|
+
- new information genuinely requires ${h}'s input
|
|
2601
|
+
|
|
2602
|
+
Choose "no_reply" when the exchange has reached its natural end \u2014 even if another clever or friendly message is easily possible:
|
|
2603
|
+
- it is trading pleasantries, mutual appreciation, agreement, or open-ended tangents / "riffing" with no open objective
|
|
2604
|
+
- 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
|
|
2605
|
+
- the other side is acknowledging or closing out (thanks / ok / got it / sounds good / \u{1F44D} / bye) and replying would only prolong it
|
|
2606
|
+
- ${h} already answered what was asked and nothing new is on the table
|
|
2607
|
+
- 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.)
|
|
2608
|
+
|
|
2609
|
+
"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".
|
|
2610
|
+
|
|
2611
|
+
Respond with ONLY a JSON object \u2014 no prose, no markdown fences:
|
|
2612
|
+
{"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>"}`;
|
|
2613
|
+
}
|
|
2614
|
+
function buildDecisionMessages(params) {
|
|
2615
|
+
return [
|
|
2616
|
+
{ role: "system", content: systemTemplate(params.handle) },
|
|
2617
|
+
{
|
|
2618
|
+
role: "user",
|
|
2619
|
+
content: buildUserContent({
|
|
2620
|
+
handle: params.handle,
|
|
2621
|
+
event: params.event,
|
|
2622
|
+
history: params.history,
|
|
2623
|
+
signals: params.signals ?? null,
|
|
2624
|
+
maxHistory: params.maxHistory ?? MAX_HISTORY_TURNS
|
|
2625
|
+
})
|
|
2626
|
+
}
|
|
2627
|
+
];
|
|
2628
|
+
}
|
|
2629
|
+
function buildUserContent(params) {
|
|
2630
|
+
const { handle, event, history, signals, maxHistory } = params;
|
|
2631
|
+
const kind = event.conversationKind === "group" ? "group" : "direct";
|
|
2632
|
+
const lines = [`Conversation type: ${kind}`];
|
|
2633
|
+
if (signals) {
|
|
2634
|
+
lines.push(`Relationship: ${relationshipPhrase(signals)}`);
|
|
2635
|
+
if (signals.secondsSincePrevious !== null) {
|
|
2636
|
+
lines.push(
|
|
2637
|
+
`Pace: ${signals.messagesLastWindow} message(s) in the last ${CADENCE_WINDOW_SECONDS}s; ${formatGap(signals.secondsSincePrevious)} since the previous message`
|
|
2638
|
+
);
|
|
2639
|
+
}
|
|
2640
|
+
}
|
|
2641
|
+
lines.push(`Prior messages in this thread: ${history.length}`);
|
|
2642
|
+
if (kind === "group") {
|
|
2643
|
+
const mentioned = (event.contentText || "").toLowerCase().includes(`@${handle.toLowerCase()}`);
|
|
2644
|
+
lines.push(
|
|
2645
|
+
`Message directly addresses you: ${mentioned ? "yes" : "not explicitly"}`
|
|
2646
|
+
);
|
|
2647
|
+
}
|
|
2648
|
+
lines.push("");
|
|
2649
|
+
const rendered = renderHistory(history, maxHistory);
|
|
2650
|
+
if (rendered.length > 0) {
|
|
2651
|
+
lines.push("Recent conversation (oldest first):");
|
|
2652
|
+
lines.push(...rendered);
|
|
2653
|
+
} else {
|
|
2654
|
+
lines.push("Recent conversation: (none \u2014 this is first contact)");
|
|
2655
|
+
}
|
|
2656
|
+
let newText = collapseWhitespace(event.contentText || "");
|
|
2657
|
+
if (newText.length > 2e3) newText = `${newText.slice(0, 2e3)}\u2026`;
|
|
2658
|
+
lines.push("");
|
|
2659
|
+
lines.push(`New message from @${event.senderHandle}: ${newText}`);
|
|
2660
|
+
lines.push("");
|
|
2661
|
+
lines.push("Decide now: reply or no_reply?");
|
|
2662
|
+
return lines.join("\n");
|
|
2663
|
+
}
|
|
2664
|
+
function renderHistory(history, maxHistory) {
|
|
2665
|
+
const recent = history.length > maxHistory ? history.slice(history.length - maxHistory) : history;
|
|
2666
|
+
const out = [];
|
|
2667
|
+
for (const turn of recent) {
|
|
2668
|
+
if (typeof turn.content !== "string" || !turn.content.trim()) continue;
|
|
2669
|
+
const speaker = turn.role === "assistant" ? "you" : "peer";
|
|
2670
|
+
let text = collapseWhitespace(turn.content);
|
|
2671
|
+
if (text.length > 400) text = `${text.slice(0, 400)}\u2026`;
|
|
2672
|
+
out.push(`${speaker}: ${text}`);
|
|
2673
|
+
}
|
|
2674
|
+
return out;
|
|
2675
|
+
}
|
|
2676
|
+
function relationshipPhrase(signals) {
|
|
2677
|
+
if (signals.firstContact) return "first contact \u2014 no prior messages in this thread";
|
|
2678
|
+
if (signals.youHaveSpoken) return "established \u2014 you have already replied in this thread";
|
|
2679
|
+
return "this peer is messaging you, but you have not replied yet";
|
|
2680
|
+
}
|
|
2681
|
+
function formatGap(seconds) {
|
|
2682
|
+
if (seconds < 90) return `${Math.round(seconds)}s`;
|
|
2683
|
+
if (seconds < 5400) return `${Math.round(seconds / 60)}m`;
|
|
2684
|
+
return `${Math.round(seconds / 3600)}h`;
|
|
2685
|
+
}
|
|
2686
|
+
function collapseWhitespace(text) {
|
|
2687
|
+
return text.split(/\s+/).filter(Boolean).join(" ");
|
|
2688
|
+
}
|
|
2689
|
+
function parseDecision(text, opts = {}) {
|
|
2690
|
+
const raw = extractJson(text);
|
|
2691
|
+
if (raw === null) return null;
|
|
2692
|
+
let obj;
|
|
2693
|
+
try {
|
|
2694
|
+
obj = JSON.parse(raw);
|
|
2695
|
+
} catch {
|
|
2696
|
+
return null;
|
|
2697
|
+
}
|
|
2698
|
+
if (!isRecord(obj)) return null;
|
|
2699
|
+
const decisionRaw = obj.decision;
|
|
2700
|
+
if (typeof decisionRaw !== "string") return null;
|
|
2701
|
+
const token = decisionRaw.trim().toLowerCase();
|
|
2702
|
+
let reply;
|
|
2703
|
+
if (REPLY_TOKENS.has(token)) reply = true;
|
|
2704
|
+
else if (NO_REPLY_TOKENS.has(token)) reply = false;
|
|
2705
|
+
else return null;
|
|
2706
|
+
const reasonRaw = obj.reason;
|
|
2707
|
+
let reason = typeof reasonRaw === "string" ? reasonRaw.trim() : "";
|
|
2708
|
+
if (reason.length > 280) reason = reason.slice(0, 280);
|
|
2709
|
+
const categoryRaw = obj.category;
|
|
2710
|
+
let category = typeof categoryRaw === "string" ? categoryRaw.trim().toLowerCase() : "other";
|
|
2711
|
+
if (!VALID_CATEGORIES.has(category)) category = "other";
|
|
2712
|
+
return {
|
|
2713
|
+
reply,
|
|
2714
|
+
reason,
|
|
2715
|
+
category,
|
|
2716
|
+
source: opts.source ?? "llm",
|
|
2717
|
+
latencyMs: opts.latencyMs ?? 0
|
|
2718
|
+
};
|
|
2719
|
+
}
|
|
2720
|
+
function extractJson(text) {
|
|
2721
|
+
if (!text || !text.trim()) return null;
|
|
2722
|
+
let s = text.trim();
|
|
2723
|
+
const fence = FENCE_RE.exec(s);
|
|
2724
|
+
if (fence?.[1]) s = fence[1].trim();
|
|
2725
|
+
const start = s.indexOf("{");
|
|
2726
|
+
const end = s.lastIndexOf("}");
|
|
2727
|
+
if (start === -1 || end === -1 || end <= start) return null;
|
|
2728
|
+
return s.slice(start, end + 1);
|
|
2729
|
+
}
|
|
2730
|
+
function gateFallback(failOpen, reason, latencyMs) {
|
|
2731
|
+
return {
|
|
2732
|
+
reply: failOpen,
|
|
2733
|
+
reason,
|
|
2734
|
+
category: "fallback",
|
|
2735
|
+
source: failOpen ? "fail_open" : "fail_closed",
|
|
2736
|
+
latencyMs
|
|
2737
|
+
};
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
// src/binding/gate.ts
|
|
2741
|
+
var DEFAULT_GATE_TIMEOUT_MS = 2e4;
|
|
2742
|
+
var GATE_REASONING_LEVEL = "off";
|
|
2743
|
+
var GateTimeoutError = class extends Error {
|
|
2744
|
+
};
|
|
2745
|
+
function withTimeout(promise, ms) {
|
|
2746
|
+
if (!Number.isFinite(ms) || ms <= 0) return promise;
|
|
2747
|
+
return new Promise((resolve2, reject) => {
|
|
2748
|
+
const timer = setTimeout(() => reject(new GateTimeoutError("gate decision timed out")), ms);
|
|
2749
|
+
promise.then(
|
|
2750
|
+
(value) => {
|
|
2751
|
+
clearTimeout(timer);
|
|
2752
|
+
resolve2(value);
|
|
2753
|
+
},
|
|
2754
|
+
(err3) => {
|
|
2755
|
+
clearTimeout(timer);
|
|
2756
|
+
reject(err3);
|
|
2757
|
+
}
|
|
2758
|
+
);
|
|
2759
|
+
});
|
|
2760
|
+
}
|
|
2761
|
+
async function decideReply(params) {
|
|
2762
|
+
const signals = computeConversationSignals(params.rawMessages, {
|
|
2763
|
+
ownHandle: params.ownHandle,
|
|
2764
|
+
triggerMessageId: params.triggerMessageId,
|
|
2765
|
+
nowMs: params.nowMs
|
|
2766
|
+
});
|
|
2767
|
+
const messages = buildDecisionMessages({
|
|
2768
|
+
handle: params.handle,
|
|
2769
|
+
event: params.event,
|
|
2770
|
+
history: params.history,
|
|
2771
|
+
signals
|
|
2772
|
+
});
|
|
2773
|
+
const systemPrompt = messages.find((m) => m.role === "system")?.content ?? "";
|
|
2774
|
+
const userContent = messages.find((m) => m.role === "user")?.content ?? "";
|
|
2775
|
+
const caller = params.caller ?? createSimpleCompletionGateCaller(params.cfg, params.agentId);
|
|
2776
|
+
const maxTokens = params.maxTokens ?? DEFAULT_GATE_MAX_TOKENS;
|
|
2777
|
+
const timeoutMs = params.timeoutMs ?? DEFAULT_GATE_TIMEOUT_MS;
|
|
2778
|
+
const start = Date.now();
|
|
2779
|
+
let text;
|
|
2780
|
+
try {
|
|
2781
|
+
text = await withTimeout(caller({ systemPrompt, userContent, maxTokens }), timeoutMs);
|
|
2782
|
+
} catch (err3) {
|
|
2783
|
+
if (err3 instanceof GateTimeoutError) {
|
|
2784
|
+
return gateFallback(params.failOpen, "decision_timeout", Date.now() - start);
|
|
2785
|
+
}
|
|
2786
|
+
const detail = err3 instanceof Error ? err3.message : String(err3);
|
|
2787
|
+
return gateFallback(
|
|
2788
|
+
params.failOpen,
|
|
2789
|
+
`decision_call_error: ${detail}`.slice(0, 220),
|
|
2790
|
+
Date.now() - start
|
|
2791
|
+
);
|
|
2792
|
+
}
|
|
2793
|
+
const latencyMs = Date.now() - start;
|
|
2794
|
+
const parsed = parseDecision(text, { source: "llm", latencyMs });
|
|
2795
|
+
return parsed ?? gateFallback(params.failOpen, "unparseable_decision", latencyMs);
|
|
2796
|
+
}
|
|
2797
|
+
function createSimpleCompletionGateCaller(cfg, agentId) {
|
|
2798
|
+
return async ({ systemPrompt, userContent, maxTokens, signal }) => {
|
|
2799
|
+
const prepared = await prepareSimpleCompletionModelForAgent({
|
|
2800
|
+
cfg,
|
|
2801
|
+
// plugin-local OpenClawConfig alias → sdk's internal type
|
|
2802
|
+
agentId,
|
|
2803
|
+
allowMissingApiKeyModes: ["aws-sdk"],
|
|
2804
|
+
// Do NOT skip discovery: it loads provider model catalogs. Skipping it
|
|
2805
|
+
// works for providers with pure dynamic resolution (e.g. Fireworks) but
|
|
2806
|
+
// makes catalog-based providers (Google/Gemini, Anthropic, OpenAI, …)
|
|
2807
|
+
// fail with "Unknown model: <ref>" — the gate must resolve the agent's
|
|
2808
|
+
// own model regardless of which provider it runs on.
|
|
2809
|
+
skipAgentDiscovery: false
|
|
2810
|
+
});
|
|
2811
|
+
if ("error" in prepared) throw new Error(prepared.error);
|
|
2812
|
+
const result = await completeWithPreparedSimpleCompletionModel({
|
|
2813
|
+
model: prepared.model,
|
|
2814
|
+
auth: prepared.auth,
|
|
2815
|
+
cfg,
|
|
2816
|
+
context: {
|
|
2817
|
+
systemPrompt,
|
|
2818
|
+
messages: [{ role: "user", content: userContent }]
|
|
2819
|
+
},
|
|
2820
|
+
// temperature 0 mirrors the Hermes gate: a binary policy decision must
|
|
2821
|
+
// be as deterministic as the provider allows, not sampled creatively.
|
|
2822
|
+
options: {
|
|
2823
|
+
maxTokens,
|
|
2824
|
+
temperature: 0,
|
|
2825
|
+
reasoning: GATE_REASONING_LEVEL,
|
|
2826
|
+
...signal ? { signal } : {}
|
|
2827
|
+
}
|
|
2828
|
+
});
|
|
2829
|
+
return result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("");
|
|
2830
|
+
};
|
|
2831
|
+
}
|
|
2832
|
+
|
|
2833
|
+
// src/binding/inbound-bridge.ts
|
|
2834
|
+
var GATE_HISTORY_LIMIT = 30;
|
|
2378
2835
|
function createInboundBridge(deps) {
|
|
2379
2836
|
return async function onInbound(event) {
|
|
2380
2837
|
switch (event.kind) {
|
|
@@ -2411,6 +2868,17 @@ async function handleMessage(deps, event) {
|
|
|
2411
2868
|
if (!body && !event.content.attachmentId && !event.content.data) {
|
|
2412
2869
|
return;
|
|
2413
2870
|
}
|
|
2871
|
+
const threadClosures = getThreadClosures(
|
|
2872
|
+
deps.gatewayCfg,
|
|
2873
|
+
deps.accountId
|
|
2874
|
+
);
|
|
2875
|
+
if (threadClosures.isClosed(event.conversationId)) {
|
|
2876
|
+
deps.logger.info(
|
|
2877
|
+
{ conversationId: event.conversationId, messageId: event.messageId, sender: event.sender },
|
|
2878
|
+
"inbound skipped for locally closed thread"
|
|
2879
|
+
);
|
|
2880
|
+
return;
|
|
2881
|
+
}
|
|
2414
2882
|
const channelRuntime = deps.channelRuntime;
|
|
2415
2883
|
if (!channelRuntime || typeof channelRuntime.reply?.dispatchReplyWithBufferedBlockDispatcher !== "function") {
|
|
2416
2884
|
deps.logger.error(
|
|
@@ -2425,6 +2893,7 @@ async function handleMessage(deps, event) {
|
|
|
2425
2893
|
);
|
|
2426
2894
|
return;
|
|
2427
2895
|
}
|
|
2896
|
+
const ts = typeof event.createdAt === "number" ? event.createdAt : Date.parse(event.createdAt);
|
|
2428
2897
|
const recipientHandle = selfHandle ?? "me";
|
|
2429
2898
|
const conversationLabel = event.conversationKind === "group" ? `group ${event.conversationId}` : `dm with @${senderHandle}`;
|
|
2430
2899
|
const sendReply = async (replyText) => {
|
|
@@ -2437,36 +2906,107 @@ async function handleMessage(deps, event) {
|
|
|
2437
2906
|
metadata: { reply_to: event.messageId }
|
|
2438
2907
|
});
|
|
2439
2908
|
};
|
|
2909
|
+
const turnStartMs = Date.now();
|
|
2440
2910
|
const deliver2 = async (payload) => {
|
|
2441
|
-
|
|
2442
|
-
|
|
2911
|
+
if (threadClosures.isClosed(event.conversationId)) {
|
|
2912
|
+
deps.logger.info(
|
|
2913
|
+
{ conversationId: event.conversationId, messageId: event.messageId },
|
|
2914
|
+
"reply suppressed for locally closed thread"
|
|
2915
|
+
);
|
|
2916
|
+
return;
|
|
2917
|
+
}
|
|
2918
|
+
if (hasAgentSendSince(deps.accountId, event.conversationId, turnStartMs)) {
|
|
2919
|
+
deps.logger.info(
|
|
2920
|
+
{ conversationId: event.conversationId, messageId: event.messageId },
|
|
2921
|
+
"final turn text suppressed \u2014 agent already sent its reply via a message tool this turn"
|
|
2922
|
+
);
|
|
2923
|
+
return;
|
|
2924
|
+
}
|
|
2925
|
+
await sendReply(payload.text ?? extractText(payload.blocks));
|
|
2443
2926
|
};
|
|
2444
2927
|
try {
|
|
2445
|
-
|
|
2446
|
-
|
|
2447
|
-
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
2453
|
-
|
|
2454
|
-
|
|
2455
|
-
|
|
2456
|
-
|
|
2457
|
-
|
|
2458
|
-
|
|
2459
|
-
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
|
|
2463
|
-
|
|
2464
|
-
|
|
2465
|
-
|
|
2466
|
-
|
|
2467
|
-
|
|
2928
|
+
const runtime = channelRuntime;
|
|
2929
|
+
const peer = event.conversationKind === "group" ? { kind: "group", id: event.conversationId } : { kind: "direct", id: senderHandle };
|
|
2930
|
+
const { route, buildEnvelope } = resolveInboundRouteEnvelopeBuilderWithRuntime({
|
|
2931
|
+
cfg: deps.gatewayCfg,
|
|
2932
|
+
channel: "agentchat",
|
|
2933
|
+
accountId: deps.accountId,
|
|
2934
|
+
peer,
|
|
2935
|
+
runtime
|
|
2936
|
+
});
|
|
2937
|
+
if (gateEnabled()) {
|
|
2938
|
+
const decision = await runReplyGate({
|
|
2939
|
+
deps,
|
|
2940
|
+
event,
|
|
2941
|
+
body,
|
|
2942
|
+
agentId: route.agentId,
|
|
2943
|
+
selfHandle,
|
|
2944
|
+
senderHandle,
|
|
2945
|
+
nowMs: Number.isFinite(ts) ? ts : Date.now()
|
|
2946
|
+
});
|
|
2947
|
+
deps.logger.info(
|
|
2948
|
+
{
|
|
2949
|
+
conversationId: event.conversationId,
|
|
2950
|
+
messageId: event.messageId,
|
|
2951
|
+
reply: decision.reply,
|
|
2952
|
+
source: decision.source,
|
|
2953
|
+
category: decision.category,
|
|
2954
|
+
latencyMs: decision.latencyMs,
|
|
2955
|
+
reason: decision.reason
|
|
2956
|
+
},
|
|
2957
|
+
"reply gate decision"
|
|
2958
|
+
);
|
|
2959
|
+
if (!decision.reply) return;
|
|
2960
|
+
}
|
|
2961
|
+
const { storePath, body: envelopeBody } = buildEnvelope({
|
|
2962
|
+
channel: "AgentChat",
|
|
2963
|
+
from: conversationLabel,
|
|
2964
|
+
body,
|
|
2965
|
+
timestamp: ts
|
|
2966
|
+
});
|
|
2967
|
+
const finalize = channelRuntime.reply.finalizeInboundContext;
|
|
2968
|
+
const ctxPayload = finalize({
|
|
2969
|
+
Body: envelopeBody,
|
|
2970
|
+
BodyForAgent: body,
|
|
2971
|
+
RawBody: body,
|
|
2972
|
+
CommandBody: body,
|
|
2973
|
+
From: `@${senderHandle}`,
|
|
2974
|
+
To: `@${recipientHandle}`,
|
|
2975
|
+
SessionKey: route.sessionKey,
|
|
2976
|
+
AccountId: deps.accountId,
|
|
2977
|
+
ChatType: event.conversationKind === "group" ? "group" : "direct",
|
|
2978
|
+
ConversationLabel: conversationLabel,
|
|
2979
|
+
SenderId: senderHandle,
|
|
2980
|
+
Provider: "agentchat",
|
|
2981
|
+
Surface: "agentchat",
|
|
2982
|
+
MessageSid: event.messageId,
|
|
2983
|
+
MessageSidFull: event.messageId,
|
|
2984
|
+
Timestamp: ts,
|
|
2985
|
+
OriginatingChannel: "agentchat",
|
|
2986
|
+
OriginatingTo: `@${recipientHandle}`
|
|
2987
|
+
});
|
|
2988
|
+
const session = channelRuntime.session;
|
|
2989
|
+
await dispatchChannelInboundReply({
|
|
2990
|
+
cfg: deps.gatewayCfg,
|
|
2991
|
+
channel: "agentchat",
|
|
2992
|
+
accountId: deps.accountId,
|
|
2993
|
+
agentId: route.agentId,
|
|
2994
|
+
routeSessionKey: route.sessionKey,
|
|
2995
|
+
storePath,
|
|
2996
|
+
ctxPayload,
|
|
2997
|
+
recordInboundSession: session.recordInboundSession,
|
|
2998
|
+
dispatchReplyWithBufferedBlockDispatcher: channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
|
|
2999
|
+
// Under `automatic` (the default) the framework hands the agent's final
|
|
3000
|
+
// turn text to this `deliver`, which sends it to the source. Under the
|
|
3001
|
+
// opt-in `message_tool_only` mode the turn text is suppressed and the
|
|
3002
|
+
// agent sends via the message tool instead, so `deliver` only fires on a
|
|
3003
|
+
// framework fallback. Either way a gated `no_reply` turn never runs, so
|
|
3004
|
+
// nothing is sent.
|
|
3005
|
+
delivery: {
|
|
3006
|
+
deliver: async (payload) => {
|
|
3007
|
+
await deliver2(payload);
|
|
2468
3008
|
},
|
|
2469
|
-
|
|
3009
|
+
onError: (err3, info) => {
|
|
2470
3010
|
deps.logger.error(
|
|
2471
3011
|
{
|
|
2472
3012
|
err: err3 instanceof Error ? err3.message : String(err3),
|
|
@@ -2476,84 +3016,103 @@ async function handleMessage(deps, event) {
|
|
|
2476
3016
|
"inbound dispatch failed"
|
|
2477
3017
|
);
|
|
2478
3018
|
}
|
|
2479
|
-
}
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
const runtime = channelRuntime;
|
|
2483
|
-
const { route, buildEnvelope } = resolveInboundRouteEnvelopeBuilderWithRuntime({
|
|
2484
|
-
cfg: deps.gatewayCfg,
|
|
2485
|
-
channel: "agentchat",
|
|
2486
|
-
accountId: deps.accountId,
|
|
2487
|
-
peer: { kind: "group", id: event.conversationId },
|
|
2488
|
-
runtime
|
|
2489
|
-
});
|
|
2490
|
-
const { storePath, body: envelopeBody } = buildEnvelope({
|
|
2491
|
-
channel: "AgentChat",
|
|
2492
|
-
from: conversationLabel,
|
|
2493
|
-
body,
|
|
2494
|
-
timestamp: ts
|
|
2495
|
-
});
|
|
2496
|
-
const finalize = channelRuntime.reply.finalizeInboundContext;
|
|
2497
|
-
const ctxPayload = finalize({
|
|
2498
|
-
Body: envelopeBody,
|
|
2499
|
-
BodyForAgent: body,
|
|
2500
|
-
RawBody: body,
|
|
2501
|
-
CommandBody: body,
|
|
2502
|
-
From: `@${senderHandle}`,
|
|
2503
|
-
To: `@${recipientHandle}`,
|
|
2504
|
-
SessionKey: route.sessionKey,
|
|
2505
|
-
AccountId: deps.accountId,
|
|
2506
|
-
ChatType: "group",
|
|
2507
|
-
ConversationLabel: conversationLabel,
|
|
2508
|
-
SenderId: senderHandle,
|
|
2509
|
-
Provider: "agentchat",
|
|
2510
|
-
Surface: "agentchat",
|
|
2511
|
-
MessageSid: event.messageId,
|
|
2512
|
-
MessageSidFull: event.messageId,
|
|
2513
|
-
Timestamp: ts,
|
|
2514
|
-
OriginatingChannel: "agentchat",
|
|
2515
|
-
OriginatingTo: `@${recipientHandle}`
|
|
2516
|
-
});
|
|
2517
|
-
const session = channelRuntime.session;
|
|
2518
|
-
await recordInboundSessionAndDispatchReply({
|
|
2519
|
-
cfg: deps.gatewayCfg,
|
|
2520
|
-
channel: "agentchat",
|
|
2521
|
-
accountId: deps.accountId,
|
|
2522
|
-
agentId: route.agentId,
|
|
2523
|
-
routeSessionKey: route.sessionKey,
|
|
2524
|
-
storePath,
|
|
2525
|
-
ctxPayload,
|
|
2526
|
-
recordInboundSession: session.recordInboundSession,
|
|
2527
|
-
dispatchReplyWithBufferedBlockDispatcher: channelRuntime.reply.dispatchReplyWithBufferedBlockDispatcher,
|
|
2528
|
-
deliver: deliver2,
|
|
3019
|
+
},
|
|
3020
|
+
replyOptions: { sourceReplyDeliveryMode: resolveSourceReplyMode() },
|
|
3021
|
+
record: {
|
|
2529
3022
|
onRecordError: (err3) => {
|
|
2530
3023
|
deps.logger.error(
|
|
2531
3024
|
{ err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
|
|
2532
|
-
"recordInboundSession failed
|
|
2533
|
-
);
|
|
2534
|
-
},
|
|
2535
|
-
onDispatchError: (err3, info) => {
|
|
2536
|
-
deps.logger.error(
|
|
2537
|
-
{
|
|
2538
|
-
err: err3 instanceof Error ? err3.message : String(err3),
|
|
2539
|
-
messageId: event.messageId,
|
|
2540
|
-
kind: info.kind
|
|
2541
|
-
},
|
|
2542
|
-
"inbound dispatch failed (group)"
|
|
3025
|
+
"recordInboundSession failed"
|
|
2543
3026
|
);
|
|
2544
3027
|
}
|
|
2545
|
-
}
|
|
2546
|
-
}
|
|
3028
|
+
}
|
|
3029
|
+
});
|
|
2547
3030
|
} catch (err3) {
|
|
2548
3031
|
deps.logger.error(
|
|
2549
|
-
{
|
|
2550
|
-
err: err3 instanceof Error ? err3.message : String(err3),
|
|
2551
|
-
messageId: event.messageId
|
|
2552
|
-
},
|
|
3032
|
+
{ err: err3 instanceof Error ? err3.message : String(err3), messageId: event.messageId },
|
|
2553
3033
|
"inbound dispatch failed"
|
|
2554
3034
|
);
|
|
2555
3035
|
}
|
|
2556
3036
|
}
|
|
3037
|
+
async function runReplyGate(params) {
|
|
3038
|
+
const { deps, event, body, agentId, selfHandle, senderHandle, nowMs } = params;
|
|
3039
|
+
const ownHandle = selfHandle ?? "";
|
|
3040
|
+
let rawMessages = [];
|
|
3041
|
+
try {
|
|
3042
|
+
const client = getClient({ accountId: deps.accountId, config: deps.config });
|
|
3043
|
+
const fetched = await client.getMessages(event.conversationId, { limit: GATE_HISTORY_LIMIT });
|
|
3044
|
+
if (Array.isArray(fetched)) rawMessages = fetched;
|
|
3045
|
+
} catch (err3) {
|
|
3046
|
+
deps.logger.warn(
|
|
3047
|
+
{ err: err3 instanceof Error ? err3.message : String(err3), conversationId: event.conversationId },
|
|
3048
|
+
"reply gate: history fetch failed \u2014 deciding on the new message alone"
|
|
3049
|
+
);
|
|
3050
|
+
}
|
|
3051
|
+
const gateEvent = {
|
|
3052
|
+
conversationKind: event.conversationKind,
|
|
3053
|
+
senderHandle,
|
|
3054
|
+
contentText: body
|
|
3055
|
+
};
|
|
3056
|
+
return decideReply({
|
|
3057
|
+
cfg: deps.gatewayCfg,
|
|
3058
|
+
agentId,
|
|
3059
|
+
handle: ownHandle.replace(/^@/, ""),
|
|
3060
|
+
event: gateEvent,
|
|
3061
|
+
history: translateHistory(rawMessages, ownHandle, event.conversationKind, event.messageId),
|
|
3062
|
+
rawMessages,
|
|
3063
|
+
triggerMessageId: event.messageId,
|
|
3064
|
+
ownHandle,
|
|
3065
|
+
nowMs,
|
|
3066
|
+
failOpen: gateFailOpen(),
|
|
3067
|
+
timeoutMs: gateTimeoutMs(),
|
|
3068
|
+
caller: deps.gateCaller
|
|
3069
|
+
});
|
|
3070
|
+
}
|
|
3071
|
+
function translateHistory(messages, ownHandle, conversationKind, triggerMessageId) {
|
|
3072
|
+
const own = ownHandle.replace(/^@/, "").toLowerCase();
|
|
3073
|
+
const isGroup = conversationKind === "group";
|
|
3074
|
+
const sorted = [...messages].filter((m) => Boolean(m) && typeof m === "object").sort((a, b) => readSeq(a) - readSeq(b));
|
|
3075
|
+
const out = [];
|
|
3076
|
+
for (const m of sorted) {
|
|
3077
|
+
if (m.id === triggerMessageId) continue;
|
|
3078
|
+
const type = typeof m.type === "string" ? m.type : "text";
|
|
3079
|
+
if (type !== "text") continue;
|
|
3080
|
+
const content = m.content;
|
|
3081
|
+
const text = content && typeof content === "object" ? content.text : void 0;
|
|
3082
|
+
if (typeof text !== "string" || !text) continue;
|
|
3083
|
+
const senderRaw = String(m.sender ?? m.from ?? m.sender_handle ?? "");
|
|
3084
|
+
const isOwn = typeof m.is_own === "boolean" ? m.is_own : senderRaw.replace(/^@/, "").toLowerCase() === own;
|
|
3085
|
+
if (isOwn) {
|
|
3086
|
+
out.push({ role: "assistant", content: text });
|
|
3087
|
+
} else if (isGroup) {
|
|
3088
|
+
out.push({ role: "user", content: `[@${senderRaw.replace(/^@/, "") || "?"}] ${text}` });
|
|
3089
|
+
} else {
|
|
3090
|
+
out.push({ role: "user", content: text });
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
return out;
|
|
3094
|
+
}
|
|
3095
|
+
function readSeq(m) {
|
|
3096
|
+
const seq = m.seq;
|
|
3097
|
+
return typeof seq === "number" ? seq : 0;
|
|
3098
|
+
}
|
|
3099
|
+
var OFF_TOKENS = /* @__PURE__ */ new Set(["0", "false", "off", "no"]);
|
|
3100
|
+
var ON_TOKENS = /* @__PURE__ */ new Set(["1", "true", "on", "yes"]);
|
|
3101
|
+
function gateEnabled() {
|
|
3102
|
+
return !OFF_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_ENABLED ?? "").trim().toLowerCase());
|
|
3103
|
+
}
|
|
3104
|
+
function gateFailOpen() {
|
|
3105
|
+
return ON_TOKENS.has((process.env.AGENTCHAT_REPLY_GATE_FAIL_OPEN ?? "").trim().toLowerCase());
|
|
3106
|
+
}
|
|
3107
|
+
function gateTimeoutMs() {
|
|
3108
|
+
const raw = process.env.AGENTCHAT_REPLY_GATE_TIMEOUT_MS;
|
|
3109
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
3110
|
+
const n = Number(raw);
|
|
3111
|
+
return Number.isFinite(n) && n > 0 ? n : void 0;
|
|
3112
|
+
}
|
|
3113
|
+
function resolveSourceReplyMode() {
|
|
3114
|
+
return (process.env.AGENTCHAT_SOURCE_REPLY_MODE ?? "").trim().toLowerCase() === "message_tool_only" ? "message_tool_only" : "automatic";
|
|
3115
|
+
}
|
|
2557
3116
|
function handleGroupInvite(deps, event) {
|
|
2558
3117
|
deps.logger.info(
|
|
2559
3118
|
{
|
|
@@ -2701,27 +3260,6 @@ var agentchatGatewayAdapter = {
|
|
|
2701
3260
|
});
|
|
2702
3261
|
}
|
|
2703
3262
|
};
|
|
2704
|
-
var cache = /* @__PURE__ */ new Map();
|
|
2705
|
-
function getClient({ accountId, config, options }) {
|
|
2706
|
-
const existing = cache.get(accountId);
|
|
2707
|
-
if (existing && existing.apiKey === config.apiKey && existing.apiBase === config.apiBase) {
|
|
2708
|
-
return existing.client;
|
|
2709
|
-
}
|
|
2710
|
-
const client = new AgentChatClient({
|
|
2711
|
-
apiKey: config.apiKey,
|
|
2712
|
-
baseUrl: config.apiBase,
|
|
2713
|
-
...options
|
|
2714
|
-
});
|
|
2715
|
-
cache.set(accountId, {
|
|
2716
|
-
client,
|
|
2717
|
-
apiKey: config.apiKey,
|
|
2718
|
-
apiBase: config.apiBase
|
|
2719
|
-
});
|
|
2720
|
-
return client;
|
|
2721
|
-
}
|
|
2722
|
-
function disposeClient(accountId) {
|
|
2723
|
-
cache.delete(accountId);
|
|
2724
|
-
}
|
|
2725
3263
|
|
|
2726
3264
|
// src/binding/outbound.ts
|
|
2727
3265
|
function resolveConfig(cfg, accountId) {
|
|
@@ -2783,6 +3321,7 @@ async function deliver(ctx, attachmentId) {
|
|
|
2783
3321
|
attachmentId
|
|
2784
3322
|
);
|
|
2785
3323
|
const result = await runtime.sendMessage(input);
|
|
3324
|
+
recordAgentSend(accountId, result.message.conversation_id);
|
|
2786
3325
|
return {
|
|
2787
3326
|
channel: AGENTCHAT_CHANNEL_ID,
|
|
2788
3327
|
messageId: result.message.id,
|
|
@@ -2852,8 +3391,8 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
|
|
|
2852
3391
|
let contentType;
|
|
2853
3392
|
let filename = "attachment";
|
|
2854
3393
|
if (mediaUrl.startsWith("file://") && ctx.mediaReadFile) {
|
|
2855
|
-
const
|
|
2856
|
-
const buf = await ctx.mediaReadFile(
|
|
3394
|
+
const path3 = decodeURIComponent(mediaUrl.replace(/^file:\/\//, ""));
|
|
3395
|
+
const buf = await ctx.mediaReadFile(path3);
|
|
2857
3396
|
if (buf.byteLength > MAX_MEDIA_BYTES) {
|
|
2858
3397
|
throw new AgentChatChannelError(
|
|
2859
3398
|
"terminal-user",
|
|
@@ -2863,7 +3402,7 @@ async function uploadMediaFromUrl(ctx, mediaUrl) {
|
|
|
2863
3402
|
const copy = new Uint8Array(buf.byteLength);
|
|
2864
3403
|
copy.set(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
|
|
2865
3404
|
bytes = copy.buffer;
|
|
2866
|
-
filename =
|
|
3405
|
+
filename = path3.split(/[\\/]/).pop() ?? filename;
|
|
2867
3406
|
} else {
|
|
2868
3407
|
assertMediaUrlSafe(mediaUrl);
|
|
2869
3408
|
const controller = new AbortController();
|
|
@@ -3018,8 +3557,8 @@ function err(message) {
|
|
|
3018
3557
|
details: { error: message }
|
|
3019
3558
|
};
|
|
3020
3559
|
}
|
|
3021
|
-
function str(params,
|
|
3022
|
-
const v = params[
|
|
3560
|
+
function str(params, key2) {
|
|
3561
|
+
const v = params[key2];
|
|
3023
3562
|
return typeof v === "string" ? v : void 0;
|
|
3024
3563
|
}
|
|
3025
3564
|
function resolveConfig2(ctx) {
|
|
@@ -3276,6 +3815,7 @@ var agentchatAgentToolsFactory = ({ cfg }) => {
|
|
|
3276
3815
|
content: { text: p.message },
|
|
3277
3816
|
...p.replyToMessageId ? { metadata: { reply_to: p.replyToMessageId } } : {}
|
|
3278
3817
|
});
|
|
3818
|
+
recordAgentSend(r.accountId, result.message.conversation_id);
|
|
3279
3819
|
const summaryParts = [
|
|
3280
3820
|
`sent to @${handle} \u2014 message ${result.message.id} in ${result.message.conversation_id}`
|
|
3281
3821
|
];
|
|
@@ -3798,6 +4338,88 @@ ${lines.join("\n")}`);
|
|
|
3798
4338
|
}
|
|
3799
4339
|
}
|
|
3800
4340
|
}),
|
|
4341
|
+
tool({
|
|
4342
|
+
name: "agentchat_close_local_thread",
|
|
4343
|
+
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.",
|
|
4344
|
+
parameters: Type.Object({
|
|
4345
|
+
conversationId: Type.String(),
|
|
4346
|
+
reason: Type.Optional(Type.String({ maxLength: 200 })),
|
|
4347
|
+
account: ACCOUNT_PARAM
|
|
4348
|
+
}),
|
|
4349
|
+
execute: async (_id, p) => {
|
|
4350
|
+
const r = clientFor(cfg, p.account);
|
|
4351
|
+
if ("error" in r) return err2(r.error);
|
|
4352
|
+
const closures = getThreadClosures(cfg, r.accountId);
|
|
4353
|
+
const record = closures.close(p.conversationId, p.reason);
|
|
4354
|
+
return {
|
|
4355
|
+
content: [
|
|
4356
|
+
{
|
|
4357
|
+
type: "text",
|
|
4358
|
+
text: `closed ${record.conversationId} locally`
|
|
4359
|
+
}
|
|
4360
|
+
],
|
|
4361
|
+
details: {
|
|
4362
|
+
conversationId: record.conversationId,
|
|
4363
|
+
closedAt: record.closedAt,
|
|
4364
|
+
reason: record.reason,
|
|
4365
|
+
localOnly: true
|
|
4366
|
+
}
|
|
4367
|
+
};
|
|
4368
|
+
}
|
|
4369
|
+
}),
|
|
4370
|
+
tool({
|
|
4371
|
+
name: "agentchat_reopen_local_thread",
|
|
4372
|
+
description: "Re-open a previously locally closed conversation thread so new inbound on that conversation id can reach the reply pipeline again.",
|
|
4373
|
+
parameters: Type.Object({
|
|
4374
|
+
conversationId: Type.String(),
|
|
4375
|
+
account: ACCOUNT_PARAM
|
|
4376
|
+
}),
|
|
4377
|
+
execute: async (_id, p) => {
|
|
4378
|
+
const r = clientFor(cfg, p.account);
|
|
4379
|
+
if ("error" in r) return err2(r.error);
|
|
4380
|
+
const closures = getThreadClosures(cfg, r.accountId);
|
|
4381
|
+
const reopened = closures.reopen(p.conversationId);
|
|
4382
|
+
return {
|
|
4383
|
+
content: [
|
|
4384
|
+
{
|
|
4385
|
+
type: "text",
|
|
4386
|
+
text: reopened ? `re-opened ${p.conversationId} locally` : `${p.conversationId} was not locally closed`
|
|
4387
|
+
}
|
|
4388
|
+
],
|
|
4389
|
+
details: {
|
|
4390
|
+
conversationId: p.conversationId,
|
|
4391
|
+
reopened,
|
|
4392
|
+
localOnly: true
|
|
4393
|
+
}
|
|
4394
|
+
};
|
|
4395
|
+
}
|
|
4396
|
+
}),
|
|
4397
|
+
tool({
|
|
4398
|
+
name: "agentchat_list_local_closed_threads",
|
|
4399
|
+
description: "List conversation threads currently closed locally for this OpenClaw AgentChat account. These are client-side only, not server-side blocks or mutes.",
|
|
4400
|
+
parameters: Type.Object({
|
|
4401
|
+
account: ACCOUNT_PARAM
|
|
4402
|
+
}),
|
|
4403
|
+
execute: async (_id, p) => {
|
|
4404
|
+
const r = clientFor(cfg, p.account);
|
|
4405
|
+
if ("error" in r) return err2(r.error);
|
|
4406
|
+
const closures = getThreadClosures(cfg, r.accountId);
|
|
4407
|
+
const closed = closures.list();
|
|
4408
|
+
if (closed.length === 0) {
|
|
4409
|
+
return {
|
|
4410
|
+
content: [{ type: "text", text: "no locally closed threads" }],
|
|
4411
|
+
details: { closedThreads: [], localOnly: true }
|
|
4412
|
+
};
|
|
4413
|
+
}
|
|
4414
|
+
const lines = closed.map(
|
|
4415
|
+
(record) => `${record.conversationId} \u2014 ${record.closedAt}${record.reason ? ` \u2014 ${record.reason}` : ""}`
|
|
4416
|
+
);
|
|
4417
|
+
return {
|
|
4418
|
+
content: [{ type: "text", text: lines.join("\n") }],
|
|
4419
|
+
details: { closedThreads: closed, localOnly: true }
|
|
4420
|
+
};
|
|
4421
|
+
}
|
|
4422
|
+
}),
|
|
3801
4423
|
tool({
|
|
3802
4424
|
name: "agentchat_get_conversation_history",
|
|
3803
4425
|
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.",
|
|
@@ -4096,6 +4718,7 @@ ${lines.join("\n")}`);
|
|
|
4096
4718
|
to: "chatfather",
|
|
4097
4719
|
content: { text: p.message }
|
|
4098
4720
|
});
|
|
4721
|
+
recordAgentSend(r.accountId, result.message.conversation_id);
|
|
4099
4722
|
return ok2(
|
|
4100
4723
|
`message sent to @chatfather (id: ${result.message.id}). Watch your inbox for the reply.`
|
|
4101
4724
|
);
|