🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(skill): publish each user skill version as an archive (#22590)
Arvin Xud74197c888e0
diff --git a/apps/server/src/routers/lambda/userSkill.ts b/apps/server/src/routers/lambda/userSkill.tsindex 2a1492353bb..47f4ee6c76c 100644--- a/apps/server/src/routers/lambda/userSkill.ts+++ b/apps/server/src/routers/lambda/userSkill.ts@@ -1,3 +1,4 @@+import type { UserSkillVersionDetail } from '@lobechat/types';import { z } from 'zod';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';@@ -24,6 +25,14 @@ export const userSkillRouter = router({get: userSkillProcedure.input(z.object({ id: z.string() })).query(async ({ ctx, input }) => (await ctx.userSkillService.getSkill(input.id)) ?? null),++ /** One version as it shipped: its `SKILL.md` and the files beside it. */+ getVersion: userSkillProcedure+ .input(z.object({ id: z.string(), version: z.number().int().min(1) }))+ .query(+ async ({ ctx, input }): Promise<UserSkillVersionDetail | null> =>+ (await ctx.userSkillService.getVersion(input.id, input.version)) ?? null,+ ),});export type UserSkillRouter = typeof userSkillRouter;diff --git a/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.tsindex 9134fc6e0c3..4545f8692e6 100644--- a/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts+++ b/apps/server/src/services/goal/GoalService/__tests__/batchLearning.test.ts@@ -97,10 +97,11 @@ describe('GoalService', () => {// v2 when the break revised it — each version kept whole.const planSkill = next.planSkill!;expect(planSkill.name).toMatch(/^goal-plan-/);- const skill = await new UserSkillService(serverDB, userId).getSkill(planSkill.id);+ const skills = new UserSkillService(serverDB, userId);+ const skill = await skills.getSkill(planSkill.id);expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);expect(skill?.content).toContain('### v2\n补上冷启动这一步');- expect(skill?.versions[0].content).not.toContain('### v2');+ expect((await skills.getVersion(planSkill.id, 1))?.content).not.toContain('### v2');// A re-opened unit names the skill, which carries every later revision…expect(reopened.description).toContain(`user-skills:${planSkill.name}`);// …and still carries the revised plan, in case the skill does not load.@@ -340,11 +341,13 @@ describe('GoalService', () => {await service.decide(graph.goal.id, decision!.id, 'revise', '补上 SSR 播种这一步');const next = (await service.graph(graph.goal.id)).goal.config!.rolloutState!;- const skill = await new UserSkillService(serverDB, userId).getSkill(next.planSkill!.id);+ const skills = new UserSkillService(serverDB, userId);+ const skill = await skills.getSkill(next.planSkill!.id);// The plan's earlier version becomes v1 and the revision v2, so version N// still reads as round N.expect(skill?.versions.map((version) => version.version)).toEqual([1, 2]);- expect(skill?.versions[0].content).toContain('把 store 换成 replica 支撑的实现');- expect(skill?.versions[1].content).toContain('### v2\n补上 SSR 播种这一步');+ const [v1, v2] = await Promise.all([1, 2].map((n) => skills.getVersion(skill!.id, n)));+ expect(v1?.content).toContain('把 store 换成 replica 支撑的实现');+ expect(v2?.content).toContain('### v2\n补上 SSR 播种这一步');});});diff --git a/apps/server/src/services/goal/releaseReview.test.ts b/apps/server/src/services/goal/releaseReview.test.tsindex 49bc42d6b7d..f5c53778087 100644--- a/apps/server/src/services/goal/releaseReview.test.ts+++ b/apps/server/src/services/goal/releaseReview.test.ts@@ -22,6 +22,7 @@ import {} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '@/server/services/aiAgent';+import { mockSkillStorage } from '@/server/services/userSkill/testUtils';import { GoalCriteriaGeneratorService } from './criteriaGenerator';import { GoalService } from './index';@@ -32,6 +33,7 @@ const userId = 'goal-release-review-test-user';beforeEach(async () => {await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+ mockSkillStorage();});afterEach(async () => {diff --git a/apps/server/src/services/goal/testUtils.ts b/apps/server/src/services/goal/testUtils.tsindex ae9979c6f42..0587fdf3988 100644--- a/apps/server/src/services/goal/testUtils.ts+++ b/apps/server/src/services/goal/testUtils.ts@@ -22,6 +22,7 @@ import {} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';+import { mockSkillStorage } from '../userSkill/testUtils';import type { GoalService } from './index';import { GoalManagerService } from './manager';@@ -46,6 +47,8 @@ export const createBatchDecomposition = () => ({export const registerGoalServiceTestCleanup = (serverDB: LobeChatDatabase, userId: string) => {beforeEach(async () => {await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+ // A batch's plan skill publishes every version to storage.+ mockSkillStorage();});afterEach(async () => {diff --git a/apps/server/src/services/skill/packageFiles.test.ts b/apps/server/src/services/skill/packageFiles.test.tsnew file mode 100644index 00000000000..8e6f4e2b3a7--- /dev/null+++ b/apps/server/src/services/skill/packageFiles.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import { MAX_PACKAGE_FILES, namesObjectBuiltIn, packageFilesSchema } from './packageFiles';++const file = (path: string, content = 'x') => ({ content, path });++describe('packageFilesSchema', () => {+ it('takes references, templates and scripts by relative path', () => {+ expect(+ packageFilesSchema.parse([file('scripts/check-pr.sh'), file('references/replica-read.md')]),+ ).toHaveLength(2);+ });++ it('keeps every path inside the package and SKILL.md as the body', () => {+ for (const path of [+ '../secrets.txt',+ '/etc/passwd',+ 'scripts/../../x',+ 'SKILL.md',+ 'a b.md',+ '__proto__',+ 'scripts/constructor',+ ])+ expect(packageFilesSchema.safeParse([file(path)]).success).toBe(false);+ });++ it('refuses two files on one path, and a package too large to load', () => {+ expect(packageFilesSchema.safeParse([file('a.md'), file('a.md')]).success).toBe(false);+ expect(+ packageFilesSchema.safeParse(+ Array.from({ length: MAX_PACKAGE_FILES + 1 }, (_, i) => file(`f${i}.md`)),+ ).success,+ ).toBe(false);+ const big = 'x'.repeat(60_000);+ expect(+ packageFilesSchema.safeParse(Array.from({ length: 5 }, (_, i) => file(`f${i}.md`, big)))+ .success,+ ).toBe(false);+ });+});++describe('namesObjectBuiltIn', () => {+ it('looks at whole segments', () => {+ expect(namesObjectBuiltIn('a/prototype/b')).toBe(true);+ expect(namesObjectBuiltIn('a/prototypes.md')).toBe(false);+ });+});diff --git a/apps/server/src/services/skill/packageFiles.ts b/apps/server/src/services/skill/packageFiles.tsnew file mode 100644index 00000000000..e2af4bda80f--- /dev/null+++ b/apps/server/src/services/skill/packageFiles.ts@@ -0,0 +1,59 @@+import { z } from 'zod';++/**+ * The files a skill package holds beside its `SKILL.md`: references,+ * templates, scripts. These are the rules every way of submitting them shares,+ * so a package reads the same whoever wrote it.+ */++export const MAX_PACKAGE_FILES = 20;+export const MAX_PACKAGE_FILE_CHARS = 64_000;+export const MAX_PACKAGE_CHARS = 256_000;++/**+ * Path segments that name object built-ins. A package is zipped and served from+ * keyed objects, so such a path would set an object's prototype instead of+ * adding an entry.+ */+const OBJECT_BUILT_INS = new Set(['__proto__', 'constructor', 'prototype']);++export const namesObjectBuiltIn = (path: string) =>+ path.split('/').some((segment) => OBJECT_BUILT_INS.has(segment));++/**+ * A path inside the package, e.g. `scripts/check.sh` or `references/rules.md`.+ * Relative, no `..`, and never `SKILL.md`, which is written as the skill's body.+ */+export const packageFilePath = z+ .string()+ .trim()+ .min(1)+ .max(200)+ .regex(/^[\w.-]+(\/[\w.-]+)*$/, 'A package path is relative, like scripts/check.sh')+ .refine((path) => !path.split('/').includes('..'), 'A package path cannot leave the package')+ .refine(+ (path) => !namesObjectBuiltIn(path),+ 'A package path cannot use __proto__, constructor or prototype as a name',+ )+ .refine(+ (path) => path.toLowerCase() !== 'skill.md',+ "SKILL.md is the skill's body; submit it as the body",+ );++/** Files that ship beside `SKILL.md`. Paths are unique; the package stays small enough to load. */+export const packageFilesSchema = z+ .array(+ z.object({ content: z.string().max(MAX_PACKAGE_FILE_CHARS), path: packageFilePath }).strict(),+ )+ .min(1)+ .max(MAX_PACKAGE_FILES)+ .refine(+ (files) => new Set(files.map((file) => file.path)).size === files.length,+ 'Each package file needs its own path',+ )+ .refine(+ (files) => files.reduce((sum, file) => sum + file.content.length, 0) <= MAX_PACKAGE_CHARS,+ `A package holds at most ${MAX_PACKAGE_CHARS} characters of files`,+ );++export type PackageFile = z.infer<typeof packageFilesSchema>[number];diff --git a/apps/server/src/services/skillMaintainer/pathSafety.test.ts b/apps/server/src/services/skillMaintainer/pathSafety.test.tsindex fa7f6397600..dbae3b7b256 100644--- a/apps/server/src/services/skillMaintainer/pathSafety.test.ts+++ b/apps/server/src/services/skillMaintainer/pathSafety.test.ts@@ -17,4 +17,13 @@ describe('assertPackageRelativePath', () => {'path traversal is not allowed',);});++ it('rejects paths that name object built-ins', () => {+ expect(() => assertPackageRelativePath('__proto__/x.md')).toThrow(+ 'object built-in names are not allowed',+ );+ expect(() => assertPackageRelativePath('references/constructor')).toThrow(+ 'object built-in names are not allowed',+ );+ });});diff --git a/apps/server/src/services/skillMaintainer/pathSafety.ts b/apps/server/src/services/skillMaintainer/pathSafety.tsindex abaa2168ac3..966a402d99e 100644--- a/apps/server/src/services/skillMaintainer/pathSafety.ts+++ b/apps/server/src/services/skillMaintainer/pathSafety.ts@@ -1,3 +1,5 @@+import { namesObjectBuiltIn } from '../skill/packageFiles';+/*** Normalizes package-relative skill paths and rejects unsafe path forms.*@@ -14,6 +16,7 @@ export const assertPackageRelativePath = (path: string) => {if (segments.includes('..')) {throw new Error('path traversal is not allowed');}+ if (namesObjectBuiltIn(path)) throw new Error('object built-in names are not allowed');return segments.join('/');};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.userSkillArchive.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.userSkillArchive.test.tsnew file mode 100644index 00000000000..c6a76ab12dd--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/skills.userSkillArchive.test.ts@@ -0,0 +1,252 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => {+ const sandboxService = {+ callTool: vi.fn(),+ capabilities: {+ backgroundCommands: true,+ exportFile: true,+ files: true,+ languages: ['python'],+ persistentSession: true,+ shell: true,+ skillScripts: true,+ },+ exportAndUploadFile: vi.fn(),+ kind: 'onlyboxes',+ };++ return {+ buildDeviceLhEnv: vi.fn(),+ checkHash: vi.fn(),+ createSandboxService: vi.fn(function () {+ return sandboxService;+ }),+ executeToolCall: vi.fn(),+ fileService: {+ getFullFileUrl: vi.fn(),+ },+ findAll: vi.fn(),+ findById: vi.fn(),+ findByName: vi.fn(),+ isLhCommand: vi.fn(),+ getAgentConfigById: vi.fn(),+ getAgentSkills: vi.fn(),+ getUserSettings: vi.fn(),+ marketService: {},+ prepareSkillDirectory: vi.fn(),+ preprocessLhCommand: vi.fn(),+ readResource: vi.fn(),+ resolveContentWorkspaceId: vi.fn(),+ resolveRunWorkspaceId: vi.fn(),+ loadRuntimeSkills: vi.fn(),+ sandboxService,+ };+});++vi.mock('@lobechat/builtin-skills', () => ({+ builtinSkills: [],+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn(function () {+ return {+ getAgentConfigById: mocks.getAgentConfigById,+ };+ }),+}));++vi.mock('@/database/models/agentSkill', () => ({+ AgentSkillModel: vi.fn(function () {+ return {+ findAll: mocks.findAll,+ findById: mocks.findById,+ findByName: mocks.findByName,+ };+ }),+}));++vi.mock('@/database/models/file', () => ({+ FileModel: vi.fn(function () {+ return {+ checkHash: mocks.checkHash,+ };+ }),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn(function () {+ return {+ getUserSettings: mocks.getUserSettings,+ };+ }),+}));++vi.mock('@/helpers/skillFilters', () => ({+ filterBuiltinSkills: vi.fn(function (skills: unknown) {+ return skills;+ }),+}));++vi.mock('@/server/services/agentDocuments', () => ({+ AgentDocumentsService: vi.fn(function () {+ return {+ getAgentSkills: mocks.getAgentSkills,+ };+ }),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function () {+ return mocks.fileService;+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn(function () {+ return mocks.marketService;+ }),+}));++vi.mock('@/server/services/sandbox', async () => {+ const actual = await vi.importActual('@/server/services/sandbox');++ return {+ ...(actual as Record<string, unknown>),+ createSandboxService: mocks.createSandboxService,+ };+});++vi.mock('@/server/services/skill/resource', () => ({+ SkillResourceService: vi.fn(function () {+ return {+ readResource: mocks.readResource,+ };+ }),+}));++vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({+ buildDeviceLhEnv: mocks.buildDeviceLhEnv,+ isLhCommand: mocks.isLhCommand,+ preprocessLhCommand: mocks.preprocessLhCommand,+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: {+ prepareSkillDirectory: mocks.prepareSkillDirectory,+ },+}));++vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>+ mocks.executeToolCall(...args),+}));++vi.mock('@/server/services/userSkill', async () => {+ const actual = await vi.importActual('@/server/services/userSkill');++ return {+ ...(actual as Record<string, unknown>),+ UserSkillService: vi.fn(function () {+ return { loadRuntimeSkills: mocks.loadRuntimeSkills };+ }),+ };+});++vi.mock('../resolveWorkspaceScope', () => ({+ resolveContentWorkspaceId: mocks.resolveContentWorkspaceId,+ resolveRunWorkspaceId: mocks.resolveRunWorkspaceId,+}));++describe('skillsRuntime user skill archives', () => {+ beforeEach(() => {+ vi.clearAllMocks();++ mocks.fileService.getFullFileUrl.mockImplementation(+ async (key: string) => `https://files.example.com/${key}`,+ );+ mocks.findAll.mockResolvedValue({ data: [], total: 0 });+ mocks.findByName.mockResolvedValue(undefined);+ mocks.getAgentSkills.mockResolvedValue([]);+ mocks.getUserSettings.mockResolvedValue({ market: { accessToken: 'market-token' } });+ mocks.preprocessLhCommand.mockImplementation(async (command: string) => ({+ command,+ isLhCommand: false,+ skipSkillLookup: false,+ }));+ mocks.isLhCommand.mockReturnValue(false);+ mocks.resolveContentWorkspaceId.mockImplementation(+ async (ctx?: { workspaceId?: string }) => ctx?.workspaceId,+ );+ mocks.resolveRunWorkspaceId.mockResolvedValue(undefined);+ mocks.sandboxService.callTool.mockResolvedValue({+ result: { exitCode: 0, output: 'ok', stdout: 'ok', success: true },+ success: true,+ });+ });++ // A user skill's scripts run from its latest published version: the archive+ // goes to the sandbox like an imported skill's zip.+ it('ships the latest version of an activated user skill to the sandbox', async () => {+ mocks.loadRuntimeSkills.mockResolvedValue([+ {+ archive: { fileHash: 'plan-hash', url: 'skills/user/plan-hash.zip' },+ body: 'Run the check',+ description: 'How each unit is done',+ identifier: 'user-skills:goal-plan-x',+ name: 'user-skills:goal-plan-x',+ title: 'Plan',+ },+ ]);+ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });++ const result = await runtime.execScript({+ activatedSkills: [{ id: 'user-skills:goal-plan-x', name: 'user-skills:goal-plan-x' }],+ command: 'bash scripts/check.sh',+ description: 'Run the plan check',+ });++ expect(result.success).toBe(true);+ expect(mocks.loadRuntimeSkills).toHaveBeenCalledWith(['user-skills:goal-plan-x'], {+ trustedGenerated: [],+ });+ // Never looked up among imported skills.+ expect(mocks.findByName).not.toHaveBeenCalled();+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith(+ 'execScript',+ expect.objectContaining({+ skillZipUrls: {+ 'user-skills:goal-plan-x': 'https://files.example.com/skills/user/plan-hash.zip',+ },+ }),+ );+ }, 20_000);++ it('ships nothing for a user skill this run may not load', async () => {+ mocks.loadRuntimeSkills.mockResolvedValue([]);+ const { skillsRuntime } = await import('../skills');+ const runtime = await skillsRuntime.factory({+ serverDB: {} as never,+ toolManifestMap: {},+ topicId: 'topic-1',+ userId: 'user-1',+ });++ await runtime.execScript({+ activatedSkills: [{ id: 'user-skills:someone-else', name: 'user-skills:someone-else' }],+ command: 'bash scripts/check.sh',+ description: 'Run a check',+ });++ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith(+ 'execScript',+ expect.not.objectContaining({ skillZipUrls: expect.anything() }),+ );+ }, 20_000);+});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts b/apps/server/src/services/toolExecution/serverRuntimes/skills.tsindex 5ac662b1c90..2d315c36482 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/skills.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/skills.ts@@ -168,6 +168,9 @@ class SkillServerRuntimeService implements SkillRuntimeService {private sandboxSpecification?: SandboxSessionSpecification;private device?: SkillDeviceExecution;private disabledSkillIds: Set<string>;+ private resolveUserSkillArchive?: (+ name: string,+ ) => Promise<{ fileHash: string; url: string } | undefined>;private isSkillGranted?: (identifier: string) => boolean;private shareVisitorBlocked: boolean;private wrapSandbox?: SandboxWrapper;@@ -193,6 +196,10 @@ class SkillServerRuntimeService implements SkillRuntimeService {marketService: MarketService;operationId?: string;resourceService: SkillResourceService;+ /** The archive of a user skill (`user-skills:<name>`) this run may load. */+ resolveUserSkillArchive?: (+ name: string,+ ) => Promise<{ fileHash: string; url: string } | undefined>;/*** Persistence for this run, resolved once by the factory. Every sandbox* this service creates MUST carry the same values the cloud-sandbox runtime@@ -218,6 +225,7 @@ class SkillServerRuntimeService implements SkillRuntimeService {this.agentId = options.agentId;this.skillModel = options.skillModel;this.resourceService = options.resourceService;+ this.resolveUserSkillArchive = options.resolveUserSkillArchive;this.marketService = options.marketService;this.fileService = options.fileService;this.fileModel = options.fileModel;@@ -426,6 +434,17 @@ class SkillServerRuntimeService implements SkillRuntimeService {for (const activatedSkill of activatedSkills) {if (!activatedSkill.name) continue;+ // A user skill's package is its latest published version.+ if (canonicalUserSkillIdentifier(activatedSkill.name)) {+ const archive = await this.resolveUserSkillArchive?.(activatedSkill.name);+ const url = archive && (await this.fileService.getFullFileUrl(archive.url));+ if (archive && url) {+ archives.push({ name: activatedSkill.name, url, zipHash: archive.fileHash });+ log('Resolved zipUrl for user skill %s', activatedSkill.name);+ }+ continue;+ }+// `findByName`, not `skillModel.findByName`: `activatedSkills` is// model-suppliable (see `ExecutionRuntime`'s `args.activatedSkills ??// this.activatedSkills`), so this resolves an arbitrary name into a skill@@ -963,6 +982,40 @@ export const skillsRuntime: ServerRuntimeRegistration = {}: undefined;+ // The user's own skill library is read per call, for the one name asked+ // for — it grows with every goal batch, and this factory runs per tool+ // call. Read under the recovered workspace (a dispatched or resumed run may+ // not carry it on the context).+ const loadUserSkill = async (requested: string) => {+ // Models vary the casing of a name, as the preloaded lookup tolerates.+ const name = canonicalUserSkillIdentifier(requested);+ if (!name || !isSkillReachable(name)) return undefined;+ const [skill] = await new UserSkillService(+ context.serverDB!,+ context.userId!,+ workspaceId,+ context.agentVisibility,+ )+ .loadRuntimeSkills([name], {+ // Only the generated skills this run's own Task names are trusted+ // past a public agent's visibility — never a name the model chose.+ trustedGenerated: context.taskId+ ? readTaskSkillIds(+ (+ await new TaskModel(context.serverDB!, context.userId!, workspaceId).findById(+ context.taskId,+ )+ )?.config,+ )+ : [],+ })+ .catch((error) => {+ log('failed to load user skill %s: %O', name, error);+ return [];+ });+ return skill;+ };+const service = new SkillServerRuntimeService({wrapSandbox: pageSandboxWrapper(context, workspaceId),agentId: context.agentId,@@ -977,6 +1030,9 @@ export const skillsRuntime: ServerRuntimeRegistration = {// device branch below carries the same id for its own routing.operationId: context.operationId,resourceService,+ // A user skill's latest version is its archive, read through the same+ // load as `activateSkill` so the same visibility rules apply.+ resolveUserSkillArchive: async (name) => (await loadUserSkill(name))?.archive,sandboxCwd: sandbox.cwd,sandboxInitialization: sandbox.initialization,sandboxInstanceId: sandbox.environment,@@ -1123,32 +1179,7 @@ export const skillsRuntime: ServerRuntimeRegistration = {// call. Same carrier shape as above, under the recovered workspace (a// dispatched or resumed run may not carry it on the context).resolveSkill: async (requested) => {- // Models vary the casing of a name, as the preloaded lookup tolerates.- const name = canonicalUserSkillIdentifier(requested);- if (!name || !isSkillReachable(name)) return undefined;- const [skill] = await new UserSkillService(- context.serverDB!,- context.userId!,- workspaceId,- context.agentVisibility,- )- .loadRuntimeSkills([name], {- // Only the generated skills this run's own Task names are trusted- // past a public agent's visibility — never a name the model chose.- trustedGenerated: context.taskId- ? readTaskSkillIds(- (- await new TaskModel(context.serverDB!, context.userId!, workspaceId).findById(- context.taskId,- )- )?.config,- )- : [],- })- .catch((error) => {- log('failed to load user skill %s: %O', name, error);- return [];- });+ const skill = await loadUserSkill(requested);return (skill && {content: skill.body,diff --git a/apps/server/src/services/userSkill/archive.test.ts b/apps/server/src/services/userSkill/archive.test.tsnew file mode 100644index 00000000000..96987d10cf2--- /dev/null+++ b/apps/server/src/services/userSkill/archive.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest';++import { packSkillArchive, unpackSkillArchive } from './archive';++describe('skill archive', () => {+ // The zip stores local calendar fields and refuses years before 1980, so its+ // timestamp has to read as 1980 on a server west of UTC too.+ it('packs to the same bytes whatever the server timezone', () => {+ const original = process.env.TZ;+ try {+ process.env.TZ = 'UTC';+ const utc = packSkillArchive('# plan', []);+ process.env.TZ = 'America/New_York';+ expect(packSkillArchive('# plan', []).hash).toBe(utc.hash);+ } finally {+ if (original === undefined) delete process.env.TZ;+ else process.env.TZ = original;+ }+ });++ // Named by its hash in storage: the same package published twice is one object.+ it('zips the same package to the same bytes, whatever order its files come in', () => {+ const a = packSkillArchive('# plan', [+ { data: 'echo ok', path: 'scripts/check.sh' },+ { data: '# rules', path: 'references/review.md' },+ ]);+ const b = packSkillArchive('# plan', [+ { data: '# rules', path: 'references/review.md' },+ { data: 'echo ok', path: 'scripts/check.sh' },+ ]);+ expect(a.hash).toBe(b.hash);+ expect(packSkillArchive('# other plan', []).hash).not.toBe(a.hash);+ });++ it('reads SKILL.md and every file back, a binary one by size', () => {+ const { bytes } = packSkillArchive('# plan', [+ { data: 'echo ok', path: 'scripts/check.sh' },+ { data: new Uint8Array([0xff, 0xfe, 0x00]), path: 'assets/logo.png' },+ ]);++ expect(unpackSkillArchive(bytes)).toEqual({+ content: '# plan',+ files: [+ { binary: true, content: '', path: 'assets/logo.png', size: 3 },+ { content: 'echo ok', path: 'scripts/check.sh', size: 7 },+ ],+ });+ });++ // Package paths come from the caller; one named after an object built-in+ // would set an object's prototype while zipping, so it is refused outright.+ it('refuses a file whose path is an object built-in', () => {+ for (const path of ['__proto__', 'scripts/constructor', 'prototype/x.sh'])+ expect(() => packSkillArchive('# plan', [{ data: 'odd', path }])).toThrow(+ 'names an object built-in',+ );+ });+});diff --git a/apps/server/src/services/userSkill/archive.ts b/apps/server/src/services/userSkill/archive.tsnew file mode 100644index 00000000000..ca5671be222--- /dev/null+++ b/apps/server/src/services/userSkill/archive.ts@@ -0,0 +1,68 @@+import { SKILL_INDEX_FILENAME } from '@lobechat/database/schemas';+import type { SkillArchiveFile } from '@lobechat/types';+import { unzipSync, zipSync } from 'fflate';+import { sha256 } from 'js-sha256';++import { namesObjectBuiltIn } from '../skill/packageFiles';++/**+ * A published skill version as one zip: `SKILL.md` at the root and every file+ * beside it at its path — the same layout a sandbox or device unpacks to run+ * the skill's scripts, and what the review reads a version back from.+ */++/**+ * Every entry carries this time, so the same package always zips to the same+ * bytes. Local, because the zip stores local calendar fields: a UTC instant+ * reads as 1979 west of UTC, which the zip refuses.+ */+const fixedMtime = () => new Date(1980, 0, 1);++export interface SkillArchiveEntry {+ /** Text, or the bytes of a binary file. */+ data: string | Uint8Array;+ path: string;+}++/** Zips `SKILL.md` and the files beside it; the hash names the bytes in storage. */+export const packSkillArchive = (skillMd: string, entries: SkillArchiveEntry[]) => {+ const unsafe = entries.find((entry) => namesObjectBuiltIn(entry.path));+ if (unsafe) throw new Error(`Skill file path ${unsafe.path} names an object built-in`);+ const encoder = new TextEncoder();+ const mtime = fixedMtime();+ const tree: Record<string, [Uint8Array, { mtime: Date }]> = {+ [SKILL_INDEX_FILENAME]: [encoder.encode(skillMd), { mtime }],+ };+ for (const entry of [...entries].sort((a, b) => a.path.localeCompare(b.path))) {+ const data = typeof entry.data === 'string' ? encoder.encode(entry.data) : entry.data;+ tree[entry.path] = [data, { mtime }];+ }+ const bytes = zipSync(tree);+ return { bytes, hash: sha256(bytes) };+};++/** Reads an archive back as its `SKILL.md` and the files beside it, by path. */+export const unpackSkillArchive = (+ bytes: Uint8Array,+): { content: string; files: SkillArchiveFile[] } => {+ const decoder = new TextDecoder('utf-8', { fatal: true });+ let content = '';+ const files: SkillArchiveFile[] = [];+ for (const [path, data] of Object.entries(unzipSync(bytes))) {+ if (path.endsWith('/')) continue;+ let text: string | undefined;+ try {+ text = decoder.decode(data);+ } catch {+ // Not UTF-8: a binary file, shown by size rather than as garbled text.+ }+ if (path === SKILL_INDEX_FILENAME) content = text ?? '';+ else+ files.push(+ text === undefined+ ? { binary: true, content: '', path, size: data.length }+ : { content: text, path, size: data.length },+ );+ }+ return { content, files: files.sort((a, b) => a.path.localeCompare(b.path)) };+};diff --git a/apps/server/src/services/userSkill/index.ts b/apps/server/src/services/userSkill/index.tsindex f7ad58911d9..6512b25c13a 100644--- a/apps/server/src/services/userSkill/index.ts+++ b/apps/server/src/services/userSkill/index.ts@@ -1,11 +1,15 @@import { buildUserSkillIdentifier, USER_SKILLS_IDENTIFIER_PREFIX } from '@lobechat/const';import type { LobeChatDatabase } from '@lobechat/database';import { resourcesTreePrompt } from '@lobechat/prompts';-import type { SkillResourceMeta } from '@lobechat/types';+import type { SkillResourceMeta, UserSkillVersionDetail } from '@lobechat/types';import { sha256 } from 'js-sha256';+import pMap from 'p-map';+import { FileModel } from '@/database/models/file';import {+ type UserSkillArchiveUpload,type UserSkillFile,+ type UserSkillFileEdits,type UserSkillItem,UserSkillModel,type UserSkillOrigin,@@ -13,6 +17,11 @@ import {} from '@/database/models/userSkill';import { renderSkillIndexContent, validateSkillName } from '../skillManagement/frontmatter';+import { packSkillArchive, unpackSkillArchive } from './archive';+import { skillStorage } from './storage';++/** Storage reads one publish runs at once. */+const STORAGE_READ_CONCURRENCY = 5;/*** The user's own skill library: skills that belong to the user rather than to@@ -22,6 +31,11 @@ import { renderSkillIndexContent, validateSkillName } from '../skillManagement/f* Every run lists the library (name and description) and can activate a skill* by name; a run that names a skill in its plugins — `user-skills:<name>` — gets* its content injected up front, scripts included.+ *+ * Every write publishes a version: the whole package zipped and uploaded, then+ * recorded with the write in one transaction. A run reads the skill's+ * documents, which every write leaves equal to its latest version; scripts run+ * from that version's archive.*/export const isUserSkillIdentifier = (id: string) => id.startsWith(USER_SKILLS_IDENTIFIER_PREFIX);@@ -48,6 +62,8 @@ export const canonicalUserSkillIdentifier = (name: string): string | undefined =/** A skill as the skill pool and the skills runtime take it. */export interface UserRuntimeSkill {+ /** The latest version's archive, which `execScript` unpacks to run its scripts. */+ archive?: { fileHash: string; url: string };/** `SKILL.md` alone — `activateSkill` appends the tree of its scripts itself. */body: string;/** `SKILL.md`, then the tree of its scripts: what a run injects up front. */@@ -61,13 +77,30 @@ export interface UserRuntimeSkill {export interface UserSkillDetail extends UserSkillItem {identifier: string;- versions: UserSkillVersion[];+ /** Each version's number, note and origin; its package is read with `getVersion`. */+ versions: Omit<UserSkillVersion, 'archive' | 'content'>[];}const MAX_NAME_ATTEMPTS = 50;-const toResources = (files: UserSkillFile[]): Record<string, SkillResourceMeta> | undefined =>- files.length+/** Writes that lose the race to another publish rebuild their archive this many times. */+const MAX_PUBLISH_ATTEMPTS = 3;++/** The package after `edits`: removed paths dropped, upserted ones replaced or added. */+const applyEdits = (files: UserSkillFile[], edits?: UserSkillFileEdits): UserSkillFile[] => {+ if (!edits) return files;+ const byPath = new Map(files.map((file) => [file.path, file]));+ for (const path of edits.remove ?? []) byPath.delete(path);+ for (const file of edits.upsert ?? []) byPath.set(file.path, file);+ return [...byPath.values()];+};++const toResources = (all: UserSkillFile[]): Record<string, SkillResourceMeta> | undefined => {+ // Resources are served inline as text. A binary file's bytes sit in its+ // `files` row, which the skills runtime does not read for user skills yet, so+ // it is left out rather than offered as an empty text file.+ const files = all.filter((file) => !file.fileId);+ return files.length? Object.fromEntries(files.map((file) => [file.path,@@ -75,11 +108,13 @@ const toResources = (files: UserSkillFile[]): Record<string, SkillResourceMeta>]),): undefined;+};export const toRuntimeSkill = (skill: UserSkillItem): UserRuntimeSkill => {const identifier = buildUserSkillIdentifier(skill.name);const resources = toResources(skill.files);return {+ ...(skill.archive && { archive: { fileHash: skill.archive.fileHash, url: skill.archive.url } }),body: skill.content,content: resources? `${skill.content}\n\n${resourcesTreePrompt(identifier, resources)}`@@ -95,6 +130,9 @@ export const toRuntimeSkill = (skill: UserSkillItem): UserRuntimeSkill => {export class UserSkillService {private model: UserSkillModel;+ private db: LobeChatDatabase;+ private userId: string;+ private workspaceId?: string;/*** `callerAgentVisibility` is the run's agent: a workspace-public agent reads@@ -107,8 +145,39 @@ export class UserSkillService {callerAgentVisibility?: 'private' | 'public' | null,) {this.model = new UserSkillModel(db, userId, workspaceId, callerAgentVisibility);+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;}+ private owner = () => ({ db: this.db, userId: this.userId, workspaceId: this.workspaceId });++ /**+ * Zips a package and uploads it, keyed by its hash: the same package+ * published again lands on the same object.+ */+ private publish = async (skillMd: string, files: UserSkillFile[]) => {+ const binaryIds = files.flatMap((file) => (file.fileId ? [file.fileId] : []));+ const stored = binaryIds.length+ ? await new FileModel(this.db, this.userId, this.workspaceId).findByIds(binaryIds)+ : [];+ // A package's size is the caller's, so its storage reads go a few at a time.+ const entries = await pMap(+ files,+ async (file) => {+ if (!file.fileId) return { data: file.content, path: file.path };+ const row = stored.find((item) => item.id === file.fileId);+ if (!row) throw new Error(`Skill file ${file.path} names a file that is not there`);+ return { data: await skillStorage.read(this.owner(), row.url), path: file.path };+ },+ { concurrency: STORAGE_READ_CONCURRENCY },+ );+ const { bytes, hash } = packSkillArchive(skillMd, entries);+ const url = `skills/user/${hash}.zip`;+ await skillStorage.write(this.owner(), url, bytes);+ return { fileHash: hash, size: bytes.length, url } satisfies UserSkillArchiveUpload;+ };+/** A free name from `base`: `base`, then `base-2`, `base-3`, … */private freeName = async (base: string) => {const name = validateSkillName(base);@@ -130,12 +199,14 @@ export class UserSkillService {title: string;}): Promise<UserSkillItem> => {const name = await this.freeName(params.name);+ const content = renderSkillIndexContent({+ bodyMarkdown: params.body,+ description: params.description,+ name,+ });return this.model.create({- content: renderSkillIndexContent({- bodyMarkdown: params.body,- description: params.description,- name,- }),+ archive: await this.publish(content, params.files ?? []),+ content,description: params.description,files: params.files,name,@@ -145,34 +216,60 @@ export class UserSkillService {});};- /** Writes the next version of a skill's body. Returns its number. */+ /** Writes and publishes the next version of a skill. Returns its number. */reviseSkill = async (id: string,- params: { body: string; note?: string; origin?: UserSkillOrigin },+ params: {+ body: string;+ files?: UserSkillFileEdits;+ note?: string;+ origin?: UserSkillOrigin;+ },): Promise<number | undefined> => {- const skill = await this.model.findById(id);- if (!skill) return undefined;- return this.model.revise(id, {- content: renderSkillIndexContent({+ for (let attempt = 1; attempt <= MAX_PUBLISH_ATTEMPTS; attempt++) {+ const skill = await this.model.findById(id);+ if (!skill) return undefined;+ const content = renderSkillIndexContent({bodyMarkdown: params.body,description: skill.description,name: skill.name,- }),- note: params.note,- origin: params.origin,- });+ });+ // The archive is the package as it reads after this write, so it is built+ // from the version read here; a publish landing in between makes it stale.+ const result = await this.model.revise(id, {+ archive: await this.publish(content, applyEdits(skill.files, params.files)),+ baseVersion: skill.version,+ content,+ files: params.files,+ note: params.note,+ origin: params.origin,+ });+ if (result !== 'stale') return result;+ }+ throw new Error(`Skill ${id} kept changing while this version was published`);};getSkill = async (id: string): Promise<UserSkillDetail | undefined> => {const skill = await this.model.findById(id);if (!skill) return undefined;+ const versions = await this.model.listVersions(id);return {...skill,identifier: buildUserSkillIdentifier(skill.name),- versions: await this.model.listVersions(id),+ versions: versions.map(({ archive: _, content: __, ...version }) => version),};};+ /** One version as it shipped, read back from its archive. */+ getVersion = async (id: string, version: number): Promise<UserSkillVersionDetail | undefined> => {+ const found = (await this.model.listVersions(id)).find((item) => item.version === version);+ if (!found) return undefined;+ const { note, origin } = found;+ if (!found.archive) return { content: found.content ?? '', note, origin, version };+ const unpacked = unpackSkillArchive(await skillStorage.read(this.owner(), found.archive.url));+ return { ...unpacked, note, origin, version };+ };+/** Every skill in the library, shaped for a run. */listRuntimeSkills = async (): Promise<UserRuntimeSkill[]> =>(await this.model.findAll()).map(toRuntimeSkill);diff --git a/apps/server/src/services/userSkill/index.versions.test.ts b/apps/server/src/services/userSkill/index.versions.test.tsnew file mode 100644index 00000000000..7b3571a073c--- /dev/null+++ b/apps/server/src/services/userSkill/index.versions.test.ts@@ -0,0 +1,142 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { UserSkillModel } from '@/database/models/userSkill';+import { documents, files, globalFiles, users } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { UserSkillService } from './index';+import { skillStorage } from './storage';+import { mockSkillStorage } from './testUtils';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'user-skill-versions-test-user';++let storage: Map<string, Uint8Array>;++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+ storage = mockSkillStorage();+});++afterEach(async () => {+ vi.restoreAllMocks();+ await serverDB.delete(documents);+ await serverDB.delete(users);+ await serverDB.delete(globalFiles);+});++const service = () => new UserSkillService(serverDB, userId);++const createPlan = () =>+ service().createSkill({+ body: 'v1 body',+ description: 'How each unit is done',+ files: [{ content: 'echo ok', path: 'scripts/check.sh' }],+ name: 'plan',+ title: 'Plan',+ });++describe('UserSkillService versions', () => {+ it('publishes each version as an archive and reads it back as it shipped', async () => {+ const skill = await createPlan();+ expect(skill.archive?.url).toMatch(/^skills\/user\/\w+\.zip$/);+ expect(storage.has(skill.archive!.url)).toBe(true);++ await service().reviseSkill(skill.id, {+ body: 'v2 body',+ files: {+ remove: ['scripts/check.sh'],+ upsert: [{ content: '# rules', path: 'references/review.md' }],+ },+ note: 'gate broke',+ });++ const v1 = await service().getVersion(skill.id, 1);+ expect(v1?.content).toContain('v1 body');+ expect(v1?.files).toEqual([{ content: 'echo ok', path: 'scripts/check.sh', size: 7 }]);+ const v2 = await service().getVersion(skill.id, 2);+ expect(v2).toMatchObject({ note: 'gate broke', version: 2 });+ expect(v2?.content).toContain('v2 body');+ expect(v2?.files).toEqual([{ content: '# rules', path: 'references/review.md', size: 7 }]);++ // The detail lists versions without reading any archive.+ const detail = await service().getSkill(skill.id);+ expect(detail?.versions.map((v) => [v.version, v.note])).toEqual([+ [1, undefined],+ [2, 'gate broke'],+ ]);+ expect(detail?.versions[0]).not.toHaveProperty('archive');+ expect(await service().getVersion(skill.id, 3)).toBeUndefined();+ });++ // The archive is built from the version the write read; another publish+ // landing in between makes it stale, so the write rebuilds on the new one.+ it('rebuilds the archive when another version lands while it publishes', async () => {+ const skill = await createPlan();+ const write = vi.mocked(skillStorage.write);+ write.mockClear();+ const store = write.getMockImplementation()!;+ // While this write uploads its archive, another one publishes v2.+ write.mockImplementationOnce(async (owner, key, bytes) => {+ await new UserSkillModel(serverDB, userId).revise(skill.id, {+ archive: { fileHash: 'f'.repeat(64), size: 1, url: 'skills/user/other.zip' },+ baseVersion: 1,+ content: 'concurrent body',+ });+ return store(owner, key, bytes);+ });++ expect(await service().reviseSkill(skill.id, { body: 'v3 body' })).toBe(3);+ expect(write).toHaveBeenCalledTimes(2);+ const v3 = await service().getVersion(skill.id, 3);+ expect(v3?.content).toContain('v3 body');+ });++ it('packs a binary file’s bytes from its files row', async () => {+ storage.set('uploads/logo.png', new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0xff, 0xfe]));+ const [logo] = await serverDB+ .insert(files)+ .values({ fileType: 'image/png', name: 'logo.png', size: 6, url: 'uploads/logo.png', userId })+ .returning({ id: files.id });+ const skill = await createPlan();++ await service().reviseSkill(skill.id, {+ body: 'v2 body',+ files: { upsert: [{ content: '', fileId: logo.id, path: 'assets/logo.png' }] },+ });++ expect((await service().getVersion(skill.id, 2))?.files).toEqual([+ { binary: true, content: '', path: 'assets/logo.png', size: 6 },+ { content: 'echo ok', path: 'scripts/check.sh', size: 7 },+ ]);+ });++ // A version from before archives kept only its SKILL.md.+ it('reads a version from before archives as its SKILL.md alone', async () => {+ const skill = await createPlan();+ await serverDB.delete(files);+ await serverDB.insert(documents).values({+ content: 'v1 as kept',+ fileType: 'skills/version',+ filename: 'v1',+ metadata: { version: 1 },+ parentId: skill.id,+ source: 'user-skills',+ sourceType: 'agent',+ title: 'v1',+ totalCharCount: 10,+ totalLineCount: 1,+ userId,+ visibility: 'private',+ });++ expect(await service().getVersion(skill.id, 1)).toEqual({+ content: 'v1 as kept',+ note: undefined,+ origin: undefined,+ version: 1,+ });+ });+});diff --git a/apps/server/src/services/userSkill/storage.ts b/apps/server/src/services/userSkill/storage.tsnew file mode 100644index 00000000000..867bb602ec0--- /dev/null+++ b/apps/server/src/services/userSkill/storage.ts@@ -0,0 +1,27 @@+import type { LobeChatDatabase } from '@lobechat/database';++import { FileService } from '../file';++interface StorageOwner {+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++/**+ * Object storage a user skill's package goes through: the archives its+ * versions publish, and the bytes of its binary files. One seam, so tests can+ * stand in for storage without an S3 behind it.+ */+export const skillStorage = {+ read: (owner: StorageOwner, key: string): Promise<Uint8Array> =>+ new FileService(owner.db, owner.userId, owner.workspaceId).getFileByteArray(key),++ write: async (owner: StorageOwner, key: string, bytes: Uint8Array): Promise<void> => {+ await new FileService(owner.db, owner.userId, owner.workspaceId).uploadBuffer(+ key,+ Buffer.from(bytes),+ 'application/zip',+ );+ },+};diff --git a/apps/server/src/services/userSkill/testUtils.ts b/apps/server/src/services/userSkill/testUtils.tsnew file mode 100644index 00000000000..a0ef01409fe--- /dev/null+++ b/apps/server/src/services/userSkill/testUtils.ts@@ -0,0 +1,20 @@+import { vi } from 'vitest';++import { skillStorage } from './storage';++/**+ * Stands in for the object storage under user skills: what a publish writes+ * reads back. Spied on `skillStorage`, so `vi.restoreAllMocks()` undoes it.+ */+export const mockSkillStorage = () => {+ const objects = new Map<string, Uint8Array>();+ vi.spyOn(skillStorage, 'write').mockImplementation(async (_owner, key, bytes) => {+ objects.set(key, bytes);+ });+ vi.spyOn(skillStorage, 'read').mockImplementation(async (_owner, key) => {+ const bytes = objects.get(key);+ if (!bytes) throw new Error(`No object at ${key}`);+ return bytes;+ });+ return objects;+};diff --git a/packages/database/src/models/__tests__/userSkill.coverage.test.ts b/packages/database/src/models/__tests__/userSkill.coverage.test.tsindex 2147ddd5060..0d89551a8b1 100644--- a/packages/database/src/models/__tests__/userSkill.coverage.test.ts+++ b/packages/database/src/models/__tests__/userSkill.coverage.test.ts@@ -39,6 +39,13 @@ const insertRow = async (values: Partial<typeof documents.$inferInsert> & { filereturn row;};+/** The package a caller publishes alongside every create / revise. */+const archiveFor = (name: string) => ({+ fileHash: `hash-${name}`,+ size: 1,+ url: `skills/${name}.zip`,+});+beforeEach(async () => {await serverDB.delete(users).where(eq(users.id, userId));await serverDB.insert(users).values({ id: userId });@@ -140,12 +147,14 @@ describe('UserSkillModel coverage', () => {describe('findAll', () => {it('loads every skill in the library with its body, ordered by name', async () => {const zeta = await model.create({+ archive: archiveFor('zeta'),content: 'zeta body',description: 'z',name: 'zeta',title: 'Zeta',});const alpha = await model.create({+ archive: archiveFor('alpha'),content: 'alpha body',description: 'a',files: [{ content: 'echo hi', path: 'scripts/run.sh' }],@@ -171,7 +180,13 @@ describe('UserSkillModel coverage', () => {describe('findByNames', () => {it('returns an empty list for no names without reading the library', async () => {- await model.create({ content: 'body', description: 'd', name: 'present', title: 'Present' });+ await model.create({+ archive: archiveFor('present'),+ content: 'body',+ description: 'd',+ name: 'present',+ title: 'Present',+ });expect(await model.findByNames([])).toEqual([]);});@@ -185,7 +200,13 @@ describe('UserSkillModel coverage', () => {metadata: null,});- expect(await model.revise(bundle.id, { content: 'v2 body' })).toBe(2);+ expect(+ await model.revise(bundle.id, {+ archive: archiveFor('legacy-v2'),+ baseVersion: 1,+ content: 'v2 body',+ }),+ ).toBe(2);expect(await model.findById(bundle.id)).toMatchObject({ version: 2 });expect((await model.listVersions(bundle.id)).map((v) => v.version)).toEqual([2]);});@@ -194,13 +215,19 @@ describe('UserSkillModel coverage', () => {describe('listVersions', () => {it('reads a version row with no content or version number as empty / 0', async () => {const bundle = await insertRow({ fileType: SKILL_BUNDLE_FILE_TYPE, filename: 'versions' });- await model.revise(bundle.id, { content: 'v2 body' });const bare = await insertRow({content: null,fileType: SKILL_VERSION_FILE_TYPE,metadata: null,parentId: bundle.id,});+ // A version written before archives: its SKILL.md lives on the row itself.+ await insertRow({+ content: 'v2 body',+ fileType: SKILL_VERSION_FILE_TYPE,+ metadata: { version: 2 },+ parentId: bundle.id,+ });const versions = await model.listVersions(bundle.id);diff --git a/packages/database/src/models/__tests__/userSkill.test.ts b/packages/database/src/models/__tests__/userSkill.test.tsindex d2f9cf36703..a567a828588 100644--- a/packages/database/src/models/__tests__/userSkill.test.ts+++ b/packages/database/src/models/__tests__/userSkill.test.ts@@ -3,7 +3,15 @@ import { and, eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { documents, users, workspaces } from '../../schemas';+import {+ documents,+ files,+ globalFiles,+ SKILL_FILE_FILE_TYPE,+ SKILL_SCRIPT_FILE_TYPE,+ users,+ workspaces,+} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { DocumentModel } from '../document';import { UserSkillModel } from '../userSkill';@@ -22,10 +30,30 @@ beforeEach(async () => {afterEach(async () => {await serverDB.delete(documents).where(eq(documents.userId, userId));await serverDB.delete(users);+ await serverDB.delete(globalFiles);});+/** A version's archive as the service hands it over: already uploaded. */+const archive = () => {+ const fileHash = crypto.randomUUID().replaceAll('-', '');+ return { fileHash, size: 42, url: `skills/user/${fileHash}.zip` };+};++/** Revises from the version the caller reads, as the service does. */+const revise = async (+ skills: UserSkillModel,+ id: string,+ params: Omit<Parameters<UserSkillModel['revise']>[1], 'archive' | 'baseVersion'>,+) =>+ skills.revise(id, {+ archive: archive(),+ baseVersion: (await skills.findById(id))?.version ?? 1,+ ...params,+ });+const create = () =>model.create({+ archive: archive(),content: '---\nname: migrate-slice\ndescription: Move one slice\n---\nv1 body',description: 'Move one slice',files: [{ content: 'echo ok', language: 'bash', path: 'scripts/check.sh' }],@@ -35,7 +63,7 @@ const create = () =>});describe('UserSkillModel', () => {- it('creates a skill with its SKILL.md, its scripts and a v1 snapshot', async () => {+ it('creates a skill with its SKILL.md, its files and v1 published', async () => {const skill = await create();expect(skill).toMatchObject({@@ -47,25 +75,169 @@ describe('UserSkillModel', () => {version: 1,});expect(skill.content).toContain('v1 body');- expect(await model.listVersions(skill.id)).toMatchObject([{ version: 1 }]);+ expect(skill.archive).toMatchObject({ size: 42 });+ const [bundle] = await serverDB+ .select({ content: documents.content })+ .from(documents)+ .where(eq(documents.id, skill.id));+ expect(bundle.content).toBe('Move one slice');+ expect(await model.listVersions(skill.id)).toMatchObject([+ { archive: skill.archive, version: 1 },+ ]);expect(await model.nameTaken('migrate-slice')).toBe(true);});- it('keeps every version whole as it revises, and serves the latest', async () => {+ // A version is a release: an archive in `files` under the bundle, never a+ // document row of its own.+ it('publishes every version as an archive under the bundle', async () => {const skill = await create();- expect(await model.revise(skill.id, { content: 'v2 body', note: 'gate broke' })).toBe(2);- expect(await model.revise(skill.id, { content: 'v3 body' })).toBe(3);+ expect(await revise(model, skill.id, { content: 'v2 body', note: 'gate broke' })).toBe(2);+ expect(await revise(model, skill.id, { content: 'v3 body' })).toBe(3);const latest = await model.findById(skill.id);expect(latest).toMatchObject({ content: 'v3 body', version: 3 });- expect((await model.listVersions(skill.id)).map((v) => [v.version, v.content, v.note])).toEqual(- [- [1, expect.stringContaining('v1 body'), undefined],- [2, 'v2 body', 'gate broke'],- [3, 'v3 body', undefined],- ],- );+ const versions = await model.listVersions(skill.id);+ expect(versions.map((v) => [v.version, v.note])).toEqual([+ [1, undefined],+ [2, 'gate broke'],+ [3, undefined],+ ]);+ expect(latest!.archive).toEqual(versions[2].archive);+ const archives = await serverDB+ .select({ name: files.name, source: files.source })+ .from(files)+ .where(eq(files.parentId, skill.id));+ expect(archives.map((row) => row.name).sort()).toEqual([+ '[email protected]',+ '[email protected]',+ '[email protected]',+ ]);+ expect(new Set(archives.map((row) => row.source))).toEqual(new Set(['skill']));+ const versionRows = await serverDB+ .select({ id: documents.id })+ .from(documents)+ .where(and(eq(documents.parentId, skill.id), eq(documents.fileType, 'skills/version')));+ expect(versionRows).toEqual([]);+ });++ it('edits the files beside SKILL.md in place', async () => {+ const skill = await create();++ await revise(model, skill.id, {+ content: 'v2 body',+ files: {+ upsert: [+ { content: 'echo strict', language: 'bash', path: 'scripts/check.sh' },+ { content: '# review rules', path: 'references/review.md' },+ ],+ },+ });+ expect((await model.findById(skill.id))!.files).toEqual([+ { content: '# review rules', path: 'references/review.md' },+ { content: 'echo strict', language: 'bash', path: 'scripts/check.sh' },+ ]);++ await revise(model, skill.id, { content: 'v3 body', files: { remove: ['scripts/check.sh'] } });+ await revise(model, skill.id, { content: 'v4 body' });++ expect((await model.findById(skill.id))!.files).toEqual([+ { content: '# review rules', path: 'references/review.md' },+ ]);+ const rows = await serverDB+ .select({ filename: documents.filename })+ .from(documents)+ .where(and(eq(documents.parentId, skill.id), eq(documents.fileType, SKILL_FILE_FILE_TYPE)));+ expect(rows.map((row) => row.filename)).toEqual(['references/review.md']);+ });++ // The archive is built from the version read before the write: a publish+ // landing in between would leave it describing a package that never was.+ it('refuses a write built on a version that is no longer the latest', async () => {+ const skill = await create();+ expect(await revise(model, skill.id, { content: 'v2 body' })).toBe(2);++ expect(+ await model.revise(skill.id, { archive: archive(), baseVersion: 1, content: 'stale body' }),+ ).toBe('stale');+ expect(await model.findById(skill.id)).toMatchObject({ content: 'v2 body', version: 2 });+ expect(await model.listVersions(skill.id)).toHaveLength(2);+ });++ // Skills written before archives: their files are `skills/script` rows and+ // their versions `skills/version` snapshots of SKILL.md. Both still read; a+ // file written again becomes a `skills/file`.+ it('reads a skill written before archives, and moves its files over as they are written', async () => {+ const skill = await create();+ await serverDB+ .update(documents)+ .set({ fileType: SKILL_SCRIPT_FILE_TYPE })+ .where(eq(documents.parentId, skill.id));+ await serverDB.delete(files).where(eq(files.parentId, skill.id));+ await serverDB.insert(documents).values({+ content: 'v1 as kept',+ fileType: 'skills/version',+ filename: 'v1',+ metadata: { note: 'first', version: 1 },+ parentId: skill.id,+ source: 'user-skills',+ sourceType: 'agent',+ title: 'v1',+ totalCharCount: 10,+ totalLineCount: 1,+ userId,+ visibility: 'private',+ });+ // Only the index row is `skills/index`; restore it.+ await serverDB+ .update(documents)+ .set({ fileType: 'skills/index' })+ .where(and(eq(documents.parentId, skill.id), eq(documents.filename, 'SKILL.md')));++ expect((await model.findById(skill.id))!.files.map((file) => file.path)).toEqual([+ 'scripts/check.sh',+ ]);+ const [legacy] = await model.listVersions(skill.id);+ expect(legacy).toMatchObject({ content: 'v1 as kept', note: 'first', version: 1 });+ expect(legacy.archive).toBeUndefined();++ await revise(model, skill.id, {+ content: 'v2 body',+ files: { upsert: [{ content: 'echo v2', path: 'scripts/check.sh' }] },+ });+ const [row] = await serverDB+ .select({ fileType: documents.fileType })+ .from(documents)+ .where(and(eq(documents.parentId, skill.id), eq(documents.filename, 'scripts/check.sh')));+ expect(row.fileType).toBe(SKILL_FILE_FILE_TYPE);+ expect((await model.listVersions(skill.id)).map((v) => [v.version, !!v.archive])).toEqual([+ [1, false],+ [2, true],+ ]);+ });++ // A binary file keeps its bytes in `files`; the package row links it.+ it('keeps a binary file in files and links it by fileId', async () => {+ const [logo] = await serverDB+ .insert(files)+ .values({+ fileType: 'image/png',+ name: 'logo.png',+ size: 3,+ url: 'skills/logo.png',+ userId,+ })+ .returning({ id: files.id });+ const skill = await create();+ await revise(model, skill.id, {+ content: 'v2 body',+ files: { upsert: [{ content: 'ignored', fileId: logo.id, path: 'assets/logo.png' }] },+ });++ expect((await model.findById(skill.id))!.files).toEqual([+ { content: '', fileId: logo.id, path: 'assets/logo.png' },+ { content: 'echo ok', language: 'bash', path: 'scripts/check.sh' },+ ]);});it('loads skills by name for a run, and only the owner sees them', async () => {@@ -76,7 +248,7 @@ describe('UserSkillModel', () => {]);const other = new UserSkillModel(serverDB, otherUserId);expect(await other.findById(skill.id)).toBeUndefined();- expect(await other.revise(skill.id, { content: 'hijack' })).toBeUndefined();+ expect(await revise(other, skill.id, { content: 'hijack' })).toBeUndefined();});it('lists the library as a catalog without reading any body', async () => {@@ -94,6 +266,7 @@ describe('UserSkillModel', () => {it('flags a skill a goal batch wrote as generated', async () => {await model.create({+ archive: archive(),content: 'v1',description: 'How each unit is done',name: 'goal-plan-x',@@ -114,6 +287,7 @@ describe('UserSkillModel', () => {.returning();const creator = new UserSkillModel(serverDB, userId, workspace.id);const skill = await creator.create({+ archive: archive(),content: 'Do it.',description: 'Move one slice',name: 'migrate-slice',@@ -124,7 +298,7 @@ describe('UserSkillModel', () => {expect(await member.listCatalog()).toEqual([]);expect(await member.findByNames(['migrate-slice'])).toEqual([]);expect(await member.findById(skill.id)).toBeUndefined();- expect(await member.revise(skill.id, { content: 'hijack' })).toBeUndefined();+ expect(await revise(member, skill.id, { content: 'hijack' })).toBeUndefined();// The creator still has it…expect((await creator.listCatalog()).map((item) => item.id)).toEqual([skill.id]);// …but not through a workspace-public agent, which must not read (and@@ -135,6 +309,7 @@ describe('UserSkillModel', () => {// A goal batch's own plan loads there only when the run's Task names it —// it is the goal's plan — never because a name was merely supplied.await creator.create({+ archive: archive(),content: 'Plan body',description: 'How each unit is done',files: [{ content: 'echo ok', path: 'scripts/check.sh' }],diff --git a/packages/database/src/models/userSkill.ts b/packages/database/src/models/userSkill.tsindex 8080771d488..0ce99c947f2 100644--- a/packages/database/src/models/userSkill.ts+++ b/packages/database/src/models/userSkill.ts@@ -1,8 +1,11 @@-import { and, asc, eq, inArray, isNull, or, type SQL, sql } from 'drizzle-orm';+import { FileSource } from '@lobechat/types';+import { and, asc, eq, inArray, isNotNull, isNull, or, type SQL, sql } from 'drizzle-orm';import {documents,+ files,SKILL_BUNDLE_FILE_TYPE,+ SKILL_FILE_FILE_TYPE,SKILL_INDEX_FILE_TYPE,SKILL_INDEX_FILENAME,SKILL_SCRIPT_FILE_TYPE,@@ -11,33 +14,74 @@ import {} from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import { FileModel } from './file';import { nonNull } from './utils/rows';/**- * A user-level skill library on the `documents` table.+ * A user-level skill library: the skill's content on the `documents` table,+ * its published versions in `files`.** A skill is a `skills/bundle` row owned by the user and bound to no agent, so- * any agent or run can load it by name. Under it sit its `SKILL.md`- * (`skills/index`), its scripts (`skills/script`, the code in `content`, the- * language in `metadata.language`) and one `skills/version` row per version —- * the full `SKILL.md` it read at that version. Versions are rows of their own,- * not document history: history is trimmed, a version must stay readable.+ * any agent or run can load it by name; its `content` is the skill's+ * description. Under it sit its `SKILL.md`+ * (`skills/index`) and the files beside it (`skills/file`, the path in+ * `filename`): text in `content`, a binary file's bytes in the `files` row its+ * `fileId` links. These are ordinary documents, edited in place.+ *+ * A version is a release, not an edit: every write publishes the whole package+ * as a zip archive — a `files` row under the bundle (`parentId`, source+ * `skill`), its number, note and origin in `metadata`. An archive never+ * changes, so version N reads exactly the package it shipped, and it is what a+ * sandbox or device unpacks to run the skill's scripts.+ *+ * Skills written before archives keep their versions as `skills/version` rows+ * (the `SKILL.md` alone) and their files as `skills/script`; both are still read.** Rows carry `sourceType: 'agent'` so the Page library never lists them.*/+/** File types a bundle's files are stored as: current, and before `skills/file`. */+const FILE_TYPES = [SKILL_FILE_FILE_TYPE, SKILL_SCRIPT_FILE_TYPE];++/** Source of the `files` rows a skill owns: binary files and version archives. */+const SKILL_FILE_SOURCE = FileSource.Skill;+export interface UserSkillFile {+ /** Text of the file; empty for a binary one. */content: string;+ /** A binary file: the `files` row holding its bytes. */+ fileId?: string;language?: string;/** Path inside the bundle, e.g. `scripts/check.sh`. */path: string;}+/** Files to write beside `SKILL.md` by path, and paths to drop; the rest stay. */+export interface UserSkillFileEdits {+ remove?: string[];+ upsert?: UserSkillFile[];+}++/** A version's archive, once its bytes are in storage. */+export interface UserSkillArchiveUpload {+ fileHash: string;+ size: number;+ /** Storage key of the zip. */+ url: string;+}++export interface UserSkillArchive extends UserSkillArchiveUpload {+ fileId: string;+}+/** Where a skill or a version came from, e.g. the goal batch that wrote it. */export type UserSkillOrigin = Record<string, unknown>;export interface UserSkillVersion {- content: string;+ /** The published package. Absent on a version from before archives. */+ archive?: UserSkillArchive;+ /** `SKILL.md` of a version from before archives; an archived one holds its own. */+ content?: string;createdAt: Date;id: string;note?: string;@@ -58,6 +102,8 @@ export interface UserSkillCatalogItem {}export interface UserSkillItem {+ /** The latest published version's archive; absent on a skill from before archives. */+ archive?: UserSkillArchive;/** The current `SKILL.md`. */content: string;createdAt: Date;@@ -76,10 +122,26 @@ interface UserSkillMeta {version: number;}-const SOURCE_TYPE = 'agent' as const;+type DocumentRow = typeof documents.$inferSelect;const lineCount = (text: string) => (text ? text.split('\n').length : 0);+const SOURCE_TYPE = 'agent' as const;++const toFile = (row: DocumentRow): UserSkillFile => ({+ content: row.content ?? '',+ ...(row.fileId && { fileId: row.fileId }),+ ...(row.metadata?.language && { language: row.metadata.language as string }),+ path: row.filename ?? '',+});++const toArchive = (row: typeof files.$inferSelect): UserSkillArchive => ({+ fileHash: row.fileHash ?? '',+ fileId: row.id,+ size: row.size,+ url: row.url,+});+export class UserSkillModel {private db: LobeChatDatabase;private userId: string;@@ -144,6 +206,7 @@ export class UserSkillModel {private row = (params: {content: string;description?: string | null;+ fileId?: string;fileType: string;filename: string;metadata?: Record<string, unknown>;@@ -155,6 +218,7 @@ export class UserSkillModel {{content: params.content,description: params.description ?? null,+ fileId: params.fileId,fileType: params.fileType,filename: params.filename,metadata: params.metadata,@@ -169,20 +233,97 @@ export class UserSkillModel {},);+ /** The caller's own `files` rows: a skill's archives and binary files. */+ private filesScope = () =>+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),+ eq(files.userId, this.userId),+ eq(files.source, SKILL_FILE_SOURCE),+ );++ /** The archive rows under these bundles, every version. */+ private archiveRows = (bundleIds: string[]) =>+ this.db+ .select()+ .from(files)+ .where(+ and(+ this.filesScope(),+ inArray(files.parentId, bundleIds),+ isNotNull(sql`${files.metadata} -> 'skillVersion'`),+ ),+ );++ /** Writes files beside `SKILL.md` in place by path, and drops removed ones. */+ private writeFiles = async (tx: Transaction, bundleId: string, edits: UserSkillFileEdits) => {+ const atPath = (path: string) =>+ and(+ this.scope(),+ eq(documents.parentId, bundleId),+ inArray(documents.fileType, FILE_TYPES),+ eq(documents.filename, path),+ );+ for (const path of edits.remove ?? []) await tx.delete(documents).where(atPath(path));+ for (const file of edits.upsert ?? []) {+ // A binary file's bytes live in its `files` row, not here.+ const content = file.fileId ? '' : file.content;+ const metadata = file.language ? { language: file.language } : undefined;+ const [updated] = await tx+ .update(documents)+ .set({+ content,+ fileId: file.fileId ?? null,+ // A file written as a script before is a file now.+ fileType: SKILL_FILE_FILE_TYPE,+ metadata,+ totalCharCount: content.length,+ totalLineCount: lineCount(content),+ updatedAt: new Date(),+ })+ .where(atPath(file.path))+ .returning({ id: documents.id });+ if (updated) continue;+ await tx.insert(documents).values(+ this.row({+ content,+ fileId: file.fileId,+ fileType: SKILL_FILE_FILE_TYPE,+ filename: file.path,+ metadata,+ parentId: bundleId,+ title: file.path,+ }),+ );+ }+ };++ /** Records a published version: its archive as a `files` row under the bundle. */private insertVersion = async (tx: Transaction,- bundleId: string,- params: { content: string; note?: string; origin?: UserSkillOrigin; version: number },+ bundle: { id: string; name: string },+ params: {+ archive: UserSkillArchiveUpload;+ note?: string;+ origin?: UserSkillOrigin;+ version: number;+ },) => {- await tx.insert(documents).values(- this.row({- content: params.content,- fileType: SKILL_VERSION_FILE_TYPE,- filename: `v${params.version}`,- metadata: { note: params.note, origin: params.origin, version: params.version },- parentId: bundleId,- title: `v${params.version}`,- }),+ await new FileModel(this.db, this.userId, this.workspaceId).create(+ {+ fileHash: params.archive.fileHash,+ fileType: 'application/zip',+ metadata: { note: params.note, origin: params.origin, skillVersion: params.version },+ name: `${bundle.name}@${params.version}.zip`,+ parentId: bundle.id,+ size: params.archive.size,+ source: SKILL_FILE_SOURCE,+ url: params.archive.url,+ // Owner-only, like the skill itself.+ visibility: 'private',+ },+ // Registers the bytes once; the same package published again reuses them.+ true,+ tx,);};@@ -197,10 +338,11 @@ export class UserSkillModel {};/**- * Creates a skill at version 1: its bundle, its `SKILL.md`, its scripts, and- * the v1 snapshot.+ * Creates a skill at version 1: its bundle, its `SKILL.md`, its files, and+ * v1 published as `archive` — the package as written here, already uploaded.*/create = async (params: {+ archive: UserSkillArchiveUpload;content: string;description: string;files?: UserSkillFile[];@@ -214,7 +356,8 @@ export class UserSkillModel {.insert(documents).values(this.row({- content: '',+ // The bundle reads as the skill it holds: its description.+ content: params.description,description: params.description,fileType: SKILL_BUNDLE_FILE_TYPE,filename: params.name,@@ -235,47 +378,45 @@ export class UserSkillModel {title: SKILL_INDEX_FILENAME,}),);- for (const file of params.files ?? []) {- await tx.insert(documents).values(- this.row({- content: file.content,- fileType: SKILL_SCRIPT_FILE_TYPE,- filename: file.path,- metadata: file.language ? { language: file.language } : undefined,- parentId: bundle.id,- title: file.path,- }),- );- }- await this.insertVersion(tx, bundle.id, {- content: params.content,- note: params.note,- origin: params.origin,- version: 1,- });+ await this.writeFiles(tx, bundle.id, { upsert: params.files });+ await this.insertVersion(+ tx,+ { id: bundle.id, name: params.name },+ { archive: params.archive, note: params.note, origin: params.origin, version: 1 },+ );return bundle.id;});return (await this.findById(id))!;};/**- * Writes a new version: replaces the current `SKILL.md` and freezes it as the- * next version. Returns the new version number, or undefined when the skill- * is not the caller's.+ * Writes the next version: replaces `SKILL.md`, applies the file edits, and+ * publishes `archive` — the package as it reads after them, built from+ * version `baseVersion`. Returns the new version number; `'stale'` when+ * another write published since `baseVersion` (the archive would not match),+ * and undefined when the skill is not the caller's.*/revise = async (id: string,- params: { content: string; note?: string; origin?: UserSkillOrigin },- ): Promise<number | undefined> =>+ params: {+ archive: UserSkillArchiveUpload;+ baseVersion: number;+ content: string;+ files?: UserSkillFileEdits;+ note?: string;+ origin?: UserSkillOrigin;+ },+ ): Promise<number | 'stale' | undefined> =>this.db.transaction(async (tx) => {const [bundle] = await tx- .select({ id: documents.id, metadata: documents.metadata })+ .select({ filename: documents.filename, id: documents.id, metadata: documents.metadata }).from(documents).where(and(this.bundleWhere(), eq(documents.id, id))).for('update').limit(1);if (!bundle) return undefined;const meta = (bundle.metadata?.userSkill ?? { version: 1 }) as UserSkillMeta;+ if (meta.version !== params.baseVersion) return 'stale';const version = meta.version + 1;await tx@@ -300,35 +441,36 @@ export class UserSkillModel {updatedAt: new Date(),}).where(and(this.bundleWhere(), eq(documents.id, id)));- await this.insertVersion(tx, id, {- content: params.content,- note: params.note,- origin: params.origin,- version,- });+ if (params.files) await this.writeFiles(tx, id, params.files);+ await this.insertVersion(+ tx,+ { id, name: bundle.filename ?? '' },+ { archive: params.archive, note: params.note, origin: params.origin, version },+ );return version;});- private load = async (bundles: (typeof documents.$inferSelect)[]): Promise<UserSkillItem[]> => {+ private load = async (bundles: DocumentRow[]): Promise<UserSkillItem[]> => {if (!bundles.length) return [];- const children = await this.db- .select()- .from(documents)- .where(- and(- // The bundles were authorized by the caller's read; their own rows- // follow them.- this.ownerScope(),- inArray(- documents.parentId,- bundles.map((bundle) => bundle.id),+ const bundleIds = bundles.map((bundle) => bundle.id);+ const [children, archives] = await Promise.all([+ this.db+ .select()+ .from(documents)+ .where(+ and(+ // The bundles were authorized by the caller's read; their own rows+ // follow them.+ this.ownerScope(),+ inArray(documents.parentId, bundleIds),+ inArray(documents.fileType, [SKILL_INDEX_FILE_TYPE, ...FILE_TYPES]),),- inArray(documents.fileType, [SKILL_INDEX_FILE_TYPE, SKILL_SCRIPT_FILE_TYPE]),- ),- )- .orderBy(asc(documents.filename));+ )+ .orderBy(asc(documents.filename)),+ this.archiveRows(bundleIds),+ ]);// One pass over the children, not one per bundle.- const byBundle = new Map<string, (typeof children)[number][]>();+ const byBundle = new Map<string, DocumentRow[]>();for (const child of children) {// Children are selected by inArray(documents.parentId, …), which never matches a NULL parentId.const parentId = nonNull(child.parentId, 'documents.parent_id');@@ -339,17 +481,17 @@ export class UserSkillModel {return bundles.map((bundle) => {const own = byBundle.get(bundle.id) ?? [];const meta = (bundle.metadata?.userSkill ?? { version: 1 }) as UserSkillMeta;+ const archive = archives.find(+ (row) =>+ row.parentId === bundle.id &&+ Number((row.metadata as Record<string, unknown>)?.skillVersion) === meta.version,+ );return {+ ...(archive && { archive: toArchive(archive) }),content: own.find((child) => child.fileType === SKILL_INDEX_FILE_TYPE)?.content ?? '',createdAt: bundle.createdAt,description: bundle.description ?? '',- files: own- .filter((child) => child.fileType === SKILL_SCRIPT_FILE_TYPE)- .map((child) => ({- content: child.content ?? '',- language: child.metadata?.language,- path: child.filename ?? '',- })),+ files: own.filter((child) => child.fileType !== SKILL_INDEX_FILE_TYPE).map(toFile),id: bundle.id,name: bundle.filename ?? '',origin: meta.origin,@@ -444,27 +586,48 @@ export class UserSkillModel {return this.load(bundles);};- /** Every version of a skill, oldest first. */+ /**+ * Every version of a skill, oldest first: the published archives, and the+ * `SKILL.md` snapshots of versions from before archives.+ */listVersions = async (id: string): Promise<UserSkillVersion[]> => {- const rows = await this.db- .select()- .from(documents)- .where(- and(- this.scope(),- eq(documents.parentId, id),- eq(documents.fileType, SKILL_VERSION_FILE_TYPE),+ const [archives, legacy] = await Promise.all([+ this.archiveRows([id]),+ this.db+ .select()+ .from(documents)+ .where(+ and(+ this.scope(),+ eq(documents.parentId, id),+ eq(documents.fileType, SKILL_VERSION_FILE_TYPE),+ ),),- );- return rows- .map((row) => ({+ ]);+ const versions = new Map<number, UserSkillVersion>();+ for (const row of legacy) {+ const version = Number(row.metadata?.version ?? 0);+ versions.set(version, {content: row.content ?? '',createdAt: row.createdAt,id: row.id,note: row.metadata?.note,origin: row.metadata?.origin,- version: Number(row.metadata?.version ?? 0),- }))- .sort((a, b) => a.version - b.version);+ version,+ });+ }+ for (const row of archives) {+ const metadata = (row.metadata ?? {}) as Record<string, any>;+ const version = Number(metadata.skillVersion);+ versions.set(version, {+ archive: toArchive(row),+ createdAt: row.createdAt,+ id: row.id,+ note: metadata.note,+ origin: metadata.origin,+ version,+ });+ }+ return [...versions.values()].sort((a, b) => a.version - b.version);};}diff --git a/packages/database/src/schemas/file.ts b/packages/database/src/schemas/file.tsindex c721c38b453..a4e6d92a9ae 100644--- a/packages/database/src/schemas/file.ts+++ b/packages/database/src/schemas/file.ts@@ -42,10 +42,23 @@ export const SKILL_BUNDLE_FILE_TYPE = 'skills/bundle';/** File type used by the SKILL.md index document inside a managed skill bundle. */export const SKILL_INDEX_FILE_TYPE = 'skills/index';-/** File type of a script file inside a skill bundle; its language sits in `metadata.language`. */+/**+ * File type of a file beside `SKILL.md` in a skill bundle, its path in+ * `filename`. Text sits in `content`; a binary file links its `files` row+ * through `fileId`. Its MIME type and a script's language sit in `metadata`.+ */+export const SKILL_FILE_FILE_TYPE = 'skills/file';++/**+ * What a bundle's files were written as before they held more than scripts.+ * Still read; rewritten as `skills/file` the next time one is written.+ */export const SKILL_SCRIPT_FILE_TYPE = 'skills/script';-/** File type of one frozen version of a user skill's `SKILL.md`, kept under its bundle. */+/**+ * File type of a version snapshot of a user skill's `SKILL.md`, from before+ * versions were published as archives in `files`. Still read, never written.+ */export const SKILL_VERSION_FILE_TYPE = 'skills/version';/**diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.tsindex 44ce39f15ad..3498f2276df 100644--- a/packages/types/src/files/index.ts+++ b/packages/types/src/files/index.ts@@ -30,6 +30,11 @@ export enum FileSource {/** Audio recording owned by a meeting (`meetings.audio_file_id`), not the resource library. */Meeting = 'meeting',PageEditor = 'page-editor',+ /**+ * A file a skill package holds: a binary file beside its `SKILL.md`, or a+ * published version's archive. Owned by the skill, not by the library.+ */+ Skill = 'skill',/*** Image an agent's tool returned — a Claude Code `Read` on an image file —* uploaded so the tool card can preview it. Owned by that message, not by@@ -58,6 +63,7 @@ export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [FileSource.Meeting,FileSource.ToolResult,FileSource.ChatAttachment,+ FileSource.Skill,];/** Sources a generation model wrote, as opposed to anything a human put there. */diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 91d0bc2b49c..c5366a59cae 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -83,6 +83,7 @@ export * from './trash';export * from './understanding';export * from './user';export * from './userMemory';+export * from './userSkill';export * from './verify';export * from './widget';export * from './work';diff --git a/packages/types/src/userSkill.ts b/packages/types/src/userSkill.tsnew file mode 100644index 00000000000..f223ce8f733--- /dev/null+++ b/packages/types/src/userSkill.ts@@ -0,0 +1,20 @@+/** A file read back from a skill's archive: text, or a binary one by size alone. */+export interface SkillArchiveFile {+ binary?: boolean;+ content: string;+ path: string;+ size: number;+}++/** One version of a user skill as it shipped: its `SKILL.md` and the files beside it. */+export interface UserSkillVersionDetail {+ content: string;+ /**+ * The files that version shipped. Absent on a version from before archives,+ * which kept only its `SKILL.md`: read the skill's current files.+ */+ files?: SkillArchiveFile[];+ note?: string;+ origin?: Record<string, unknown>;+ version: number;+}diff --git a/src/features/Acceptance/Viewer/Gate/GateReview.tsx b/src/features/Acceptance/Viewer/Gate/GateReview.tsxindex 6417f28ee3e..95880b2a3cc 100644--- a/src/features/Acceptance/Viewer/Gate/GateReview.tsx+++ b/src/features/Acceptance/Viewer/Gate/GateReview.tsx@@ -494,7 +494,10 @@ interface GateReviewProps {const GateReview = memo<GateReviewProps>(({ dossier, inModal, onClose, onDecided }) => {const { t } = useTranslation('verify');const [selected, setSelected] = useState<Selection>();- const { extraFiles, filesOpen, toggleFiles } = usePlanFiles(dossier.plan.skillId);+ const { extraFiles, filesOpen, toggleFiles } = usePlanFiles(+ dossier.plan.skillId,+ dossier.plan.revision,+ );const average =dossier.units.reduce((sum, unit) => sum + unit.tokens, 0) / Math.max(1, dossier.units.length);const probes = dossier.kind === 'probes';diff --git a/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx b/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsxindex db6665c9543..eaccbcd6779 100644--- a/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx+++ b/src/features/Acceptance/Viewer/Gate/SkillDirectory.tsx@@ -3,8 +3,12 @@import { createStaticStyles, cssVar, Flexbox, Highlighter, Markdown } from '@lobehub/ui';import { memo, useMemo, useState } from 'react';+import AsyncError from '@/components/AsyncError';import Loading from '@/components/Loading/CircleLoading';-import { skillVersionContent } from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';+import {+ unreadableVersions,+ useSkillVersion,+} from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';import { getLanguage } from '@/features/AgentSkillDetail/ContentViewer';import FileTree from '@/features/FileTree';import { skillFileTree } from '@/features/SkillViewer/skillFileTree';@@ -58,16 +62,33 @@ const SkillDirectory = memo<SkillDirectoryProps>(const { data: skill, isLoading } = useClientDataSWR(['goal-gate-plan-skill', skillId], () =>userSkillService.get(skillId),);- const files = useMemo(() => skill?.files ?? [], [skill]);+ const {+ data: shipped,+ error,+ isLoading: isVersionLoading,+ mutate,+ } = useSkillVersion(skillId, revision);+ // The package as the reviewed version shipped it, when that version kept its files.+ const files = useMemo(() => shipped?.files ?? skill?.files ?? [], [shipped, skill]);const resourceTree = useMemo(() => skillFileTree(files), [files]);const contentMap = useMemo(() => Object.fromEntries(files.map((file) => [file.path, file.content])),[files],);- if (isLoading) return <Loading />;+ if (isLoading || isVersionLoading) return <Loading />;+ // Unread, the fallback and the latest files would pass as this version.+ if (unreadableVersions([{ body: shipped?.content, error }]).length > 0)+ return (+ <AsyncError+ error={error}+ onRetry={() => {+ void mutate();+ }}+ />+ );- const index = skillVersionContent(skill?.versions, revision) ?? fallbackContent;+ const index = shipped?.content ?? fallbackContent;// Folded, the tree can't switch files: the viewer is back on `SKILL.md`.const shown = filesOpen ? selectedFile : SKILL_INDEX;diff --git a/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts b/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.tsindex 30e1ca321cd..36801dd7235 100644--- a/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts+++ b/src/features/Acceptance/Viewer/Gate/usePlanFiles.test.ts@@ -6,11 +6,18 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { usePlanFiles } from './usePlanFiles';-const skill = vi.hoisted(() => ({ current: undefined as { files: unknown[] } | undefined }));+const skill = vi.hoisted(() => ({+ current: undefined as { files: unknown[] } | undefined,+ /** Each version's package as its archive reads, by number. */+ versions: {} as Record<number, { files?: unknown[] }>,+}));vi.mock('@/libs/swr', () => ({useClientDataSWR: (key: unknown) => ({ data: key ? skill.current : undefined }),}));+vi.mock('@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions', () => ({+ useSkillVersion: (_skillId: string, version: number) => ({ data: skill.versions[version] }),+}));vi.mock('@/services/userSkill', () => ({ userSkillService: { get: vi.fn() } }));const file = (path: string) => ({ content: '', path });@@ -18,6 +25,7 @@ const file = (path: string) => ({ content: '', path });describe('usePlanFiles', () => {beforeEach(() => {skill.current = undefined;+ skill.versions = {};});// The owner asked whether the plan carries scripts or more documents: a plan@@ -25,14 +33,14 @@ describe('usePlanFiles', () => {it('opens the directory of a plan that ships more than SKILL.md', () => {skill.current = { files: [file('scripts/check.sh'), file('references/review.md')] };- const { result } = renderHook(() => usePlanFiles('skill-1'));+ const { result } = renderHook(() => usePlanFiles('skill-1', 1));expect(result.current).toMatchObject({ extraFiles: 2, filesOpen: true });});it('reads a lone SKILL.md as a document until the owner opens the tree', () => {skill.current = { files: [] };- const { result } = renderHook(() => usePlanFiles('skill-1'));+ const { result } = renderHook(() => usePlanFiles('skill-1', 1));expect(result.current).toMatchObject({ extraFiles: 0, filesOpen: false });act(() => result.current.toggleFiles());@@ -42,10 +50,25 @@ describe('usePlanFiles', () => {it('lets the owner fold a directory that opened on its own', () => {skill.current = { files: [file('scripts/check.sh')] };- const { result } = renderHook(() => usePlanFiles('skill-1'));+ const { result } = renderHook(() => usePlanFiles('skill-1', 1));act(() => result.current.toggleFiles());expect(result.current.filesOpen).toBe(false);});++ // The owner reviews one version: its package is what that version shipped,+ // not whatever the skill carries now.+ it('counts the files of the version under review', () => {+ skill.current = {+ files: [file('scripts/check.sh'), file('references/review.md'), file('templates/pr.md')],+ };+ skill.versions = { 1: { files: [] }, 2: { files: [file('scripts/check.sh')] } };++ expect(renderHook(() => usePlanFiles('skill-1', 1)).result.current).toMatchObject({+ extraFiles: 0,+ filesOpen: false,+ });+ expect(renderHook(() => usePlanFiles('skill-1', 2)).result.current.extraFiles).toBe(1);+ });});diff --git a/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts b/src/features/Acceptance/Viewer/Gate/usePlanFiles.tsindex cd7d66393ba..2e5ef9f1583 100644--- a/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts+++ b/src/features/Acceptance/Viewer/Gate/usePlanFiles.ts@@ -1,5 +1,6 @@import { useState } from 'react';+import { useSkillVersion } from '@/features/AgentGoals/ProcessControl/BatchPlan/skillVersions';import { useClientDataSWR } from '@/libs/swr';import { userSkillService } from '@/services/userSkill';@@ -7,14 +8,15 @@ import { userSkillService } from '@/services/userSkill';* The plan skill's directory under review. A plan that ships scripts or* references opens on its whole directory, so the owner sees every file it* carries; a lone `SKILL.md` reads as a document until they open the tree.- * Shares the directory's request, so it costs no second fetch.+ * Shares the directory's requests, so it costs no second fetch.*/-export const usePlanFiles = (skillId?: string) => {+export const usePlanFiles = (skillId: string | undefined, revision: number) => {const { data: skill } = useClientDataSWR(skillId ? ['goal-gate-plan-skill', skillId] : null, () =>userSkillService.get(skillId!),);- // `files` holds what sits beside `SKILL.md`, not `SKILL.md` itself.- const extraFiles = skill?.files?.length ?? 0;+ const { data: shipped } = useSkillVersion(skillId, revision);+ // What sits beside `SKILL.md` in the reviewed version (not `SKILL.md` itself).+ const extraFiles = (shipped?.files ?? skill?.files ?? []).length;const [toggled, setToggled] = useState<boolean>();const filesOpen = toggled ?? extraFiles > 0;return {diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsxindex 267a65e41e2..b391951320f 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanCompareModal.tsx@@ -14,10 +14,13 @@ import { t } from 'i18next';import { memo, useState } from 'react';import { useTranslation } from 'react-i18next';+import AsyncError from '@/components/AsyncError';+import Loading from '@/components/Loading/CircleLoading';import { DIFF_OPTIONS, withTrailingNewline } from '@/features/Dashboard/WidgetDetail/diffContent';import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';import type { PlanVersion } from './planVersion';+import { unreadableVersions, useSkillVersion } from './skillVersions';const styles = createStaticStyles(({ css }) => ({bar: css`@@ -47,15 +50,25 @@ const styles = createStaticStyles(({ css }) => ({interface PlanCompareProps {/** Compared with by default; the version before `target` when omitted. */base?: number;+ /** The plan skill whose versions these are; absent for a plan from before skills. */+ skillId?: string;target: number;versions: PlanVersion[];}-const bodyOf = (version?: PlanVersion) =>- version ? parseSkillMarkdownFrontmatter(version.content).body : '';+/** One side of the diff: a skill version read from its archive, else the round's text. */+const useBody = (skillId: string | undefined, versions: PlanVersion[], revision: number) => {+ const { data, error, mutate } = useSkillVersion(skillId, revision);+ const content = data?.content ?? versions.find((v) => v.revision === revision)?.content;+ return {+ body: content === undefined ? undefined : parseSkillMarkdownFrontmatter(content).body,+ error,+ retry: mutate,+ };+};/** Two versions of a batch's plan, side by side as a diff, each one pickable. */-const PlanCompare = memo<PlanCompareProps>(({ base, target, versions }) => {+const PlanCompare = memo<PlanCompareProps>(({ base, skillId, target, versions }) => {const { t } = useTranslation('chat');const [to, setTo] = useState(target);const [from, setFrom] = useState(@@ -65,8 +78,9 @@ const PlanCompare = memo<PlanCompareProps>(({ base, target, versions }) => {label: `v${version.revision}`,value: version.revision,}));- const before = bodyOf(versions.find((version) => version.revision === from));- const after = bodyOf(versions.find((version) => version.revision === to));+ const before = useBody(skillId, versions, from);+ const after = useBody(skillId, versions, to);+ const failed = unreadableVersions([before, after]);return (<div data-plan-compare className={styles.root}>@@ -88,14 +102,23 @@ const PlanCompare = memo<PlanCompareProps>(({ base, target, versions }) => {/></Flexbox><div className={styles.body}>- {before.trim() === after.trim() ? (+ {failed.length > 0 ? (+ <AsyncError+ error={failed[0].error}+ onRetry={() => {+ for (const side of failed) void side.retry();+ }}+ />+ ) : before.body === undefined || after.body === undefined ? (+ <Loading />+ ) : before.body.trim() === after.body.trim() ? (<Text type={'secondary'}>{t('goalBatch.planPanel.same', { base: from })}</Text>) : (<CodeDiffdiffOptions={DIFF_OPTIONS}language={'markdown'}- newContent={withTrailingNewline(after)}- oldContent={withTrailingNewline(before)}+ newContent={withTrailingNewline(after.body)}+ oldContent={withTrailingNewline(before.body)}showHeader={false}viewMode={'unified'}/>diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsxindex e68b14c7123..df7f29bd54c 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanDetail.tsx@@ -2,12 +2,14 @@ import { Text } from '@lobehub/ui';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import AsyncError from '@/components/AsyncError';import Loading from '@/components/Loading/CircleLoading';import SkillViewer from '@/features/SkillViewer';import type { GoalGraphView } from '../goalGraphViewModel';import type { BatchModel, BatchRound } from '../Graph/batchModel';import { usePlanVersions, usePlanVersionSelection } from './planVersion';+import { unreadableVersions, useSkillVersion } from './skillVersions';/*** A batch's plan, opened from its node, read as the skill it is kept as: the@@ -26,19 +28,35 @@ interface PlanDetailProps {const PlanDetail = memo<PlanDetailProps>(({ graph, model, round }) => {const { t } = useTranslation('chat');const { selected } = usePlanVersionSelection();- const { files, isLoading, versions } = usePlanVersions(graph, model);-- if (isLoading) return <Loading />;-+ const { files: latestFiles, isLoading, skillId, versions } = usePlanVersions(graph, model);const revision = selected ?? round.planVersion;const current = versions.find((version) => version.revision === revision);+ const {+ data: shipped,+ error,+ isLoading: isVersionLoading,+ mutate,+ } = useSkillVersion(current && skillId, revision);++ if (isLoading || isVersionLoading) return <Loading />;+ if (unreadableVersions([{ body: shipped?.content, error }]).length > 0)+ return (+ <AsyncError+ error={error}+ onRetry={() => {+ void mutate();+ }}+ />+ );+const forked = model.rounds.find((item) => item.planVersion === revision)?.forked;return (<SkillViewer- content={current?.content}+ content={shipped?.content ?? current?.content}entityId={`${model.planSkill?.id ?? model.batchId}:${revision}`}- files={files}+ // The package as this version shipped it, when it kept its own files.+ files={shipped?.files ?? latestFiles}notice={forked && (<Text fontSize={12} style={{ paddingBlockStart: 12 }} type={'secondary'}>diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions.tsxindex 9817eec0561..00b54c9fc7e 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/PlanHeaderActions.tsx@@ -24,7 +24,7 @@ interface PlanHeaderActionsProps {const PlanHeaderActions = memo<PlanHeaderActionsProps>(({ graph, model, round }) => {const { t } = useTranslation('chat');const { selected, setSelected } = usePlanVersionSelection();- const { versions } = usePlanVersions(graph, model);+ const { skillId, versions } = usePlanVersions(graph, model);if (versions.length < 2) return null;const current = selected ?? round.planVersion;@@ -58,7 +58,7 @@ const PlanHeaderActions = memo<PlanHeaderActionsProps>(({ graph, model, round })icon={GitCompareArrows}size={DESKTOP_HEADER_ICON_SMALL_SIZE}title={t('goalBatch.planPanel.compare')}- onClick={() => openPlanCompareModal({ target: current, versions })}+ onClick={() => openPlanCompareModal({ skillId, target: current, versions })}/></Flexbox>);diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx b/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsxindex f5dc4cc281b..4ce6e7b7610 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/planVersion.tsx@@ -28,8 +28,11 @@ PlanVersionProvider.displayName = 'GoalPlanVersionProvider';export const usePlanVersionSelection = () => use(PlanVersionContext);export interface PlanVersion {- /** `SKILL.md` as kept, frontmatter included. */- content: string;+ /**+ * The plan's text, for a batch from before the plan became a skill. A skill+ * version's package is read on demand (`useSkillVersion`).+ */+ content?: string;revision: number;}@@ -48,13 +51,19 @@ export const usePlanVersions = (graph: GoalGraphView, model: BatchModel) => {);const kept = [...(skill?.versions ?? [])].sort((a, b) => a.version - b.version);const versions: PlanVersion[] = kept.length- ? kept.map((version) => ({ content: version.content, revision: version.version }))+ ? kept.map((version) => ({ revision: version.version })): model.rounds.filter((item) => item.templateId).map((item: BatchRound) => ({content: (item.templateId && graph.byId[item.templateId]?.node.description) || '',revision: item.planVersion,}));- // A skill's scripts are its latest set; versions keep `SKILL.md` alone.- return { files: skill?.files ?? [], isLoading: !!planSkill && isLoading, versions };+ // The skill's current files, for a version that did not keep its own.+ return {+ files: skill?.files ?? [],+ isLoading: !!planSkill && isLoading,+ // Whose versions to read: only once the skill has listed them.+ skillId: kept.length ? planSkill?.id : undefined,+ versions,+ };};diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.tsindex e3400a4cc4e..08bf6750190 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.test.ts@@ -1,15 +1,23 @@-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { skillVersionContent } from './skillVersions';+import { unreadableVersions } from './skillVersions';-describe('skillVersionContent', () => {- it('reads a kept version whole, frontmatter included', () => {- const versions = [{ content: '---\nname: plan\n---\nv2 body', version: 2 }];- expect(skillVersionContent(versions, 2)).toBe('---\nname: plan\n---\nv2 body');- expect(skillVersionContent(versions, 3)).toBeUndefined();+vi.mock('@/services/userSkill', () => ({ userSkillService: {} }));++describe('unreadableVersions', () => {+ const error = new Error('storage down');++ // A failed read has to surface: it must not read as still loading.+ it('names a version that failed with nothing to show', () => {+ const failed = { error };+ expect(unreadableVersions([{ body: '# v1' }, failed])).toEqual([failed]);+ });++ it('leaves out one still loading', () => {+ expect(unreadableVersions([{}])).toEqual([]);});- it('has nothing to offer when the payload carries no versions', () => {- expect(skillVersionContent(undefined, 1)).toBeUndefined();+ it('leaves out one whose text survived a failed refresh', () => {+ expect(unreadableVersions([{ body: '', error }])).toEqual([]);});});diff --git a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.tsindex 087b71c3504..46a77c1ba32 100644--- a/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts+++ b/src/features/AgentGoals/ProcessControl/BatchPlan/skillVersions.ts@@ -1,9 +1,21 @@+import { useClientDataSWR } from '@/libs/swr';+import { userSkillService } from '@/services/userSkill';+/**- * One version's `SKILL.md` as a plan skill kept it — frontmatter included, as- * the document view shows it. A payload without `versions` (an older server)- * has none to offer, rather than throwing.+ * One version of a skill as it shipped — its `SKILL.md` and the files beside+ * it — read from its archive on demand. A version never changes, so it is+ * fetched once and shared by every view that reads it.*/-export const skillVersionContent = (- versions: readonly { content: string; version: number }[] | null | undefined,- revision: number,-): string | undefined => (versions ?? []).find((version) => version.version === revision)?.content;+export const useSkillVersion = (skillId: string | undefined, version: number | undefined) =>+ useClientDataSWR(+ skillId && version ? ['user-skill-version', skillId, version] : null,+ () => userSkillService.getVersion(skillId!, version!),+ { revalidateOnFocus: false, revalidateOnReconnect: false },+ );++/**+ * The versions that failed to read and have nothing to show. Pending ones are+ * not among them, and neither is one whose text is already there.+ */+export const unreadableVersions = <T extends { body?: string; error?: unknown }>(versions: T[]) =>+ versions.filter((version) => version.body === undefined && !!version.error);diff --git a/src/features/SkillViewer/index.tsx b/src/features/SkillViewer/index.tsxindex 52b184a8876..86af085f804 100644--- a/src/features/SkillViewer/index.tsx+++ b/src/features/SkillViewer/index.tsx@@ -19,7 +19,7 @@ import FileTree from '@/features/FileTree';import SkillFrontmatterCard from '@/features/Portal/Document/SkillFrontmatterCard';import { parseSkillMarkdownFrontmatter } from '@/utils/skillMarkdown';-import { skillFileTree } from './skillFileTree';+import { shownSkillFile, skillFileTree } from './skillFileTree';const SKILL_INDEX = 'SKILL.md';@@ -108,6 +108,9 @@ const SkillViewer = ({[files],);+ // A file picked in another version may not be in this one.+ const shown = shownSkillFile(selectedFile, files ?? [], SKILL_INDEX);+const { body, frontmatter } = parseSkillMarkdownFrontmatter(content);const atStart = filesPosition === 'start';@@ -149,7 +152,7 @@ const SkillViewer = ({</Flexbox><FileTreeresourceTree={resourceTree}- selectedFile={selectedFile}+ selectedFile={shown}onSelectFile={setSelectedFile}/></>@@ -171,7 +174,7 @@ const SkillViewer = ({{atStart && fileTree}<div {...stylex.props(styles.body)}>{atStart && intro}- {selectedFile === SKILL_INDEX ? (+ {shown === SKILL_INDEX ? (<div {...stylex.props(styles.index)}><EditorCanvaseditable={false}@@ -182,7 +185,7 @@ const SkillViewer = ({/></div>) : (- <ContentViewer contentMap={contentMap} key={selectedFile} selectedFile={selectedFile} />+ <ContentViewer contentMap={contentMap} key={shown} selectedFile={shown} />)}</div>{!atStart && fileTree}diff --git a/src/features/SkillViewer/skillFileTree.test.ts b/src/features/SkillViewer/skillFileTree.test.tsindex b15e16d4a4e..d080127b75c 100644--- a/src/features/SkillViewer/skillFileTree.test.ts+++ b/src/features/SkillViewer/skillFileTree.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { skillFileTree } from './skillFileTree';+import { shownSkillFile, skillFileTree } from './skillFileTree';describe('skillFileTree', () => {it('nests a skill’s files into folders, folders first', () => {@@ -28,3 +28,17 @@ describe('skillFileTree', () => {expect(skillFileTree(undefined)).toEqual([]);});});++describe('shownSkillFile', () => {+ const v2 = [{ path: 'scripts/check-pr.sh' }, { path: 'references/replica-read.md' }];++ it('keeps the file the reader picked while the version ships it', () => {+ expect(shownSkillFile('scripts/check-pr.sh', v2)).toBe('scripts/check-pr.sh');+ });++ // Picked in v2, then v1 opened: v1 has no such file, so its SKILL.md shows.+ it('falls back to SKILL.md in a version without the picked file', () => {+ expect(shownSkillFile('scripts/check-pr.sh', [])).toBe('SKILL.md');+ expect(shownSkillFile('SKILL.md', [])).toBe('SKILL.md');+ });+});diff --git a/src/features/SkillViewer/skillFileTree.ts b/src/features/SkillViewer/skillFileTree.tsindex edb8f8f8a8b..faca7691728 100644--- a/src/features/SkillViewer/skillFileTree.ts+++ b/src/features/SkillViewer/skillFileTree.ts@@ -34,3 +34,14 @@ export const skillFileTree = ();return sort(root);};++/**+ * The file a reader sees: the one they picked, while the version on screen+ * ships it. A version without it — the reader picked a script in v2, then+ * switched to v1 — shows its `SKILL.md` rather than an empty viewer.+ */+export const shownSkillFile = (+ selected: string,+ files: readonly { path: string }[],+ index = 'SKILL.md',+): string => (files.some((file) => file.path === selected) ? selected : index);diff --git a/src/services/userSkill.ts b/src/services/userSkill.tsindex 85af33f6e82..3f5119b7882 100644--- a/src/services/userSkill.ts+++ b/src/services/userSkill.ts@@ -1,3 +1,5 @@+import type { UserSkillVersionDetail } from '@lobechat/types';+import { lambdaClient } from '@/libs/trpc/client';export type UserSkillDetail = NonNullable<@@ -7,6 +9,9 @@ export type UserSkillVersion = UserSkillDetail['versions'][number];class UserSkillService {get = async (id: string) => lambdaClient.userSkill.get.query({ id });++ getVersion = async (id: string, version: number): Promise<UserSkillVersionDetail | null> =>+ lambdaClient.userSkill.getVersion.query({ id, version });}export const userSkillService = new UserSkillService();