libp2p-mesh 2026.6.21 → 2026.6.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/instance-router.js +11 -1
- package/dist/src/plugin.js +31 -1
- package/dist/src/prompt-config.js +1 -1
- package/dist/src/types.d.ts +3 -0
- package/dist/src/user-md-openclaw-extractor.d.ts +14 -0
- package/dist/src/user-md-openclaw-extractor.js +135 -0
- package/package.json +1 -1
- package/src/instance-router.ts +12 -1
- package/src/plugin.ts +35 -1
- package/src/prompt-config.ts +1 -1
- package/src/types.ts +3 -0
- package/src/user-md-openclaw-extractor.ts +171 -0
|
@@ -121,6 +121,7 @@ export function createInstanceRouter(options) {
|
|
|
121
121
|
const deliveryCache = new Map();
|
|
122
122
|
const unsubs = [];
|
|
123
123
|
const pendingAttributePeers = new Set();
|
|
124
|
+
let publicAttributeRefreshEnabled = options.publicAttributeRefreshInitiallyEnabled !== false;
|
|
124
125
|
let attributeRefreshPromise;
|
|
125
126
|
function localInstanceId() {
|
|
126
127
|
const identity = mesh.getInstanceIdentity();
|
|
@@ -215,7 +216,9 @@ export function createInstanceRouter(options) {
|
|
|
215
216
|
if (pendingAttributePeers.size === 0 && !attributeRefreshPromise) {
|
|
216
217
|
return;
|
|
217
218
|
}
|
|
218
|
-
|
|
219
|
+
if (publicAttributeRefreshEnabled) {
|
|
220
|
+
drainAttributeRefresh();
|
|
221
|
+
}
|
|
219
222
|
}
|
|
220
223
|
function drainAttributeRefresh() {
|
|
221
224
|
if (!attributeRefreshPromise) {
|
|
@@ -233,6 +236,12 @@ export function createInstanceRouter(options) {
|
|
|
233
236
|
}
|
|
234
237
|
return attributeRefreshPromise;
|
|
235
238
|
}
|
|
239
|
+
function enablePublicAttributeRefresh() {
|
|
240
|
+
publicAttributeRefreshEnabled = true;
|
|
241
|
+
if (pendingAttributePeers.size > 0) {
|
|
242
|
+
drainAttributeRefresh();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
236
245
|
async function announceToPeer(peerId) {
|
|
237
246
|
if (!isNonEmptyString(peerId) || peerId === mesh.getLocalPeerId()) {
|
|
238
247
|
return;
|
|
@@ -667,6 +676,7 @@ export function createInstanceRouter(options) {
|
|
|
667
676
|
stop,
|
|
668
677
|
handleMessage,
|
|
669
678
|
announceToPeer,
|
|
679
|
+
enablePublicAttributeRefresh,
|
|
670
680
|
refreshPublicAttributes,
|
|
671
681
|
listInstances,
|
|
672
682
|
resolveInstance,
|
package/dist/src/plugin.js
CHANGED
|
@@ -6,9 +6,11 @@ import { createInstanceRouter } from "./instance-router.js";
|
|
|
6
6
|
import { createMeshNetwork } from "./mesh.js";
|
|
7
7
|
import { createPeerLabelStore } from "./peer-label-store.js";
|
|
8
8
|
import { createUserMdAgentAttributeSource } from "./user-md-agent-attributes.js";
|
|
9
|
+
import { createOpenClawUserMdAttributeExtractor } from "./user-md-openclaw-extractor.js";
|
|
9
10
|
import { createUserProfileStore } from "./user-profile-store.js";
|
|
10
11
|
import { buildP2PTools } from "./agent-tools.js";
|
|
11
12
|
import { registerLibp2pMeshCli } from "./profile-cli.js";
|
|
13
|
+
const DEFAULT_PUBLIC_ATTRIBUTE_REFRESH_STARTUP_DELAY_MS = 10000;
|
|
12
14
|
export function registerLibp2pMesh(api) {
|
|
13
15
|
registerLibp2pMeshWithDeps(api);
|
|
14
16
|
}
|
|
@@ -17,13 +19,17 @@ export function registerLibp2pMeshWithDeps(api, deps = {}) {
|
|
|
17
19
|
let unsubscribeInbound;
|
|
18
20
|
let serviceStarted = false;
|
|
19
21
|
let startPromise;
|
|
22
|
+
let publicAttributeRefreshTimer;
|
|
20
23
|
const mesh = (deps.createMeshNetwork ?? createMeshNetwork)({
|
|
21
24
|
config,
|
|
22
25
|
logger: api.logger,
|
|
23
26
|
});
|
|
24
27
|
const store = createInstancePeerStore({ logger: api.logger });
|
|
25
28
|
const peerLabelStore = createPeerLabelStore({ logger: api.logger });
|
|
26
|
-
const userAttributeSource = createUserMdAgentAttributeSource({
|
|
29
|
+
const userAttributeSource = createUserMdAgentAttributeSource({
|
|
30
|
+
logger: api.logger,
|
|
31
|
+
extractor: createOpenClawUserMdAttributeExtractor(api),
|
|
32
|
+
});
|
|
27
33
|
const userProfileStore = createUserProfileStore({ logger: api.logger });
|
|
28
34
|
const delivery = createOpenClawRuntimeInboundDelivery({
|
|
29
35
|
config: api.config,
|
|
@@ -46,6 +52,7 @@ export function registerLibp2pMeshWithDeps(api, deps = {}) {
|
|
|
46
52
|
userAttributeSource,
|
|
47
53
|
userProfileStore,
|
|
48
54
|
peerLabelStore,
|
|
55
|
+
publicAttributeRefreshInitiallyEnabled: false,
|
|
49
56
|
});
|
|
50
57
|
registerLibp2pMeshCli(api, {
|
|
51
58
|
profile: {
|
|
@@ -87,7 +94,28 @@ export function registerLibp2pMeshWithDeps(api, deps = {}) {
|
|
|
87
94
|
}
|
|
88
95
|
});
|
|
89
96
|
}
|
|
97
|
+
function publicAttributeRefreshStartupDelayMs() {
|
|
98
|
+
const configured = config?.publicAttributeRefreshStartupDelayMs;
|
|
99
|
+
if (typeof configured === "number" && Number.isFinite(configured) && configured >= 0) {
|
|
100
|
+
return configured;
|
|
101
|
+
}
|
|
102
|
+
return DEFAULT_PUBLIC_ATTRIBUTE_REFRESH_STARTUP_DELAY_MS;
|
|
103
|
+
}
|
|
104
|
+
function clearPublicAttributeRefreshTimer() {
|
|
105
|
+
if (publicAttributeRefreshTimer) {
|
|
106
|
+
clearTimeout(publicAttributeRefreshTimer);
|
|
107
|
+
publicAttributeRefreshTimer = undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function schedulePublicAttributeRefreshEnable() {
|
|
111
|
+
clearPublicAttributeRefreshTimer();
|
|
112
|
+
publicAttributeRefreshTimer = setTimeout(() => {
|
|
113
|
+
publicAttributeRefreshTimer = undefined;
|
|
114
|
+
router.enablePublicAttributeRefresh();
|
|
115
|
+
}, publicAttributeRefreshStartupDelayMs());
|
|
116
|
+
}
|
|
90
117
|
async function cleanupStartupFailure() {
|
|
118
|
+
clearPublicAttributeRefreshTimer();
|
|
91
119
|
try {
|
|
92
120
|
unsubscribeInbound?.();
|
|
93
121
|
}
|
|
@@ -145,6 +173,7 @@ export function registerLibp2pMeshWithDeps(api, deps = {}) {
|
|
|
145
173
|
api.logger.info?.(`[libp2p-mesh] Active relay reservations: ${nat.reservedRelays.join(", ")}`);
|
|
146
174
|
}
|
|
147
175
|
serviceStarted = true;
|
|
176
|
+
schedulePublicAttributeRefreshEnable();
|
|
148
177
|
}
|
|
149
178
|
catch (error) {
|
|
150
179
|
await cleanupStartupFailure();
|
|
@@ -158,6 +187,7 @@ export function registerLibp2pMeshWithDeps(api, deps = {}) {
|
|
|
158
187
|
},
|
|
159
188
|
stop: async () => {
|
|
160
189
|
await startPromise?.catch(() => undefined);
|
|
190
|
+
clearPublicAttributeRefreshTimer();
|
|
161
191
|
unsubscribeInbound?.();
|
|
162
192
|
unsubscribeInbound = undefined;
|
|
163
193
|
await router.stop();
|
|
@@ -40,7 +40,7 @@ export const LIBP2P_MESH_AGENT_PROMPT = `
|
|
|
40
40
|
|
|
41
41
|
- \`source="USER.md"\` 表示 gateway 使用 OpenClaw 已配置的 agent/API 模型,从 USER.md 异步提取并公开广播的 tag。
|
|
42
42
|
- \`source="profile"\` 表示用户通过 \`openclaw libp2p-mesh profile\` 手动配置的公开结构化属性。
|
|
43
|
-
- gateway 的基础 \`instance-announce\` 可能省略 \`userPublicAttributes\`;这表示本次 announce
|
|
43
|
+
- gateway 的基础 \`instance-announce\` 可能省略 \`userPublicAttributes\`;这表示本次 announce 没有携带属性,不一定表示该用户没有公开属性。启动后 USER.md 属性刷新可能会延迟数秒完成。按公开属性发送前先用 \`p2p_list_instances\` 查看当前实例记录。
|
|
44
44
|
- 普通对话 agent 不应自己读取 USER.md 来决定公开属性。USER.md 属性提取是 gateway 后台职责。
|
|
45
45
|
|
|
46
46
|
3. \`openclaw libp2p-mesh labels\` manages local labels for remote instances. These labels are stored in the local \`peer-labels.json\`, stay on this machine, and are used only when the send tool uses \`scope="local"\` or \`scope="all"\`.
|
package/dist/src/types.d.ts
CHANGED
|
@@ -216,6 +216,7 @@ export type InstanceRouterOptions = {
|
|
|
216
216
|
peerLabelStore?: {
|
|
217
217
|
listLabels(instanceId: string): Promise<LocalPeerLabelAttribute[]>;
|
|
218
218
|
};
|
|
219
|
+
publicAttributeRefreshInitiallyEnabled?: boolean;
|
|
219
220
|
};
|
|
220
221
|
export interface InstanceRouter {
|
|
221
222
|
attachHandlers(): void;
|
|
@@ -224,6 +225,7 @@ export interface InstanceRouter {
|
|
|
224
225
|
stop(): Promise<void>;
|
|
225
226
|
handleMessage(msg: P2PMessage): Promise<void>;
|
|
226
227
|
announceToPeer(peerId: string): Promise<void>;
|
|
228
|
+
enablePublicAttributeRefresh(): void;
|
|
227
229
|
refreshPublicAttributes(): Promise<void>;
|
|
228
230
|
listInstances(): Promise<InstancePeerRecord[]>;
|
|
229
231
|
resolveInstance(instanceId: string): Promise<InstancePeerRecord | undefined>;
|
|
@@ -246,6 +248,7 @@ export interface MeshConfig {
|
|
|
246
248
|
bootstrapList?: string[];
|
|
247
249
|
meshTopic?: string;
|
|
248
250
|
announceLogDetail?: AnnounceLogDetail;
|
|
251
|
+
publicAttributeRefreshStartupDelayMs?: number;
|
|
249
252
|
enableAgentSync?: boolean;
|
|
250
253
|
enableWebSocket?: boolean;
|
|
251
254
|
peerIdPath?: string;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
|
|
2
|
+
import type { UserPublicAttribute } from "./types.js";
|
|
3
|
+
import type { UserMdAttributeExtractor } from "./user-md-agent-attributes.js";
|
|
4
|
+
export declare const USER_MD_ATTRIBUTE_EXTRACTION_PROMPT: string;
|
|
5
|
+
type Logger = {
|
|
6
|
+
warn?: (message: string) => void;
|
|
7
|
+
};
|
|
8
|
+
export declare function extractLatestAssistantText(messages: unknown[]): string | undefined;
|
|
9
|
+
export declare function parseUserMdAttributeResponse(text: string): UserPublicAttribute[];
|
|
10
|
+
export declare function createOpenClawUserMdAttributeExtractor(api: OpenClawPluginApi, options?: {
|
|
11
|
+
timeoutMs?: number;
|
|
12
|
+
logger?: Logger;
|
|
13
|
+
}): UserMdAttributeExtractor;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { validateExtractedUserMdTags } from "./user-md-agent-attributes.js";
|
|
3
|
+
const EXTRACTION_TIMEOUT_MS = 30000;
|
|
4
|
+
const SESSION_HASH_LENGTH = 16;
|
|
5
|
+
export const USER_MD_ATTRIBUTE_EXTRACTION_PROMPT = [
|
|
6
|
+
"你是 libp2p-mesh 的 USER.md 公开属性提取器。",
|
|
7
|
+
"",
|
|
8
|
+
"任务:从 USER.md 中提取少量适合公开广播的用户 tag。",
|
|
9
|
+
"",
|
|
10
|
+
"规则:",
|
|
11
|
+
"- 只输出 JSON 数组,不要输出解释、Markdown 或代码块。",
|
|
12
|
+
'- 每项必须是:{"kind":"tag","value":"...","label":"...","source":"USER.md"}',
|
|
13
|
+
"- 最多 10 个。",
|
|
14
|
+
"- 每个 value 不超过 40 个字符。",
|
|
15
|
+
"- 不要提取寒暄、联系方式提示、占位内容、完整句子。",
|
|
16
|
+
"- 不要提取“刚认识”“还在了解”“随时告诉我”这类无分类价值内容。",
|
|
17
|
+
"- 优先提取稳定身份、技术方向、项目方向、长期偏好。",
|
|
18
|
+
].join("\n");
|
|
19
|
+
function hashForSessionKey(value) {
|
|
20
|
+
return createHash("sha256").update(value, "utf8").digest("hex").slice(0, SESSION_HASH_LENGTH);
|
|
21
|
+
}
|
|
22
|
+
function buildUserMdExtractionMessage(markdown, sourcePath) {
|
|
23
|
+
return [
|
|
24
|
+
`sourcePath: ${sourcePath}`,
|
|
25
|
+
"",
|
|
26
|
+
"USER.md:",
|
|
27
|
+
"```md",
|
|
28
|
+
markdown,
|
|
29
|
+
"```",
|
|
30
|
+
"",
|
|
31
|
+
"只输出 JSON 数组。",
|
|
32
|
+
].join("\n");
|
|
33
|
+
}
|
|
34
|
+
function isRecord(value) {
|
|
35
|
+
return typeof value === "object" && value !== null;
|
|
36
|
+
}
|
|
37
|
+
function extractTextFromContent(content) {
|
|
38
|
+
if (typeof content === "string") {
|
|
39
|
+
return content;
|
|
40
|
+
}
|
|
41
|
+
if (!Array.isArray(content)) {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const parts = [];
|
|
45
|
+
for (const item of content) {
|
|
46
|
+
if (typeof item === "string") {
|
|
47
|
+
parts.push(item);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (!isRecord(item)) {
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (typeof item.text === "string") {
|
|
54
|
+
parts.push(item.text);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (typeof item.content === "string") {
|
|
58
|
+
parts.push(item.content);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return parts.length > 0 ? parts.join("") : undefined;
|
|
62
|
+
}
|
|
63
|
+
export function extractLatestAssistantText(messages) {
|
|
64
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
65
|
+
const message = messages[index];
|
|
66
|
+
if (!isRecord(message) || message.role !== "assistant") {
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const text = extractTextFromContent(message.content) ??
|
|
70
|
+
(typeof message.text === "string" ? message.text : undefined) ??
|
|
71
|
+
(typeof message.message === "string" ? message.message : undefined);
|
|
72
|
+
if (text?.trim()) {
|
|
73
|
+
return text;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
function stripJsonFence(text) {
|
|
79
|
+
const trimmed = text.trim();
|
|
80
|
+
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
|
|
81
|
+
return fenced ? fenced[1].trim() : trimmed;
|
|
82
|
+
}
|
|
83
|
+
export function parseUserMdAttributeResponse(text) {
|
|
84
|
+
try {
|
|
85
|
+
return validateExtractedUserMdTags(JSON.parse(stripJsonFence(text)));
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function unavailable(reason) {
|
|
92
|
+
return { unavailable: true, reason };
|
|
93
|
+
}
|
|
94
|
+
export function createOpenClawUserMdAttributeExtractor(api, options) {
|
|
95
|
+
const timeoutMs = options?.timeoutMs ?? EXTRACTION_TIMEOUT_MS;
|
|
96
|
+
const logger = options?.logger ?? api.logger;
|
|
97
|
+
return {
|
|
98
|
+
async extract({ markdown, sourcePath }) {
|
|
99
|
+
const subagent = api.runtime?.subagent;
|
|
100
|
+
if (!subagent?.run || !subagent.waitForRun || !subagent.getSessionMessages) {
|
|
101
|
+
return unavailable("OpenClaw subagent runtime is unavailable");
|
|
102
|
+
}
|
|
103
|
+
const sessionKey = `libp2p-mesh:user-md-attributes:${hashForSessionKey(sourcePath)}:${randomUUID()}`;
|
|
104
|
+
try {
|
|
105
|
+
await subagent.deleteSession?.({ sessionKey, deleteTranscript: true }).catch(() => undefined);
|
|
106
|
+
const { runId } = await subagent.run({
|
|
107
|
+
sessionKey,
|
|
108
|
+
message: buildUserMdExtractionMessage(markdown, sourcePath),
|
|
109
|
+
extraSystemPrompt: USER_MD_ATTRIBUTE_EXTRACTION_PROMPT,
|
|
110
|
+
lane: "libp2p-mesh-user-md-attributes",
|
|
111
|
+
lightContext: true,
|
|
112
|
+
deliver: false,
|
|
113
|
+
});
|
|
114
|
+
const waitResult = await subagent.waitForRun({ runId, timeoutMs });
|
|
115
|
+
if (waitResult.status !== "ok") {
|
|
116
|
+
return unavailable(waitResult.error ?? `OpenClaw subagent extraction ${waitResult.status}`);
|
|
117
|
+
}
|
|
118
|
+
const { messages } = await subagent.getSessionMessages({ sessionKey, limit: 10 });
|
|
119
|
+
const text = extractLatestAssistantText(messages);
|
|
120
|
+
if (!text) {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
return parseUserMdAttributeResponse(text);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
127
|
+
logger?.warn?.(`[libp2p-mesh] USER.md agent extraction failed: ${reason}`);
|
|
128
|
+
return unavailable(reason);
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
await subagent.deleteSession?.({ sessionKey, deleteTranscript: true }).catch(() => undefined);
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
package/package.json
CHANGED
package/src/instance-router.ts
CHANGED
|
@@ -218,6 +218,7 @@ export function createInstanceRouter(options: InstanceRouterOptions): InstanceRo
|
|
|
218
218
|
const deliveryCache = new Map<string, DeliveryCacheEntry>();
|
|
219
219
|
const unsubs: Array<() => void> = [];
|
|
220
220
|
const pendingAttributePeers = new Set<string>();
|
|
221
|
+
let publicAttributeRefreshEnabled = options.publicAttributeRefreshInitiallyEnabled !== false;
|
|
221
222
|
let attributeRefreshPromise: Promise<void> | undefined;
|
|
222
223
|
|
|
223
224
|
function localInstanceId(): string {
|
|
@@ -335,7 +336,9 @@ export function createInstanceRouter(options: InstanceRouterOptions): InstanceRo
|
|
|
335
336
|
return;
|
|
336
337
|
}
|
|
337
338
|
|
|
338
|
-
|
|
339
|
+
if (publicAttributeRefreshEnabled) {
|
|
340
|
+
drainAttributeRefresh();
|
|
341
|
+
}
|
|
339
342
|
}
|
|
340
343
|
|
|
341
344
|
function drainAttributeRefresh(): Promise<void> {
|
|
@@ -358,6 +361,13 @@ export function createInstanceRouter(options: InstanceRouterOptions): InstanceRo
|
|
|
358
361
|
return attributeRefreshPromise;
|
|
359
362
|
}
|
|
360
363
|
|
|
364
|
+
function enablePublicAttributeRefresh(): void {
|
|
365
|
+
publicAttributeRefreshEnabled = true;
|
|
366
|
+
if (pendingAttributePeers.size > 0) {
|
|
367
|
+
drainAttributeRefresh();
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
361
371
|
async function announceToPeer(peerId: string): Promise<void> {
|
|
362
372
|
if (!isNonEmptyString(peerId) || peerId === mesh.getLocalPeerId()) {
|
|
363
373
|
return;
|
|
@@ -896,6 +906,7 @@ export function createInstanceRouter(options: InstanceRouterOptions): InstanceRo
|
|
|
896
906
|
stop,
|
|
897
907
|
handleMessage,
|
|
898
908
|
announceToPeer,
|
|
909
|
+
enablePublicAttributeRefresh,
|
|
899
910
|
refreshPublicAttributes,
|
|
900
911
|
listInstances,
|
|
901
912
|
resolveInstance,
|
package/src/plugin.ts
CHANGED
|
@@ -7,12 +7,15 @@ import { createInstanceRouter } from "./instance-router.js";
|
|
|
7
7
|
import { createMeshNetwork } from "./mesh.js";
|
|
8
8
|
import { createPeerLabelStore } from "./peer-label-store.js";
|
|
9
9
|
import { createUserMdAgentAttributeSource } from "./user-md-agent-attributes.js";
|
|
10
|
+
import { createOpenClawUserMdAttributeExtractor } from "./user-md-openclaw-extractor.js";
|
|
10
11
|
import { createUserProfileStore } from "./user-profile-store.js";
|
|
11
12
|
import { buildP2PTools } from "./agent-tools.js";
|
|
12
13
|
import { registerLibp2pMeshCli } from "./profile-cli.js";
|
|
13
14
|
import type { ChannelPlugin } from "openclaw/plugin-sdk/core";
|
|
14
15
|
import type { MeshConfig } from "./types.js";
|
|
15
16
|
|
|
17
|
+
const DEFAULT_PUBLIC_ATTRIBUTE_REFRESH_STARTUP_DELAY_MS = 10000;
|
|
18
|
+
|
|
16
19
|
export type Libp2pMeshPluginDeps = {
|
|
17
20
|
createMeshNetwork?: typeof createMeshNetwork;
|
|
18
21
|
createInstanceRouter?: typeof createInstanceRouter;
|
|
@@ -30,13 +33,17 @@ export function registerLibp2pMeshWithDeps(
|
|
|
30
33
|
let unsubscribeInbound: (() => void) | undefined;
|
|
31
34
|
let serviceStarted = false;
|
|
32
35
|
let startPromise: Promise<void> | undefined;
|
|
36
|
+
let publicAttributeRefreshTimer: ReturnType<typeof setTimeout> | undefined;
|
|
33
37
|
const mesh = (deps.createMeshNetwork ?? createMeshNetwork)({
|
|
34
38
|
config,
|
|
35
39
|
logger: api.logger,
|
|
36
40
|
});
|
|
37
41
|
const store = createInstancePeerStore({ logger: api.logger });
|
|
38
42
|
const peerLabelStore = createPeerLabelStore({ logger: api.logger });
|
|
39
|
-
const userAttributeSource = createUserMdAgentAttributeSource({
|
|
43
|
+
const userAttributeSource = createUserMdAgentAttributeSource({
|
|
44
|
+
logger: api.logger,
|
|
45
|
+
extractor: createOpenClawUserMdAttributeExtractor(api),
|
|
46
|
+
});
|
|
40
47
|
const userProfileStore = createUserProfileStore({ logger: api.logger });
|
|
41
48
|
const delivery = createOpenClawRuntimeInboundDelivery({
|
|
42
49
|
config: api.config,
|
|
@@ -61,6 +68,7 @@ export function registerLibp2pMeshWithDeps(
|
|
|
61
68
|
userAttributeSource,
|
|
62
69
|
userProfileStore,
|
|
63
70
|
peerLabelStore,
|
|
71
|
+
publicAttributeRefreshInitiallyEnabled: false,
|
|
64
72
|
});
|
|
65
73
|
|
|
66
74
|
registerLibp2pMeshCli(api, {
|
|
@@ -110,7 +118,31 @@ export function registerLibp2pMeshWithDeps(
|
|
|
110
118
|
});
|
|
111
119
|
}
|
|
112
120
|
|
|
121
|
+
function publicAttributeRefreshStartupDelayMs(): number {
|
|
122
|
+
const configured = config?.publicAttributeRefreshStartupDelayMs;
|
|
123
|
+
if (typeof configured === "number" && Number.isFinite(configured) && configured >= 0) {
|
|
124
|
+
return configured;
|
|
125
|
+
}
|
|
126
|
+
return DEFAULT_PUBLIC_ATTRIBUTE_REFRESH_STARTUP_DELAY_MS;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function clearPublicAttributeRefreshTimer(): void {
|
|
130
|
+
if (publicAttributeRefreshTimer) {
|
|
131
|
+
clearTimeout(publicAttributeRefreshTimer);
|
|
132
|
+
publicAttributeRefreshTimer = undefined;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function schedulePublicAttributeRefreshEnable(): void {
|
|
137
|
+
clearPublicAttributeRefreshTimer();
|
|
138
|
+
publicAttributeRefreshTimer = setTimeout(() => {
|
|
139
|
+
publicAttributeRefreshTimer = undefined;
|
|
140
|
+
router.enablePublicAttributeRefresh();
|
|
141
|
+
}, publicAttributeRefreshStartupDelayMs());
|
|
142
|
+
}
|
|
143
|
+
|
|
113
144
|
async function cleanupStartupFailure(): Promise<void> {
|
|
145
|
+
clearPublicAttributeRefreshTimer();
|
|
114
146
|
try {
|
|
115
147
|
unsubscribeInbound?.();
|
|
116
148
|
} catch (error) {
|
|
@@ -182,6 +214,7 @@ export function registerLibp2pMeshWithDeps(
|
|
|
182
214
|
);
|
|
183
215
|
}
|
|
184
216
|
serviceStarted = true;
|
|
217
|
+
schedulePublicAttributeRefreshEnable();
|
|
185
218
|
} catch (error) {
|
|
186
219
|
await cleanupStartupFailure();
|
|
187
220
|
throw error;
|
|
@@ -194,6 +227,7 @@ export function registerLibp2pMeshWithDeps(
|
|
|
194
227
|
},
|
|
195
228
|
stop: async () => {
|
|
196
229
|
await startPromise?.catch(() => undefined);
|
|
230
|
+
clearPublicAttributeRefreshTimer();
|
|
197
231
|
unsubscribeInbound?.();
|
|
198
232
|
unsubscribeInbound = undefined;
|
|
199
233
|
await router.stop();
|
package/src/prompt-config.ts
CHANGED
|
@@ -42,7 +42,7 @@ export const LIBP2P_MESH_AGENT_PROMPT = `
|
|
|
42
42
|
|
|
43
43
|
- \`source="USER.md"\` 表示 gateway 使用 OpenClaw 已配置的 agent/API 模型,从 USER.md 异步提取并公开广播的 tag。
|
|
44
44
|
- \`source="profile"\` 表示用户通过 \`openclaw libp2p-mesh profile\` 手动配置的公开结构化属性。
|
|
45
|
-
- gateway 的基础 \`instance-announce\` 可能省略 \`userPublicAttributes\`;这表示本次 announce
|
|
45
|
+
- gateway 的基础 \`instance-announce\` 可能省略 \`userPublicAttributes\`;这表示本次 announce 没有携带属性,不一定表示该用户没有公开属性。启动后 USER.md 属性刷新可能会延迟数秒完成。按公开属性发送前先用 \`p2p_list_instances\` 查看当前实例记录。
|
|
46
46
|
- 普通对话 agent 不应自己读取 USER.md 来决定公开属性。USER.md 属性提取是 gateway 后台职责。
|
|
47
47
|
|
|
48
48
|
3. \`openclaw libp2p-mesh labels\` manages local labels for remote instances. These labels are stored in the local \`peer-labels.json\`, stay on this machine, and are used only when the send tool uses \`scope="local"\` or \`scope="all"\`.
|
package/src/types.ts
CHANGED
|
@@ -244,6 +244,7 @@ export type InstanceRouterOptions = {
|
|
|
244
244
|
peerLabelStore?: {
|
|
245
245
|
listLabels(instanceId: string): Promise<LocalPeerLabelAttribute[]>;
|
|
246
246
|
};
|
|
247
|
+
publicAttributeRefreshInitiallyEnabled?: boolean;
|
|
247
248
|
};
|
|
248
249
|
|
|
249
250
|
export interface InstanceRouter {
|
|
@@ -253,6 +254,7 @@ export interface InstanceRouter {
|
|
|
253
254
|
stop(): Promise<void>;
|
|
254
255
|
handleMessage(msg: P2PMessage): Promise<void>;
|
|
255
256
|
announceToPeer(peerId: string): Promise<void>;
|
|
257
|
+
enablePublicAttributeRefresh(): void;
|
|
256
258
|
refreshPublicAttributes(): Promise<void>;
|
|
257
259
|
listInstances(): Promise<InstancePeerRecord[]>;
|
|
258
260
|
resolveInstance(instanceId: string): Promise<InstancePeerRecord | undefined>;
|
|
@@ -280,6 +282,7 @@ export interface MeshConfig {
|
|
|
280
282
|
bootstrapList?: string[];
|
|
281
283
|
meshTopic?: string;
|
|
282
284
|
announceLogDetail?: AnnounceLogDetail;
|
|
285
|
+
publicAttributeRefreshStartupDelayMs?: number;
|
|
283
286
|
enableAgentSync?: boolean;
|
|
284
287
|
enableWebSocket?: boolean;
|
|
285
288
|
peerIdPath?: string;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
|
|
3
|
+
import type { UserPublicAttribute } from "./types.js";
|
|
4
|
+
import type {
|
|
5
|
+
UserMdAttributeExtractionUnavailable,
|
|
6
|
+
UserMdAttributeExtractor,
|
|
7
|
+
} from "./user-md-agent-attributes.js";
|
|
8
|
+
import { validateExtractedUserMdTags } from "./user-md-agent-attributes.js";
|
|
9
|
+
|
|
10
|
+
const EXTRACTION_TIMEOUT_MS = 30000;
|
|
11
|
+
const SESSION_HASH_LENGTH = 16;
|
|
12
|
+
|
|
13
|
+
export const USER_MD_ATTRIBUTE_EXTRACTION_PROMPT = [
|
|
14
|
+
"你是 libp2p-mesh 的 USER.md 公开属性提取器。",
|
|
15
|
+
"",
|
|
16
|
+
"任务:从 USER.md 中提取少量适合公开广播的用户 tag。",
|
|
17
|
+
"",
|
|
18
|
+
"规则:",
|
|
19
|
+
"- 只输出 JSON 数组,不要输出解释、Markdown 或代码块。",
|
|
20
|
+
'- 每项必须是:{"kind":"tag","value":"...","label":"...","source":"USER.md"}',
|
|
21
|
+
"- 最多 10 个。",
|
|
22
|
+
"- 每个 value 不超过 40 个字符。",
|
|
23
|
+
"- 不要提取寒暄、联系方式提示、占位内容、完整句子。",
|
|
24
|
+
"- 不要提取“刚认识”“还在了解”“随时告诉我”这类无分类价值内容。",
|
|
25
|
+
"- 优先提取稳定身份、技术方向、项目方向、长期偏好。",
|
|
26
|
+
].join("\n");
|
|
27
|
+
|
|
28
|
+
type Logger = {
|
|
29
|
+
warn?: (message: string) => void;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function hashForSessionKey(value: string): string {
|
|
33
|
+
return createHash("sha256").update(value, "utf8").digest("hex").slice(0, SESSION_HASH_LENGTH);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function buildUserMdExtractionMessage(markdown: string, sourcePath: string): string {
|
|
37
|
+
return [
|
|
38
|
+
`sourcePath: ${sourcePath}`,
|
|
39
|
+
"",
|
|
40
|
+
"USER.md:",
|
|
41
|
+
"```md",
|
|
42
|
+
markdown,
|
|
43
|
+
"```",
|
|
44
|
+
"",
|
|
45
|
+
"只输出 JSON 数组。",
|
|
46
|
+
].join("\n");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
50
|
+
return typeof value === "object" && value !== null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function extractTextFromContent(content: unknown): string | undefined {
|
|
54
|
+
if (typeof content === "string") {
|
|
55
|
+
return content;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (!Array.isArray(content)) {
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const parts: string[] = [];
|
|
63
|
+
for (const item of content) {
|
|
64
|
+
if (typeof item === "string") {
|
|
65
|
+
parts.push(item);
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (!isRecord(item)) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (typeof item.text === "string") {
|
|
72
|
+
parts.push(item.text);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (typeof item.content === "string") {
|
|
76
|
+
parts.push(item.content);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return parts.length > 0 ? parts.join("") : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function extractLatestAssistantText(messages: unknown[]): string | undefined {
|
|
84
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
85
|
+
const message = messages[index];
|
|
86
|
+
if (!isRecord(message) || message.role !== "assistant") {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const text =
|
|
91
|
+
extractTextFromContent(message.content) ??
|
|
92
|
+
(typeof message.text === "string" ? message.text : undefined) ??
|
|
93
|
+
(typeof message.message === "string" ? message.message : undefined);
|
|
94
|
+
if (text?.trim()) {
|
|
95
|
+
return text;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function stripJsonFence(text: string): string {
|
|
103
|
+
const trimmed = text.trim();
|
|
104
|
+
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);
|
|
105
|
+
return fenced ? fenced[1].trim() : trimmed;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function parseUserMdAttributeResponse(text: string): UserPublicAttribute[] {
|
|
109
|
+
try {
|
|
110
|
+
return validateExtractedUserMdTags(JSON.parse(stripJsonFence(text)));
|
|
111
|
+
} catch {
|
|
112
|
+
return [];
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function unavailable(reason: string): UserMdAttributeExtractionUnavailable {
|
|
117
|
+
return { unavailable: true, reason };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function createOpenClawUserMdAttributeExtractor(
|
|
121
|
+
api: OpenClawPluginApi,
|
|
122
|
+
options?: {
|
|
123
|
+
timeoutMs?: number;
|
|
124
|
+
logger?: Logger;
|
|
125
|
+
},
|
|
126
|
+
): UserMdAttributeExtractor {
|
|
127
|
+
const timeoutMs = options?.timeoutMs ?? EXTRACTION_TIMEOUT_MS;
|
|
128
|
+
const logger = options?.logger ?? api.logger;
|
|
129
|
+
|
|
130
|
+
return {
|
|
131
|
+
async extract({ markdown, sourcePath }) {
|
|
132
|
+
const subagent = api.runtime?.subagent;
|
|
133
|
+
if (!subagent?.run || !subagent.waitForRun || !subagent.getSessionMessages) {
|
|
134
|
+
return unavailable("OpenClaw subagent runtime is unavailable");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const sessionKey = `libp2p-mesh:user-md-attributes:${hashForSessionKey(sourcePath)}:${randomUUID()}`;
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
await subagent.deleteSession?.({ sessionKey, deleteTranscript: true }).catch(() => undefined);
|
|
141
|
+
const { runId } = await subagent.run({
|
|
142
|
+
sessionKey,
|
|
143
|
+
message: buildUserMdExtractionMessage(markdown, sourcePath),
|
|
144
|
+
extraSystemPrompt: USER_MD_ATTRIBUTE_EXTRACTION_PROMPT,
|
|
145
|
+
lane: "libp2p-mesh-user-md-attributes",
|
|
146
|
+
lightContext: true,
|
|
147
|
+
deliver: false,
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const waitResult = await subagent.waitForRun({ runId, timeoutMs });
|
|
151
|
+
if (waitResult.status !== "ok") {
|
|
152
|
+
return unavailable(waitResult.error ?? `OpenClaw subagent extraction ${waitResult.status}`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const { messages } = await subagent.getSessionMessages({ sessionKey, limit: 10 });
|
|
156
|
+
const text = extractLatestAssistantText(messages);
|
|
157
|
+
if (!text) {
|
|
158
|
+
return [];
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return parseUserMdAttributeResponse(text);
|
|
162
|
+
} catch (error) {
|
|
163
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
164
|
+
logger?.warn?.(`[libp2p-mesh] USER.md agent extraction failed: ${reason}`);
|
|
165
|
+
return unavailable(reason);
|
|
166
|
+
} finally {
|
|
167
|
+
await subagent.deleteSession?.({ sessionKey, deleteTranscript: true }).catch(() => undefined);
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|