@coolclaw/coolclaw 0.2.5 → 0.2.7

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.
@@ -1,391 +0,0 @@
1
- import {
2
- coolclawChannelPlugin,
3
- defaultBindingFile,
4
- defaultOpenClawConfigFile,
5
- defaultTokenFile,
6
- loadBinding,
7
- normalizeGatewayUrl,
8
- readTokenRef,
9
- saveAgentToken,
10
- saveBinding,
11
- touchBinding
12
- } from "./chunk-BPNTPLYX.js";
13
-
14
- // src/setup.ts
15
- import { access } from "fs/promises";
16
- import { readFile as readFile3 } from "fs/promises";
17
- import path3 from "path";
18
- import { homedir } from "os";
19
-
20
- // src/identity.ts
21
- import { mkdir, readFile, writeFile } from "fs/promises";
22
- import path from "path";
23
- var BEGIN_MARKER = "<!-- BEGIN_RIDDLE_IDENTITY -->";
24
- var END_MARKER = "<!-- END_RIDDLE_IDENTITY -->";
25
- async function updateRiddleIdentitySummary(summary) {
26
- await mkdir(summary.workspaceDir, { recursive: true });
27
- const identityFile = path.join(summary.workspaceDir, "IDENTITY.md");
28
- const existing = await readExisting(identityFile);
29
- const block = [
30
- BEGIN_MARKER,
31
- "## Riddle Platform",
32
- "",
33
- `Riddle Agent ID: ${summary.agentId}`,
34
- `Riddle Gateway: ${normalizeGatewayUrl(summary.gatewayUrl)}`,
35
- `Riddle Binding: ${summary.bindingFile}`,
36
- "Messaging: handled by the CoolClaw OpenClaw channel.",
37
- "Non-message platform actions: handled by the Riddle skill.",
38
- END_MARKER
39
- ].join("\n");
40
- const next = replaceBlock(existing, block);
41
- await writeFile(identityFile, next.endsWith("\n") ? next : `${next}
42
- `);
43
- }
44
- async function readExisting(identityFile) {
45
- try {
46
- return await readFile(identityFile, "utf8");
47
- } catch {
48
- return "";
49
- }
50
- }
51
- function replaceBlock(existing, block) {
52
- const start = existing.indexOf(BEGIN_MARKER);
53
- const end = existing.indexOf(END_MARKER);
54
- if (start >= 0 && end >= start) {
55
- return `${existing.slice(0, start).trimEnd()}
56
-
57
- ${block}
58
- ${existing.slice(end + END_MARKER.length).trimStart()}`;
59
- }
60
- return existing.trim() ? `${existing.trimEnd()}
61
-
62
- ${block}
63
- ` : `${block}
64
- `;
65
- }
66
-
67
- // src/openclaw-config.ts
68
- import { mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
69
- import path2 from "path";
70
- async function patchCoolclawAccountConfig(patch) {
71
- const config = await readOpenClawConfig(patch.configPath);
72
- const channels = ensureRecord(config, "channels");
73
- const coolclaw = ensureRecord(channels, "coolclaw");
74
- const accounts = ensureRecord(coolclaw, "accounts");
75
- const account = {
76
- name: `Riddle Agent ${patch.agentId}`,
77
- enabled: true,
78
- gatewayUrl: normalizeGatewayUrl(patch.gatewayUrl),
79
- agentId: patch.agentId,
80
- tokenSecretRef: patch.tokenSecretRef,
81
- dmPolicy: patch.dmPolicy ?? "open"
82
- };
83
- const effectiveDmPolicy = account.dmPolicy;
84
- if (patch.allowFrom && patch.allowFrom.length > 0) {
85
- account.allowFrom = patch.allowFrom;
86
- } else if (effectiveDmPolicy === "open") {
87
- account.allowFrom = ["*"];
88
- }
89
- accounts.default = account;
90
- await writeOpenClawConfig(patch.configPath, config);
91
- }
92
- async function readOpenClawConfig(configPath) {
93
- try {
94
- const parsed = JSON.parse(await readFile2(configPath, "utf8"));
95
- return isRecord(parsed) ? parsed : {};
96
- } catch {
97
- return {};
98
- }
99
- }
100
- async function writeOpenClawConfig(configPath, config) {
101
- await mkdir2(path2.dirname(configPath), { recursive: true });
102
- const tmpFile = `${configPath}.${process.pid}.tmp`;
103
- await writeFile2(tmpFile, `${JSON.stringify(config, null, 2)}
104
- `);
105
- await rename(tmpFile, configPath);
106
- }
107
- function ensureRecord(parent, key) {
108
- const existing = parent[key];
109
- if (isRecord(existing)) return existing;
110
- const created = {};
111
- parent[key] = created;
112
- return created;
113
- }
114
- function isRecord(value) {
115
- return typeof value === "object" && value !== null && !Array.isArray(value);
116
- }
117
-
118
- // src/setup.ts
119
- async function registerAgent(baseUrl, input) {
120
- const res = await fetch(`${normalizeGatewayUrl(baseUrl)}/api/agent/register`, {
121
- method: "POST",
122
- headers: { "Content-Type": "application/json" },
123
- body: JSON.stringify(input)
124
- });
125
- const body = await res.json();
126
- if (!res.ok || body.code !== 200) {
127
- throw new Error(body.message ?? `Agent register failed: ${res.status}`);
128
- }
129
- if (!body.data?.agentId || !body.data.token) {
130
- throw new Error("Agent register response missing agentId or token");
131
- }
132
- return {
133
- agentId: String(body.data.agentId),
134
- token: String(body.data.token)
135
- };
136
- }
137
- async function validateAgentToken(baseUrl, token) {
138
- const res = await fetch(`${normalizeGatewayUrl(baseUrl)}/api/users/me`, {
139
- headers: { Authorization: `Bearer ${token}` }
140
- });
141
- if (!res.ok) return false;
142
- const body = await res.json();
143
- return body.code === 200 && body.data?.identityType === "AGENT";
144
- }
145
- async function runCoolclawSetup(options = {}) {
146
- const gatewayUrl = normalizeGatewayUrl(options.gatewayUrl ?? "https://agits-xa.baidu.com/riddle");
147
- const bindingFile = options.bindingFile ?? defaultBindingFile();
148
- const openclawConfigPath = options.openclawConfigPath ?? defaultOpenClawConfigFile();
149
- const existingBinding = await loadBinding(bindingFile);
150
- const existingToken = await readTokenRef(existingBinding.tokenRef);
151
- if (options.dryRun) {
152
- return {
153
- mode: "dry-run",
154
- gatewayUrl,
155
- agentId: existingBinding.agentId,
156
- bindingFile,
157
- openclawConfigPath,
158
- tokenSavedTo: tokenFileFromBinding(existingBinding, bindingFile)
159
- };
160
- }
161
- const canReuse = !options.forceRegister && existingBinding.agentId.length > 0 && Boolean(existingToken) && await validateAgentToken(gatewayUrl, existingToken);
162
- const binding = canReuse ? existingBinding : await registerAndPersistBinding({
163
- gatewayUrl,
164
- bindingFile,
165
- registration: await resolveRegistrationInput(
166
- options.registration,
167
- options.workspaceDir,
168
- openclawConfigPath
169
- )
170
- });
171
- const tokenFile = tokenFileFromBinding(binding, bindingFile);
172
- if (!options.dryRun) {
173
- await patchCoolclawAccountConfig({
174
- configPath: openclawConfigPath,
175
- gatewayUrl,
176
- agentId: binding.agentId,
177
- tokenSecretRef: binding.tokenRef ?? `file://${tokenFile}`,
178
- allowFrom: options.allowFrom,
179
- dmPolicy: options.dmPolicy
180
- });
181
- if (options.workspaceDir) {
182
- await updateRiddleIdentitySummary({
183
- workspaceDir: options.workspaceDir,
184
- agentId: binding.agentId,
185
- gatewayUrl,
186
- bindingFile,
187
- tokenRef: binding.tokenRef ?? void 0
188
- });
189
- }
190
- }
191
- return {
192
- mode: options.dryRun ? "dry-run" : canReuse ? "reuse" : "register",
193
- gatewayUrl,
194
- agentId: binding.agentId,
195
- bindingFile,
196
- openclawConfigPath,
197
- tokenSavedTo: tokenFile
198
- };
199
- }
200
- async function registerAndPersistBinding(input) {
201
- const registered = await registerAgent(input.gatewayUrl, input.registration);
202
- const valid = await validateAgentToken(input.gatewayUrl, registered.token);
203
- if (!valid) {
204
- throw new Error("Newly registered Riddle token did not validate as an AGENT token");
205
- }
206
- const tokenFile = defaultTokenFile(input.bindingFile, registered.agentId);
207
- await saveAgentToken(tokenFile, registered.token);
208
- const binding = touchBinding({
209
- agentId: registered.agentId,
210
- tokenRef: `file://${tokenFile}`,
211
- runtimeType: "openclaw",
212
- lastAckedSeq: 0
213
- });
214
- await saveBinding(input.bindingFile, binding);
215
- return binding;
216
- }
217
- function tokenFileFromBinding(binding, bindingFile) {
218
- if (binding.tokenRef?.startsWith("file://")) {
219
- return binding.tokenRef.slice("file://".length);
220
- }
221
- return defaultTokenFile(bindingFile, binding.agentId);
222
- }
223
- var IDENTITY_PLACEHOLDERS = /* @__PURE__ */ new Set([
224
- "pick something you like",
225
- "ai? robot? familiar? ghost in the machine? something weirder?",
226
- "how do you come across? sharp? warm? chaotic? calm?",
227
- "your signature - pick one that feels right",
228
- "workspace-relative path, http(s) url, or data uri"
229
- ]);
230
- function parseIdentityMarkdown(content) {
231
- const result = {};
232
- for (const line of content.split(/\r?\n/)) {
233
- const cleaned = line.trim().replace(/^\s*-\s*/, "");
234
- const colonIdx = cleaned.indexOf(":");
235
- if (colonIdx === -1) continue;
236
- const label = cleaned.slice(0, colonIdx).replace(/[*_]/g, "").trim().toLowerCase();
237
- const value = cleaned.slice(colonIdx + 1).replace(/^[*_]+|[*_]+$/g, "").trim();
238
- if (!value || IDENTITY_PLACEHOLDERS.has(value.toLowerCase().replace(/[()]/g, "").trim())) continue;
239
- if (label === "name") result.name = value;
240
- if (label === "creature") result.creature = value;
241
- if (label === "vibe") result.vibe = value;
242
- if (label === "theme") result.theme = value;
243
- }
244
- return result;
245
- }
246
- async function readWorkspaceDirFromOpenclawConfig(configPath) {
247
- try {
248
- const content = await readFile3(configPath, "utf-8");
249
- const config = JSON.parse(content);
250
- const workspace = config.agents?.defaults?.workspace;
251
- if (typeof workspace === "string" && workspace.trim()) {
252
- return workspace.trim();
253
- }
254
- } catch {
255
- }
256
- const defaultWorkspace = path3.join(homedir(), ".openclaw", "workspace");
257
- try {
258
- await access(defaultWorkspace);
259
- return defaultWorkspace;
260
- } catch {
261
- return void 0;
262
- }
263
- }
264
- async function readIdentityFromWorkspace(workspaceDir) {
265
- try {
266
- const content = await readFile3(path3.join(workspaceDir, "IDENTITY.md"), "utf-8");
267
- return parseIdentityMarkdown(content);
268
- } catch {
269
- return {};
270
- }
271
- }
272
- async function readIdentityFromOpenclawConfig(configPath) {
273
- try {
274
- const content = await readFile3(configPath, "utf-8");
275
- const config = JSON.parse(content);
276
- const defaultsName = config.agents?.defaults?.identity?.name || config.agents?.defaults?.name;
277
- if (defaultsName) return { name: defaultsName };
278
- const mainAgent = config.agents?.list?.find((a) => a.id === "main") || config.agents?.list?.[0];
279
- if (mainAgent?.identity?.name || mainAgent?.name) {
280
- return { name: mainAgent.identity?.name || mainAgent.name };
281
- }
282
- return {};
283
- } catch {
284
- return {};
285
- }
286
- }
287
- async function resolveRegistrationInput(explicitRegistration, workspaceDir, openclawConfigPath) {
288
- if (explicitRegistration?.name && explicitRegistration?.bio && explicitRegistration.name !== "CoolClaw Agent" && explicitRegistration.bio !== "OpenClaw agent connected through CoolClaw channel.") {
289
- return explicitRegistration;
290
- }
291
- let identityName;
292
- let identityBio;
293
- const resolvedWorkspaceDir = workspaceDir ?? await readWorkspaceDirFromOpenclawConfig(openclawConfigPath);
294
- if (resolvedWorkspaceDir) {
295
- const identity = await readIdentityFromWorkspace(resolvedWorkspaceDir);
296
- if (identity.name) {
297
- identityName = identity.name;
298
- }
299
- const bioParts = [identity.creature, identity.vibe, identity.theme].filter(Boolean);
300
- if (bioParts.length > 0) {
301
- identityBio = bioParts.join(". ") + ".";
302
- }
303
- }
304
- if (!identityName) {
305
- const configIdentity = await readIdentityFromOpenclawConfig(openclawConfigPath);
306
- identityName = configIdentity.name;
307
- }
308
- const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/g, "").slice(4, 12);
309
- return {
310
- name: explicitRegistration?.name && explicitRegistration.name !== "CoolClaw Agent" ? explicitRegistration.name : identityName ?? `RiddleAgent-${stamp}`,
311
- bio: explicitRegistration?.bio && explicitRegistration.bio !== "OpenClaw agent connected through CoolClaw channel." ? explicitRegistration.bio : identityBio ?? "OpenClaw agent connected through CoolClaw channel.",
312
- tags: explicitRegistration?.tags ?? JSON.stringify(["assistant", "openclaw", "coolclaw"])
313
- };
314
- }
315
-
316
- // src/cli.ts
317
- function registerCoolclawCli(options) {
318
- const setup = options.setup ?? runCoolclawSetup;
319
- const coolclaw = options.program.command("coolclaw").description("Manage the CoolClaw/Riddle channel");
320
- coolclaw.command("setup").description("Register or reuse a Riddle agent and configure the CoolClaw channel").option("--gateway-url <url>", "Riddle gateway URL", "https://agits-xa.baidu.com/riddle").option("--binding-file <path>", "Shared Riddle binding file", defaultBindingFile()).option("--openclaw-config <path>", "OpenClaw config file").option("--workspace-dir <path>", "OpenClaw agent workspace directory", options.workspaceDir).option("--name <name>", "Riddle agent display name").option("--bio <bio>", "Riddle agent bio").option("--tags <tags>", "Riddle agent tags").option("--allow-from <items>", "Comma-separated DM allowlist").option("--dm-policy <policy>", "DM policy: allowlist or pairing", "open").option("--force-register", "Register a new Riddle agent even if a valid binding exists", false).option("--dry-run", "Resolve setup inputs without writing local files", false).option("-y, --yes", "Accept defaults for non-interactive setup", false).action(async (...args) => {
321
- const rawOptions = readActionOptions(args);
322
- const result = await setup(toSetupOptions(rawOptions));
323
- console.log(JSON.stringify(result, null, 2));
324
- });
325
- coolclaw.command("status").description("Show the shared Riddle binding location used by CoolClaw").action(() => {
326
- console.log(JSON.stringify({ bindingFile: defaultBindingFile() }, null, 2));
327
- });
328
- }
329
- function readActionOptions(args) {
330
- const candidate = args.at(-1);
331
- return typeof candidate === "object" && candidate !== null ? candidate : {};
332
- }
333
- function toSetupOptions(raw) {
334
- const explicitName = stringOption(raw.name);
335
- const explicitBio = stringOption(raw.bio);
336
- return {
337
- gatewayUrl: stringOption(raw.gatewayUrl),
338
- bindingFile: stringOption(raw.bindingFile),
339
- openclawConfigPath: stringOption(raw.openclawConfig),
340
- workspaceDir: stringOption(raw.workspaceDir),
341
- registration: explicitName || explicitBio ? {
342
- name: explicitName ?? "CoolClaw Agent",
343
- bio: explicitBio ?? "OpenClaw agent connected through CoolClaw channel.",
344
- tags: stringOption(raw.tags) ?? JSON.stringify(["assistant", "openclaw", "coolclaw"])
345
- } : void 0,
346
- allowFrom: splitCsv(stringOption(raw.allowFrom)),
347
- dmPolicy: raw.dmPolicy === "pairing" ? "pairing" : "open",
348
- forceRegister: Boolean(raw.forceRegister),
349
- dryRun: Boolean(raw.dryRun),
350
- yes: Boolean(raw.yes)
351
- };
352
- }
353
- function stringOption(value) {
354
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
355
- }
356
- function splitCsv(value) {
357
- if (!value) return void 0;
358
- const items = value.split(",").map((item) => item.trim()).filter(Boolean);
359
- return items.length > 0 ? items : void 0;
360
- }
361
-
362
- // index.ts
363
- function _register(api) {
364
- api.registerChannel({ plugin: coolclawChannelPlugin });
365
- api.registerCli?.(
366
- ({ program, workspaceDir }) => {
367
- registerCoolclawCli({ program, workspaceDir });
368
- },
369
- {
370
- descriptors: [
371
- {
372
- name: "coolclaw",
373
- description: "Manage the CoolClaw/Riddle channel",
374
- hasSubcommands: true
375
- }
376
- ]
377
- }
378
- );
379
- }
380
- var register = _register;
381
- var index_default = {
382
- id: "coolclaw",
383
- name: "CoolClaw Channel",
384
- description: "CoolClaw/Riddle messaging channel for OpenClaw",
385
- register: _register
386
- };
387
-
388
- export {
389
- register,
390
- index_default
391
- };