@suifei/dsh-ai-team 0.4.149 → 0.4.151
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/CHANGELOG.md +11 -0
- package/README.md +6 -2
- package/client.js +235 -22
- package/index.js +152 -20
- package/lib/domain/catalog.js +14 -6
- package/lib/host/skill-import.js +204 -0
- package/lib/runtime/skill-catalog.js +56 -41
- package/lib/runtime/skill-provider.js +69 -44
- package/package.json +75 -74
package/index.js
CHANGED
|
@@ -12,9 +12,10 @@ import { HOST_SUBAGENT_LIMIT, planDispatch, planIdleRetry, planIdleStaffing, pla
|
|
|
12
12
|
import { pmoHasNews } from './lib/ledger/fold.js';
|
|
13
13
|
import { homedir, tmpdir } from 'node:os';
|
|
14
14
|
import { randomUUID } from 'node:crypto';
|
|
15
|
-
import { join, sep } from 'node:path';
|
|
15
|
+
import { isAbsolute, join, relative, sep } from 'node:path';
|
|
16
16
|
import { fileURLToPath } from 'node:url';
|
|
17
17
|
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
|
|
18
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
18
19
|
import z from '@deepseek-ai/schemastery';
|
|
19
20
|
import { ProjectRuntime } from './lib/host/project-runtime.js';
|
|
20
21
|
import { ProjectRegistry } from './lib/host/project-registry.js';
|
|
@@ -31,9 +32,10 @@ import { memberIdentity } from './lib/domain/member-profile.js';
|
|
|
31
32
|
import { blocksBlueprintTask, blueprintFingerprint, blueprintUseCases, buildTeamBlueprint, renderTeamBlueprint } from './lib/domain/team-blueprint.js';
|
|
32
33
|
import { findSkill, findSkillText, loadSkillContext } from './lib/runtime/skill-loader.js';
|
|
33
34
|
import { skillKindForMember } from './lib/runtime/core-skill.js';
|
|
34
|
-
import {
|
|
35
|
+
import { formatSkillSummaries, modelInvocableSkills, readSkillCatalog } from './lib/runtime/skill-catalog.js';
|
|
35
36
|
import { isSkillExcluded } from './lib/runtime/skill-policy.js';
|
|
36
37
|
import { installFileSkillProvider, pickProjectForCwd } from './lib/runtime/skill-provider.js';
|
|
38
|
+
import { installSkillPack, MAX_SKILL_IMPORT_REQUEST_BYTES } from './lib/host/skill-import.js';
|
|
37
39
|
import { apply as applySkillOpt } from './lib/vendor/skillopt/src/index.js';
|
|
38
40
|
import { createAdoptGate, wrapToolsWithAdoptGate } from './lib/skillopt/adopt-gate.js';
|
|
39
41
|
import { wrapToolsWithSkilloptAccess } from './lib/skillopt/tool-access.js';
|
|
@@ -150,14 +152,28 @@ function memberCatalogDirs(member, diag) {
|
|
|
150
152
|
return talent === undefined ? [] : [talent.dir];
|
|
151
153
|
}
|
|
152
154
|
|
|
155
|
+
function memberWorkspace(member, runtime) {
|
|
156
|
+
const workspacePath = runtime?.service?.state?.projects?.[runtime.id]?.workspacePath;
|
|
157
|
+
return member?.workspace || (typeof workspacePath === 'string' ? workspacePath.trim() : '');
|
|
158
|
+
}
|
|
159
|
+
|
|
153
160
|
/**
|
|
154
161
|
* 成员技能的查找根(团队规程目录另由 preset 前置):人才自带 → 工作区 `.dsh` → 用户 `~/.dsh` → 项目数据目录。
|
|
155
|
-
*
|
|
162
|
+
* 用于兼容宿主技能目录之外的 Markdown。
|
|
156
163
|
*/
|
|
157
|
-
function memberSkillRoots(member, runtime, diag) {
|
|
158
|
-
const
|
|
159
|
-
|
|
160
|
-
|
|
164
|
+
function memberSkillRoots(member, runtime, diag, talentRoots = memberCatalogDirs(member, diag)) {
|
|
165
|
+
const dir = memberWorkspace(member, runtime);
|
|
166
|
+
return [...talentRoots, ...(dir ? [join(dir, '.dsh')] : []), dshHome(), runtime?.dir].filter((root) => typeof root === 'string' && root !== '');
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 团队、人才自带 Markdown 仍优先;注册表里的整包通过宿主 skill 工具加载。 */
|
|
170
|
+
async function memberHostSkillReferences(names, ownedRoots, summaries) {
|
|
171
|
+
const registered = new Set(summaries.map((skill) => skill?.name));
|
|
172
|
+
const references = new Set();
|
|
173
|
+
for (const name of names) {
|
|
174
|
+
if (registered.has(name) && await findSkill(ownedRoots, name) === null) references.add(name);
|
|
175
|
+
}
|
|
176
|
+
return references;
|
|
161
177
|
}
|
|
162
178
|
|
|
163
179
|
/** 新项目用哪个团队:新建时选的优先,其次插件设置 `teamPreset`,最后内置默认团队。 */
|
|
@@ -216,12 +232,14 @@ function send(res, body, status = 200) {
|
|
|
216
232
|
res.end(JSON.stringify(body));
|
|
217
233
|
}
|
|
218
234
|
|
|
219
|
-
async function readJson(req) {
|
|
235
|
+
async function readJson(req, limit = 1_000_000) {
|
|
236
|
+
const tooLarge = () => Object.assign(new Error('body too large'), { code: 'E_INVALID_ARGUMENT', status: 413 });
|
|
237
|
+
if (Number(req.headers?.['content-length']) > limit) throw tooLarge();
|
|
220
238
|
const chunks = [];
|
|
221
239
|
let size = 0;
|
|
222
240
|
for await (const chunk of req) {
|
|
223
241
|
size += chunk.length;
|
|
224
|
-
if (size >
|
|
242
|
+
if (size > limit) throw tooLarge();
|
|
225
243
|
chunks.push(chunk);
|
|
226
244
|
}
|
|
227
245
|
if (chunks.length === 0) return {};
|
|
@@ -1573,6 +1591,17 @@ export function apply(ctx, config = {}) {
|
|
|
1573
1591
|
|
|
1574
1592
|
const skillsService = serviceOf(ctx, 'skills');
|
|
1575
1593
|
let disposeSkillProvider = () => {};
|
|
1594
|
+
const lookupHostSkills = async (cwd, { requireRegistry = false, refresh = false } = {}) => {
|
|
1595
|
+
try {
|
|
1596
|
+
const skills = serviceOf(ctx, 'skills');
|
|
1597
|
+
if (requireRegistry && typeof skills?.list !== 'function') throw new Error('DSH skill registry is unavailable');
|
|
1598
|
+
if (refresh) disposeSkillProvider.invalidate?.();
|
|
1599
|
+
return await readSkillCatalog(skills, { cwd });
|
|
1600
|
+
} catch (error) {
|
|
1601
|
+
diag.append({ ev: 'skill.catalog.fail', cwd, message: error?.message ?? String(error) });
|
|
1602
|
+
return null;
|
|
1603
|
+
}
|
|
1604
|
+
};
|
|
1576
1605
|
try {
|
|
1577
1606
|
// A vendor failure must never fail composition activation: that left
|
|
1578
1607
|
// fresh installs with a half-activated host until a process restart.
|
|
@@ -2193,8 +2222,7 @@ export function apply(ctx, config = {}) {
|
|
|
2193
2222
|
// 无目录项目 fail-closed:成员绝不落到宿主默认目录或插件数据目录
|
|
2194
2223
|
// (projectCwd 的 dir 兜底)里执行。显式判工作目录,不吃兜底。
|
|
2195
2224
|
// 先于 reseat 释放旧句柄——否则无目录的 force 会先杀句柄再 409。
|
|
2196
|
-
const
|
|
2197
|
-
const effectiveDir = member?.workspace || (typeof workspacePath === 'string' ? workspacePath.trim() : '');
|
|
2225
|
+
const effectiveDir = memberWorkspace(member, projectRuntime);
|
|
2198
2226
|
if (effectiveDir === '') {
|
|
2199
2227
|
diag?.append({ ev: 'activate.reject', projectId: projectRuntime.id, memberId: member.id, code: 'E_WORKSPACE_REQUIRED' });
|
|
2200
2228
|
return {
|
|
@@ -2262,17 +2290,34 @@ export function apply(ctx, config = {}) {
|
|
|
2262
2290
|
cwd: effectiveDir,
|
|
2263
2291
|
});
|
|
2264
2292
|
const blueprintRole = project?.blueprint?.roles.find((role) => role.id === member.id);
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2293
|
+
let skillContext;
|
|
2294
|
+
let promptMember = activationMember;
|
|
2295
|
+
if (blueprintRole) {
|
|
2296
|
+
skillContext = `\n\n${blueprintRole.prompt}`;
|
|
2297
|
+
} else {
|
|
2298
|
+
const preset = resolveTeam(talentCatalog(diag), activationMember.team ?? DEFAULT_TEAM, { diag });
|
|
2299
|
+
const assigned = Array.isArray(activationMember.skills) ? activationMember.skills : [];
|
|
2300
|
+
const summaries = await lookupHostSkills(effectiveDir);
|
|
2301
|
+
const talentRoots = memberCatalogDirs(activationMember, diag);
|
|
2302
|
+
const references = await memberHostSkillReferences(assigned, [preset.dir, ...talentRoots], summaries ?? []);
|
|
2303
|
+
const modelSkills = new Set(modelInvocableSkills(summaries ?? []).map((skill) => skill.name));
|
|
2304
|
+
promptMember = {
|
|
2305
|
+
...activationMember,
|
|
2306
|
+
skills: assigned.filter((name) => !isSkillExcluded(name) && (!references.has(name) || modelSkills.has(name))),
|
|
2307
|
+
};
|
|
2308
|
+
const dshSummaries = (summaries ?? []).filter((skill) => !assigned.includes(skill?.name) || references.has(skill.name));
|
|
2309
|
+
const dshSkills = formatSkillSummaries(dshSummaries, { assigned: [...references] });
|
|
2310
|
+
const inlineMember = { ...promptMember, skills: promptMember.skills.filter((name) => !references.has(name)) };
|
|
2311
|
+
const roots = summaries === null ? [...talentRoots, projectRuntime.dir] : memberSkillRoots(activationMember, projectRuntime, diag, talentRoots);
|
|
2312
|
+
skillContext = dshSkills + await loadSkillContext(inlineMember, roots, {
|
|
2268
2313
|
vars: { GOAL: goalForProject(projectRuntime), PROJECT: project?.name ?? '', MEMBER: activationMember.name ?? '', WORKSPACE: effectiveDir },
|
|
2269
|
-
preset
|
|
2314
|
+
preset,
|
|
2270
2315
|
ownerId: project?.ownerMemberId ?? project?.ownerId,
|
|
2271
|
-
})
|
|
2272
|
-
|
|
2316
|
+
});
|
|
2317
|
+
}
|
|
2273
2318
|
const result = await runtime.activate(activationMember, {
|
|
2274
2319
|
// #65:激活时若带着 Human 消息的图片/文件,一并放进首条消息。
|
|
2275
|
-
prompt: messageContent(`${memberIdentity(
|
|
2320
|
+
prompt: messageContent(`${memberIdentity(promptMember)}\n\n${typeof body.payload?.prompt === 'string'
|
|
2276
2321
|
? body.payload.prompt
|
|
2277
2322
|
: '你被加入 AI Team。先读取项目简报与收件箱,再处理分配给你的任务。'}${skillContext}`, body.payload?.attachments),
|
|
2278
2323
|
});
|
|
@@ -2513,6 +2558,84 @@ export function apply(ctx, config = {}) {
|
|
|
2513
2558
|
get: await skillsService.get('distilly', {}).then((skill) => skill?.name ?? null).catch(() => null),
|
|
2514
2559
|
});
|
|
2515
2560
|
}
|
|
2561
|
+
if (url.pathname === '/ai-team/api/host-skills' && (req.method === 'GET' || req.method === 'POST')) {
|
|
2562
|
+
const projectId = url.searchParams.get('project');
|
|
2563
|
+
const memberId = url.searchParams.get('member');
|
|
2564
|
+
if (projectId === null && memberId !== null) return send(res, { error: { code: 'E_INVALID_ARGUMENT', message: 'project is required with member' } }, 400);
|
|
2565
|
+
const importing = req.method === 'POST';
|
|
2566
|
+
let workspace = null;
|
|
2567
|
+
let targetRoot = projectId === null ? 'user-dsh' : null;
|
|
2568
|
+
if (projectId !== null) {
|
|
2569
|
+
const runtime = projectRuntime(projectId);
|
|
2570
|
+
if (runtime === null) return send(res, { error: { code: 'NOT_FOUND', message: 'project not found' } }, 404);
|
|
2571
|
+
if (importing && runtime.service.state.projects?.[projectId]?.status === 'archived') {
|
|
2572
|
+
return send(res, { error: { code: 'E_PROJECT_ARCHIVED', message: 'This project is archived.' } }, 409);
|
|
2573
|
+
}
|
|
2574
|
+
const member = memberId === null ? undefined : runtime.service.state.members?.[memberId];
|
|
2575
|
+
if (memberId !== null && member?.kind !== 'agent') return send(res, { error: { code: 'NOT_FOUND', message: 'member not found' } }, 404);
|
|
2576
|
+
workspace = memberWorkspace(member, runtime) || null;
|
|
2577
|
+
if (workspace !== null && isAbsolute(workspace)) {
|
|
2578
|
+
try {
|
|
2579
|
+
const canonical = await realpath(workspace);
|
|
2580
|
+
if ((await stat(canonical)).isDirectory()) {
|
|
2581
|
+
workspace = canonical;
|
|
2582
|
+
targetRoot = 'project-dsh:' + canonical;
|
|
2583
|
+
}
|
|
2584
|
+
} catch (error) {
|
|
2585
|
+
diag.append({ ev: 'skill.workspace.fail', projectId, workspace, message: error?.message ?? String(error) });
|
|
2586
|
+
}
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
// Give the personal view an explicit cwd so the fallback provider cannot adopt the host's startup project.
|
|
2590
|
+
const cwd = workspace ?? dshHome();
|
|
2591
|
+
if (importing && targetRoot === null) {
|
|
2592
|
+
return send(res, { error: { code: 'E_SKILL_WORKSPACE_REQUIRED', message: 'Set an existing workspace for this project or member.' } }, 400);
|
|
2593
|
+
}
|
|
2594
|
+
const summaries = await lookupHostSkills(cwd, {
|
|
2595
|
+
requireRegistry: true, refresh: url.searchParams.get('refresh') === '1',
|
|
2596
|
+
});
|
|
2597
|
+
if (summaries === null) return send(res, { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'DSH skill catalog is unavailable' } }, 503);
|
|
2598
|
+
if (importing) {
|
|
2599
|
+
let confirming = false;
|
|
2600
|
+
try {
|
|
2601
|
+
const payload = await readJson(req, MAX_SKILL_IMPORT_REQUEST_BYTES);
|
|
2602
|
+
const source = projectId === null ? 'user-dsh' : 'project-dsh';
|
|
2603
|
+
const installedNames = new Set(summaries.filter((item) => item.source === source).map((item) => item.name));
|
|
2604
|
+
const skill = await installSkillPack(payload, {
|
|
2605
|
+
baseDir: cwd,
|
|
2606
|
+
project: projectId !== null,
|
|
2607
|
+
installedNames,
|
|
2608
|
+
async confirm({ name, path }) {
|
|
2609
|
+
confirming = true;
|
|
2610
|
+
// 子工作区可能处于宿主监视根的下一层。主动刷新,再确认胜出的路径。
|
|
2611
|
+
const updated = await lookupHostSkills(cwd, { requireRegistry: true, refresh: true });
|
|
2612
|
+
const item = modelInvocableSkills(updated ?? []).find((entry) => entry.name === name && entry.source === source);
|
|
2613
|
+
const loadedPath = typeof item?.path === 'string' ? await realpath(item.path).catch(() => null) : null;
|
|
2614
|
+
if (loadedPath === null || relative(path, loadedPath) !== '') {
|
|
2615
|
+
throw Object.assign(new Error('DSH did not resolve the imported skill in the selected scope.'), {
|
|
2616
|
+
code: 'E_SKILL_NOT_VISIBLE', status: 409, details: { name },
|
|
2617
|
+
});
|
|
2618
|
+
}
|
|
2619
|
+
return { name, description: item.description ?? '', source };
|
|
2620
|
+
},
|
|
2621
|
+
});
|
|
2622
|
+
diag.append({ ev: 'skill.import', projectId, memberId, workspace, name: skill.name, source: skill.source });
|
|
2623
|
+
return send(res, { skill }, 201);
|
|
2624
|
+
} catch (error) {
|
|
2625
|
+
if (confirming) disposeSkillProvider.invalidate?.();
|
|
2626
|
+
const status = error?.status ?? (error instanceof SyntaxError ? 400 : 500);
|
|
2627
|
+
const code = error?.code && error?.status ? error.code : 'E_SKILL_IMPORT';
|
|
2628
|
+
diag.append({ ev: 'skill.import.fail', projectId, memberId, workspace, code, status, message: error?.message ?? String(error) });
|
|
2629
|
+
const message = status === 500 ? 'Could not save the package to the DSH skill directory.' : error.message;
|
|
2630
|
+
return send(res, { error: { code, message, details: error.details } }, status);
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
const skills = modelInvocableSkills(summaries)
|
|
2634
|
+
.filter((skill) => workspace !== null || !skill.source?.startsWith('project-'))
|
|
2635
|
+
.map((skill) => ({ name: skill.name, description: skill.description ?? '', source: skill.source ?? '' }));
|
|
2636
|
+
diag.append({ ev: 'skill.catalog', projectId, memberId, workspace, targetRoot, count: skills.length });
|
|
2637
|
+
return send(res, { skills, workspace, targetRoot });
|
|
2638
|
+
}
|
|
2516
2639
|
// 人才市场:「添加成员」弹窗里可招聘的人才(用户自建优先于内置)。
|
|
2517
2640
|
if (req.method === 'GET' && url.pathname === '/ai-team/api/talents') {
|
|
2518
2641
|
return send(res, { talents: listTalents(talentCatalog(diag)) });
|
|
@@ -2591,9 +2714,18 @@ export function apply(ctx, config = {}) {
|
|
|
2591
2714
|
if (member === undefined || member.kind !== 'agent') return send(res, { error: { code: 'NOT_FOUND', message: 'member not found' } }, 404);
|
|
2592
2715
|
const project = runtime.service.state.projects?.[runtime.id];
|
|
2593
2716
|
const draft = talentFromMember(member, skillKindForMember(member, { ownerId: project?.ownerMemberId ?? project?.ownerId }));
|
|
2594
|
-
const
|
|
2717
|
+
const teamDir = resolveTeam(talentCatalog(diag), member.team ?? DEFAULT_TEAM, { diag }).dir;
|
|
2718
|
+
const talentRoots = memberCatalogDirs(member, diag);
|
|
2719
|
+
const roots = [teamDir, ...memberSkillRoots(member, runtime, diag, talentRoots)];
|
|
2720
|
+
const summaries = draft.skills.length > 0 ? await lookupHostSkills(memberWorkspace(member, runtime) || dshHome()) : [];
|
|
2721
|
+
if (summaries === null) return send(res, { error: { code: 'E_RUNTIME_UNAVAILABLE', message: 'DSH skill catalog is unavailable' } }, 503);
|
|
2722
|
+
const references = await memberHostSkillReferences(draft.skills, [teamDir, ...talentRoots], summaries);
|
|
2723
|
+
const available = new Set(modelInvocableSkills(summaries).map((skill) => skill.name));
|
|
2595
2724
|
const skills = [];
|
|
2596
|
-
for (const name of draft.skills)
|
|
2725
|
+
for (const name of draft.skills) {
|
|
2726
|
+
if (references.has(name)) skills.push({ name, found: available.has(name), host: true });
|
|
2727
|
+
else skills.push({ name, found: (await findSkillText(roots, name)) !== null });
|
|
2728
|
+
}
|
|
2597
2729
|
return send(res, { draft: { ...draft, skills }, projectId: runtime.id, memberId: member.id });
|
|
2598
2730
|
}
|
|
2599
2731
|
// 可安装的技能清单(每个人才自带的技能),给「从已有装」挑。
|
package/lib/domain/catalog.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
16
|
-
import { join } from 'node:path';
|
|
16
|
+
import { dirname, join } from 'node:path';
|
|
17
17
|
import { fileURLToPath } from 'node:url';
|
|
18
18
|
import { parse, stringify } from 'yaml';
|
|
19
19
|
import { parseAvatar } from './avatar.js';
|
|
@@ -313,19 +313,23 @@ export function forkTalent(userRoot, talent) {
|
|
|
313
313
|
return { forked: true, dir };
|
|
314
314
|
}
|
|
315
315
|
|
|
316
|
+
function talentSkillPath(talentDir, name) {
|
|
317
|
+
return join(talentDir, 'skills', name, 'SKILL.md');
|
|
318
|
+
}
|
|
319
|
+
|
|
316
320
|
/** 把一份技能装进某人才自己的文件夹:`<talentDir>/skills/<name>/SKILL.md`。返回规范后的技能名。 */
|
|
317
321
|
export function installSkill(talentDir, name, markdown) {
|
|
318
322
|
if (typeof talentDir !== 'string' || talentDir === '') throw new Error('installSkill: 需要 talentDir');
|
|
319
323
|
const safe = skillName(name, '技能名');
|
|
320
|
-
const
|
|
321
|
-
mkdirSync(
|
|
322
|
-
writeFileSync(
|
|
324
|
+
const file = talentSkillPath(talentDir, safe);
|
|
325
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
326
|
+
writeFileSync(file, typeof markdown === 'string' ? markdown : '', 'utf8');
|
|
323
327
|
return safe;
|
|
324
328
|
}
|
|
325
329
|
|
|
326
330
|
/** 读某人才自带技能的正文(给预览与 fork)。 */
|
|
327
331
|
export function readSkillText(talentDir, name) {
|
|
328
|
-
return readFileSync(
|
|
332
|
+
return readFileSync(talentSkillPath(talentDir, skillName(name, '技能名')), 'utf8');
|
|
329
333
|
}
|
|
330
334
|
|
|
331
335
|
/**
|
|
@@ -430,6 +434,10 @@ export function talentFromMember(member, duty) {
|
|
|
430
434
|
/** 列出可安装的技能:当前目录里每个人才自带的技能(名字 + 来源人才),给「从已有装」挑。 */
|
|
431
435
|
export function listInstallableSkills(catalog) {
|
|
432
436
|
const out = [];
|
|
433
|
-
for (const t of catalog.talents.values())
|
|
437
|
+
for (const t of catalog.talents.values()) {
|
|
438
|
+
for (const name of t.skills) {
|
|
439
|
+
if (existsSync(talentSkillPath(t.dir, name))) out.push({ name, talent: t.id, talentName: t.name, source: t.source });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
434
442
|
return out.sort((a, b) => a.name.localeCompare(b.name) || a.talent.localeCompare(b.talent));
|
|
435
443
|
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { lstat, mkdir, mkdtemp, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { dirname, join, posix, relative } from 'node:path';
|
|
3
|
+
import { buffer } from 'node:stream/consumers';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import { crc32 } from 'node:zlib';
|
|
6
|
+
import yauzl from 'yauzl';
|
|
7
|
+
import { inspectFileSkill, MAX_SKILL_BODY_BYTES } from '../runtime/skill-provider.js';
|
|
8
|
+
|
|
9
|
+
export const MAX_SKILL_IMPORT_REQUEST_BYTES = 64 * 1024 * 1024;
|
|
10
|
+
const MAX_FILES = 10_000;
|
|
11
|
+
const MAX_FILE_BYTES = 64 * 1024 * 1024;
|
|
12
|
+
const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
|
|
13
|
+
const MANIFEST = 'SKILL.md';
|
|
14
|
+
const imports = new Set();
|
|
15
|
+
const publishDelays = [0, 50, 150, 350, 800];
|
|
16
|
+
const transientRenameErrors = new Set(['EACCES', 'EBUSY', 'EPERM']);
|
|
17
|
+
|
|
18
|
+
function importError(message, { code = 'E_INVALID_SKILL_PACK', status = 400, details } = {}) {
|
|
19
|
+
return Object.assign(new Error(message), { code, status, details });
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function packTooLarge() {
|
|
23
|
+
return importError('Skill package exceeds the import size limit.', { code: 'E_SKILL_PACK_TOO_LARGE', status: 413 });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function filePath(path) {
|
|
27
|
+
if (typeof path !== 'string' || !path.isWellFormed() || path.split('/').some((part) => (
|
|
28
|
+
part === '' || /[. ]$/.test(part) || /[\x00-\x1f<>:"\\|?*]/.test(part)
|
|
29
|
+
|| /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part)
|
|
30
|
+
))) throw importError('Skill package contains an invalid file path.');
|
|
31
|
+
return path;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function base64(value) {
|
|
35
|
+
if (typeof value !== 'string' || value.length % 4 !== 0 || /[^A-Za-z0-9+/=]|=[^=]|={3}/.test(value)) {
|
|
36
|
+
throw importError('Skill package contains invalid file data.');
|
|
37
|
+
}
|
|
38
|
+
return Buffer.from(value, 'base64');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function zipFiles(encoded) {
|
|
42
|
+
try {
|
|
43
|
+
const zip = await yauzl.fromBufferPromise(base64(encoded), { validateEntrySizes: true });
|
|
44
|
+
if (zip.entryCount > MAX_FILES) throw packTooLarge();
|
|
45
|
+
const files = [];
|
|
46
|
+
let expanded = 0;
|
|
47
|
+
for await (const entry of zip.eachEntry()) {
|
|
48
|
+
const directory = entry.fileName.endsWith('/');
|
|
49
|
+
const path = filePath(directory ? entry.fileName.slice(0, -1) : entry.fileName);
|
|
50
|
+
const kind = (entry.externalFileAttributes >>> 16) & 0o170000;
|
|
51
|
+
if (kind && kind !== (directory ? 0o040000 : 0o100000)) {
|
|
52
|
+
throw importError('Skill package may contain only regular files and directories.');
|
|
53
|
+
}
|
|
54
|
+
if (directory) continue;
|
|
55
|
+
if (entry.uncompressedSize > MAX_FILE_BYTES) throw packTooLarge();
|
|
56
|
+
expanded += entry.uncompressedSize;
|
|
57
|
+
if (expanded > MAX_EXPANDED_BYTES) throw packTooLarge();
|
|
58
|
+
files.push({
|
|
59
|
+
path,
|
|
60
|
+
size: entry.uncompressedSize,
|
|
61
|
+
async read() {
|
|
62
|
+
let bytes;
|
|
63
|
+
try {
|
|
64
|
+
bytes = await buffer(await zip.openReadStreamPromise(entry));
|
|
65
|
+
} catch {
|
|
66
|
+
throw importError('A file in the ZIP skill package could not be read.');
|
|
67
|
+
}
|
|
68
|
+
if (crc32(bytes) !== entry.crc32) throw importError('A file in the ZIP skill package failed its checksum.');
|
|
69
|
+
return bytes;
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return files;
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (error?.status) throw error;
|
|
76
|
+
throw importError('The ZIP or .skill package could not be opened.');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function readPack(payload) {
|
|
81
|
+
const hasArchive = typeof payload?.zipBase64 === 'string';
|
|
82
|
+
const hasFiles = Array.isArray(payload?.files);
|
|
83
|
+
if (hasArchive === hasFiles) throw importError('Upload one skill folder or one ZIP/.skill package.');
|
|
84
|
+
if (hasFiles && payload.files.length > MAX_FILES) throw packTooLarge();
|
|
85
|
+
const files = hasArchive ? await zipFiles(payload.zipBase64) : payload.files.map((file) => {
|
|
86
|
+
const bytes = base64(file?.contentBase64);
|
|
87
|
+
if (bytes.length > MAX_FILE_BYTES) throw packTooLarge();
|
|
88
|
+
return { path: filePath(file?.path), size: bytes.length, read: () => bytes };
|
|
89
|
+
});
|
|
90
|
+
const manifests = files.filter((file) => posix.basename(file.path) === MANIFEST)
|
|
91
|
+
.sort((a, b) => a.path.length - b.path.length);
|
|
92
|
+
if (!manifests.length) throw importError('The skill package is missing SKILL.md.');
|
|
93
|
+
const manifest = manifests[0];
|
|
94
|
+
const folder = posix.dirname(manifest.path);
|
|
95
|
+
const prefix = folder === '.' ? '' : folder + '/';
|
|
96
|
+
if (manifests.some((file) => !file.path.startsWith(prefix))) {
|
|
97
|
+
throw importError('Select one skill package per import.');
|
|
98
|
+
}
|
|
99
|
+
if (manifest.size > MAX_SKILL_BODY_BYTES) throw packTooLarge();
|
|
100
|
+
const selected = files.filter((file) => file.path.startsWith(prefix))
|
|
101
|
+
.map((file) => ({ ...file, path: file.path.slice(prefix.length) }));
|
|
102
|
+
const paths = new Set(selected.map((file) => file.path.normalize('NFC').toLowerCase()));
|
|
103
|
+
if (paths.size !== selected.length) throw importError('The skill package contains duplicate file paths.');
|
|
104
|
+
for (const path of paths) {
|
|
105
|
+
for (let parent = posix.dirname(path); parent !== '.'; parent = posix.dirname(parent)) {
|
|
106
|
+
if (paths.has(parent)) throw importError('The skill package uses a file as a directory.');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const markdown = await manifest.read();
|
|
110
|
+
let text;
|
|
111
|
+
try {
|
|
112
|
+
text = new TextDecoder('utf-8', { fatal: true }).decode(markdown);
|
|
113
|
+
} catch {
|
|
114
|
+
throw importError('SKILL.md must be UTF-8 text.');
|
|
115
|
+
}
|
|
116
|
+
const metadata = inspectFileSkill(text);
|
|
117
|
+
if (metadata.problem || metadata.name.length > 64) {
|
|
118
|
+
throw importError('SKILL.md needs a valid skill name, description, and invocation settings.', {
|
|
119
|
+
details: { reason: metadata.problem ?? 'name-too-long' },
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
if (!metadata.invocation.modelInvocable) throw importError('This skill disables model invocation.');
|
|
123
|
+
return { name: filePath(metadata.name), selected, markdown };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function installRoot(baseDir, project) {
|
|
127
|
+
let root = await realpath(baseDir);
|
|
128
|
+
if (!(await stat(root)).isDirectory()) throw importError('The skill destination must be a directory.');
|
|
129
|
+
for (const segment of project ? ['.dsh', 'skills'] : ['skills']) {
|
|
130
|
+
root = join(root, segment);
|
|
131
|
+
await mkdir(root).catch((error) => { if (error.code !== 'EEXIST') throw error; });
|
|
132
|
+
if (!(await lstat(root)).isDirectory()) throw importError('The skill destination must be a real directory.');
|
|
133
|
+
}
|
|
134
|
+
return root;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function pathExists(path) {
|
|
138
|
+
try {
|
|
139
|
+
await lstat(path);
|
|
140
|
+
return true;
|
|
141
|
+
} catch (error) {
|
|
142
|
+
if (error.code === 'ENOENT') return false;
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Both upload formats create one complete, discoverable DSH skill directory. */
|
|
148
|
+
export async function installSkillPack(payload, { baseDir, project, installedNames, confirm, moveDirectory = rename }) {
|
|
149
|
+
const { name, selected, markdown } = await readPack(payload);
|
|
150
|
+
const conflict = () => importError('A skill with this name is already installed or being imported.', {
|
|
151
|
+
code: 'E_SKILL_EXISTS', status: 409, details: { name },
|
|
152
|
+
});
|
|
153
|
+
if (installedNames?.has(name)) throw conflict();
|
|
154
|
+
const root = await installRoot(baseDir, project);
|
|
155
|
+
const target = join(root, name);
|
|
156
|
+
const checkDestination = async () => {
|
|
157
|
+
if (await pathExists(target) || await pathExists(target + '.md')) throw conflict();
|
|
158
|
+
};
|
|
159
|
+
if (imports.has(target)) throw conflict();
|
|
160
|
+
imports.add(target);
|
|
161
|
+
let temporary;
|
|
162
|
+
try {
|
|
163
|
+
await checkDestination();
|
|
164
|
+
// DSH scans every immediate child of the skill root, including most dot directories.
|
|
165
|
+
temporary = await mkdtemp(join(dirname(root), '.ai-team-skill-'));
|
|
166
|
+
for (const file of selected) {
|
|
167
|
+
const destination = join(temporary, file.path);
|
|
168
|
+
await mkdir(dirname(destination), { recursive: true });
|
|
169
|
+
await writeFile(destination, file.path === MANIFEST ? markdown : await file.read(), { flag: 'wx' });
|
|
170
|
+
}
|
|
171
|
+
for (const [attempt, pause] of publishDelays.entries()) {
|
|
172
|
+
if (pause > 0) await delay(pause);
|
|
173
|
+
await checkDestination();
|
|
174
|
+
try {
|
|
175
|
+
await moveDirectory(temporary, target);
|
|
176
|
+
break;
|
|
177
|
+
} catch (error) {
|
|
178
|
+
if (attempt === publishDelays.length - 1 || !transientRenameErrors.has(error?.code)) {
|
|
179
|
+
await checkDestination();
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// Keep ownership of this newly published directory until the DSH catalog confirms it.
|
|
185
|
+
temporary = target;
|
|
186
|
+
const installed = await confirm({ name, path: join(target, MANIFEST) });
|
|
187
|
+
temporary = undefined;
|
|
188
|
+
return installed;
|
|
189
|
+
} finally {
|
|
190
|
+
try {
|
|
191
|
+
if (temporary) {
|
|
192
|
+
const canonical = await realpath(temporary).catch((error) => {
|
|
193
|
+
if (error.code === 'ENOENT') return null;
|
|
194
|
+
throw error;
|
|
195
|
+
});
|
|
196
|
+
if (canonical !== null && relative(temporary, canonical) === '') {
|
|
197
|
+
await rm(temporary, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
} finally {
|
|
201
|
+
imports.delete(target);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
@@ -1,41 +1,56 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Bounded, invocation-neutral view of the DSH skill catalog for a member
|
|
3
|
-
* prompt. Full bodies stay with the `skill` tool; this only makes names,
|
|
4
|
-
* descriptions and "when to use" discoverable so a member can load one on
|
|
5
|
-
* demand instead of guessing.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { isSkillExcluded } from './skill-policy.js';
|
|
9
|
-
|
|
10
|
-
function clean(value, limit) {
|
|
11
|
-
const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
|
|
12
|
-
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
export async function
|
|
16
|
-
if (
|
|
17
|
-
const summaries = await skills.list({
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
//
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
return
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Bounded, invocation-neutral view of the DSH skill catalog for a member
|
|
3
|
+
* prompt. Full bodies stay with the `skill` tool; this only makes names,
|
|
4
|
+
* descriptions and "when to use" discoverable so a member can load one on
|
|
5
|
+
* demand instead of guessing.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { isSkillExcluded } from './skill-policy.js';
|
|
9
|
+
|
|
10
|
+
function clean(value, limit) {
|
|
11
|
+
const text = typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '';
|
|
12
|
+
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function readSkillCatalog(skills, { cwd } = {}) {
|
|
16
|
+
if (typeof skills?.list !== 'function') return [];
|
|
17
|
+
const summaries = await skills.list(cwd ? { cwd } : {});
|
|
18
|
+
return Array.isArray(summaries) ? summaries : [];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function modelInvocableSkills(summaries) {
|
|
22
|
+
// 只注入「模型可以自己调用」的技能:`disable-model-invocation: true` 的技能
|
|
23
|
+
// 是给 Human 显式用的,列进成员 prompt 会把成员引向一个它无权调用的入口。
|
|
24
|
+
// SkillSummary 把这两个开关放在 `invocation` 下;直接读顶层字段会让过滤永远
|
|
25
|
+
// 通过(字段恒为 undefined),被禁的技能照样写进 prompt。
|
|
26
|
+
return summaries.filter((skill) => {
|
|
27
|
+
if (typeof skill?.name !== 'string' || skill.name === '' || isSkillExcluded(skill.name)) return false;
|
|
28
|
+
const modelInvocable = skill?.invocation?.modelInvocable ?? skill?.modelInvocable;
|
|
29
|
+
const disabled = skill?.invocation?.disableModelInvocation ?? skill?.disableModelInvocation;
|
|
30
|
+
if (modelInvocable === false || disabled === true) return false;
|
|
31
|
+
return true;
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function formatSkillSummaries(summaries, options = {}) {
|
|
36
|
+
const assigned = new Set(Array.isArray(options.assigned) ? options.assigned : []);
|
|
37
|
+
const available = modelInvocableSkills(summaries);
|
|
38
|
+
if (available.length === 0) return '';
|
|
39
|
+
const selected = available.filter((skill) => assigned.has(skill.name));
|
|
40
|
+
const limit = Number.isSafeInteger(options.limit) && options.limit > 0 ? options.limit : 12;
|
|
41
|
+
const discoverable = available.filter((skill) => !assigned.has(skill.name)).slice(0, Math.max(0, limit - selected.length));
|
|
42
|
+
const rows = [...selected, ...discoverable].map((skill) => {
|
|
43
|
+
const name = skill.name;
|
|
44
|
+
const description = clean(skill?.description, 240);
|
|
45
|
+
const when = clean(skill?.whenToUse, 180);
|
|
46
|
+
return `- ${name}${assigned.has(name) ? '(已为你配置)' : ''}:${description}${when ? `(何时用:${when})` : ''}`;
|
|
47
|
+
});
|
|
48
|
+
if (rows.length === 0) return '';
|
|
49
|
+
const priority = selected.length > 0 ? '处理匹配任务时优先使用已为你配置的技能。' : '';
|
|
50
|
+
return `\n\n## 可用 DSH 技能\n${rows.join('\n')}\n${priority}需要时用 skill 工具按名字加载完整技能说明;不要凭描述臆造步骤。`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function formatSkillCatalog(skills, options = {}) {
|
|
54
|
+
const summaries = await readSkillCatalog(skills, options).catch(() => []);
|
|
55
|
+
return formatSkillSummaries(summaries, options);
|
|
56
|
+
}
|