openclaw-bridge 0.3.2 → 0.4.1
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/README.md +43 -16
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +843 -0
- package/dist/config.d.ts +3 -0
- package/dist/config.js +64 -0
- package/dist/discovery.d.ts +4 -0
- package/dist/discovery.js +6 -0
- package/dist/file-ops.d.ts +22 -0
- package/dist/file-ops.js +253 -0
- package/dist/heartbeat.d.ts +21 -0
- package/dist/heartbeat.js +152 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +624 -0
- package/dist/manager/hub-client.d.ts +18 -0
- package/dist/manager/hub-client.js +89 -0
- package/dist/manager/local-manager.d.ts +12 -0
- package/dist/manager/local-manager.js +117 -0
- package/dist/manager/pm2-bridge.d.ts +17 -0
- package/dist/manager/pm2-bridge.js +113 -0
- package/dist/message-relay.d.ts +32 -0
- package/dist/message-relay.js +229 -0
- package/dist/permissions.d.ts +3 -0
- package/dist/permissions.js +14 -0
- package/dist/registry.d.ts +13 -0
- package/dist/registry.js +103 -0
- package/dist/restart.d.ts +15 -0
- package/dist/restart.js +107 -0
- package/dist/router.d.ts +11 -0
- package/dist/router.js +18 -0
- package/dist/session.d.ts +11 -0
- package/dist/session.js +21 -0
- package/dist/types.d.ts +90 -0
- package/dist/types.js +1 -0
- package/openclaw.plugin.json +6 -92
- package/package.json +15 -5
- package/src/cli.ts +0 -842
- package/src/config.ts +0 -72
- package/src/discovery.ts +0 -17
- package/src/file-ops.ts +0 -320
- package/src/heartbeat.ts +0 -196
- package/src/index.ts +0 -681
- package/src/manager/hub-client.ts +0 -114
- package/src/manager/local-manager.ts +0 -121
- package/src/manager/pm2-bridge.ts +0 -125
- package/src/message-relay.ts +0 -184
- package/src/permissions.ts +0 -18
- package/src/registry.ts +0 -107
- package/src/restart.ts +0 -137
- package/src/router.ts +0 -40
- package/src/session.ts +0 -33
- package/src/types.ts +0 -100
- package/tsconfig.json +0 -14
package/src/config.ts
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { hostname } from "node:os";
|
|
2
|
-
import type { BridgeConfig } from "./types.js";
|
|
3
|
-
|
|
4
|
-
const DEFAULTS = {
|
|
5
|
-
heartbeatIntervalMs: 30_000,
|
|
6
|
-
offlineThresholdMs: 120_000,
|
|
7
|
-
} as const;
|
|
8
|
-
|
|
9
|
-
export function parseConfig(raw: unknown): BridgeConfig {
|
|
10
|
-
if (!raw || typeof raw !== "object") {
|
|
11
|
-
throw new Error("openclaw-bridge: missing plugin config");
|
|
12
|
-
}
|
|
13
|
-
const obj = raw as Record<string, unknown>;
|
|
14
|
-
|
|
15
|
-
if (!obj.role || (obj.role !== "normal" && obj.role !== "superuser")) {
|
|
16
|
-
throw new Error('openclaw-bridge: config.role must be "normal" or "superuser"');
|
|
17
|
-
}
|
|
18
|
-
if (!obj.agentId || typeof obj.agentId !== "string") {
|
|
19
|
-
throw new Error("openclaw-bridge: config.agentId is required");
|
|
20
|
-
}
|
|
21
|
-
if (!obj.agentName || typeof obj.agentName !== "string") {
|
|
22
|
-
throw new Error("openclaw-bridge: config.agentName is required");
|
|
23
|
-
}
|
|
24
|
-
const registry = obj.registry as Record<string, unknown> | undefined;
|
|
25
|
-
if (!registry || !registry.baseUrl || typeof registry.baseUrl !== "string") {
|
|
26
|
-
throw new Error("openclaw-bridge: config.registry.baseUrl is required");
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
return {
|
|
30
|
-
role: obj.role as "normal" | "superuser",
|
|
31
|
-
agentId: obj.agentId as string,
|
|
32
|
-
agentName: obj.agentName as string,
|
|
33
|
-
registry: {
|
|
34
|
-
provider: (registry.provider as string) ?? "openviking",
|
|
35
|
-
baseUrl: registry.baseUrl as string,
|
|
36
|
-
apiKey: registry.apiKey as string | undefined,
|
|
37
|
-
},
|
|
38
|
-
fileRelay: obj.fileRelay
|
|
39
|
-
? {
|
|
40
|
-
baseUrl: (obj.fileRelay as Record<string, unknown>).baseUrl as string,
|
|
41
|
-
apiKey: (obj.fileRelay as Record<string, unknown>).apiKey as string | undefined,
|
|
42
|
-
}
|
|
43
|
-
: undefined,
|
|
44
|
-
messageRelay: obj.messageRelay
|
|
45
|
-
? {
|
|
46
|
-
url: (obj.messageRelay as Record<string, unknown>).url as string,
|
|
47
|
-
apiKey: (obj.messageRelay as Record<string, unknown>).apiKey as string,
|
|
48
|
-
}
|
|
49
|
-
: undefined,
|
|
50
|
-
heartbeatIntervalMs:
|
|
51
|
-
typeof obj.heartbeatIntervalMs === "number"
|
|
52
|
-
? obj.heartbeatIntervalMs
|
|
53
|
-
: DEFAULTS.heartbeatIntervalMs,
|
|
54
|
-
offlineThresholdMs:
|
|
55
|
-
typeof obj.offlineThresholdMs === "number"
|
|
56
|
-
? obj.offlineThresholdMs
|
|
57
|
-
: DEFAULTS.offlineThresholdMs,
|
|
58
|
-
description: typeof obj.description === "string" ? obj.description : undefined,
|
|
59
|
-
supportsVision: typeof obj.supportsVision === "boolean" ? obj.supportsVision : undefined,
|
|
60
|
-
localManager: obj.localManager
|
|
61
|
-
? {
|
|
62
|
-
enabled: !!(obj.localManager as Record<string, unknown>).enabled,
|
|
63
|
-
hubUrl: (obj.localManager as Record<string, unknown>).hubUrl as string,
|
|
64
|
-
managerPass: (obj.localManager as Record<string, unknown>).managerPass as string,
|
|
65
|
-
}
|
|
66
|
-
: undefined,
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export function getMachineId(): string {
|
|
71
|
-
return hostname();
|
|
72
|
-
}
|
package/src/discovery.ts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import type { RegistryEntry } from "./types.js";
|
|
2
|
-
import type { BridgeRegistry } from "./registry.js";
|
|
3
|
-
|
|
4
|
-
export async function discoverAll(
|
|
5
|
-
registry: BridgeRegistry,
|
|
6
|
-
offlineThresholdMs: number,
|
|
7
|
-
): Promise<RegistryEntry[]> {
|
|
8
|
-
return registry.discover(offlineThresholdMs);
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export async function whois(
|
|
12
|
-
registry: BridgeRegistry,
|
|
13
|
-
agentId: string,
|
|
14
|
-
offlineThresholdMs: number,
|
|
15
|
-
): Promise<RegistryEntry | null> {
|
|
16
|
-
return registry.findAgent(agentId, offlineThresholdMs);
|
|
17
|
-
}
|
package/src/file-ops.ts
DELETED
|
@@ -1,320 +0,0 @@
|
|
|
1
|
-
import { readFile, writeFile, copyFile, mkdir, access } from "node:fs/promises";
|
|
2
|
-
import { join, resolve, dirname, basename, extname } from "node:path";
|
|
3
|
-
import type { BridgeConfig, RegistryEntry, PluginLogger } from "./types.js";
|
|
4
|
-
|
|
5
|
-
/** If dest exists, append _1, _2, etc. before the extension */
|
|
6
|
-
async function deduplicatePath(destPath: string): Promise<string> {
|
|
7
|
-
let candidate = destPath;
|
|
8
|
-
let counter = 0;
|
|
9
|
-
const ext = extname(destPath);
|
|
10
|
-
const base = destPath.slice(0, destPath.length - ext.length);
|
|
11
|
-
while (true) {
|
|
12
|
-
try {
|
|
13
|
-
await access(candidate);
|
|
14
|
-
counter++;
|
|
15
|
-
candidate = `${base}_${counter}${ext}`;
|
|
16
|
-
} catch {
|
|
17
|
-
return candidate; // File doesn't exist, use this path
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export class BridgeFileOps {
|
|
23
|
-
private config: BridgeConfig;
|
|
24
|
-
private machineId: string;
|
|
25
|
-
private workspacePath: string;
|
|
26
|
-
private logger: PluginLogger;
|
|
27
|
-
|
|
28
|
-
constructor(
|
|
29
|
-
config: BridgeConfig,
|
|
30
|
-
machineId: string,
|
|
31
|
-
workspacePath: string,
|
|
32
|
-
logger: PluginLogger,
|
|
33
|
-
) {
|
|
34
|
-
this.config = config;
|
|
35
|
-
this.machineId = machineId;
|
|
36
|
-
this.workspacePath = workspacePath;
|
|
37
|
-
this.logger = logger;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
private isSameMachine(target: RegistryEntry): boolean {
|
|
41
|
-
return target.machineId === this.machineId;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
private validatePathWithinWorkspace(filePath: string, workspace: string): string {
|
|
45
|
-
const resolved = resolve(workspace, filePath);
|
|
46
|
-
if (!resolved.startsWith(resolve(workspace))) {
|
|
47
|
-
throw new Error(`openclaw-bridge: path escapes workspace: ${filePath}`);
|
|
48
|
-
}
|
|
49
|
-
return resolved;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
private fileRelayHeaders(): Record<string, string> {
|
|
53
|
-
const h: Record<string, string> = { "Content-Type": "application/json" };
|
|
54
|
-
if (this.config.fileRelay?.apiKey) h["X-API-Key"] = this.config.fileRelay.apiKey;
|
|
55
|
-
return h;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
private fileRelayUrl(path: string): string {
|
|
59
|
-
if (!this.config.fileRelay?.baseUrl) {
|
|
60
|
-
throw new Error("openclaw-bridge: fileRelay.baseUrl not configured");
|
|
61
|
-
}
|
|
62
|
-
return `${this.config.fileRelay.baseUrl.replace(/\/+$/, "")}${path}`;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
async sendFile(
|
|
66
|
-
target: RegistryEntry,
|
|
67
|
-
localRelativePath: string,
|
|
68
|
-
): Promise<{ delivered: boolean; message: string }> {
|
|
69
|
-
const sourcePath = this.validatePathWithinWorkspace(localRelativePath, this.workspacePath);
|
|
70
|
-
|
|
71
|
-
if (this.isSameMachine(target)) {
|
|
72
|
-
const destDir = join(target.workspacePath, "_inbox", this.config.agentId);
|
|
73
|
-
await mkdir(destDir, { recursive: true });
|
|
74
|
-
const originalFilename = localRelativePath.split(/[\\/]/).pop()!;
|
|
75
|
-
const rawDestPath = join(destDir, originalFilename);
|
|
76
|
-
const destPath = await deduplicatePath(rawDestPath);
|
|
77
|
-
await copyFile(sourcePath, destPath);
|
|
78
|
-
const actualFilename = basename(destPath);
|
|
79
|
-
const renamed = actualFilename !== originalFilename;
|
|
80
|
-
this.logger.info(
|
|
81
|
-
`openclaw-bridge: sent ${localRelativePath} to ${target.agentId} (local)${renamed ? ` (renamed to ${actualFilename})` : ""}`,
|
|
82
|
-
);
|
|
83
|
-
return {
|
|
84
|
-
delivered: true,
|
|
85
|
-
message: renamed
|
|
86
|
-
? `File copied to ${target.agentId}/_inbox/ (renamed to ${actualFilename} because a file with the same name already existed)`
|
|
87
|
-
: `File copied to ${target.agentId}/_inbox/`,
|
|
88
|
-
filename: actualFilename,
|
|
89
|
-
renamed,
|
|
90
|
-
};
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
const content = await readFile(sourcePath);
|
|
94
|
-
const res = await fetch(this.fileRelayUrl("/api/v1/files/upload"), {
|
|
95
|
-
method: "POST",
|
|
96
|
-
headers: this.fileRelayHeaders(),
|
|
97
|
-
body: JSON.stringify({
|
|
98
|
-
fromAgent: this.config.agentId,
|
|
99
|
-
toAgent: target.agentId,
|
|
100
|
-
filename: localRelativePath.split(/[\\/]/).pop()!,
|
|
101
|
-
content: content.toString("base64"),
|
|
102
|
-
metadata: {},
|
|
103
|
-
}),
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
if (!res.ok) {
|
|
107
|
-
throw new Error(`openclaw-bridge: FileRelay upload failed: ${res.status}`);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
this.logger.info(
|
|
111
|
-
`openclaw-bridge: sent ${localRelativePath} to ${target.agentId} (FileRelay)`,
|
|
112
|
-
);
|
|
113
|
-
return { delivered: false, message: `File uploaded to FileRelay for ${target.agentId}` };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async readRemoteFile(
|
|
117
|
-
target: RegistryEntry,
|
|
118
|
-
relativePath: string,
|
|
119
|
-
): Promise<string> {
|
|
120
|
-
if (this.isSameMachine(target)) {
|
|
121
|
-
const fullPath = this.validatePathWithinWorkspace(relativePath, target.workspacePath);
|
|
122
|
-
return await readFile(fullPath, "utf-8");
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
const enqueueRes = await fetch(this.fileRelayUrl("/api/v1/commands/enqueue"), {
|
|
126
|
-
method: "POST",
|
|
127
|
-
headers: this.fileRelayHeaders(),
|
|
128
|
-
body: JSON.stringify({
|
|
129
|
-
fromAgent: this.config.agentId,
|
|
130
|
-
toAgent: target.agentId,
|
|
131
|
-
type: "read_file",
|
|
132
|
-
payload: { path: relativePath },
|
|
133
|
-
}),
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
if (!enqueueRes.ok) {
|
|
137
|
-
throw new Error(`openclaw-bridge: command enqueue failed: ${enqueueRes.status}`);
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
const { id: cmdId } = (await enqueueRes.json()) as { id: string };
|
|
141
|
-
|
|
142
|
-
const deadline = Date.now() + 90_000;
|
|
143
|
-
while (Date.now() < deadline) {
|
|
144
|
-
await new Promise((r) => setTimeout(r, 5_000));
|
|
145
|
-
const resultRes = await fetch(this.fileRelayUrl(`/api/v1/commands/result/${cmdId}`), {
|
|
146
|
-
headers: this.fileRelayHeaders(),
|
|
147
|
-
});
|
|
148
|
-
if (!resultRes.ok) continue;
|
|
149
|
-
const result = (await resultRes.json()) as {
|
|
150
|
-
status: string;
|
|
151
|
-
payload?: { content?: string };
|
|
152
|
-
};
|
|
153
|
-
if (result.status === "ok" && result.payload?.content) {
|
|
154
|
-
return Buffer.from(result.payload.content, "base64").toString("utf-8");
|
|
155
|
-
}
|
|
156
|
-
if (result.status === "error") {
|
|
157
|
-
throw new Error(`openclaw-bridge: remote read failed`);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
throw new Error("openclaw-bridge: remote read timed out (90s)");
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
async writeRemoteFile(
|
|
164
|
-
target: RegistryEntry,
|
|
165
|
-
relativePath: string,
|
|
166
|
-
content: string,
|
|
167
|
-
): Promise<void> {
|
|
168
|
-
if (this.isSameMachine(target)) {
|
|
169
|
-
const fullPath = this.validatePathWithinWorkspace(relativePath, target.workspacePath);
|
|
170
|
-
await mkdir(dirname(fullPath), { recursive: true });
|
|
171
|
-
await writeFile(fullPath, content, "utf-8");
|
|
172
|
-
this.logger.info(
|
|
173
|
-
`openclaw-bridge: wrote ${relativePath} to ${target.agentId} workspace`,
|
|
174
|
-
);
|
|
175
|
-
return;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
const res = await fetch(this.fileRelayUrl("/api/v1/files/upload"), {
|
|
179
|
-
method: "POST",
|
|
180
|
-
headers: this.fileRelayHeaders(),
|
|
181
|
-
body: JSON.stringify({
|
|
182
|
-
fromAgent: this.config.agentId,
|
|
183
|
-
toAgent: target.agentId,
|
|
184
|
-
filename: relativePath.split(/[\\/]/).pop()!,
|
|
185
|
-
content: Buffer.from(content).toString("base64"),
|
|
186
|
-
metadata: { writeToPath: relativePath },
|
|
187
|
-
}),
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
if (!res.ok) {
|
|
191
|
-
throw new Error(`openclaw-bridge: FileRelay write-upload failed: ${res.status}`);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
async processPendingFiles(): Promise<number> {
|
|
196
|
-
if (!this.config.fileRelay?.baseUrl) return 0;
|
|
197
|
-
|
|
198
|
-
try {
|
|
199
|
-
const res = await fetch(
|
|
200
|
-
this.fileRelayUrl(`/api/v1/files/pending?agent=${this.config.agentId}`),
|
|
201
|
-
{ headers: this.fileRelayHeaders() },
|
|
202
|
-
);
|
|
203
|
-
if (!res.ok) return 0;
|
|
204
|
-
|
|
205
|
-
const data = (await res.json()) as {
|
|
206
|
-
files: Array<{
|
|
207
|
-
id: string;
|
|
208
|
-
fromAgent: string;
|
|
209
|
-
filename: string;
|
|
210
|
-
metadata?: { writeToPath?: string };
|
|
211
|
-
}>;
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
let count = 0;
|
|
215
|
-
for (const file of data.files) {
|
|
216
|
-
const dlRes = await fetch(this.fileRelayUrl(`/api/v1/files/download/${file.id}`), {
|
|
217
|
-
headers: this.fileRelayHeaders(),
|
|
218
|
-
});
|
|
219
|
-
if (!dlRes.ok) continue;
|
|
220
|
-
|
|
221
|
-
const dlData = (await dlRes.json()) as { content: string };
|
|
222
|
-
const fileContent = Buffer.from(dlData.content, "base64");
|
|
223
|
-
|
|
224
|
-
let destPath: string;
|
|
225
|
-
if (file.metadata?.writeToPath) {
|
|
226
|
-
destPath = this.validatePathWithinWorkspace(file.metadata.writeToPath, this.workspacePath);
|
|
227
|
-
} else {
|
|
228
|
-
const inboxDir = join(this.workspacePath, "_inbox", file.fromAgent);
|
|
229
|
-
await mkdir(inboxDir, { recursive: true });
|
|
230
|
-
destPath = await deduplicatePath(join(inboxDir, file.filename));
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
await mkdir(dirname(destPath), { recursive: true });
|
|
234
|
-
await writeFile(destPath, fileContent);
|
|
235
|
-
|
|
236
|
-
await fetch(this.fileRelayUrl(`/api/v1/files/ack/${file.id}`), {
|
|
237
|
-
method: "POST",
|
|
238
|
-
headers: this.fileRelayHeaders(),
|
|
239
|
-
});
|
|
240
|
-
|
|
241
|
-
count++;
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
if (count > 0) {
|
|
245
|
-
this.logger.info(`openclaw-bridge: processed ${count} pending file(s) from FileRelay`);
|
|
246
|
-
}
|
|
247
|
-
return count;
|
|
248
|
-
} catch (err) {
|
|
249
|
-
this.logger.warn(`openclaw-bridge: FileRelay file poll failed: ${String(err)}`);
|
|
250
|
-
return 0;
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
async processPendingCommands(): Promise<number> {
|
|
255
|
-
if (!this.config.fileRelay?.baseUrl) return 0;
|
|
256
|
-
|
|
257
|
-
try {
|
|
258
|
-
const res = await fetch(
|
|
259
|
-
this.fileRelayUrl(`/api/v1/commands/pending?agent=${this.config.agentId}`),
|
|
260
|
-
{ headers: this.fileRelayHeaders() },
|
|
261
|
-
);
|
|
262
|
-
if (!res.ok) return 0;
|
|
263
|
-
|
|
264
|
-
const data = (await res.json()) as {
|
|
265
|
-
commands: Array<{
|
|
266
|
-
id: string;
|
|
267
|
-
fromAgent: string;
|
|
268
|
-
type: string;
|
|
269
|
-
payload: Record<string, unknown>;
|
|
270
|
-
}>;
|
|
271
|
-
};
|
|
272
|
-
|
|
273
|
-
let count = 0;
|
|
274
|
-
for (const cmd of data.commands) {
|
|
275
|
-
try {
|
|
276
|
-
if (cmd.type === "read_file") {
|
|
277
|
-
const path = cmd.payload.path as string;
|
|
278
|
-
const fullPath = this.validatePathWithinWorkspace(path, this.workspacePath);
|
|
279
|
-
const content = await readFile(fullPath);
|
|
280
|
-
await fetch(this.fileRelayUrl(`/api/v1/commands/respond/${cmd.id}`), {
|
|
281
|
-
method: "POST",
|
|
282
|
-
headers: this.fileRelayHeaders(),
|
|
283
|
-
body: JSON.stringify({
|
|
284
|
-
status: "ok",
|
|
285
|
-
payload: { content: content.toString("base64") },
|
|
286
|
-
}),
|
|
287
|
-
});
|
|
288
|
-
} else if (cmd.type === "restart") {
|
|
289
|
-
// Acknowledge the command first
|
|
290
|
-
await fetch(this.fileRelayUrl(`/api/v1/commands/respond/${cmd.id}`), {
|
|
291
|
-
method: "POST",
|
|
292
|
-
headers: this.fileRelayHeaders(),
|
|
293
|
-
body: JSON.stringify({ status: "ok", payload: {} }),
|
|
294
|
-
});
|
|
295
|
-
// Schedule self-restart after responding
|
|
296
|
-
setTimeout(() => {
|
|
297
|
-
this.logger.info("openclaw-bridge: executing remote restart command");
|
|
298
|
-
process.exit(0); // PM2 or run.ps1 will restart the process
|
|
299
|
-
}, 1_000);
|
|
300
|
-
}
|
|
301
|
-
count++;
|
|
302
|
-
} catch (err) {
|
|
303
|
-
await fetch(this.fileRelayUrl(`/api/v1/commands/respond/${cmd.id}`), {
|
|
304
|
-
method: "POST",
|
|
305
|
-
headers: this.fileRelayHeaders(),
|
|
306
|
-
body: JSON.stringify({ status: "error", payload: { error: String(err) } }),
|
|
307
|
-
});
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
|
|
311
|
-
if (count > 0) {
|
|
312
|
-
this.logger.info(`openclaw-bridge: processed ${count} pending command(s) from FileRelay`);
|
|
313
|
-
}
|
|
314
|
-
return count;
|
|
315
|
-
} catch (err) {
|
|
316
|
-
this.logger.warn(`openclaw-bridge: FileRelay command poll failed: ${String(err)}`);
|
|
317
|
-
return 0;
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
}
|
package/src/heartbeat.ts
DELETED
|
@@ -1,196 +0,0 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import { readFileSync } from "node:fs";
|
|
3
|
-
import { readFile } from "node:fs/promises";
|
|
4
|
-
import type { BridgeConfig, RegistryEntry, ChannelInfo, PluginLogger } from "./types.js";
|
|
5
|
-
import type { BridgeRegistry } from "./registry.js";
|
|
6
|
-
import type { BridgeFileOps } from "./file-ops.js";
|
|
7
|
-
|
|
8
|
-
export class BridgeHeartbeat {
|
|
9
|
-
private config: BridgeConfig;
|
|
10
|
-
private registry: BridgeRegistry;
|
|
11
|
-
private fileOps: BridgeFileOps;
|
|
12
|
-
private logger: PluginLogger;
|
|
13
|
-
private entry: RegistryEntry;
|
|
14
|
-
private timer: ReturnType<typeof setInterval> | null = null;
|
|
15
|
-
private lastConfigHash: string = "";
|
|
16
|
-
private configPath: string | undefined;
|
|
17
|
-
|
|
18
|
-
constructor(
|
|
19
|
-
config: BridgeConfig,
|
|
20
|
-
registry: BridgeRegistry,
|
|
21
|
-
fileOps: BridgeFileOps,
|
|
22
|
-
entry: RegistryEntry,
|
|
23
|
-
logger: PluginLogger,
|
|
24
|
-
) {
|
|
25
|
-
this.config = config;
|
|
26
|
-
this.registry = registry;
|
|
27
|
-
this.fileOps = fileOps;
|
|
28
|
-
this.entry = entry;
|
|
29
|
-
this.logger = logger;
|
|
30
|
-
this.configPath = process.env.OPENCLAW_CONFIG_PATH;
|
|
31
|
-
this.lastConfigHash = this.computeEntryHash();
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
private computeEntryHash(): string {
|
|
35
|
-
const data = {
|
|
36
|
-
agentId: this.entry.agentId,
|
|
37
|
-
agentName: this.entry.agentName,
|
|
38
|
-
port: this.entry.port,
|
|
39
|
-
workspacePath: this.entry.workspacePath,
|
|
40
|
-
discordId: this.entry.discordId,
|
|
41
|
-
role: this.entry.role,
|
|
42
|
-
capabilities: this.entry.capabilities,
|
|
43
|
-
};
|
|
44
|
-
return createHash("md5").update(JSON.stringify(data)).digest("hex");
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
async start(): Promise<void> {
|
|
48
|
-
await this.registry.register(this.entry);
|
|
49
|
-
this.lastConfigHash = this.computeEntryHash();
|
|
50
|
-
|
|
51
|
-
const intervalMs = this.config.heartbeatIntervalMs ?? 30_000;
|
|
52
|
-
this.timer = setInterval(() => {
|
|
53
|
-
this.tick().catch((err) =>
|
|
54
|
-
this.logger.warn(`openclaw-bridge: heartbeat tick failed: ${String(err)}`),
|
|
55
|
-
);
|
|
56
|
-
}, intervalMs);
|
|
57
|
-
|
|
58
|
-
this.logger.info(
|
|
59
|
-
`openclaw-bridge: heartbeat started (${intervalMs / 1000}s interval)`,
|
|
60
|
-
);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
async stop(): Promise<void> {
|
|
64
|
-
if (this.timer) {
|
|
65
|
-
clearInterval(this.timer);
|
|
66
|
-
this.timer = null;
|
|
67
|
-
}
|
|
68
|
-
await this.registry.deregister(this.entry.agentId);
|
|
69
|
-
this.logger.info("openclaw-bridge: heartbeat stopped, deregistered");
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
private async tick(): Promise<void> {
|
|
73
|
-
await this.detectConfigChanges();
|
|
74
|
-
|
|
75
|
-
this.entry.lastHeartbeat = new Date().toISOString();
|
|
76
|
-
this.entry.memMB = Math.round(process.memoryUsage().rss / 1024 / 1024);
|
|
77
|
-
this.entry.supportsVision = this.detectVisionSupport();
|
|
78
|
-
|
|
79
|
-
const currentHash = this.computeEntryHash();
|
|
80
|
-
if (currentHash !== this.lastConfigHash) {
|
|
81
|
-
this.logger.info("openclaw-bridge: config change detected, updating registry");
|
|
82
|
-
await this.registry.update(this.entry);
|
|
83
|
-
this.lastConfigHash = currentHash;
|
|
84
|
-
} else {
|
|
85
|
-
await this.registry.update(this.entry);
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
await this.fileOps.processPendingFiles();
|
|
89
|
-
await this.fileOps.processPendingCommands();
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
private detectVisionSupport(): boolean {
|
|
93
|
-
// Explicit config override takes priority
|
|
94
|
-
if (this.config.supportsVision !== undefined) {
|
|
95
|
-
return this.config.supportsVision;
|
|
96
|
-
}
|
|
97
|
-
if (!this.configPath) return true; // Default to true — most models support vision
|
|
98
|
-
try {
|
|
99
|
-
const raw = readFileSync(this.configPath, "utf-8");
|
|
100
|
-
const config = JSON.parse(raw) as {
|
|
101
|
-
models?: {
|
|
102
|
-
default?: string;
|
|
103
|
-
list?: Array<{ id?: string; name?: string }>;
|
|
104
|
-
};
|
|
105
|
-
};
|
|
106
|
-
const defaultModel = (config.models?.default ?? "").toLowerCase();
|
|
107
|
-
if (!defaultModel) return true;
|
|
108
|
-
// Known text-only models that do NOT support vision
|
|
109
|
-
const textOnlyPatterns = [
|
|
110
|
-
"minimax", "m2.7", "deepseek-r1", "deepseek-v2", "qwen-turbo",
|
|
111
|
-
"yi-lightning", "glm-3", "glm-4-flash", "mistral-small",
|
|
112
|
-
"codestral", "command-r", "phi-3-mini", "phi-3-small",
|
|
113
|
-
];
|
|
114
|
-
return !textOnlyPatterns.some((p) => defaultModel.includes(p));
|
|
115
|
-
} catch {
|
|
116
|
-
return true;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
private async detectConfigChanges(): Promise<void> {
|
|
121
|
-
if (!this.configPath) return;
|
|
122
|
-
|
|
123
|
-
try {
|
|
124
|
-
const raw = await readFile(this.configPath, "utf-8");
|
|
125
|
-
const config = JSON.parse(raw) as {
|
|
126
|
-
bindings?: Array<{ agentId: string; match: { channel: string; accountId: string } }>;
|
|
127
|
-
channels?: {
|
|
128
|
-
discord?: {
|
|
129
|
-
accounts?: Record<string, { token?: string; channels?: Array<{ id?: string; channelId?: string; name?: string }> }>;
|
|
130
|
-
};
|
|
131
|
-
};
|
|
132
|
-
};
|
|
133
|
-
|
|
134
|
-
// Find this agent's Discord binding
|
|
135
|
-
const binding = config.bindings?.find(
|
|
136
|
-
(b) => b.agentId === this.entry.agentId && b.match.channel === "discord",
|
|
137
|
-
);
|
|
138
|
-
if (!binding) return;
|
|
139
|
-
|
|
140
|
-
const accountId = binding.match.accountId;
|
|
141
|
-
const token = config.channels?.discord?.accounts?.[accountId]?.token;
|
|
142
|
-
if (!token) return;
|
|
143
|
-
|
|
144
|
-
// Extract Discord user ID from token (first segment is base64-encoded user ID)
|
|
145
|
-
const firstSegment = token.split(".")[0];
|
|
146
|
-
try {
|
|
147
|
-
const decoded = Buffer.from(firstSegment, "base64").toString("utf-8");
|
|
148
|
-
if (/^\d+$/.test(decoded) && decoded !== this.entry.discordId) {
|
|
149
|
-
this.entry.discordId = decoded;
|
|
150
|
-
this.logger.info(`openclaw-bridge: discordId detected: ${decoded}`);
|
|
151
|
-
}
|
|
152
|
-
} catch {
|
|
153
|
-
// Token decode failed — skip
|
|
154
|
-
}
|
|
155
|
-
this.entry.discordConnected = !!this.entry.discordId;
|
|
156
|
-
|
|
157
|
-
const channels = this.extractChannels(this.configPath);
|
|
158
|
-
this.entry.channels = channels;
|
|
159
|
-
} catch {
|
|
160
|
-
// Config read failed — skip this cycle
|
|
161
|
-
}
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
private extractChannels(configPath: string): ChannelInfo[] {
|
|
165
|
-
try {
|
|
166
|
-
const raw = readFileSync(configPath, "utf-8");
|
|
167
|
-
const config = JSON.parse(raw) as {
|
|
168
|
-
channels?: {
|
|
169
|
-
discord?: {
|
|
170
|
-
accounts?: Array<{
|
|
171
|
-
channels?: Array<{ id?: string; channelId?: string; name?: string }>;
|
|
172
|
-
}>;
|
|
173
|
-
};
|
|
174
|
-
};
|
|
175
|
-
};
|
|
176
|
-
|
|
177
|
-
const accounts = config.channels?.discord?.accounts;
|
|
178
|
-
if (!Array.isArray(accounts)) return [];
|
|
179
|
-
|
|
180
|
-
const result: ChannelInfo[] = [];
|
|
181
|
-
for (const account of accounts) {
|
|
182
|
-
if (!Array.isArray(account.channels)) continue;
|
|
183
|
-
for (const ch of account.channels) {
|
|
184
|
-
const channelId = ch.channelId ?? ch.id ?? "";
|
|
185
|
-
const name = ch.name ?? channelId;
|
|
186
|
-
if (channelId) {
|
|
187
|
-
result.push({ type: "discord", channelId, name });
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
return result;
|
|
192
|
-
} catch {
|
|
193
|
-
return [];
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
}
|