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