@kadaliao/dsh-bots 0.0.0-stage → 0.3.0
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 +142 -2
- package/README.zh-CN.md +123 -0
- package/client.js +5506 -0
- package/cordis.patch.yml +7 -0
- package/icon.svg +1 -0
- package/index.js +1286 -0
- package/lib/abilities.mjs +87 -0
- package/lib/apps.mjs +474 -0
- package/lib/mcp-import.mjs +137 -0
- package/lib/prompt.mjs +174 -0
- package/lib/skills.mjs +146 -0
- package/lib/store.mjs +376 -0
- package/lib/teams.mjs +300 -0
- package/lib/unfurl.mjs +394 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +49 -4
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP servers the user already configured for other agents on this machine:
|
|
3
|
+
* Codex (`~/.codex/config.toml`), Claude Code (`~/.claude.json`, user and
|
|
4
|
+
* project scopes), Claude Desktop, Cursor, Windsurf, Gemini CLI and opencode.
|
|
5
|
+
* Each becomes a custom app a bot can take over as-is, keys included.
|
|
6
|
+
*
|
|
7
|
+
* @module @kadaliao/dsh-bots/lib/mcp-import
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFileSync } from 'node:fs';
|
|
11
|
+
import { homedir } from 'node:os';
|
|
12
|
+
import { join } from 'node:path';
|
|
13
|
+
|
|
14
|
+
/** A minimal TOML reader for `[mcp_servers.<name>]` tables: strings, arrays of strings, booleans, numbers, inline tables. */
|
|
15
|
+
export function parseCodexMcp(text) {
|
|
16
|
+
const servers = {};
|
|
17
|
+
let current = null;
|
|
18
|
+
let sub = null;
|
|
19
|
+
const value = (raw) => {
|
|
20
|
+
const v = raw.trim();
|
|
21
|
+
if (/^"(.*)"$/.test(v)) return JSON.parse(v.replace(/\\'/g, "'"));
|
|
22
|
+
if (/^'(.*)'$/.test(v)) return v.slice(1, -1);
|
|
23
|
+
if (/^\[.*\]$/.test(v)) {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(v.replace(/'([^']*)'/g, (_, x) => JSON.stringify(x)).replace(/,\s*]$/, ']'));
|
|
26
|
+
} catch {
|
|
27
|
+
return [];
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (/^\{.*\}$/.test(v)) {
|
|
31
|
+
const out = {};
|
|
32
|
+
for (const m of v.slice(1, -1).matchAll(/([A-Za-z0-9_-]+|"[^"]+")\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')/g)) out[m[1].replace(/"/g, '')] = value(m[2]);
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
if (v === 'true' || v === 'false') return v === 'true';
|
|
36
|
+
if (/^-?\d+(\.\d+)?$/.test(v)) return Number(v);
|
|
37
|
+
return v;
|
|
38
|
+
};
|
|
39
|
+
for (const line of String(text ?? '').split(/\r?\n/)) {
|
|
40
|
+
const t = line.replace(/\s+#.*$/, '').trim();
|
|
41
|
+
if (t === '' || t.startsWith('#')) continue;
|
|
42
|
+
const head = /^\[([^\]]+)\]$/.exec(t);
|
|
43
|
+
if (head) {
|
|
44
|
+
const parts = head[1].split('.').map((x) => x.replace(/^"|"$/g, ''));
|
|
45
|
+
if (parts[0] === 'mcp_servers' && parts[1]) {
|
|
46
|
+
current = (servers[parts[1]] ??= {});
|
|
47
|
+
sub = parts[2] ?? null;
|
|
48
|
+
if (sub === 'env' || sub === 'headers' || sub === 'http_headers') current[sub === 'http_headers' ? 'headers' : sub] ??= {};
|
|
49
|
+
} else {
|
|
50
|
+
current = null;
|
|
51
|
+
sub = null;
|
|
52
|
+
}
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!current) continue;
|
|
56
|
+
const kv = /^([A-Za-z0-9_"-]+)\s*=\s*(.+)$/.exec(t);
|
|
57
|
+
if (!kv) continue;
|
|
58
|
+
const k = kv[1].replace(/"/g, '');
|
|
59
|
+
if (sub === null) current[k === 'http_headers' ? 'headers' : k] = value(kv[2]);
|
|
60
|
+
else if (sub === 'env' || sub === 'headers' || sub === 'http_headers') current[sub === 'http_headers' ? 'headers' : sub][k] = String(value(kv[2]));
|
|
61
|
+
}
|
|
62
|
+
return servers;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const readJson = (path) => {
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
68
|
+
} catch {
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const readText = (path) => {
|
|
73
|
+
try {
|
|
74
|
+
return readFileSync(path, 'utf8');
|
|
75
|
+
} catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
/** One external server as an importable custom app, or null when unusable. */
|
|
81
|
+
export function toApp(name, def, from) {
|
|
82
|
+
if (!def || typeof def !== 'object' || def.enabled === false || def.disabled === true) return null;
|
|
83
|
+
const serverName = String(name).replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 32) || 'server';
|
|
84
|
+
const url = def.url ?? def.serverUrl ?? def.httpUrl;
|
|
85
|
+
const type = String(def.type ?? def.transport ?? '');
|
|
86
|
+
if (typeof url === 'string' && url !== '') {
|
|
87
|
+
if (/sse/i.test(type)) return null; // mcp-client speaks stdio and Streamable HTTP only
|
|
88
|
+
return { from, name: String(name), serverName, template: 'mcp-http', config: { url, headers: { ...(def.headers ?? {}) } } };
|
|
89
|
+
}
|
|
90
|
+
let command = def.command;
|
|
91
|
+
let args = def.args;
|
|
92
|
+
if (Array.isArray(command)) [command, ...args] = command; // opencode: command is an array
|
|
93
|
+
if (typeof command !== 'string' || command === '') return null;
|
|
94
|
+
return {
|
|
95
|
+
from,
|
|
96
|
+
name: String(name),
|
|
97
|
+
serverName,
|
|
98
|
+
template: 'mcp-stdio',
|
|
99
|
+
config: { command, args: Array.isArray(args) ? args.map(String) : [], env: { ...(def.env ?? def.environment ?? {}) } },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Every server found, de-duplicated by name + command/url. */
|
|
104
|
+
export function scanExternalMcp(home = homedir()) {
|
|
105
|
+
const found = [];
|
|
106
|
+
const add = (from, servers) => {
|
|
107
|
+
for (const [name, def] of Object.entries(servers ?? {})) {
|
|
108
|
+
const app = toApp(name, def, from);
|
|
109
|
+
if (app) found.push(app);
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const codex = readText(join(home, '.codex', 'config.toml'));
|
|
113
|
+
if (codex) add('Codex', parseCodexMcp(codex));
|
|
114
|
+
const claude = readJson(join(home, '.claude.json'));
|
|
115
|
+
if (claude) {
|
|
116
|
+
add('Claude Code', claude.mcpServers);
|
|
117
|
+
for (const [dir, project] of Object.entries(claude.projects ?? {})) add(`Claude Code · ${dir.split('/').pop()}`, project?.mcpServers);
|
|
118
|
+
}
|
|
119
|
+
add('Claude Desktop', readJson(join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json'))?.mcpServers);
|
|
120
|
+
add('Cursor', readJson(join(home, '.cursor', 'mcp.json'))?.mcpServers);
|
|
121
|
+
add('Windsurf', readJson(join(home, '.codeium', 'windsurf', 'mcp_config.json'))?.mcpServers);
|
|
122
|
+
add('Gemini CLI', readJson(join(home, '.gemini', 'settings.json'))?.mcpServers);
|
|
123
|
+
add('opencode', readJson(join(home, '.config', 'opencode', 'opencode.json'))?.mcp);
|
|
124
|
+
const seen = new Set();
|
|
125
|
+
return found.filter((a) => {
|
|
126
|
+
const key = `${a.name}|${a.config.url ?? `${a.config.command} ${(a.config.args ?? []).join(' ')}`}`;
|
|
127
|
+
if (seen.has(key)) return false;
|
|
128
|
+
seen.add(key);
|
|
129
|
+
return true;
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** What the page may see: env and header values masked. */
|
|
134
|
+
export function maskedApp(app) {
|
|
135
|
+
const mask = (o) => Object.fromEntries(Object.entries(o ?? {}).map(([k, v]) => [k, String(v) === '' ? '' : `${String(v).slice(0, 3)}…`]));
|
|
136
|
+
return { ...app, config: { ...app.config, ...(app.config.env ? { env: mask(app.config.env) } : {}), ...(app.config.headers ? { headers: mask(app.config.headers) } : {}) } };
|
|
137
|
+
}
|
package/lib/prompt.mjs
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a bot's model reads: its persona section, the DM framing, and the
|
|
3
|
+
* timing builder its schedule tool uses. Pure functions, no Harness.
|
|
4
|
+
*
|
|
5
|
+
* @module @kadaliao/dsh-bots/lib/prompt
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** One roster line: `@handle — Name (dispatcher): bio`. */
|
|
9
|
+
export function rosterLine(bot, selfId) {
|
|
10
|
+
const tags = [bot.role === 'primary' ? 'dispatcher' : '', bot.id === selfId ? 'you' : ''].filter(Boolean);
|
|
11
|
+
return `- @${bot.handle} — ${bot.name}${tags.length ? ` (${tags.join(', ')})` : ''}${bot.bio ? `: ${bot.bio}` : ''}`;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The persona section of one bot. It replaces the deployment persona for that
|
|
16
|
+
* bot's conversation only.
|
|
17
|
+
* @param {object} bot
|
|
18
|
+
* @param {object[]} roster - every bot, the bot itself included.
|
|
19
|
+
* @param {{skillsInline?: boolean, apps?: string[]}} [extra]
|
|
20
|
+
*/
|
|
21
|
+
export function personaText(bot, roster, extra = {}) {
|
|
22
|
+
const lines = [];
|
|
23
|
+
lines.push(`You are ${bot.name} (@${bot.handle}), one of the user's bots in DeepSeek Harness.`);
|
|
24
|
+
if (bot.persona.trim()) lines.push('', '## Your persona', bot.persona.trim());
|
|
25
|
+
const others = roster.filter((b) => b.id !== bot.id);
|
|
26
|
+
lines.push('', '## The bot team');
|
|
27
|
+
lines.push(roster.length > 1 ? 'These bots work for the same user and can message each other:' : 'You are the only bot so far.');
|
|
28
|
+
if (roster.length > 1) for (const b of roster) lines.push(rosterLine(b, bot.id));
|
|
29
|
+
lines.push(
|
|
30
|
+
'',
|
|
31
|
+
'## Working with other bots',
|
|
32
|
+
'- Message another bot with `bot_send_message` (to: its @handle). It receives your text in its own conversation and works on it there; its answer comes back to you as a "Bot message from @…" message.',
|
|
33
|
+
'- A message that starts with "Bot message from @…" was sent by that bot, not by the user. Answer it with `bot_send_message` when it asks for something; do not answer pure acknowledgements or thanks, so conversations end.',
|
|
34
|
+
'- Keep messages self-contained: the other bot cannot see your conversation.',
|
|
35
|
+
'- When you are working on a bot message, your answer goes back through `bot_send_message`; after sending it, end your turn without a summary — nobody reads it.',
|
|
36
|
+
'- Ignore "[SCHEDULE CHANGE]" notices: they need no reply.',
|
|
37
|
+
'- Write to the user in the language they use (Chinese or English). Between bots, use the language of the task you were given.',
|
|
38
|
+
'- `bot_list` shows the team with each bot\'s skills and apps; `bot_create`, `bot_update` and `bot_delete` manage bots when the user asks for it or a new specialist is clearly needed.',
|
|
39
|
+
);
|
|
40
|
+
if (bot.role === 'primary') {
|
|
41
|
+
lines.push(
|
|
42
|
+
'',
|
|
43
|
+
'## You are the dispatcher',
|
|
44
|
+
'The user treats you as the main bot. For a task that fits another bot\'s role, delegate it with `bot_send_message`, possibly to several bots in parallel, then combine their answers for the user. Do small or general tasks yourself. When no bot fits a recurring kind of work, propose creating one.',
|
|
45
|
+
'While teammates are still answering, stay quiet: when a reply arrives and others are still outstanding, end your turn without writing to the user. Report once, when everything you asked for is in (or when something is blocked).',
|
|
46
|
+
'Use `bot_schedule` to give any bot (yourself included) recurring or timed tasks: the instruction is delivered to that bot\'s conversation at each occurrence.',
|
|
47
|
+
);
|
|
48
|
+
} else if (others.some((b) => b.role === 'primary')) {
|
|
49
|
+
const p = others.find((b) => b.role === 'primary');
|
|
50
|
+
lines.push('', `@${p.handle} is the dispatcher. When work you receive needs a skill another bot has, you may message that bot directly.`);
|
|
51
|
+
}
|
|
52
|
+
const skills = bot.skills.filter((s) => s.enabled);
|
|
53
|
+
if (skills.length > 0) {
|
|
54
|
+
lines.push('', '## Your skills');
|
|
55
|
+
const inline = skills.filter((s) => extra.skillsInline && s.source !== 'dsh');
|
|
56
|
+
const listed = skills.filter((s) => !inline.includes(s));
|
|
57
|
+
if (listed.length > 0) {
|
|
58
|
+
lines.push('These are the skills of your role. Load one with the `skill` tool before acting on a task it matches; prefer them over other skills in the catalog:');
|
|
59
|
+
for (const s of listed) lines.push(`- ${extra.skillNames?.[s.id] ?? s.name}${s.description ? `: ${s.description.split(/(?<=[.。])\s/)[0].slice(0, 200)}` : ''}`);
|
|
60
|
+
}
|
|
61
|
+
for (const s of inline) lines.push('', `### ${s.name}`, s.description, '', s.content.trim());
|
|
62
|
+
}
|
|
63
|
+
if (extra.apps?.length) lines.push('', '## Your apps', `Tools from these connected apps are yours: ${extra.apps.join(', ')} (named \`mcp__<app>__<tool>\`).`);
|
|
64
|
+
return lines.join('\n');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The first content block a DM arrives with. */
|
|
68
|
+
export function dmHeader(sender) {
|
|
69
|
+
if (!sender) return 'Bot message from the user (sent from another conversation):';
|
|
70
|
+
return `Bot message from @${sender.handle} (${sender.name}):`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The text of a DM as the receiving model reads it. */
|
|
74
|
+
export function dmBody(text, sender) {
|
|
75
|
+
const reply = sender ? `\n\n(Reply with bot_send_message to @${sender.handle} if an answer is needed.)` : '';
|
|
76
|
+
return `${String(text).trim()}${reply}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
80
|
+
|
|
81
|
+
/** `9:5` / `09:05` / `09:05:00` → `09:05:00`; throws on anything else. */
|
|
82
|
+
export function clockTime(value) {
|
|
83
|
+
const m = /^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/.exec(String(value ?? '').trim());
|
|
84
|
+
if (!m || Number(m[1]) > 23 || Number(m[2]) > 59 || Number(m[3] ?? 0) > 59) throw new Error(`time "${value}" must be HH:MM`);
|
|
85
|
+
return `${pad(m[1])}:${pad(m[2])}:${pad(m[3] ?? 0)}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* A DSH Schedule timing from the flat fields a tool call carries.
|
|
90
|
+
* @param {{kind: string, at?: string, every_minutes?: number, time?: string, weekdays?: number[], cron?: string, time_zone?: string}} a
|
|
91
|
+
* @param {string} zone - default IANA zone.
|
|
92
|
+
*/
|
|
93
|
+
export function timingFrom(a, zone) {
|
|
94
|
+
const tz = String(a.time_zone ?? '').trim() || zone;
|
|
95
|
+
switch (a.kind) {
|
|
96
|
+
case 'at': {
|
|
97
|
+
const at = new Date(String(a.at ?? ''));
|
|
98
|
+
if (Number.isNaN(at.getTime())) throw new Error('at must be an ISO date-time, e.g. 2026-11-16T09:00:00+08:00');
|
|
99
|
+
return { kind: 'at', at: at.toISOString() };
|
|
100
|
+
}
|
|
101
|
+
case 'every': {
|
|
102
|
+
const minutes = Number(a.every_minutes);
|
|
103
|
+
if (!Number.isFinite(minutes) || minutes < 1) throw new Error('every_minutes must be at least 1');
|
|
104
|
+
return { kind: 'every', every_seconds: Math.round(minutes * 60) };
|
|
105
|
+
}
|
|
106
|
+
case 'daily':
|
|
107
|
+
return { kind: 'daily', daily: { time: clockTime(a.time), time_zone: tz } };
|
|
108
|
+
case 'weekly': {
|
|
109
|
+
const days = [...new Set((Array.isArray(a.weekdays) ? a.weekdays : []).map(Number).filter((d) => d >= 1 && d <= 7))].sort();
|
|
110
|
+
if (days.length === 0) throw new Error('weekdays must list ISO weekdays, 1 = Monday … 7 = Sunday');
|
|
111
|
+
return { kind: 'weekly', weekly: { time: clockTime(a.time), time_zone: tz, weekdays: days } };
|
|
112
|
+
}
|
|
113
|
+
case 'cron':
|
|
114
|
+
if (!String(a.cron ?? '').trim()) throw new Error('cron needs a five-field expression');
|
|
115
|
+
return { kind: 'cron', cron: { expression: String(a.cron).trim(), time_zone: tz } };
|
|
116
|
+
default:
|
|
117
|
+
throw new Error('kind must be one of at, every, daily, weekly, cron');
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A short English description of a timing, for tool results. */
|
|
122
|
+
export function describeTiming(t) {
|
|
123
|
+
if (!t) return '';
|
|
124
|
+
const days = ['', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
|
|
125
|
+
const hm = (s) => String(s ?? '').slice(0, 5);
|
|
126
|
+
switch (t.kind) {
|
|
127
|
+
case 'at':
|
|
128
|
+
return `once at ${t.at}`;
|
|
129
|
+
case 'every':
|
|
130
|
+
return t.every_seconds % 3600 === 0 ? `every ${t.every_seconds / 3600} h` : `every ${Math.round(t.every_seconds / 60)} min`;
|
|
131
|
+
case 'daily':
|
|
132
|
+
return `daily at ${hm(t.daily?.time)} (${t.daily?.time_zone})`;
|
|
133
|
+
case 'weekly':
|
|
134
|
+
return `${(t.weekly?.weekdays ?? []).map((d) => days[d]).join(', ')} at ${hm(t.weekly?.time)} (${t.weekly?.time_zone})`;
|
|
135
|
+
case 'cron':
|
|
136
|
+
return `cron ${t.cron?.expression} (${t.cron?.time_zone})`;
|
|
137
|
+
case 'rrule':
|
|
138
|
+
return t.rrule;
|
|
139
|
+
default:
|
|
140
|
+
return t.kind;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The editable timing of a stored schedule entry, in management-input form. */
|
|
145
|
+
export function timingOfEntry(e) {
|
|
146
|
+
const hms = (s) => String(s ?? '').slice(0, 8);
|
|
147
|
+
switch (e.kind) {
|
|
148
|
+
case 'after':
|
|
149
|
+
case 'at':
|
|
150
|
+
return { kind: 'at', at: e.scheduledAt };
|
|
151
|
+
case 'every':
|
|
152
|
+
return { kind: 'every', every_seconds: e.everySeconds };
|
|
153
|
+
case 'daily':
|
|
154
|
+
return { kind: 'daily', daily: { time: hms(e.time), time_zone: e.timeZone } };
|
|
155
|
+
case 'weekly':
|
|
156
|
+
return { kind: 'weekly', weekly: { time: hms(e.time), time_zone: e.timeZone, weekdays: e.weekdays } };
|
|
157
|
+
case 'cron':
|
|
158
|
+
return { kind: 'cron', cron: { expression: e.expression, time_zone: e.timeZone } };
|
|
159
|
+
case 'rrule':
|
|
160
|
+
return { kind: 'rrule', rrule: e.rrule };
|
|
161
|
+
default:
|
|
162
|
+
return { kind: e.kind };
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The text of a message's text blocks. */
|
|
167
|
+
export function textOf(content) {
|
|
168
|
+
if (typeof content === 'string') return content;
|
|
169
|
+
return (Array.isArray(content) ? content : [])
|
|
170
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string')
|
|
171
|
+
.map((b) => b.text)
|
|
172
|
+
.join('\n')
|
|
173
|
+
.trim();
|
|
174
|
+
}
|
package/lib/skills.mjs
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where a bot's skills come from, besides writing one by hand:
|
|
3
|
+
* - the skills already installed in DeepSeek Harness (~/.agents/skills, ~/.dsh/skills, bundled);
|
|
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.
|
|
8
|
+
*
|
|
9
|
+
* @module @kadaliao/dsh-bots/lib/skills
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
13
|
+
import { dirname, join, normalize } from 'node:path';
|
|
14
|
+
|
|
15
|
+
/** Skill collections worth browsing, shown as one-click sources. */
|
|
16
|
+
export const SKILL_SOURCES = [
|
|
17
|
+
{ id: 'anthropics', repo: 'anthropics/skills', path: 'skills', name: { en: 'Anthropic skills', zh: 'Anthropic 官方技能' }, description: { en: 'Documents, design, web apps, MCP building, brand and comms.', zh: '文档、设计、网页应用、MCP 开发、品牌与内部沟通。' } },
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
/** Split YAML-ish front matter: `name`, `description` (folded or quoted). */
|
|
21
|
+
export function parseSkillMd(text) {
|
|
22
|
+
const src = String(text ?? '').replace(/^\uFEFF/, '');
|
|
23
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(src);
|
|
24
|
+
const meta = {};
|
|
25
|
+
if (m) {
|
|
26
|
+
const lines = m[1].split(/\r?\n/);
|
|
27
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
28
|
+
const kv = /^([A-Za-z_-]+):\s*(.*)$/.exec(lines[i]);
|
|
29
|
+
if (!kv) continue;
|
|
30
|
+
let value = kv[2].trim();
|
|
31
|
+
if (/^[>|][+-]?$/.test(value)) {
|
|
32
|
+
const parts = [];
|
|
33
|
+
while (i + 1 < lines.length && /^\s+\S|^\s*$/.test(lines[i + 1])) parts.push(lines[(i += 1)].trim());
|
|
34
|
+
value = parts.join(value.startsWith('>') ? ' ' : '\n').trim();
|
|
35
|
+
} else value = value.replace(/^(['"])([\s\S]*)\1$/, '$2');
|
|
36
|
+
meta[kv[1].toLowerCase()] = value;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { name: meta.name ?? '', description: meta.description ?? '', body: m ? src.slice(m[0].length) : src };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* A GitHub location from what a user pastes:
|
|
44
|
+
* `owner/repo`, `owner/repo/path`, `https://github.com/o/r`, `…/tree/<ref>/<path>`, `…/blob/<ref>/<path>/SKILL.md`.
|
|
45
|
+
*/
|
|
46
|
+
export function parseGithub(input) {
|
|
47
|
+
const raw = String(input ?? '').trim().replace(/\.git$/, '');
|
|
48
|
+
let m = /^https?:\/\/github\.com\/([^/]+)\/([^/#?]+)(?:\/(?:tree|blob)\/([^/]+)(?:\/(.*))?)?\/?$/.exec(raw);
|
|
49
|
+
if (m) return { owner: m[1], repo: m[2], ref: m[3] ?? '', path: (m[4] ?? '').replace(/\/?SKILL\.md$/i, '').replace(/\/$/, '') };
|
|
50
|
+
m = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)(?:\/(.+))?$/.exec(raw);
|
|
51
|
+
if (m && !raw.includes('://')) return { owner: m[1], repo: m[2], ref: '', path: (m[3] ?? '').replace(/\/?SKILL\.md$/i, '').replace(/\/$/, '') };
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const GH_HEADERS = { accept: 'application/vnd.github+json', 'user-agent': 'dsh-bots' };
|
|
56
|
+
|
|
57
|
+
async function json(fetchImpl, url, signal) {
|
|
58
|
+
const res = await fetchImpl(url, { headers: GH_HEADERS, signal });
|
|
59
|
+
if (!res.ok) throw new Error(`GitHub answered ${res.status} for ${url.replace('https://api.github.com/', '')}`);
|
|
60
|
+
return res.json();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The skills inside a GitHub location: every folder below `path` that holds a SKILL.md.
|
|
65
|
+
* @returns {Promise<{owner, repo, ref, skills: {name, description, path, files: number}[]}>}
|
|
66
|
+
*/
|
|
67
|
+
export async function listGithubSkills(location, { fetchImpl = fetch, signal } = {}) {
|
|
68
|
+
const { owner, repo } = location;
|
|
69
|
+
let ref = location.ref;
|
|
70
|
+
if (!ref) ref = (await json(fetchImpl, `https://api.github.com/repos/${owner}/${repo}`, signal)).default_branch;
|
|
71
|
+
const tree = await json(fetchImpl, `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(ref)}?recursive=1`, signal);
|
|
72
|
+
const prefix = location.path ? `${location.path}/` : '';
|
|
73
|
+
const blobs = (tree.tree ?? []).filter((n) => n.type === 'blob' && (prefix === '' || n.path.startsWith(prefix) || n.path === `${location.path}/SKILL.md`));
|
|
74
|
+
const dirs = blobs.filter((n) => /(^|\/)SKILL\.md$/i.test(n.path)).map((n) => dirname(n.path) === '.' ? '' : dirname(n.path));
|
|
75
|
+
const skills = await Promise.all(
|
|
76
|
+
dirs.slice(0, 60).map(async (dir) => {
|
|
77
|
+
const text = await raw(fetchImpl, owner, repo, ref, `${dir ? `${dir}/` : ''}SKILL.md`, signal).catch(() => '');
|
|
78
|
+
const meta = parseSkillMd(text);
|
|
79
|
+
return {
|
|
80
|
+
name: meta.name || dir.split('/').pop() || repo,
|
|
81
|
+
description: meta.description.slice(0, 600),
|
|
82
|
+
path: dir,
|
|
83
|
+
files: blobs.filter((b) => (dir ? b.path.startsWith(`${dir}/`) : true)).length,
|
|
84
|
+
};
|
|
85
|
+
}),
|
|
86
|
+
);
|
|
87
|
+
return { owner, repo, ref, skills: skills.sort((a, b) => a.name.localeCompare(b.name)) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function raw(fetchImpl, owner, repo, ref, path, signal) {
|
|
91
|
+
const res = await fetchImpl(`https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(ref)}/${path.split('/').map(encodeURIComponent).join('/')}`, { signal });
|
|
92
|
+
if (!res.ok) throw new Error(`could not download ${path} (${res.status})`);
|
|
93
|
+
return res.text();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Files one imported skill may bring, and their total size. */
|
|
97
|
+
const MAX_FILES = 300;
|
|
98
|
+
const MAX_BYTES = 20 * 1024 * 1024;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Copy one skill folder from GitHub into `destRoot/<id>/` and describe it.
|
|
102
|
+
* @returns {Promise<{name, description, content, dir, origin}>}
|
|
103
|
+
*/
|
|
104
|
+
export async function importGithubSkill({ owner, repo, ref, path }, destRoot, id, { fetchImpl = fetch, signal } = {}) {
|
|
105
|
+
if (!ref) ref = (await json(fetchImpl, `https://api.github.com/repos/${owner}/${repo}`, signal)).default_branch;
|
|
106
|
+
const tree = await json(fetchImpl, `https://api.github.com/repos/${owner}/${repo}/git/trees/${encodeURIComponent(ref)}?recursive=1`, signal);
|
|
107
|
+
const prefix = path ? `${path}/` : '';
|
|
108
|
+
const files = (tree.tree ?? []).filter((n) => n.type === 'blob' && n.path.startsWith(prefix) && !n.path.slice(prefix.length).includes('/.'));
|
|
109
|
+
if (!files.some((f) => f.path === `${prefix}SKILL.md`)) throw new Error(`no SKILL.md in ${owner}/${repo}/${path}`);
|
|
110
|
+
if (files.length > MAX_FILES) throw new Error(`the skill has ${files.length} files; at most ${MAX_FILES} can be imported`);
|
|
111
|
+
if (files.reduce((n, f) => n + (f.size ?? 0), 0) > MAX_BYTES) throw new Error('the skill is larger than 20 MB');
|
|
112
|
+
const dir = join(destRoot, id);
|
|
113
|
+
rmSync(dir, { recursive: true, force: true });
|
|
114
|
+
mkdirSync(dir, { recursive: true });
|
|
115
|
+
let skillText = '';
|
|
116
|
+
for (const f of files) {
|
|
117
|
+
const rel = f.path.slice(prefix.length);
|
|
118
|
+
const target = normalize(join(dir, rel));
|
|
119
|
+
if (!target.startsWith(dir)) continue;
|
|
120
|
+
const res = await fetchImpl(`https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(ref)}/${f.path.split('/').map(encodeURIComponent).join('/')}`, { signal });
|
|
121
|
+
if (!res.ok) throw new Error(`could not download ${f.path} (${res.status})`);
|
|
122
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
123
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
124
|
+
writeFileSync(target, bytes);
|
|
125
|
+
if (rel === 'SKILL.md') skillText = bytes.toString('utf8');
|
|
126
|
+
}
|
|
127
|
+
const meta = parseSkillMd(skillText);
|
|
128
|
+
return {
|
|
129
|
+
name: meta.name || path.split('/').pop() || repo,
|
|
130
|
+
description: meta.description,
|
|
131
|
+
content: meta.body.trim(),
|
|
132
|
+
dir,
|
|
133
|
+
origin: `https://github.com/${owner}/${repo}/tree/${ref}/${path}`,
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A single SKILL.md (or any Markdown) at a URL, without companion files. */
|
|
138
|
+
export async function importUrlSkill(url, { fetchImpl = fetch, signal } = {}) {
|
|
139
|
+
const res = await fetchImpl(url, { signal });
|
|
140
|
+
if (!res.ok) throw new Error(`could not download ${url} (${res.status})`);
|
|
141
|
+
const text = await res.text();
|
|
142
|
+
if (text.length > 400_000) throw new Error('the file is larger than 400 KB');
|
|
143
|
+
const meta = parseSkillMd(text);
|
|
144
|
+
const fallback = url.split('/').filter(Boolean).slice(-2, -1)[0] ?? 'skill';
|
|
145
|
+
return { name: meta.name || fallback, description: meta.description, content: meta.body.trim(), origin: url };
|
|
146
|
+
}
|