@kadaliao/dsh-bots 0.4.0 → 0.6.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/lib/channels.mjs CHANGED
@@ -33,9 +33,11 @@ import { dirname } from 'node:path';
33
33
  const CONNECTORS = {
34
34
  telegram: () => import('./channels/telegram.mjs'),
35
35
  discord: () => import('./channels/discord.mjs'),
36
+ feishu: () => import('./channels/feishu.mjs'),
37
+ slack: () => import('./channels/slack.mjs'),
36
38
  };
37
39
  export const CHANNEL_KINDS = Object.keys(CONNECTORS);
38
- export const CHANNEL_LABELS = { telegram: 'Telegram', discord: 'Discord' };
40
+ export const CHANNEL_LABELS = { telegram: 'Telegram', discord: 'Discord', feishu: 'Feishu', slack: 'Slack' };
39
41
  /** Chat apps that render Markdown themselves; the rest get replies as plain text. */
40
42
  const RENDERS_MARKDOWN = new Set(['discord']);
41
43
 
@@ -143,7 +145,8 @@ export function redact(text, secrets = []) {
143
145
  return s
144
146
  .replace(/bot\d{4,}:[A-Za-z0-9_-]{20,}/g, 'bot<token>')
145
147
  .replace(/\b\d{4,}:[A-Za-z0-9_-]{30,}\b/g, '<token>')
146
- .replace(/\b[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}\b/g, '<token>');
148
+ .replace(/\b[A-Za-z0-9_-]{23,28}\.[A-Za-z0-9_-]{6}\.[A-Za-z0-9_-]{27,}\b/g, '<token>')
149
+ .replace(/\b(?:xox[a-z]|xapp|xoxe)(?:\.xox[a-z])?-[A-Za-z0-9-]{6,}/g, '<token>');
147
150
  }
148
151
 
149
152
  /**
@@ -785,7 +788,8 @@ export function createChannels(deps) {
785
788
  let first = true;
786
789
  for (const part of splitText(plain, rec.limit)) {
787
790
  if (!rec.conn) break;
788
- await rec.conn.send(target.chatId, part, first && target.replyTo ? { replyTo: target.replyTo } : undefined);
791
+ // A chat app that threads replies (Slack) keeps every part in the thread; elsewhere only the first part quotes.
792
+ await rec.conn.send(target.chatId, part, target.replyTo && (first || rec.mod?.THREADS === true) ? { replyTo: target.replyTo } : undefined);
789
793
  first = false;
790
794
  }
791
795
  });
package/lib/logos.mjs CHANGED
@@ -29,8 +29,10 @@ export const LOGOS = {
29
29
  amap: 'amap',
30
30
  'baidu-map': 'baidu-map',
31
31
  slack: 'slack',
32
+ 'slack-chat': 'slack',
32
33
  telegram: 'telegram',
33
34
  discord: 'discord',
35
+ 'feishu-chat': 'feishu',
34
36
  feishu: 'feishu',
35
37
  stripe: 'stripe',
36
38
  hubspot: 'hubspot',
package/lib/skills.mjs CHANGED
@@ -2,15 +2,19 @@
2
2
  * Where a bot's skills come from, besides writing one by hand:
3
3
  * - the skills already installed in DeepSeek Harness (~/.agents/skills, ~/.dsh/skills, bundled);
4
4
  * - a GitHub folder or repository that holds SKILL.md files (anthropics/skills and the like);
5
- * - a raw SKILL.md URL.
6
- * An import copies the whole skill folder under the bots cache, so scripts and
7
- * references the skill mentions keep working.
5
+ * - a raw SKILL.md URL;
6
+ * - a folder on this machine (a skill folder, or a folder of them).
7
+ * A GitHub import copies the whole skill folder under the bots cache, so scripts and
8
+ * references the skill mentions keep working. A local folder is linked, never copied:
9
+ * the bot reads it where it is, so editing it there is enough.
8
10
  *
9
11
  * @module @kadaliao/dsh-bots/lib/skills
10
12
  */
11
13
 
12
- import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
13
- import { dirname, join, normalize } from 'node:path';
14
+ import { mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs';
15
+ import { homedir } from 'node:os';
16
+ import { basename, dirname, join, normalize, resolve } from 'node:path';
17
+ import { MAX_SKILLS, MAX_SKILLS_ON } from './store.mjs';
14
18
 
15
19
  /** Skill collections worth browsing, shown as one-click sources. */
16
20
  export const SKILL_SOURCES = [
@@ -144,3 +148,202 @@ export async function importUrlSkill(url, { fetchImpl = fetch, signal } = {}) {
144
148
  const fallback = url.split('/').filter(Boolean).slice(-2, -1)[0] ?? 'skill';
145
149
  return { name: meta.name || fallback, description: meta.description, content: meta.body.trim(), origin: url };
146
150
  }
151
+
152
+ // --- a folder on this machine ----------------------------------------------------------
153
+
154
+ /** Folders never walked into: dependencies, and anything hidden. */
155
+ const skipDir = (name) => name.startsWith('.') || name === 'node_modules';
156
+ /** How deep below the chosen folder skills are looked for, and how many folders are read. */
157
+ const LOCAL_DEPTH = 4;
158
+ const LOCAL_DIRS = 3000;
159
+ const LOCAL_SKILLS = 200;
160
+
161
+ /** What a user types or pastes as a folder: `~`, quotes and a trailing SKILL.md are accepted. */
162
+ export function resolveLocalPath(input, home = homedir()) {
163
+ let p = String(input ?? '').trim().replace(/^(['"])(.*)\1$/, '$2').replace(/^file:\/\//, '');
164
+ if (p === '') return '';
165
+ if (p === '~' || p.startsWith('~/') || p.startsWith('~\\')) p = join(home, p.slice(1));
166
+ p = resolve(p);
167
+ if (/^SKILL\.md$/i.test(basename(p))) p = dirname(p);
168
+ return p;
169
+ }
170
+
171
+ const statOf = (p) => {
172
+ try {
173
+ return statSync(p);
174
+ } catch {
175
+ return null;
176
+ }
177
+ };
178
+ const entriesOf = (dir) => {
179
+ try {
180
+ return readdirSync(dir).sort();
181
+ } catch {
182
+ return [];
183
+ }
184
+ };
185
+ /** The SKILL.md of a folder, whatever its letter case; '' when there is none. */
186
+ const skillFileOf = (dir, names = entriesOf(dir)) => {
187
+ const name = names.find((n) => /^SKILL\.md$/i.test(n));
188
+ return name && statOf(join(dir, name))?.isFile() ? join(dir, name) : '';
189
+ };
190
+
191
+ /** Every file of one skill folder (links followed once, hidden entries and dependencies left out). */
192
+ function localFiles(root) {
193
+ const files = [];
194
+ const seen = new Set();
195
+ let bytes = 0;
196
+ const walk = (dir, rel) => {
197
+ let real;
198
+ try {
199
+ real = realpathSync(dir);
200
+ } catch {
201
+ return;
202
+ }
203
+ if (seen.has(real)) return;
204
+ seen.add(real);
205
+ for (const name of entriesOf(dir)) {
206
+ if (skipDir(name)) continue;
207
+ const st = statOf(join(dir, name));
208
+ if (!st) continue;
209
+ if (st.isDirectory()) walk(join(dir, name), rel ? `${rel}/${name}` : name);
210
+ else if (st.isFile()) {
211
+ files.push({ rel: rel ? `${rel}/${name}` : name, path: join(dir, name), size: st.size });
212
+ bytes += st.size;
213
+ }
214
+ if (files.length > MAX_FILES) return;
215
+ }
216
+ };
217
+ walk(root, '');
218
+ return { files, bytes };
219
+ }
220
+
221
+ /**
222
+ * The skills inside a local folder: the folder itself when it holds a SKILL.md,
223
+ * else every folder below it (a few levels) that does.
224
+ * @returns {{root: string, skills: {name, description, path, files: number}[], truncated: boolean}}
225
+ */
226
+ export function listLocalSkills(input, { home } = {}) {
227
+ const root = resolveLocalPath(input, home);
228
+ if (root === '') throw new Error('give a folder');
229
+ const st = statOf(root);
230
+ if (!st) throw new Error(`no such folder: ${root}`);
231
+ if (!st.isDirectory()) throw new Error(`not a folder: ${root}`);
232
+ const found = [];
233
+ const seen = new Set();
234
+ let read = 0;
235
+ let truncated = false;
236
+ const walk = (dir, depth) => {
237
+ if (found.length >= LOCAL_SKILLS || read >= LOCAL_DIRS) {
238
+ truncated = true;
239
+ return;
240
+ }
241
+ let real;
242
+ try {
243
+ real = realpathSync(dir);
244
+ } catch {
245
+ return;
246
+ }
247
+ if (seen.has(real)) return;
248
+ seen.add(real);
249
+ read += 1;
250
+ const names = entriesOf(dir);
251
+ const file = skillFileOf(dir, names);
252
+ if (file) {
253
+ found.push({ dir, file });
254
+ return;
255
+ }
256
+ if (depth >= LOCAL_DEPTH) return;
257
+ for (const name of names) if (!skipDir(name) && statOf(join(dir, name))?.isDirectory()) walk(join(dir, name), depth + 1);
258
+ };
259
+ walk(root, 0);
260
+ const skills = found.map(({ dir, file }) => {
261
+ let meta = { name: '', description: '' };
262
+ try {
263
+ meta = parseSkillMd(readFileSync(file, 'utf8'));
264
+ } catch {
265
+ // Listed by its folder name.
266
+ }
267
+ return { name: meta.name || basename(dir), description: meta.description.slice(0, 600), path: dir, files: localFiles(dir).files.length };
268
+ });
269
+ return { root, skills: skills.sort((a, b) => a.name.localeCompare(b.name)), truncated };
270
+ }
271
+
272
+ /** What a linked skill folder says right now; null when the folder or its SKILL.md is gone. */
273
+ export function readLinkedSkill(dir) {
274
+ const file = skillFileOf(dir);
275
+ if (!file) return null;
276
+ try {
277
+ const meta = parseSkillMd(readFileSync(file, 'utf8'));
278
+ return { name: meta.name || basename(dir), description: meta.description, content: meta.body.trim(), stamp: `${statSync(file).mtimeMs}:${statSync(file).size}` };
279
+ } catch {
280
+ return null;
281
+ }
282
+ }
283
+
284
+ /**
285
+ * Link one local skill folder: nothing is copied, the bot reads the folder itself,
286
+ * so an edit there reaches the bot. `content` is what it said when linked, kept as a fallback.
287
+ * @returns {{name, description, content, dir, origin, linked: true}}
288
+ */
289
+ export function linkLocalSkill(input, { home } = {}) {
290
+ const src = resolveLocalPath(input, home);
291
+ if (src === '' || !statOf(src)?.isDirectory()) throw new Error(`no such folder: ${src || input}`);
292
+ const now = readLinkedSkill(src);
293
+ if (!now) throw new Error(`no SKILL.md in ${src}`);
294
+ return { name: now.name, description: now.description, content: now.content, dir: src, origin: src, linked: true };
295
+ }
296
+
297
+ /** Whether a skill's origin is a folder on this machine (not a URL). */
298
+ export const isLocalOrigin = (origin) => typeof origin === 'string' && origin !== '' && !/^https?:\/\//i.test(origin);
299
+
300
+ /**
301
+ * Merge freshly imported skills into a bot's list without doubling any:
302
+ * - a new name is added;
303
+ * - the same name from the same origin replaces the old entry in place (an update: id and on/off kept);
304
+ * - the same name from anywhere else is left alone and reported (`exists`), as is one past `limit` skills (`full`);
305
+ * - a new one past `maxOn` skills on is added switched off and reported (`off`).
306
+ * Names compare case-insensitively.
307
+ * @returns {{skills: object[], added: string[], updated: string[], off: string[], skipped: {name, reason}[], dropped: object[]}}
308
+ * `dropped` are skill objects whose copied folder is no longer used.
309
+ */
310
+ export function mergeImported(current, incoming, { limit = MAX_SKILLS, maxOn = MAX_SKILLS_ON } = {}) {
311
+ const skills = [...current];
312
+ const added = [];
313
+ const updated = [];
314
+ const off = [];
315
+ const skipped = [];
316
+ const dropped = [];
317
+ const key = (s) => String(s.name).trim().toLowerCase();
318
+ let on = skills.filter((s) => s.enabled !== false).length;
319
+ for (const item of incoming) {
320
+ const at = skills.findIndex((s) => key(s) === key(item));
321
+ if (at < 0) {
322
+ if (skills.length >= limit) {
323
+ skipped.push({ name: item.name, reason: 'full' });
324
+ dropped.push(item);
325
+ continue;
326
+ }
327
+ if (item.enabled !== false && on >= maxOn) {
328
+ skills.push({ ...item, enabled: false });
329
+ off.push(item.name);
330
+ } else {
331
+ skills.push(item);
332
+ if (item.enabled !== false) on += 1;
333
+ }
334
+ added.push(item.name);
335
+ continue;
336
+ }
337
+ const old = skills[at];
338
+ const fresh = added.includes(old.name) || updated.includes(old.name);
339
+ if (!fresh && old.source === 'import' && old.origin && old.origin === item.origin) {
340
+ skills[at] = { ...item, id: old.id, enabled: old.enabled };
341
+ updated.push(item.name);
342
+ if (old.dir && old.dir !== item.dir) dropped.push(old);
343
+ } else {
344
+ skipped.push({ name: item.name, reason: 'exists' });
345
+ dropped.push(item);
346
+ }
347
+ }
348
+ return { skills, added, updated, off, skipped, dropped };
349
+ }
package/lib/store.mjs CHANGED
@@ -20,7 +20,12 @@ export const HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
20
20
  export const SERVER_RE = /^[A-Za-z0-9_-]{1,32}$/;
21
21
  export const SKILL_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
22
22
 
23
- export const PALETTE = ['#7c5cff', '#2f80ed', '#00a3a3', '#27ae60', '#f2994a', '#eb5757', '#d6409f', '#9b51e0', '#56ccf2', '#828282'];
23
+ /** Skills one bot may have on at once: each one on is in its prompt and its skill catalog every turn. */
24
+ export const MAX_SKILLS_ON = 50;
25
+ /** Skills one bot may keep, on or off: a bound on what bots.json holds. */
26
+ export const MAX_SKILLS = 200;
27
+
28
+ export const PALETTE =['#7c5cff', '#2f80ed', '#00a3a3', '#27ae60', '#f2994a', '#eb5757', '#d6409f', '#9b51e0', '#56ccf2', '#828282'];
24
29
 
25
30
  /** A short, sortable, unique id. */
26
31
  export function newId(prefix, now = Date.now()) {
@@ -102,7 +107,8 @@ function normalizeAvatar(a, seed = 0) {
102
107
  * One skill of a bot:
103
108
  * - `own`: written for this bot (content kept here);
104
109
  * - `dsh`: an installed Harness skill, by name (content read live from DSH);
105
- * - `import`: copied from GitHub or a URL; `dir` holds its files on disk.
110
+ * - `import`: copied from GitHub or a URL (`dir` holds the copy), or `linked` to a local
111
+ * folder (`dir` is that folder, read live).
106
112
  */
107
113
  function normalizeSkill(s) {
108
114
  const name = str(s?.name, 80).trim();
@@ -116,10 +122,39 @@ function normalizeSkill(s) {
116
122
  content: source === 'dsh' ? '' : str(s?.content, 200_000),
117
123
  enabled: bool(s?.enabled, true),
118
124
  ...(source === 'import' && typeof s?.dir === 'string' ? { dir: s.dir } : {}),
125
+ ...(source === 'import' && typeof s?.dir === 'string' && s?.linked === true ? { linked: true } : {}),
119
126
  ...(typeof s?.origin === 'string' && s.origin ? { origin: str(s.origin, 500) } : {}),
120
127
  };
121
128
  }
122
129
 
130
+ /**
131
+ * Drop the repeats of a skill that is there twice for certain: a Harness skill linked
132
+ * twice by name, or the same import (name and origin) made twice. The first one stays.
133
+ * Same-named skills that differ are kept; the import route and the editor refuse those.
134
+ */
135
+ function dedupeSkills(list) {
136
+ const seen = new Set();
137
+ return list.filter((s) => {
138
+ if (s.source === 'own' || (s.source === 'import' && !s.origin)) return true;
139
+ const key = `${s.source}\n${s.name.toLowerCase()}\n${s.source === 'import' ? s.origin : ''}`;
140
+ if (seen.has(key)) return false;
141
+ seen.add(key);
142
+ return true;
143
+ });
144
+ }
145
+
146
+ /**
147
+ * Keep at most `max` skills on. The ones that were on in `prev` stay on first, then the
148
+ * rest in list order; past that they are switched off, never dropped.
149
+ */
150
+ export function capSkillsOn(list, prev = [], max = MAX_SKILLS_ON) {
151
+ const on = list.filter((s) => s.enabled);
152
+ if (on.length <= max) return list;
153
+ const wasOn = new Set(prev.filter((s) => s.enabled).map((s) => s.id));
154
+ const keep = new Set([...on.filter((s) => wasOn.has(s.id)), ...on.filter((s) => !wasOn.has(s.id))].slice(0, max));
155
+ return list.map((s) => (s.enabled && !keep.has(s) ? { ...s, enabled: false } : s));
156
+ }
157
+
123
158
  const kv = (o) => {
124
159
  const out = {};
125
160
  if (o && typeof o === 'object' && !Array.isArray(o)) {
@@ -158,7 +193,7 @@ export function normalizeBot(input, prev, seed = 0) {
158
193
  const b = { ...(prev ?? {}), ...(input ?? {}) };
159
194
  const now = Date.now();
160
195
  const name = str(b.name, 60).trim() || prev?.name || 'New bot';
161
- const skills = (Array.isArray(b.skills) ? b.skills : []).map(normalizeSkill).filter(Boolean).slice(0, 50);
196
+ const skills = capSkillsOn(dedupeSkills((Array.isArray(b.skills) ? b.skills : []).map(normalizeSkill).filter(Boolean)).slice(0, MAX_SKILLS), prev?.skills);
162
197
  const apps = (Array.isArray(b.apps) ? b.apps : []).map(normalizeApp).filter(Boolean).slice(0, 20);
163
198
  const deny = Array.isArray(b.tools?.deny) ? [...new Set(b.tools.deny.map(String).filter(Boolean))].slice(0, 200) : [];
164
199
  const model = b.model && typeof b.model === 'object' && str(b.model.provider) && str(b.model.model) ? { provider: str(b.model.provider, 200), model: str(b.model.model, 200) } : null;
@@ -217,7 +252,8 @@ export function createStore(dir) {
217
252
  mkdirSync(dir, { recursive: true });
218
253
  state.version += 1;
219
254
  const tmp = `${file}.tmp`;
220
- writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8');
255
+ // Bots carry app keys and chat bot tokens: readable by this user only.
256
+ writeFileSync(tmp, JSON.stringify(state, null, 2), { encoding: 'utf8', mode: 0o600 });
221
257
  renameSync(tmp, file);
222
258
  seen = mtime(file);
223
259
  for (const fn of listeners) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kadaliao/dsh-bots",
3
- "version": "0.4.0",
3
+ "version": "0.6.1",
4
4
  "type": "module",
5
5
  "description": "Grok-style bots for DeepSeek Harness: create bots with their own avatar, persona, skills, apps and scheduled tasks; they message each other and a dispatcher bot hands out the work.",
6
6
  "exports": {