@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/index.js CHANGED
@@ -13,7 +13,7 @@
13
13
  * Nothing touches other conversations, except the bot tools themselves, which
14
14
  * every conversation gets so the user can manage bots from anywhere.
15
15
  *
16
- * Chat channel apps (Telegram, Discord) are no MCP servers: lib/channels.mjs
16
+ * Chat channel apps (Telegram, Discord, Feishu / Lark, Slack) are no MCP servers: lib/channels.mjs
17
17
  * keeps a connector running for each, so paired people can message the team
18
18
  * from that chat app and read the replies there.
19
19
  *
@@ -22,14 +22,14 @@
22
22
 
23
23
  import { createReadStream, existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
24
24
  import { homedir } from 'node:os';
25
- import { join } from 'node:path';
25
+ import { join, sep } from 'node:path';
26
26
  import { fileURLToPath } from 'node:url';
27
27
  import { randomUUID } from 'node:crypto';
28
28
 
29
- import { createStore, initialsOf, slugify, SKILL_RE, PALETTE } from './lib/store.mjs';
29
+ import { createStore, initialsOf, slugify, SKILL_RE, PALETTE, MAX_SKILLS, MAX_SKILLS_ON } from './lib/store.mjs';
30
30
  import { catalog as appCatalog, CATEGORIES, mcpConfigFor } from './lib/apps.mjs';
31
31
  import { ABILITIES } from './lib/abilities.mjs';
32
- import { SKILL_SOURCES, importGithubSkill, importUrlSkill, listGithubSkills, parseGithub } from './lib/skills.mjs';
32
+ import { SKILL_SOURCES, importGithubSkill, importUrlSkill, linkLocalSkill, listGithubSkills, listLocalSkills, mergeImported, parseGithub, readLinkedSkill, resolveLocalPath } from './lib/skills.mjs';
33
33
  import { TEAMS, teamTiming, teamView } from './lib/teams.mjs';
34
34
  import { maskedApp, scanExternalMcp } from './lib/mcp-import.mjs';
35
35
  import { createUnfurler } from './lib/unfurl.mjs';
@@ -215,7 +215,8 @@ export function apply(ctx, config, deps = {}) {
215
215
 
216
216
  const isChannel = (app) => Boolean(channelEntry(app, templates()));
217
217
  // Chat channels run outside the Agent; changing one does not restart the bot's MCP clients.
218
- const signatureOf = (bot) => JSON.stringify({ s: bot.skills, a: bot.apps.filter((a) => !isChannel(a)), t: bot.tools, h: bot.handle });
218
+ // A linked local skill counts by what its SKILL.md is now, so an edit there re-installs it.
219
+ const signatureOf = (bot) => JSON.stringify({ s: bot.skills, l: bot.skills.filter((s) => s.linked && s.enabled).map((s) => readLinkedSkill(s.dir)?.stamp ?? ''), a: bot.apps.filter((a) => !isChannel(a)), t: bot.tools, h: bot.handle });
219
220
  /** The chat apps the team can be reached from ('Telegram'), for the persona. */
220
221
  const channelNames = (bots) => {
221
222
  const tpl = templates();
@@ -250,7 +251,11 @@ export function apply(ctx, config, deps = {}) {
250
251
  const local = enabledSkills.filter((s) => s.source !== 'dsh');
251
252
  if (local.length > 0) {
252
253
  if (skills && typeof skills.register === 'function') {
253
- for (const s of local) {
254
+ for (const stored of local) {
255
+ // A linked folder speaks for itself; what was stored when it was linked stands in if it is gone.
256
+ const live = stored.linked ? readLinkedSkill(stored.dir) : null;
257
+ if (stored.linked && !live) ctx.logger?.warn?.(`bots: skill folder ${stored.dir} of @${bot.handle} is gone; using what was read when it was linked`);
258
+ const s = live ? { ...stored, description: live.description || stored.description, content: live.content } : stored;
254
259
  let n = slugify(s.name, 'skill');
255
260
  if (!SKILL_RE.test(n)) n = `skill-${s.id.slice(-5)}`;
256
261
  n = `${bot.handle}-${n}`.slice(0, 64).replace(/-+$/, '');
@@ -472,7 +477,7 @@ export function apply(ctx, config, deps = {}) {
472
477
  return agent.session.id;
473
478
  }
474
479
 
475
- // --- chat channels: Telegram, Discord -----------------------------------------------------
480
+ // --- chat channels: Telegram, Discord, Feishu / Lark, Slack -------------------------------
476
481
  const channels = createChannels({
477
482
  file: join(dir, 'channels.json'),
478
483
  bots: () => store.list(),
@@ -690,6 +695,15 @@ export function apply(ctx, config, deps = {}) {
690
695
  items: { type: 'object', additionalProperties: false, properties: { name: { type: 'string', required: true }, description: { type: 'string' }, content: { type: 'string', description: 'Markdown instructions the bot loads when the skill applies.' } } },
691
696
  };
692
697
  const card = (bot) => `@${bot.handle} — ${bot.name}${bot.role === 'primary' ? ' (dispatcher)' : ''}`;
698
+ const tooManySkills = (n) => {
699
+ if (n > MAX_SKILLS) throw new Error(`a bot keeps at most ${MAX_SKILLS} skills (this would make ${n}); remove some first`);
700
+ };
701
+ /** The tool-result sentence for skills asked on that the store had to leave off (past MAX_SKILLS_ON). */
702
+ const offNote = (asked, saved) => {
703
+ const names = new Set((asked ?? []).map((s) => String(s?.name ?? '').trim().toLowerCase()));
704
+ const off = saved.skills.filter((s) => !s.enabled && names.has(s.name.toLowerCase())).map((s) => s.name);
705
+ return off.length ? ` Added switched off, since at most ${MAX_SKILLS_ON} skills can be on at once: ${off.join(', ')}. To use them, remove skills it no longer needs (remove_skills) or ask the user to switch some off in Bots.` : '';
706
+ };
693
707
 
694
708
  const tools = [
695
709
  defineTool({
@@ -730,6 +744,7 @@ export function apply(ctx, config, deps = {}) {
730
744
  output: { schema: anyValue, render: (_a, v) => text(v.text), presentationMeta: (_a, v) => ({ bot: v.bot }) },
731
745
  execute: async (args, exec) => {
732
746
  const by = callerBot(exec);
747
+ tooManySkills((args.skills ?? []).length);
733
748
  const bot = store.save(
734
749
  {
735
750
  name: args.name,
@@ -741,7 +756,7 @@ export function apply(ctx, config, deps = {}) {
741
756
  },
742
757
  { createdBy: by?.id ?? 'user' },
743
758
  );
744
- return { ok: true, text: `Created ${card(bot)}. Message it with bot_send_message to @${bot.handle}.`, bot: face(bot) };
759
+ return { ok: true, text: `Created ${card(bot)}. Message it with bot_send_message to @${bot.handle}.${offNote(args.skills, bot)}`, bot: face(bot) };
745
760
  },
746
761
  }),
747
762
  defineTool({
@@ -754,7 +769,7 @@ export function apply(ctx, config, deps = {}) {
754
769
  persona: { type: 'string', description: 'Replaces the whole persona.' },
755
770
  initials: { type: 'string', description: 'Avatar letters, at most two.' },
756
771
  color: { type: 'string', description: 'Avatar background colour, CSS hex.' },
757
- add_skills: { ...skillInput, description: 'Skills to add (a skill with the same name is replaced).' },
772
+ add_skills: { ...skillInput, description: `Skills to add (a skill with the same name is replaced). At most ${MAX_SKILLS_ON} can be on at once; past that they are added switched off.` },
758
773
  remove_skills: { type: 'array', items: { type: 'string' }, description: 'Names of skills to remove.' },
759
774
  make_dispatcher: { type: 'boolean', description: 'true to make this bot the dispatcher.' },
760
775
  },
@@ -767,10 +782,11 @@ export function apply(ctx, config, deps = {}) {
767
782
  if (args.add_skills || args.remove_skills) {
768
783
  const drop = new Set([...(args.remove_skills ?? []), ...(args.add_skills ?? []).map((s) => s.name)].map((s) => String(s).toLowerCase()));
769
784
  next.skills = [...bot.skills.filter((s) => !drop.has(s.name.toLowerCase())), ...(args.add_skills ?? []).map((s) => ({ ...s, enabled: true }))];
785
+ tooManySkills(next.skills.length);
770
786
  }
771
787
  if (args.make_dispatcher === true) next.role = 'primary';
772
788
  const saved = store.save(next);
773
- return { ok: true, text: `Updated ${card(saved)}.`, bot: face(saved) };
789
+ return { ok: true, text: `Updated ${card(saved)}.${offNote(args.add_skills, saved)}`, bot: face(saved) };
774
790
  },
775
791
  }),
776
792
  defineTool({
@@ -969,28 +985,55 @@ export function apply(ctx, config, deps = {}) {
969
985
  appIssues[app.id] = error?.message ?? String(error);
970
986
  }
971
987
  }
972
- const skills = b.skills.map((s) => (s.source === 'dsh' && !s.description && dshSkillInfo.get(s.name) ? { ...s, description: dshSkillInfo.get(s.name) } : s));
988
+ const skills = b.skills.map((s) => {
989
+ if (s.source === 'dsh' && !s.description && dshSkillInfo.get(s.name)) return { ...s, description: dshSkillInfo.get(s.name) };
990
+ if (!s.linked) return s;
991
+ // A linked folder is shown as it is now, or flagged when it is gone.
992
+ const live = readLinkedSkill(s.dir);
993
+ return live ? { ...s, description: live.description || s.description, content: live.content } : { ...s, missing: true };
994
+ });
973
995
  return { ...publicBot(b), skills, status: botStatus(b), appIssues, channels: channels.view(b) };
974
996
  });
975
997
  const sessionMap = {};
976
998
  for (const b of bots) if (b.sessionId) sessionMap[b.sessionId] = b.id;
977
- return { bots, primaryId: store.primary()?.id ?? null, sessionMap, messageCount: store.messageCount(), version: store.version() };
999
+ return { bots, primaryId: store.primary()?.id ?? null, sessionMap, messageCount: store.messageCount(), version: store.version(), limits: { skills: MAX_SKILLS, skillsOn: MAX_SKILLS_ON } };
978
1000
  }
979
1001
 
980
1002
  let ocuInstalling = false;
981
1003
  // --- skills from elsewhere -------------------------------------------------------
982
1004
  const skillDir = join(dir, 'skills');
983
- /** Import one skill (GitHub folder or URL) as a bot skill object, files kept under the cache. */
1005
+ /** Import one skill (local folder, GitHub folder or URL) as a bot skill object, files kept under the cache. */
984
1006
  async function importSkill(spec) {
985
1007
  const signal = AbortSignal.timeout(120_000);
986
1008
  const id = `skill-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
1009
+ if (typeof spec.local === 'string' && spec.local.trim() !== '') return { id, source: 'import', enabled: true, ...linkLocalSkill(spec.local) };
987
1010
  const gh = spec.repo ? { ...parseGithub(spec.repo), ...(spec.path !== undefined ? { path: spec.path } : {}), ...(spec.ref ? { ref: spec.ref } : {}) } : parseGithub(spec.url ?? '');
988
1011
  if (gh) {
989
1012
  const got = await importGithubSkill(gh, skillDir, id, { signal });
990
1013
  return { id, source: 'import', enabled: true, ...got };
991
1014
  }
992
1015
  if (/^https?:\/\//.test(String(spec.url ?? ''))) return { id, source: 'import', enabled: true, ...(await importUrlSkill(spec.url, { signal })) };
993
- throw new Error('give a GitHub repository or folder (owner/repo/path) or a SKILL.md URL');
1016
+ throw new Error('give a local folder, a GitHub repository or folder (owner/repo/path) or a SKILL.md URL');
1017
+ }
1018
+ /** Remove copied skill folders nothing points at any more (only ever inside the bots cache). */
1019
+ function dropSkillDirs(skills) {
1020
+ const used = new Set(store.list().flatMap((b) => b.skills.map((s) => s.dir).filter(Boolean)));
1021
+ for (const s of skills) {
1022
+ if (typeof s.dir === 'string' && s.dir.startsWith(skillDir + sep) && !used.has(s.dir)) rmSync(s.dir, { recursive: true, force: true });
1023
+ }
1024
+ }
1025
+ /** Folders on this machine where other agents keep skills, as one-click starting points. */
1026
+ function localSkillPlaces() {
1027
+ const home = homedir();
1028
+ return [join(home, '.claude', 'skills'), join(home, '.codex', 'skills'), join(home, '.agents', 'skills')]
1029
+ .filter((p) => {
1030
+ try {
1031
+ return statSync(p).isDirectory();
1032
+ } catch {
1033
+ return false;
1034
+ }
1035
+ })
1036
+ .map((p) => ({ path: p, label: `~${p.slice(home.length)}` }));
994
1037
  }
995
1038
 
996
1039
  // --- teams -------------------------------------------------------------------------
@@ -1108,8 +1151,31 @@ export function apply(ctx, config, deps = {}) {
1108
1151
  failed.push({ spec, reason: error?.message ?? String(error) });
1109
1152
  }
1110
1153
  }
1111
- const saved = store.save({ id: bot.id, skills: [...store.get(bot.id).skills, ...added] });
1112
- return { ok: added.length > 0 || failed.length === 0, bot: publicBot(saved), added: added.map((x) => x.name), failed, ...(failed.length && !added.length ? { reason: failed[0].reason } : {}) };
1154
+ // No doubles: a name the bot already has is updated (same origin) or skipped, never added again.
1155
+ const merged = mergeImported(store.get(bot.id).skills, added);
1156
+ const changed = merged.added.length + merged.updated.length > 0;
1157
+ const saved = changed ? store.save({ id: bot.id, skills: merged.skills }) : store.get(bot.id);
1158
+ dropSkillDirs(merged.dropped);
1159
+ return {
1160
+ ok: changed || failed.length === 0,
1161
+ bot: publicBot(saved),
1162
+ added: merged.added,
1163
+ updated: merged.updated,
1164
+ off: merged.off,
1165
+ skipped: merged.skipped,
1166
+ failed,
1167
+ ...(failed.length && !changed ? { reason: failed[0].reason } : {}),
1168
+ };
1169
+ },
1170
+ },
1171
+ 'skills/local': {
1172
+ get: () => ({ places: localSkillPlaces() }),
1173
+ post: (body) => {
1174
+ try {
1175
+ return { ok: true, ...listLocalSkills(String(body.path ?? '')) };
1176
+ } catch (error) {
1177
+ return { ok: false, reason: error?.message ?? String(error), path: resolveLocalPath(String(body.path ?? '')) };
1178
+ }
1113
1179
  },
1114
1180
  },
1115
1181
  'skills/write': {
package/lib/apps.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The app catalog: MCP servers a bot can connect, each described well enough
3
3
  * that the panel shows a form (keys, paths) instead of a command line, and
4
- * chat channels (`kind: 'channel'`: Telegram, Discord) people message the team
4
+ * chat channels (`kind: 'channel'`: Telegram, Discord, Feishu / Lark, Slack) people message the team
5
5
  * from, which lib/channels.mjs runs instead of an MCP client.
6
6
  *
7
7
  * Every entry is checked against its registry (npm / PyPI) or vendor docs;
@@ -294,7 +294,7 @@ export function catalog(ocuPath = '') {
294
294
  },
295
295
  {
296
296
  id: 'slack',
297
- name: L('Slack', 'Slack'),
297
+ name: L('Slack workspace', 'Slack 工作区'),
298
298
  description: L('Read channels and threads, post messages and reactions in a Slack workspace.', '读取 Slack 频道与讨论串,发消息、加表情。'),
299
299
  category: 'work',
300
300
  icon: 'SL',
@@ -367,6 +367,87 @@ export function catalog(ocuPath = '') {
367
367
  },
368
368
  ],
369
369
  },
370
+ {
371
+ id: 'feishu-chat',
372
+ kind: 'channel',
373
+ channel: 'feishu',
374
+ name: L('Feishu / Lark', '飞书'),
375
+ description: L(
376
+ 'Message your bot team from Feishu or Lark: chat with the bot one to one, or @ it in a group. Only people you pair can talk to it.',
377
+ '在飞书里给 Bot 团队发消息:和机器人单聊,或在群里 @ 它。只有你配对过的人能和它说话。',
378
+ ),
379
+ category: 'work',
380
+ icon: '飞',
381
+ color: '#3370ff',
382
+ serverName: 'feishu-chat',
383
+ homepage: 'https://open.feishu.cn/document/server-docs/event-subscription-guide/event-subscription-configure-/request-url-configuration-case',
384
+ keyUrl: 'https://open.feishu.cn/app',
385
+ featured: true,
386
+ fields: [
387
+ {
388
+ key: 'appId',
389
+ kind: 'text',
390
+ required: true,
391
+ label: L('App ID', 'App ID'),
392
+ placeholder: 'cli_…',
393
+ help: L(
394
+ 'Developer console (open.feishu.cn/app; for Lark open.larksuite.com/app) → Create Custom App. Add Features → Bot. Permissions & Scopes: add im:message.p2p_msg:readonly, im:message.group_at_msg:readonly and im:message:send_as_bot (optional: contact:contact.base:readonly and contact:user.base:readonly for names, im:message.reactions:write_only for a typing sign, im:chat:readonly for group names). Copy the App ID and App Secret from Credentials & Basic Info and save. Then, with this channel running (the console only accepts it while it is online), Events & Callbacks → subscription mode "Receive events through persistent connection" → save, add the event im.message.receive_v1, and publish a version. Use an app made for this team only.',
395
+ '开发者后台(open.feishu.cn/app;Lark 用 open.larksuite.com/app)→ 创建企业自建应用 → 添加应用能力「机器人」。在「权限管理」开通 im:message.p2p_msg:readonly、im:message.group_at_msg:readonly、im:message:send_as_bot(可选:contact:contact.base:readonly 和 contact:user.base:readonly 显示姓名,im:message.reactions:write_only 显示"正在处理",im:chat:readonly 显示群名)。到「凭证与基础信息」复制 App ID 和 App Secret 填到这里并保存。保存后保持这个频道运行(长连接在线时后台才允许保存),再到「事件与回调」把订阅方式设为「使用长连接接收事件」并保存,添加事件 im.message.receive_v1,最后在「版本管理与发布」发布版本。请用专门给这个团队新建的应用。',
396
+ ),
397
+ },
398
+ {
399
+ key: 'appSecret',
400
+ kind: 'secret',
401
+ required: true,
402
+ label: L('App secret', 'App Secret'),
403
+ help: L(
404
+ 'In Credentials & Basic Info, next to the App ID. If another program already uses this app, Feishu hands each message to only one of them.',
405
+ '在「凭证与基础信息」里,App ID 旁边。如果别的程序也在用这个应用,飞书每条消息只会交给其中一个。',
406
+ ),
407
+ },
408
+ ],
409
+ },
410
+ {
411
+ id: 'slack-chat',
412
+ kind: 'channel',
413
+ channel: 'slack',
414
+ name: L('Slack', 'Slack'),
415
+ description: L(
416
+ 'Message your bot team from Slack: DM the app, or @mention it in a channel. Only people you pair can talk to it.',
417
+ '在 Slack 里给 Bot 团队发消息:私信这个应用,或在频道里 @ 它。只有你配对过的人能和它说话。',
418
+ ),
419
+ category: 'work',
420
+ icon: 'SL',
421
+ color: '#4a154b',
422
+ serverName: 'slack-chat',
423
+ homepage: 'https://docs.slack.dev/apis/events-api/using-socket-mode',
424
+ keyUrl: 'https://api.slack.com/apps',
425
+ featured: true,
426
+ fields: [
427
+ {
428
+ key: 'token',
429
+ kind: 'secret',
430
+ required: true,
431
+ label: L('Bot token', 'Bot Token'),
432
+ placeholder: 'xoxb-…',
433
+ help: L(
434
+ 'At api.slack.com/apps choose Create New App → From a manifest and paste the manifest from the Bots README (it turns on Socket Mode, DMs and the permissions). Then Install App → Install to Workspace, and copy the Bot User OAuth Token. Use an app made for this team only.',
435
+ '在 api.slack.com/apps 选 Create New App → From a manifest,粘贴 Bots README 里的清单(它会打开 Socket Mode、私信和所需权限)。再点 Install App → Install to Workspace,复制 Bot User OAuth Token。请用专门给这个团队新建的应用。',
436
+ ),
437
+ },
438
+ {
439
+ key: 'appToken',
440
+ kind: 'secret',
441
+ required: true,
442
+ label: L('App-level token', 'App 级 Token'),
443
+ placeholder: 'xapp-…',
444
+ help: L(
445
+ 'Same app → Basic Information → App-Level Tokens → Generate Token and Scopes: add the connections:write scope, generate, and copy the token. With it the Harness connects out to Slack, so no public URL is needed.',
446
+ '同一个应用 → Basic Information → App-Level Tokens → Generate Token and Scopes:添加 connections:write 权限,生成后复制 Token。有了它 Harness 主动连到 Slack,不需要公网地址。',
447
+ ),
448
+ },
449
+ ],
450
+ },
370
451
  {
371
452
  id: 'stripe',
372
453
  name: L('Stripe', 'Stripe 收款'),
@@ -400,7 +481,7 @@ export function catalog(ocuPath = '') {
400
481
  },
401
482
  {
402
483
  id: 'feishu',
403
- name: L('Feishu / Lark', '飞书'),
484
+ name: L('Feishu / Lark Open Platform', '飞书开放平台'),
404
485
  description: L('Feishu docs, Bitable, messages, calendars and contacts through the official Open Platform server.', '官方开放平台服务:飞书文档、多维表格、消息、日历与通讯录。'),
405
486
  category: 'work',
406
487
  icon: '飞',
@@ -476,7 +557,7 @@ export function catalog(ocuPath = '') {
476
557
  */
477
558
  export function mcpConfigFor(app, entries, ctx = {}) {
478
559
  const t = entries.find((e) => e.id === app.template);
479
- // A chat channel (Telegram, Discord) is no MCP server: lib/channels.mjs runs it.
560
+ // A chat channel (Telegram, Discord, Feishu, Slack) is no MCP server: lib/channels.mjs runs it.
480
561
  if (t?.kind === 'channel') return null;
481
562
  const values = app.values && typeof app.values === 'object' ? app.values : {};
482
563
  const reconnect = { maxAttempts: 3 };