Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(agent-vault): add skills to access bundles (#8981)
Saif Ur Rahman80c24189e34f
diff --git a/backend/e2e-test/routes/v1/agent-vault.spec.ts b/backend/e2e-test/routes/v1/agent-vault.spec.tsindex 0bcf0e46d1..6561f16cf6 100644--- a/backend/e2e-test/routes/v1/agent-vault.spec.ts+++ b/backend/e2e-test/routes/v1/agent-vault.spec.ts@@ -21,6 +21,7 @@ import {import { agentVaultResolveDALFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-resolve-dal";import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";import { agentVaultSessionLogConfigDALFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-config-dal";+import { AGENT_VAULT_MAX_SKILLS } from "@app/ee/services/agent-vault-skill/agent-vault-skill-fns";import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-dal";import { groupDALFactory } from "@app/ee/services/group/group-dal";import { isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";@@ -48,6 +49,7 @@ import { projectDALFactory } from "@app/services/project/project-dal";import { roleDALFactory } from "@app/services/role/role-dal";import { secretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";import { serviceTokenDALFactory } from "@app/services/service-token/service-token-dal";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { userDALFactory } from "@app/services/user/user-dal";declare const testKeyStore: TKeyStoreFactory;@@ -265,6 +267,38 @@ const createAccessBundle = async (name: string) => {return (JSON.parse(res.payload) as { accessBundle: { id: string; name: string } }).accessBundle;};+// The project's own key, loaded the way the server loads it, so a test can read and write sealed text directly.+// The spec runs in its own module graph, which is why the env config is initialized again here.+let kmsService: TKmsServiceFactory | undefined;+const projectCipher = async (projectId: string) => {+ if (!kmsService) {+ await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);+ kmsService = kmsServiceFactory({+ kmsRootConfigDAL: testKmsRootConfigDAL,+ kmsLegacyEncryptionKeyDAL: kmsLegacyEncryptionKeyDALFactory(testDb),+ kmsKekHistoryDAL: kmsKekHistoryDALFactory(testDb),+ kmsDAL: kmskeyDALFactory(testDb),+ internalKmsDAL: internalKmsDALFactory(testDb),+ internalKmsKeyVersionDAL: internalKmsKeyVersionDALFactory(testDb),+ orgDAL: orgDALFactory(testDb),+ projectDAL: projectDALFactory(testDb),+ hsmService: testHsmService,+ keyStore: {+ getItem: async () => null,+ setItemWithExpiry: async () => "OK" as const,+ deleteItem: async () => 0+ },+ envConfig: getConfig()+ });+ const hsmStatus = await isHsmActiveAndEnabled({+ hsmService: testHsmService,+ kmsRootConfigDAL: testKmsRootConfigDAL+ });+ await kmsService.startService(hsmStatus, { skipRotationState: true });+ }+ return kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+};+describe("Agent Vault V1 Router", async () => {// Tests create their own proxies, and an org can hold only AGENT_VAULT_MAX_PROXIES_PER_ORG.beforeEach(async () => {@@ -1303,39 +1337,11 @@ describe("Agent Vault V1 Router", async () => {};};- // The project's own key, loaded the way the server loads it, so a test can read and write sealed text directly.- // The spec runs in its own module graph, which is why the env config is initialized again here.- let kmsService: TKmsServiceFactory | undefined;const cipherFor = async (accessBundleId: string) => {- if (!kmsService) {- await initEnvConfig(testHsmService, testKmsRootConfigDAL, testSuperAdminDAL, logger);- kmsService = kmsServiceFactory({- kmsRootConfigDAL: testKmsRootConfigDAL,- kmsLegacyEncryptionKeyDAL: kmsLegacyEncryptionKeyDALFactory(testDb),- kmsKekHistoryDAL: kmsKekHistoryDALFactory(testDb),- kmsDAL: kmskeyDALFactory(testDb),- internalKmsDAL: internalKmsDALFactory(testDb),- internalKmsKeyVersionDAL: internalKmsKeyVersionDALFactory(testDb),- orgDAL: orgDALFactory(testDb),- projectDAL: projectDALFactory(testDb),- hsmService: testHsmService,- keyStore: {- getItem: async () => null,- setItemWithExpiry: async () => "OK" as const,- deleteItem: async () => 0- },- envConfig: getConfig()- });- const hsmStatus = await isHsmActiveAndEnabled({- hsmService: testHsmService,- kmsRootConfigDAL: testKmsRootConfigDAL- });- await kmsService.startService(hsmStatus, { skipRotationState: true });- }const { projectId } = (await testDb("agent_vault_access_bundles").where({ id: accessBundleId }).first()) as {projectId: string;};- return kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });+ return projectCipher(projectId);};const STORED_REFERENCE = /\{\{([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}\}/g;@@ -4528,6 +4534,8 @@ describe("Agent Vault V1 Router", async () => {agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),+ projectDAL: projectDALFactory(testDb),+ userDAL: userDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })@@ -4663,6 +4671,8 @@ describe("Agent Vault V1 Router", async () => {agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),+ projectDAL: projectDALFactory(testDb),+ userDAL: userDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () =>@@ -4836,6 +4846,8 @@ describe("Agent Vault V1 Router", async () => {agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),+ projectDAL: projectDALFactory(testDb),+ userDAL: userDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })@@ -4880,6 +4892,913 @@ describe("Agent Vault V1 Router", async () => {});});+ describe("skills", async () => {+ const skillsUrl = "/api/v1/agent-vault/skills";+ const bundleSkillsUrl = (accessBundleId: string) => `/api/v1/agent-vault/access-bundles/${accessBundleId}/skills`;++ // Names are unique across the org's Agent Vault and every test here shares it.+ beforeEach(async () => {+ const project = await testDb("projects")+ .where({ orgId: seedData1.organization.id, type: ProjectType.AgentVault })+ .first();+ if (project) await testDb("agent_vault_skills").where({ projectId: project.id }).del();+ });++ type TSkill = { id: string; name: string; description: string; latestVersion: number };+ type TListedSkill = TSkill & { accessBundles: { id: string; name: string }[] };+ type TSkillVersion = { id: string; version: number; sha256: string; sizeBytes: number; fileCount: number };+ type TFile = { path: string; mode: string; contentBase64: string };++ const skillFiles = (name: string, body = "Do the thing.", extra: TFile[] = []): TFile[] => [+ {+ path: "SKILL.md",+ mode: "0644",+ contentBase64: Buffer.from(`---\nname: ${name}\ndescription: ${body}\n---\n${body}\n`).toString("base64")+ },+ ...extra+ ];++ const createSkill = async (name: string, body?: string) => {+ const res = await inject("POST", skillsUrl, { files: skillFiles(name, body) });+ expect(res.statusCode).toBe(200);+ return JSON.parse(res.payload) as { skill: TSkill; version: TSkillVersion };+ };++ const publish = (skillId: string, files: TFile[]) => inject("PATCH", `${skillsUrl}/${skillId}`, { files });++ const sessionSkillsUrl = "/api/v1/agent-vault/session/skills";++ const mintFor = async (bundles: { name: string }[], mintAs = inject) => {+ const mint = await mintAs("POST", "/api/v1/agent-vault/sessions", {+ accessBundles: bundles.map((bundle) => bundle.name),+ ttl: "1h"+ });+ expect(mint.statusCode).toBe(200);+ return (JSON.parse(mint.payload) as { session: { id: string; token: string } }).session;+ };++ type TCreateAuditLog = (dto: { actor: unknown; orgId?: string; event: unknown }) => Promise<void>;+ // The route's audit calls, recorded as they are made: the e2e plan has no audit log retention, so none+ // reach the audit_logs table.+ const recordAuditLogs = () => {+ const { auditLog } = (+ globalThis as unknown as { testServices: { auditLog: { createAuditLog: TCreateAuditLog } } }+ ).testServices;+ return vi.spyOn(auditLog, "createAuditLog");+ };++ const fetchSessionSkills = (authorization?: string) =>+ testServer.inject({+ method: "GET",+ url: sessionSkillsUrl,+ headers: authorization === undefined ? {} : { authorization }+ });++ test("an admin creates, reads, lists and deletes a skill", async () => {+ const { skill, version } = await createSkill("crud-skill", "Reviews code");+ expect(skill).toMatchObject({+ name: "crud-skill",+ description: "Reviews code",+ latestVersion: 1+ });+ expect(skill).not.toHaveProperty("bundleCount");+ expect(version).toMatchObject({ version: 1, fileCount: 1 });+ expect(version.sha256).toMatch(/^[0-9a-f]{64}$/);++ const list = await inject("GET", skillsUrl);+ expect(list.statusCode).toBe(200);+ expect(JSON.parse(list.payload)).toMatchObject({+ skills: [{ name: "crud-skill", accessBundles: [] }],+ totalCount: 1+ });++ const bundle = await createAccessBundle("skills-crud-bundle");+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: skill.id })).statusCode).toBe(200);++ const detail = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(detail.payload).skill).toMatchObject({+ accessBundles: [{ id: bundle.id, name: bundle.name }],+ files: skillFiles("crud-skill", "Reviews code")+ });++ const files = await inject("GET", `${skillsUrl}/${skill.id}/versions/1`);+ expect(files.statusCode).toBe(200);+ const { version: withFiles } = JSON.parse(files.payload) as { version: TSkillVersion & { files: TFile[] } };+ expect(withFiles.files).toEqual(skillFiles("crud-skill", "Reviews code"));+ expect(withFiles.sha256).toBe(crypto.createHash("sha256").update(JSON.stringify(withFiles.files)).digest("hex"));++ const removed = await inject("DELETE", `${skillsUrl}/${skill.id}`);+ expect(removed.statusCode).toBe(200);+ expect(JSON.parse(removed.payload).skill).toMatchObject({ id: skill.id, name: "crud-skill" });++ expect((await inject("GET", `${skillsUrl}/${skill.id}`)).statusCode).toBe(404);+ const bundleSkills = await inject("GET", bundleSkillsUrl(bundle.id));+ expect(JSON.parse(bundleSkills.payload).skills).toEqual([]);+ });++ test("a duplicate name is a 409", async () => {+ await createSkill("dup-skill");+ const again = await inject("POST", skillsUrl, { files: skillFiles("dup-skill") });+ expect(again.statusCode).toBe(409);+ expect(JSON.parse(again.payload).message).toBe("A skill named 'dup-skill' already exists.");+ });++ test("lists page, search and filter by exact name", async () => {+ await createSkill("list-alpha", "Reviews code");+ await createSkill("list-beta", "Writes docs");+ await createSkill("list-gamma", "Reviews tests");++ const page = await inject("GET", `${skillsUrl}?limit=2&offset=1`);+ expect(page.statusCode).toBe(200);+ const paged = JSON.parse(page.payload) as { skills: TSkill[]; totalCount: number };+ expect(paged.skills.map((row) => row.name)).toEqual(["list-beta", "list-gamma"]);+ expect(paged.totalCount).toBe(3);++ const searched = JSON.parse((await inject("GET", `${skillsUrl}?search=reviews`)).payload) as {+ skills: TSkill[];+ totalCount: number;+ };+ expect(searched.skills.map((row) => row.name)).toEqual(["list-alpha", "list-gamma"]);+ expect(searched.totalCount).toBe(2);++ const named = JSON.parse((await inject("GET", `${skillsUrl}?name=list-beta`)).payload) as {+ skills: TSkill[];+ totalCount: number;+ };+ expect(named).toMatchObject({ skills: [{ name: "list-beta" }], totalCount: 1 });++ const none = JSON.parse((await inject("GET", `${skillsUrl}?name=list`)).payload) as { totalCount: number };+ expect(none.totalCount).toBe(0);+ });++ test("the list names each skill's access bundles, ordered by name", async () => {+ const { skill: shared } = await createSkill("bundles-shared");+ const { skill: single } = await createSkill("bundles-single");+ await createSkill("bundles-unused");+ const zeta = await createAccessBundle("skills-list-zeta");+ const alpha = await createAccessBundle("skills-list-alpha");+ for (const [bundle, skill] of [+ [zeta, shared],+ [alpha, shared],+ [zeta, single]+ ] as const) {+ // eslint-disable-next-line no-await-in-loop+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: skill.id })).statusCode).toBe(200);+ }++ const list = await inject("GET", `${skillsUrl}?search=bundles-`);+ expect(list.statusCode).toBe(200);+ const { skills } = JSON.parse(list.payload) as { skills: TListedSkill[] };+ expect(skills.map(({ name, accessBundles }) => ({ name, accessBundles }))).toEqual([+ {+ name: "bundles-shared",+ accessBundles: [+ { id: alpha.id, name: alpha.name },+ { id: zeta.id, name: zeta.name }+ ]+ },+ { name: "bundles-single", accessBundles: [{ id: zeta.id, name: zeta.name }] },+ { name: "bundles-unused", accessBundles: [] }+ ]);+ });++ test("a member reads only the latest version of skills on bundles it holds, and is refused every write", async () => {+ const { skill } = await createSkill("member-reader");+ expect((await publish(skill.id, skillFiles("member-reader", "Second."))).statusCode).toBe(200);+ const { skill: hidden } = await createSkill("member-hidden");+ await createSkill("member-no-bundle");+ const granted = await createAccessBundle("skills-member-granted");+ const other = await createAccessBundle("skills-member-other");+ for (const [bundle, bundleSkill] of [+ [granted, skill],+ [other, skill],+ [other, hidden]+ ] as const) {+ // eslint-disable-next-line no-await-in-loop+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: bundleSkill.id })).statusCode).toBe(200);+ }+ const member = await createMemberIdentity("skills-member");+ try {+ expect(+ (+ await inject("POST", `/api/v1/agent-vault/access-bundles/${granted.id}/members`, {+ machineIdentityIds: [member.id]+ })+ ).statusCode+ ).toBe(200);++ const calls: [string, "GET" | "POST" | "PATCH" | "DELETE", string, number, Record<string, unknown>?][] = [+ ["list", "GET", skillsUrl, 200],+ ["get", "GET", `${skillsUrl}/${skill.id}`, 200],+ ["get unreachable", "GET", `${skillsUrl}/${hidden.id}`, 404],+ ["list versions", "GET", `${skillsUrl}/${skill.id}/versions`, 403],+ ["get latest version", "GET", `${skillsUrl}/${skill.id}/versions/2`, 200],+ ["get old version", "GET", `${skillsUrl}/${skill.id}/versions/1`, 404],+ ["get unreachable version", "GET", `${skillsUrl}/${hidden.id}/versions/1`, 404],+ ["bundle skills", "GET", bundleSkillsUrl(granted.id), 200],+ ["unreachable bundle skills", "GET", bundleSkillsUrl(other.id), 404],+ ["create", "POST", skillsUrl, 403, { files: skillFiles("member-made") }],+ ["delete", "DELETE", `${skillsUrl}/${skill.id}`, 403],+ ["update", "PATCH", `${skillsUrl}/${skill.id}`, 403, { files: skillFiles("member-reader", "x") }],+ ["restore", "POST", `${skillsUrl}/${skill.id}/versions/1/restore`, 403],+ ["add", "POST", bundleSkillsUrl(granted.id), 403, { skillId: skill.id }],+ ["remove", "DELETE", `${bundleSkillsUrl(granted.id)}/${skill.id}`, 403]+ ];+ const statuses = await Promise.all(+ calls.map(async ([label, method, url, , body]) => [label, (await member.as(method, url, body)).statusCode])+ );+ expect(statuses).toEqual(calls.map(([label, , , status]) => [label, status]));++ const listed = JSON.parse((await member.as("GET", skillsUrl)).payload) as {+ skills: TListedSkill[];+ totalCount: number;+ };+ expect(listed).toMatchObject({+ skills: [{ id: skill.id, accessBundles: [{ id: granted.id, name: granted.name }] }],+ totalCount: 1+ });+ expect(listed.skills).toHaveLength(1);+ expect(listed.skills[0].accessBundles).toHaveLength(1);++ const detail = JSON.parse((await member.as("GET", `${skillsUrl}/${skill.id}`)).payload) as {+ skill: TListedSkill & { files: TFile[] };+ };+ expect(detail.skill.accessBundles).toEqual([{ id: granted.id, name: granted.name }]);+ expect(detail.skill).toMatchObject({ latestVersion: 2, files: skillFiles("member-reader", "Second.") });++ const unreachable = await member.as("GET", bundleSkillsUrl(other.id));+ expect(JSON.parse(unreachable.payload).message).toBe(`Access bundle with ID '${other.id}' not found`);++ const files = JSON.parse((await member.as("GET", `${skillsUrl}/${skill.id}/versions/2`)).payload) as {+ version: { files: TFile[] };+ };+ expect(files.version.files).toEqual(skillFiles("member-reader", "Second."));+ } finally {+ await member.cleanup();+ }+ });++ test("file paths and header values are refused with a message naming the file or field", async () => {+ const refused = async (files: TFile[]) => {+ const res = await inject("POST", skillsUrl, { files });+ expect(res.statusCode).toBe(400);+ return JSON.parse(res.payload).message as string;+ };+ const extra = (path: string): TFile => ({ path, mode: "0644", contentBase64: "" });++ expect(await refused(skillFiles("p", "x", [extra("docs"), extra("docs/a.md")]))).toBe(+ "'docs' is a file, but 'docs/a.md' puts it inside a folder of the same name. Rename one of them."+ );+ expect(await refused(skillFiles("p", "x", [extra("SKILL.md/x")]))).toMatch(/^'SKILL.md' is a file/);+ expect(await refused(skillFiles("p", "x", [extra("Notes.md"), extra("notes.md")]))).toBe(+ "Files 'Notes.md' and 'notes.md' would be the same file on disk. File paths must be unique ignoring case."+ );+ expect(await refused(skillFiles("p", "x", [extra("caf\u00e9.md"), extra("cafe\u0301.md")]))).toMatch(+ /would be the same file on disk/+ );+ expect(await refused(skillFiles("p", "x", [extra("a?.md")]))).toMatch(+ /^File path 'a\?\.md' can't contain any of/+ );+ expect(await refused(skillFiles("p", "x", [extra("docs./a.md")]))).toMatch(/part ending in a dot or a space/);+ expect(await refused(skillFiles("p", "x", [extra("aux.md")]))).toMatch(/which is a reserved name/);++ const numeric = await refused([+ {+ path: "SKILL.md",+ mode: "0644",+ contentBase64: Buffer.from("---\nname: 12\ndescription: d\n---\n").toString("base64")+ }+ ]);+ expect(numeric).toBe("The 'name' in SKILL.md must be text. Put it in quotes.");+ expect(await refused(skillFiles("code--review"))).toBe(+ "The 'name' in SKILL.md is 'code--review'. A skill name can only use lowercase letters, numbers and single hyphens, and can't start or end with a hyphen."+ );+ });++ test("a single file over 1 MB gets the 400 that names it, not a body or schema error", async () => {+ const res = await inject("POST", skillsUrl, {+ files: skillFiles("big-file", "x", [+ {+ path: "data/big.bin",+ mode: "0644",+ contentBase64: Buffer.alloc(Math.round(1.05 * 1024 * 1024)).toString("base64")+ }+ ])+ });+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.payload).message).toBe("File 'data/big.bin' is larger than 256 KB.");+ });++ test("the limits are refused with a message naming the problem", async () => {+ const missing = await inject("POST", skillsUrl, {+ files: [{ path: "README.md", mode: "0644", contentBase64: Buffer.from("hi").toString("base64") }]+ });+ expect(missing.statusCode).toBe(400);+ expect(JSON.parse(missing.payload).message).toBe("SKILL.md is missing.");++ const oversize = await inject("POST", skillsUrl, {+ files: skillFiles("too-big", "x", [+ { path: "scripts/x.sh", mode: "0755", contentBase64: Buffer.alloc(256 * 1024 + 1).toString("base64") }+ ])+ });+ expect(oversize.statusCode).toBe(400);+ expect(JSON.parse(oversize.payload).message).toBe("File 'scripts/x.sh' is larger than 256 KB.");++ const traversal = await inject("POST", skillsUrl, {+ files: skillFiles("escape", "x", [{ path: "../evil.sh", mode: "0755", contentBase64: "" }])+ });+ expect(traversal.statusCode).toBe(400);++ const badYaml = await inject("POST", skillsUrl, {+ files: [+ {+ path: "SKILL.md",+ mode: "0644",+ contentBase64: Buffer.from("---\nname: [oops\n---\n").toString("base64")+ }+ ]+ });+ expect(badYaml.statusCode).toBe(400);+ expect(JSON.parse(badYaml.payload).message).toBe(+ "Line 2 of SKILL.md: the 'name' value opens a '[' that never closes."+ );++ const unquotedColon = await inject("POST", skillsUrl, {+ files: [+ {+ path: "SKILL.md",+ mode: "0644",+ contentBase64: Buffer.from("---\nname: colon\ndescription: Review: then fix\n---\n").toString("base64")+ }+ ]+ });+ expect(unquotedColon.statusCode).toBe(400);+ expect(JSON.parse(unquotedColon.payload).message).toBe(+ "Line 3 of SKILL.md: the 'description' value contains ': '. Put the value in double quotes."+ );++ const controlCharacter = await inject("POST", skillsUrl, {+ files: [+ {+ path: "SKILL.md",+ mode: "0644",+ contentBase64: Buffer.from('---\nname: ctrl\ndescription: "x\\0y"\n---\n').toString("base64")+ }+ ]+ });+ expect(controlCharacter.statusCode).toBe(400);+ expect(JSON.parse(controlCharacter.payload).message).toBe(+ "The 'description' in SKILL.md contains a control character."+ );+ });++ test("getting a skill returns its latest files and records a version view, and the old publish route is gone", async () => {+ const { skill } = await createSkill("latest-files-skill", "First.");+ const second = skillFiles("latest-files-skill", "Second.", [+ { path: "scripts/run.sh", mode: "0755", contentBase64: Buffer.from("echo hi\n").toString("base64") }+ ]);+ expect((await publish(skill.id, second)).statusCode).toBe(200);++ const auditLogs = recordAuditLogs();+ try {+ const detail = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(detail.statusCode).toBe(200);+ const { skill: got } = JSON.parse(detail.payload) as { skill: TListedSkill & { files: TFile[] } };+ expect(got).toMatchObject({ latestVersion: 2, description: "Second." });+ expect(got.files).toEqual(second);+ expect(auditLogs).toHaveBeenCalledWith(+ expect.objectContaining({+ event: {+ type: "agent-vault-skill-version-view",+ metadata: { skillId: skill.id, skillName: "latest-files-skill", version: 2 }+ }+ })+ );+ } finally {+ auditLogs.mockRestore();+ }++ const listed = JSON.parse((await inject("GET", skillsUrl)).payload) as { skills: Record<string, unknown>[] };+ expect(listed.skills[0]).not.toHaveProperty("files");++ expect((await inject("POST", `${skillsUrl}/${skill.id}/versions`, { files: second })).statusCode).toBe(404);+ });++ test("updating with the same content is a no-op, and a new name in SKILL.md renames the skill", async () => {+ const { skill, version } = await createSkill("publish-skill");++ const same = await publish(skill.id, skillFiles("publish-skill"));+ expect(same.statusCode).toBe(200);+ expect(JSON.parse(same.payload)).toMatchObject({+ unchanged: true,+ version: { version: 1, sha256: version.sha256 }+ });++ const changed = await publish(skill.id, skillFiles("publish-skill", "Now different."));+ expect(changed.statusCode).toBe(200);+ expect(JSON.parse(changed.payload)).toMatchObject({ unchanged: false, version: { version: 2 } });++ const detail = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(detail.payload).skill).toMatchObject({ latestVersion: 2, description: "Now different." });++ const renamed = await publish(skill.id, skillFiles("publish-renamed", "Now different."));+ expect(renamed.statusCode).toBe(200);+ expect(JSON.parse(renamed.payload)).toMatchObject({ unchanged: false, version: { version: 3 } });+ const afterRename = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(afterRename.payload).skill).toMatchObject({ name: "publish-renamed", latestVersion: 3 });++ await createSkill("publish-taken");+ const taken = await publish(skill.id, skillFiles("publish-taken"));+ expect(taken.statusCode).toBe(409);+ expect(JSON.parse(taken.payload).message).toBe("A skill named 'publish-taken' already exists.");+ const unchanged = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(unchanged.payload).skill).toMatchObject({ name: "publish-renamed", latestVersion: 3 });++ // A rollback past the rename keeps the current name, in the skill row and in the restored SKILL.md.+ const restored = await inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`);+ expect(restored.statusCode).toBe(200);+ expect(JSON.parse(restored.payload)).toMatchObject({ unchanged: false, version: { version: 4 } });+ const afterRestore = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(afterRestore.payload).skill).toMatchObject({+ name: "publish-renamed",+ description: "Do the thing.",+ latestVersion: 4+ });+ const files = JSON.parse((await inject("GET", `${skillsUrl}/${skill.id}/versions/4`)).payload) as {+ version: { files: TFile[] };+ };+ expect(files.version.files).toEqual(skillFiles("publish-renamed"));+ });++ test("restore copies an old version forward as a new one", async () => {+ const { skill, version: first } = await createSkill("restore-skill", "First.");+ expect((await publish(skill.id, skillFiles("restore-skill", "Second."))).statusCode).toBe(200);++ const restored = await inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`);+ expect(restored.statusCode).toBe(200);+ expect(JSON.parse(restored.payload).version).toMatchObject({ version: 3, sha256: first.sha256 });++ const detail = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(detail.payload).skill).toMatchObject({ latestVersion: 3, description: "First." });++ expect((await inject("POST", `${skillsUrl}/${skill.id}/versions/99/restore`)).statusCode).toBe(404);+ });++ test("restoring a version with the latest version's files publishes nothing", async () => {+ const { skill } = await createSkill("restore-same-skill", "First.");+ expect((await publish(skill.id, skillFiles("restore-same-skill", "Second."))).statusCode).toBe(200);+ expect((await inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`)).statusCode).toBe(200);++ const again = await inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`);+ expect(again.statusCode).toBe(200);+ expect(JSON.parse(again.payload)).toMatchObject({ unchanged: true, version: { version: 3 } });++ const fresh = await inject("POST", `${skillsUrl}/${skill.id}/versions/2/restore`);+ expect(JSON.parse(fresh.payload)).toMatchObject({ unchanged: false, version: { version: 4 } });+ });++ test("restoring a version whose SKILL.md no longer parses keeps the current description", async () => {+ const { skill } = await createSkill("legacy-skill", "Old.");+ expect((await publish(skill.id, skillFiles("legacy-skill", "Current."))).statusCode).toBe(200);++ // The API refuses a SKILL.md that does not parse, so a version saved under older header rules can only be+ // stood in for by sealing one directly over version 1.+ const files = skillFiles("legacy-skill", "d".repeat(1100));+ const serialized = Buffer.from(JSON.stringify(files));+ const { encryptor } = await projectCipher(+ (await testDb("agent_vault_skills").where({ id: skill.id }).first()).projectId+ );+ await testDb("agent_vault_skill_versions")+ .where({ skillId: skill.id, version: 1 })+ .update({+ encryptedFiles: encryptor({ plainText: serialized }).cipherTextBlob,+ sha256: crypto.createHash("sha256").update(serialized).digest("hex"),+ sizeBytes: Buffer.from(files[0].contentBase64, "base64").length+ });++ const restored = await inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`);+ expect(restored.statusCode).toBe(200);+ expect(JSON.parse(restored.payload)).toMatchObject({ unchanged: false, version: { version: 3 } });++ const detail = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(detail.payload).skill).toMatchObject({ latestVersion: 3, description: "Current." });+ });++ test("restoring a version whose name line can't be rewritten to the current name is a 400", async () => {+ const { skill } = await createSkill("block-old");+ expect((await publish(skill.id, skillFiles("block-new"))).statusCode).toBe(200);++ // The API now refuses a name it could not rewrite, so a version saved before that rule can only be stood in+ // for by sealing one directly over version 1.+ const files = skillFiles("block-old");+ files[0].contentBase64 = Buffer.from(+ "---\nname: >-\n block-old\ndescription: Do the thing.\n---\nDo the thing.\n"+ ).toString("base64");+ const serialized = Buffer.from(JSON.stringify(files));+ const { encryptor } = await projectCipher(+ (await testDb("agent_vault_skills").where({ id: skill.id }).first()).projectId+ );+ await testDb("agent_vault_skill_versions")+ .where({ skillId: skill.id, version: 1 })+ .update({+ encryptedFiles: encryptor({ plainText: serialized }).cipherTextBlob,+ sha256: crypto.createHash("sha256").update(serialized).digest("hex"),+ sizeBytes: Buffer.from(files[0].contentBase64, "base64").length+ });++ const restored = await inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`);+ expect(restored.statusCode).toBe(400);+ expect(JSON.parse(restored.payload).message).toBe(+ "Version 1 of skill 'block-new' names 'block-old' in SKILL.md, and its 'name' line could not be changed to 'block-new'. Publish a new version instead."+ );+ const detail = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(detail.payload).skill).toMatchObject({ name: "block-new", latestVersion: 2 });+ });++ test("a restore that meets a rename made after it read the name is a 409, not a rename back", async () => {+ const { skill } = await createSkill("race-skill", "First.");+ expect((await publish(skill.id, skillFiles("race-skill", "Second."))).statusCode).toBe(200);++ // Holding the skill row queues the restore on it after it has read the name. The rename is written under the+ // same hold, standing in for a publish that renames, which would otherwise queue on the row too.+ const trx = await testDb.transaction();+ let restore: ReturnType<typeof inject> | undefined;+ try {+ const { rows } = await trx.raw("select pg_backend_pid() as pid");+ await trx("agent_vault_skills").where({ id: skill.id }).forUpdate().first();++ restore = inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`);+ await waitUntilBlockedBy(rows[0].pid);+ await trx("agent_vault_skills").where({ id: skill.id }).update({ name: "race-renamed" });+ await trx.commit();++ const res = await restore;+ expect(res.statusCode).toBe(409);+ expect(JSON.parse(res.payload).message).toBe(+ "Skill 'race-skill' was renamed to 'race-renamed' while this version was being restored. Try again."+ );+ } catch (err) {+ if (!trx.isCompleted()) await trx.rollback();+ await restore?.catch(() => undefined);+ throw err;+ }++ const detail = await inject("GET", `${skillsUrl}/${skill.id}`);+ expect(JSON.parse(detail.payload).skill).toMatchObject({ name: "race-renamed", latestVersion: 2 });+ });++ test("a skill with more than 50 files is refused with a message saying so", async () => {+ const extra = Array.from({ length: 50 }, (_, i) => ({+ path: `docs/${i}.md`,+ mode: "0644",+ contentBase64: ""+ }));+ const res = await inject("POST", skillsUrl, { files: skillFiles("too-many-files", "x", extra) });+ expect(res.statusCode).toBe(400);+ expect(JSON.parse(res.payload).message).toBe("A skill can have at most 50 files.");+ });++ test("only the newest 20 versions are kept", async () => {+ const { skill } = await createSkill("prune-skill", "v1");+ for (let i = 2; i <= 21; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ expect((await publish(skill.id, skillFiles("prune-skill", `v${i}`))).statusCode).toBe(200);+ }++ const list = await inject("GET", `${skillsUrl}/${skill.id}/versions`);+ const { versions } = JSON.parse(list.payload) as { versions: TSkillVersion[] };+ expect(versions).toHaveLength(20);+ expect(versions[0].version).toBe(21);+ expect(versions[19].version).toBe(2);+ expect((await inject("GET", `${skillsUrl}/${skill.id}/versions/1`)).statusCode).toBe(404);+ });++ test("add and remove, and a second add is a 409", async () => {+ const { skill } = await createSkill("add-skill");+ const bundle = await createAccessBundle("skills-add-bundle");++ const added = await inject("POST", bundleSkillsUrl(bundle.id), { skillId: skill.id });+ expect(added.statusCode).toBe(200);+ expect(JSON.parse(added.payload).skill).toMatchObject({+ id: skill.id,+ name: "add-skill",+ latestVersion: 1+ });++ const again = await inject("POST", bundleSkillsUrl(bundle.id), { skillId: skill.id });+ expect(again.statusCode).toBe(409);+ expect(JSON.parse(again.payload).message).toBe(+ "The skill 'add-skill' is already in the access bundle 'skills-add-bundle'."+ );++ const listed = await inject("GET", bundleSkillsUrl(bundle.id));+ expect((JSON.parse(listed.payload) as { skills: TSkill[] }).skills.map((row) => row.id)).toEqual([skill.id]);++ expect((await inject("DELETE", `${bundleSkillsUrl(bundle.id)}/${skill.id}`)).statusCode).toBe(200);+ const missing = await inject("DELETE", `${bundleSkillsUrl(bundle.id)}/${skill.id}`);+ expect(missing.statusCode).toBe(404);+ expect(JSON.parse(missing.payload).message).toBe(+ "The skill 'add-skill' isn't in the access bundle 'skills-add-bundle'."+ );+ });++ test("an access bundle holds at most 25 skills", async () => {+ const bundle = await createAccessBundle("skills-cap-bundle");+ const created = await Promise.all(+ Array.from({ length: 26 }, (_, i) => createSkill(`cap-skill-${String(i).padStart(2, "0")}`))+ );+ for (const { skill } of created.slice(0, 25)) {+ // eslint-disable-next-line no-await-in-loop+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: skill.id })).statusCode).toBe(200);+ }++ const over = await inject("POST", bundleSkillsUrl(bundle.id), { skillId: created[25].skill.id });+ expect(over.statusCode).toBe(400);+ expect(JSON.parse(over.payload).message).toBe(+ "This access bundle already has 25 skills, the maximum. Remove one to add another."+ );++ const other = await createAccessBundle("skills-cap-other-bundle");+ expect((await inject("POST", bundleSkillsUrl(other.id), { skillId: created[25].skill.id })).statusCode).toBe(200);++ expect((await inject("DELETE", `${bundleSkillsUrl(bundle.id)}/${created[0].skill.id}`)).statusCode).toBe(200);+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: created[25].skill.id })).statusCode).toBe(+ 200+ );+ });++ test("a session token gets every skill of the session's bundles in one call, and nothing from other bundles", async () => {+ const bundle = await createAccessBundle("skills-deliver-bundle");+ const otherBundle = await createAccessBundle("skills-deliver-other");+ const session = await mintFor([bundle]);+ const asSession = () => fetchSessionSkills(`Bearer ${session.token}`);++ const emptyAuditLogs = recordAuditLogs();+ try {+ const empty = await asSession();+ expect(empty.statusCode).toBe(200);+ expect(JSON.parse(empty.payload)).toEqual({ skills: [] });+ expect(emptyAuditLogs).not.toHaveBeenCalled();+ } finally {+ emptyAuditLogs.mockRestore();+ }++ const { skill: zeta, version: zetaV1 } = await createSkill("zeta-skill");+ const { skill: alpha } = await createSkill("alpha-skill");+ const { skill: foreign } = await createSkill("foreign-skill");+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: zeta.id })).statusCode).toBe(200);+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: alpha.id })).statusCode).toBe(200);+ expect((await inject("POST", bundleSkillsUrl(otherBundle.id), { skillId: foreign.id })).statusCode).toBe(200);+ const republished = await publish(+ alpha.id,+ skillFiles("alpha-skill", "Second.", [+ { path: "scripts/run.sh", mode: "0755", contentBase64: Buffer.from("echo hi\n").toString("base64") }+ ])+ );+ const { version: alphaV2 } = JSON.parse(republished.payload) as { version: TSkillVersion };++ const auditLogs = recordAuditLogs();+ let delivered: Awaited<ReturnType<typeof asSession>>;+ try {+ delivered = await asSession();+ expect(auditLogs).toHaveBeenCalledTimes(1);+ expect(auditLogs).toHaveBeenCalledWith(+ expect.objectContaining({+ orgId: seedData1.organization.id,+ actor: expect.objectContaining({+ type: ActorType.USER,+ metadata: expect.objectContaining({ userId: seedData1.id })+ }),+ event: {+ type: "agent-vault-skills-delivered",+ metadata: {+ sessionId: session.id,+ accessBundleId: bundle.id,+ accessBundleName: bundle.name,+ skills: [+ { skillId: alpha.id, skillName: "alpha-skill", version: 2, sha256: alphaV2.sha256 },+ { skillId: zeta.id, skillName: "zeta-skill", version: 1, sha256: zetaV1.sha256 }+ ]+ }+ }+ })+ );+ } finally {+ auditLogs.mockRestore();+ }+ expect(delivered.statusCode).toBe(200);+ const { skills } = JSON.parse(delivered.payload) as {+ skills: { id: string; name: string; version: number; sha256: string; files: TFile[] }[];+ };+ expect(skills.map((row) => row.name)).toEqual(["alpha-skill", "zeta-skill"]);+ expect(skills[0]).toEqual({+ id: alpha.id,+ name: "alpha-skill",+ version: 2,+ sha256: alphaV2.sha256,+ files: [+ ...skillFiles("alpha-skill", "Second."),+ { path: "scripts/run.sh", mode: "0755", contentBase64: Buffer.from("echo hi\n").toString("base64") }+ ]+ });+ expect(skills[0].sha256).toBe(crypto.createHash("sha256").update(JSON.stringify(skills[0].files)).digest("hex"));+ expect(skills.some((row) => row.id === foreign.id)).toBe(false);++ expect((await inject("DELETE", `${bundleSkillsUrl(bundle.id)}/${alpha.id}`)).statusCode).toBe(200);+ const afterRemove = JSON.parse((await asSession()).payload) as { skills: { id: string }[] };+ expect(afterRemove.skills.map((row) => row.id)).toEqual([zeta.id]);++ const revoked = await inject("POST", `/api/v1/agent-vault/sessions/${session.id}/revoke`);+ expect(revoked.statusCode).toBe(200);+ const afterRevoke = await asSession();+ expect(afterRevoke.statusCode).toBe(401);+ expect(JSON.parse(afterRevoke.payload).message).toBe("This session has been revoked");+ });++ test("the skills route refuses an expired, unknown or malformed session token with a 401", async () => {+ const bundle = await createAccessBundle("skills-refused-bundle");+ const session = await mintFor([bundle]);+ await testDb("agent_vault_sessions")+ .where({ id: session.id })+ .update({ expiresAt: new Date(Date.now() - 1000) });+ const expired = await fetchSessionSkills(`Bearer ${session.token}`);+ expect(expired.statusCode).toBe(401);+ expect(JSON.parse(expired.payload).message).toBe("This session has expired");++ const unknown = await fetchSessionSkills(`Bearer agv_${crypto.randomBytes(32).toString("base64url")}`);+ expect(unknown.statusCode).toBe(401);+ expect(JSON.parse(unknown.payload).message).toBe("This Agent Vault session token is not valid");++ const malformedMessage = "Send an Agent Vault session token in the Authorization header, as 'Bearer agv_...'.";+ const refused = await Promise.all(+ [+ undefined,+ "",+ session.token,+ `Basic ${session.token}`,+ `Bearer ${jwtAuthToken}`,+ "Bearer agv_",+ `Bearer agv_${"a".repeat(200)}`+ ].map((authorization) => fetchSessionSkills(authorization))+ );+ refused.forEach((res) => {+ expect(res.statusCode).toBe(401);+ expect(JSON.parse(res.payload).message).toBe(malformedMessage);+ });+ });++ test("a member's session gets only the skills its owner still reaches", async () => {+ const bundle = await createAccessBundle("skills-lost-grant-bundle");+ const otherBundle = await createAccessBundle("skills-lost-grant-other");+ const { skill } = await createSkill("lost-grant-skill");+ const { skill: unreachable } = await createSkill("unreachable-skill");+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: skill.id })).statusCode).toBe(200);+ expect((await inject("POST", bundleSkillsUrl(otherBundle.id), { skillId: unreachable.id })).statusCode).toBe(200);+ const member = await createMemberIdentity("skills-lost-grant");+ try {+ const bundleMembersUrl = `/api/v1/agent-vault/access-bundles/${bundle.id}/members`;+ expect((await inject("POST", bundleMembersUrl, { machineIdentityIds: [member.id] })).statusCode).toBe(200);+ const session = await mintFor([bundle], member.as);+ const asSession = () => fetchSessionSkills(`Bearer ${session.token}`);++ const auditLogs = recordAuditLogs();+ let before: Awaited<ReturnType<typeof asSession>>;+ try {+ before = await asSession();+ expect(auditLogs).toHaveBeenCalledWith(+ expect.objectContaining({+ actor: expect.objectContaining({+ type: ActorType.IDENTITY,+ metadata: expect.objectContaining({ identityId: member.id, name: "skills-lost-grant" })+ })+ })+ );+ } finally {+ auditLogs.mockRestore();+ }+ expect(before.statusCode).toBe(200);+ expect((JSON.parse(before.payload) as { skills: { id: string }[] }).skills.map((row) => row.id)).toEqual([+ skill.id+ ]);++ expect((await inject("DELETE", bundleMembersUrl, { machineIdentityIds: [member.id] })).statusCode).toBe(200);++ const after = await asSession();+ expect(after.statusCode).toBe(200);+ expect(JSON.parse(after.payload)).toEqual({ skills: [] });+ } finally {+ await member.cleanup();+ }+ });+ test("Agent Vault holds at most 250 skills", async () => {+ const projectId = await getProjectId();+ // Seeded directly: 250 creates through the API would be slow, and the cap counts skill rows only.+ await testDb("agent_vault_skills").insert(+ Array.from({ length: AGENT_VAULT_MAX_SKILLS }, (_, i) => ({+ projectId,+ name: `seeded-skill-${String(i).padStart(3, "0")}`,+ description: "Seeded."+ }))+ );+ try {+ const over = await inject("POST", skillsUrl, { files: skillFiles("over-cap-skill") });+ expect(over.statusCode).toBe(400);+ expect(JSON.parse(over.payload).message).toBe(+ "This organization already has 250 skills, the most allowed. Delete an unused one first."+ );+ expect(await testDb("agent_vault_skills").where({ projectId, name: "over-cap-skill" })).toHaveLength(0);++ await testDb("agent_vault_skills").where({ projectId, name: "seeded-skill-000" }).del();+ await createSkill("over-cap-skill");+ } finally {+ await testDb("agent_vault_skills").where({ projectId }).del();+ }+ });++ test("publish and restore reply with the skill as it now stands", async () => {+ const { skill } = await createSkill("summary-skill");++ const renamed = await publish(skill.id, skillFiles("summary-renamed", "Renamed."));+ expect(renamed.statusCode).toBe(200);+ expect(JSON.parse(renamed.payload)).toMatchObject({+ unchanged: false,+ skill: { id: skill.id, name: "summary-renamed", description: "Renamed.", latestVersion: 2 },+ version: { version: 2 }+ });++ const restored = await inject("POST", `${skillsUrl}/${skill.id}/versions/1/restore`);+ expect(restored.statusCode).toBe(200);+ expect(JSON.parse(restored.payload)).toMatchObject({+ unchanged: false,+ skill: { id: skill.id, name: "summary-renamed", description: "Do the thing.", latestVersion: 3 },+ version: { version: 3 }+ });+ });++ test("an update with a stale baseVersion is refused, and one with the latest or none goes through", async () => {+ const { skill } = await createSkill("base-version-skill");+ const skillUrl = `${skillsUrl}/${skill.id}`;+ expect((await publish(skill.id, skillFiles("base-version-skill", "Second."))).statusCode).toBe(200);++ const stale = await inject("PATCH", skillUrl, {+ files: skillFiles("base-version-skill", "Stale."),+ baseVersion: 1+ });+ expect(stale.statusCode).toBe(409);+ expect(JSON.parse(stale.payload).message).toBe(+ "Version 2 was published after you opened this skill. Review it, then save again."+ );+ expect(await testDb("agent_vault_skill_versions").where({ skillId: skill.id })).toHaveLength(2);++ const current = await inject("PATCH", skillUrl, {+ files: skillFiles("base-version-skill", "Third."),+ baseVersion: 2+ });+ expect(current.statusCode).toBe(200);+ expect(JSON.parse(current.payload)).toMatchObject({ unchanged: false, version: { version: 3 } });++ const omitted = await publish(skill.id, skillFiles("base-version-skill", "Fourth."));+ expect(omitted.statusCode).toBe(200);+ expect(JSON.parse(omitted.payload)).toMatchObject({ unchanged: false, version: { version: 4 } });+ });++ test("the Skills Delivered event is sent only when a session gets at least one skill", async () => {+ const { telemetry } = (+ globalThis as unknown as {+ testServices: { telemetry: { sendPostHogEvents: (event: unknown) => Promise<void> } };+ }+ ).testServices;+ const emptyBundle = await createAccessBundle("skills-event-empty-bundle");+ const bundle = await createAccessBundle("skills-event-bundle");+ const { skill } = await createSkill("event-skill");+ expect((await inject("POST", bundleSkillsUrl(bundle.id), { skillId: skill.id })).statusCode).toBe(200);+ const emptySession = await mintFor([emptyBundle]);+ const session = await mintFor([bundle]);++ const isSkillsDelivered = (call: unknown[]) =>+ (call[0] as { event: string }).event === PostHogEventTypes.AgentVaultSkillsDelivered;+ const sent = vi.spyOn(telemetry, "sendPostHogEvents").mockResolvedValue(undefined);+ try {+ const empty = await fetchSessionSkills(`Bearer ${emptySession.token}`);+ expect(empty.statusCode).toBe(200);+ expect(JSON.parse(empty.payload)).toEqual({ skills: [] });+ expect(sent.mock.calls.filter(isSkillsDelivered)).toHaveLength(0);++ const delivered = await fetchSessionSkills(`Bearer ${session.token}`);+ expect(delivered.statusCode).toBe(200);+ const events = sent.mock.calls.filter(isSkillsDelivered);+ expect(events).toHaveLength(1);+ expect(events[0][0]).toMatchObject({+ distinctId: `agent-vault-session-${session.id}`,+ organizationId: seedData1.organization.id,+ properties: { orgId: seedData1.organization.id, actorType: ActorType.USER, skillCount: 1 }+ });+ } finally {+ sent.mockRestore();+ }+ });+ });+describe("proxies", async () => {test("an org can hold AGENT_VAULT_MAX_PROXIES_PER_ORG proxies, and the next create is refused", async () => {for (let i = 0; i < AGENT_VAULT_MAX_PROXIES_PER_ORG; i += 1) {@@ -5796,6 +6715,8 @@ describe("Agent Vault V1 Router", async () => {agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),+ projectDAL: projectDALFactory(testDb),+ userDAL: userDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })@@ -5898,6 +6819,8 @@ describe("Agent Vault V1 Router", async () => {agentVaultSessionLogConfigDAL: agentVaultSessionLogConfigDALFactory(testDb),membershipDAL: membershipDALFactory(testDb),orgDAL: orgDALFactory(testDb),+ projectDAL: projectDALFactory(testDb),+ userDAL: userDALFactory(testDb),permissionService: buildPermissionService(),kmsService: {createCipherPairWithDataKey: () => Promise.resolve({ decryptor: () => Buffer.from("{}") })diff --git a/backend/package-lock.json b/backend/package-lock.jsonindex 029559df61..60c9d6488b 100644--- a/backend/package-lock.json+++ b/backend/package-lock.json@@ -103,6 +103,7 @@"ioredis": "^5.3.2","isomorphic-dompurify": "^2.22.0","jose": "^6.1.0",+ "js-yaml": "^4.3.0","jsforce": "^3.10.14","jsonwebtoken": "^9.0.2","jsrp": "^0.2.4",@@ -171,6 +172,7 @@"@smithy/types": "^4.3.1","@types/bcrypt": "^5.0.2","@types/dns-packet": "^5.6.5",+ "@types/js-yaml": "^4.0.9","@types/jsonwebtoken": "^9.0.5","@types/jsrp": "^0.2.6","@types/libsodium-wrappers": "^0.7.13",@@ -10484,6 +10486,13 @@"integrity": "sha512-DaZNUvLDCAnCTjgwxgiL1eQdxIKEpNLOlTNtAgnZc50bG2copGhRrFN9/PxPBuJe+tZVLCbQ7ls0xveXVRPkvw==","license": "MIT"},+ "node_modules/@types/js-yaml": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",+ "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/jsonwebtoken": {"version": "9.0.6","resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-9.0.6.tgz",diff --git a/backend/package.json b/backend/package.jsonindex b6a857d117..741b3b112b 100644--- a/backend/package.json+++ b/backend/package.json@@ -95,7 +95,7 @@"path-to-regexp": "^8.4.0","protobufjs": "^7.6.5","dompurify": "^3.4.9",- "js-yaml": "^4.3.0",+ "js-yaml": "$js-yaml","@grpc/grpc-js": "^1.14.4","fast-xml-builder": "^1.1.7","form-data": "^4.0.6",@@ -115,6 +115,7 @@"@smithy/types": "^4.3.1","@types/bcrypt": "^5.0.2","@types/dns-packet": "^5.6.5",+ "@types/js-yaml": "^4.0.9","@types/jsonwebtoken": "^9.0.5","@types/jsrp": "^0.2.6","@types/libsodium-wrappers": "^0.7.13",@@ -241,6 +242,7 @@"ioredis": "^5.3.2","isomorphic-dompurify": "^2.22.0","jose": "^6.1.0",+ "js-yaml": "^4.3.0","jsforce": "^3.10.14","jsonwebtoken": "^9.0.2","jsrp": "^0.2.4",diff --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.tsindex e3a25df0e7..a1947f5e6c 100644--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@ -14,6 +14,7 @@ import { TAgentVaultProjectResolverFactory } from "@app/ee/services/agent-vault-import { TAgentVaultProxyServiceFactory } from "@app/ee/services/agent-vault-proxy/agent-vault-proxy-service";import { TAgentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vault-session-log/agent-vault-session-log-service";import { TAgentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";+import { TAgentVaultSkillServiceFactory } from "@app/ee/services/agent-vault-skill/agent-vault-skill-service";import { TAgentVaultVariableServiceFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-service";import { TAssumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-types";import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream/audit-log-stream-service";@@ -406,6 +407,7 @@ declare module "fastify" {agentVaultPersonalValue: TAgentVaultPersonalValueServiceFactory;agentVaultProxy: TAgentVaultProxyServiceFactory;agentVaultSession: TAgentVaultSessionServiceFactory;+ agentVaultSkill: TAgentVaultSkillServiceFactory;agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;agentVaultMembership: TAgentVaultMembershipServiceFactory;certManagerInstance: TCertManagerInstanceServiceFactory;diff --git a/backend/src/@types/knex.d.ts b/backend/src/@types/knex.d.tsindex e5dc659741..e1ff165e1f 100644--- a/backend/src/@types/knex.d.ts+++ b/backend/src/@types/knex.d.ts@@ -22,6 +22,9 @@ import {TAdditionalPrivilegesUpdate,TAgentVaultAccessBundles,TAgentVaultAccessBundlesInsert,+ TAgentVaultAccessBundleSkills,+ TAgentVaultAccessBundleSkillsInsert,+ TAgentVaultAccessBundleSkillsUpdate,TAgentVaultAccessBundlesUpdate,TAgentVaultPersonalValueReferences,TAgentVaultPersonalValueReferencesInsert,@@ -53,6 +56,12 @@ import {TAgentVaultSessions,TAgentVaultSessionsInsert,TAgentVaultSessionsUpdate,+ TAgentVaultSkills,+ TAgentVaultSkillsInsert,+ TAgentVaultSkillsUpdate,+ TAgentVaultSkillVersions,+ TAgentVaultSkillVersionsInsert,+ TAgentVaultSkillVersionsUpdate,TAgentVaultVariables,TAgentVaultVariablesInsert,TAgentVaultVariablesUpdate,@@ -1894,6 +1903,21 @@ declare module "knex/types/tables" {TAgentVaultSessionLogConfigsInsert,TAgentVaultSessionLogConfigsUpdate>;+ [TableName.AgentVaultSkill]: KnexOriginal.CompositeTableType<+ TAgentVaultSkills,+ TAgentVaultSkillsInsert,+ TAgentVaultSkillsUpdate+ >;+ [TableName.AgentVaultSkillVersion]: KnexOriginal.CompositeTableType<+ TAgentVaultSkillVersions,+ TAgentVaultSkillVersionsInsert,+ TAgentVaultSkillVersionsUpdate+ >;+ [TableName.AgentVaultAccessBundleSkill]: KnexOriginal.CompositeTableType<+ TAgentVaultAccessBundleSkills,+ TAgentVaultAccessBundleSkillsInsert,+ TAgentVaultAccessBundleSkillsUpdate+ >;[TableName.PamAccountPolicy]: KnexOriginal.CompositeTableType<TPamAccountPolicies,TPamAccountPoliciesInsert,diff --git a/backend/src/db/migrations/20261028090000_agent-vault-skills.ts b/backend/src/db/migrations/20261028090000_agent-vault-skills.tsnew file mode 100644index 0000000000..300ea4e2f9--- /dev/null+++ b/backend/src/db/migrations/20261028090000_agent-vault-skills.ts@@ -0,0 +1,71 @@+import { Knex } from "knex";++import { TableName } from "../schemas";+import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";++export async function up(knex: Knex): Promise<void> {+ if (!(await knex.schema.hasTable(TableName.AgentVaultSkill))) {+ await knex.schema.createTable(TableName.AgentVaultSkill, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.string("projectId", 36).notNullable();+ t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");++ t.string("name", 64).notNullable();+ t.string("description", 1024).notNullable();++ t.timestamps(true, true, true);++ // Also the index the projectId foreign key needs, as its leftmost column.+ t.unique(["projectId", "name"]);+ });++ await createOnUpdateTrigger(knex, TableName.AgentVaultSkill);+ }++ if (!(await knex.schema.hasTable(TableName.AgentVaultSkillVersion))) {+ await knex.schema.createTable(TableName.AgentVaultSkillVersion, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("skillId").notNullable();+ t.foreign("skillId").references("id").inTable(TableName.AgentVaultSkill).onDelete("CASCADE");++ t.integer("version").notNullable();+ t.binary("encryptedFiles").notNullable();+ t.string("sha256", 64).notNullable();+ t.integer("sizeBytes").notNullable();+ t.integer("fileCount").notNullable();++ t.timestamp("createdAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());++ // Also the index the skillId foreign key needs, as its leftmost column.+ t.unique(["skillId", "version"]);+ });+ }++ if (!(await knex.schema.hasTable(TableName.AgentVaultAccessBundleSkill))) {+ await knex.schema.createTable(TableName.AgentVaultAccessBundleSkill, (t) => {+ t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());++ t.uuid("accessBundleId").notNullable();+ t.foreign("accessBundleId").references("id").inTable(TableName.AgentVaultAccessBundle).onDelete("CASCADE");++ t.uuid("skillId").notNullable();+ t.foreign("skillId").references("id").inTable(TableName.AgentVaultSkill).onDelete("CASCADE");+ t.index("skillId");++ t.timestamp("createdAt", { useTz: true }).notNullable().defaultTo(knex.fn.now());++ // Also the index the accessBundleId foreign key needs, as its leftmost column.+ t.unique(["accessBundleId", "skillId"]);+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ await knex.schema.dropTableIfExists(TableName.AgentVaultAccessBundleSkill);+ await knex.schema.dropTableIfExists(TableName.AgentVaultSkillVersion);++ await knex.schema.dropTableIfExists(TableName.AgentVaultSkill);+ await dropOnUpdateTrigger(knex, TableName.AgentVaultSkill);+}diff --git a/backend/src/db/schemas/agent-vault-access-bundle-skills.ts b/backend/src/db/schemas/agent-vault-access-bundle-skills.tsnew file mode 100644index 0000000000..8df115f168--- /dev/null+++ b/backend/src/db/schemas/agent-vault-access-bundle-skills.ts@@ -0,0 +1,24 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultAccessBundleSkillsSchema = z.object({+ id: z.string().uuid(),+ accessBundleId: z.string().uuid(),+ skillId: z.string().uuid(),+ createdAt: z.date()+});++export type TAgentVaultAccessBundleSkills = z.infer<typeof AgentVaultAccessBundleSkillsSchema>;+export type TAgentVaultAccessBundleSkillsInsert = Omit<+ z.input<typeof AgentVaultAccessBundleSkillsSchema>,+ TImmutableDBKeys+>;+export type TAgentVaultAccessBundleSkillsUpdate = Partial<+ Omit<z.input<typeof AgentVaultAccessBundleSkillsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/agent-vault-skill-versions.ts b/backend/src/db/schemas/agent-vault-skill-versions.tsnew file mode 100644index 0000000000..421f67a3e5--- /dev/null+++ b/backend/src/db/schemas/agent-vault-skill-versions.ts@@ -0,0 +1,27 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { zodBuffer } from "@app/lib/zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultSkillVersionsSchema = z.object({+ id: z.string().uuid(),+ skillId: z.string().uuid(),+ version: z.number(),+ encryptedFiles: zodBuffer,+ sha256: z.string(),+ sizeBytes: z.number(),+ fileCount: z.number(),+ createdAt: z.date()+});++export type TAgentVaultSkillVersions = z.infer<typeof AgentVaultSkillVersionsSchema>;+export type TAgentVaultSkillVersionsInsert = Omit<z.input<typeof AgentVaultSkillVersionsSchema>, TImmutableDBKeys>;+export type TAgentVaultSkillVersionsUpdate = Partial<+ Omit<z.input<typeof AgentVaultSkillVersionsSchema>, TImmutableDBKeys>+>;diff --git a/backend/src/db/schemas/agent-vault-skills.ts b/backend/src/db/schemas/agent-vault-skills.tsnew file mode 100644index 0000000000..34e0d889c7--- /dev/null+++ b/backend/src/db/schemas/agent-vault-skills.ts@@ -0,0 +1,21 @@+// Code generated by automation script, DO NOT EDIT.+// Automated by pulling database and generating zod schema+// To update. Just run npm run generate:schema+// Written by akhilmhdh.++import { z } from "zod";++import { TImmutableDBKeys } from "./models";++export const AgentVaultSkillsSchema = z.object({+ id: z.string().uuid(),+ projectId: z.string(),+ name: z.string(),+ description: z.string(),+ createdAt: z.date(),+ updatedAt: z.date()+});++export type TAgentVaultSkills = z.infer<typeof AgentVaultSkillsSchema>;+export type TAgentVaultSkillsInsert = Omit<z.input<typeof AgentVaultSkillsSchema>, TImmutableDBKeys>;+export type TAgentVaultSkillsUpdate = Partial<Omit<z.input<typeof AgentVaultSkillsSchema>, TImmutableDBKeys>>;diff --git a/backend/src/db/schemas/index.ts b/backend/src/db/schemas/index.tsindex 0e9564afda..e759e97bed 100644--- a/backend/src/db/schemas/index.ts+++ b/backend/src/db/schemas/index.ts@@ -4,6 +4,7 @@ export * from "./access-approval-policies-bypassers";export * from "./access-approval-requests";export * from "./access-approval-requests-reviewers";export * from "./additional-privileges";+export * from "./agent-vault-access-bundle-skills";export * from "./agent-vault-access-bundles";export * from "./agent-vault-personal-value-references";export * from "./agent-vault-personal-values";@@ -15,6 +16,8 @@ export * from "./agent-vault-services";export * from "./agent-vault-session-access-bundles";export * from "./agent-vault-session-log-configs";export * from "./agent-vault-sessions";+export * from "./agent-vault-skill-versions";+export * from "./agent-vault-skills";export * from "./agent-vault-variables";export * from "./alert-channel-memberships";export * from "./alert-channel-recipients";diff --git a/backend/src/db/schemas/models.ts b/backend/src/db/schemas/models.tsindex f5f72477e2..19ea19118a 100644--- a/backend/src/db/schemas/models.ts+++ b/backend/src/db/schemas/models.ts@@ -287,6 +287,9 @@ export enum TableName {AgentVaultSessionAccessBundle = "agent_vault_session_access_bundles",AgentVaultProxy = "agent_vault_proxies",AgentVaultSessionLogConfig = "agent_vault_session_log_configs",+ AgentVaultSkill = "agent_vault_skills",+ AgentVaultSkillVersion = "agent_vault_skill_versions",+ AgentVaultAccessBundleSkill = "agent_vault_access_bundle_skills",// Dropped; kept only for the migrations that create and drop it.AgentVaultSessionLogChunk = "agent_vault_session_log_chunks",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.tsindex e305b0a408..40488521f5 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-access-bundle-router.ts@@ -20,6 +20,7 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { actorContext } from "./agent-vault-router-fns";import {AgentVaultActorRefSchema,+ AgentVaultBundleSkillSchema,AgentVaultCreatedMemberSchema,AgentVaultCreateServiceBodySchema,agentVaultListQuery,@@ -636,6 +637,128 @@ export const registerAgentVaultAccessBundleRouter = async (server: FastifyZodPro}});+ server.route({+ method: "GET",+ url: "/:accessBundleId/skills",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listAgentVaultAccessBundleSkills",+ description: "List the skills in an Agent Vault access bundle, ordered by name",+ tags: [ApiDocsTags.AgentVaultAccessBundles],+ params: z.object({+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)+ }),+ response: { 200: z.object({ skills: AgentVaultBundleSkillSchema.array() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) =>+ server.services.agentVaultSkill.listBundleSkills({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ accessBundleId: req.params.accessBundleId+ })+ });++ server.route({+ method: "POST",+ url: "/:accessBundleId/skills",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "addAgentVaultAccessBundleSkill",+ description:+ "Add a skill to an Agent Vault access bundle. Agents get the skill when they start with the bundle, so agents already running get it after a restart.",+ tags: [ApiDocsTags.AgentVaultAccessBundles],+ params: z.object({+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId)+ }),+ body: z.object({+ skillId: z.string().uuid().describe(AGENT_VAULT.SKILL.addSkillId)+ }),+ response: { 200: z.object({ skill: AgentVaultBundleSkillSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, accessBundle } = await server.services.agentVaultSkill.addToBundle({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ accessBundleId: req.params.accessBundleId,+ skillId: req.body.skillId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_ADD,+ metadata: {+ skillId: skill.id,+ skillName: skill.name,+ accessBundleId: accessBundle.id,+ accessBundleName: accessBundle.name+ }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultAccessBundleSkillAdded,+ properties: { skillId: skill.id, accessBundleId: accessBundle.id }+ });++ return { skill };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:accessBundleId/skills/:skillId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "removeAgentVaultAccessBundleSkill",+ description: "Remove a skill from an Agent Vault access bundle.",+ tags: [ApiDocsTags.AgentVaultAccessBundles],+ params: z.object({+ accessBundleId: z.string().uuid().describe(AGENT_VAULT.ACCESS_BUNDLE.accessBundleId),+ skillId: z.string().uuid().describe(AGENT_VAULT.SKILL.skillId)+ }),+ response: { 200: z.object({ skill: AgentVaultBundleSkillSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, accessBundle } = await server.services.agentVaultSkill.removeFromBundle({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ accessBundleId: req.params.accessBundleId,+ skillId: req.params.skillId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_REMOVE,+ metadata: {+ skillId: skill.id,+ skillName: skill.name,+ accessBundleId: accessBundle.id,+ accessBundleName: accessBundle.name+ }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultAccessBundleSkillRemoved,+ properties: { skillId: skill.id, accessBundleId: accessBundle.id }+ });++ return { skill };+ }+ });+server.route({method: "GET",url: "/:accessBundleId/members",diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.tsindex 62acfd26dc..68f9bbd47f 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-schemas.ts@@ -2,6 +2,11 @@ import { z } from "zod";import { ProjectMembershipRole } from "@app/db/schemas";import { AGENT_VAULT_MAX_GRANTEES } from "@app/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service";+import {+ AGENT_VAULT_SKILL_MAX_PATH_LENGTH,+ AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT+} from "@app/ee/services/agent-vault-skill/agent-vault-skill-fns";+import { AgentVaultSkillFileMode } from "@app/ee/services/agent-vault-skill/agent-vault-skill-types";import {AGENT_VAULT_NO_CONTROL_CHARS_MESSAGE,AGENT_VAULT_NO_CONTROL_CHARS_RE@@ -783,3 +788,79 @@ export const AgentVaultCreatedMemberSchema = z.discriminatedUnion("type", [actorRefSchemas.machineIdentity.extend({ grantedAt: grantedAtSchema }),actorRefSchemas.group.extend({ grantedAt: grantedAtSchema })]);++// Paths and limits are checked in the service, so a bad file gets a 400 that names it. These are outer bounds.+const AgentVaultSkillFileSchema = z.object({+ path: z.string().min(1).max(AGENT_VAULT_SKILL_MAX_PATH_LENGTH).describe(AGENT_VAULT.SKILL.filePath),+ mode: z.nativeEnum(AgentVaultSkillFileMode).describe(AGENT_VAULT.SKILL.fileMode),+ contentBase64: z.string().max(AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT).describe(AGENT_VAULT.SKILL.fileContent)+});++// The service refuses more than AGENT_VAULT_SKILL_MAX_FILES with a 400 that says so; a schema failure would be a 422.+const AGENT_VAULT_SKILL_UPLOAD_MAX_FILES = 1000;++export const AgentVaultSkillUploadSchema = z.object({+ files: AgentVaultSkillFileSchema.array()+ .min(1, "Upload at least SKILL.md")+ .max(AGENT_VAULT_SKILL_UPLOAD_MAX_FILES)+ .describe(AGENT_VAULT.SKILL.files)+});++export const AgentVaultSkillUpdateSchema = AgentVaultSkillUploadSchema.extend({+ baseVersion: z.number().int().positive().optional().describe(AGENT_VAULT.SKILL.baseVersion)+});++export const AgentVaultSkillVersionParamSchema = z.coerce+ .number()+ .int()+ .min(1)+ .max(2147483647)+ .describe(AGENT_VAULT.SKILL.version);++export const AgentVaultSkillSchema = z.object({+ id: z.string().uuid().describe(AGENT_VAULT.SKILL.skillId),+ name: z.string().describe(AGENT_VAULT.SKILL.name),+ description: z.string().describe(AGENT_VAULT.SKILL.description),+ latestVersion: z.number().describe(AGENT_VAULT.SKILL.latestVersion),+ createdAt: z.date().describe(AGENT_VAULT.SKILL.createdAt),+ updatedAt: z.date().describe(AGENT_VAULT.SKILL.updatedAt)+});++export const AgentVaultSkillDetailSchema = AgentVaultSkillSchema.extend({+ accessBundles: z+ .object({+ id: z.string().uuid().describe(AGENT_VAULT.SKILL.accessBundleId),+ name: z.string().describe(AGENT_VAULT.SKILL.accessBundleName)+ })+ .array()+ .describe(AGENT_VAULT.SKILL.accessBundles)+});++export const AgentVaultSkillVersionSchema = z.object({+ id: z.string().uuid().describe(AGENT_VAULT.SKILL.versionId),+ version: z.number().describe(AGENT_VAULT.SKILL.version),+ sha256: z.string().describe(AGENT_VAULT.SKILL.sha256),+ sizeBytes: z.number().describe(AGENT_VAULT.SKILL.sizeBytes),+ fileCount: z.number().describe(AGENT_VAULT.SKILL.fileCount),+ createdAt: z.date().describe(AGENT_VAULT.SKILL.versionCreatedAt)+});++export const AgentVaultSkillFilesResponseSchema = z+ .object({+ path: z.string().describe(AGENT_VAULT.SKILL.filePath),+ mode: z.nativeEnum(AgentVaultSkillFileMode).describe(AGENT_VAULT.SKILL.fileMode),+ contentBase64: z.string().describe(AGENT_VAULT.SKILL.fileContent)+ })+ .array()+ .describe(AGENT_VAULT.SKILL.files);++export const AgentVaultSkillVersionWithFilesSchema = AgentVaultSkillVersionSchema.extend({+ files: AgentVaultSkillFilesResponseSchema+});++export const AgentVaultBundleSkillSchema = z.object({+ id: z.string().uuid().describe(AGENT_VAULT.SKILL.skillId),+ name: z.string().describe(AGENT_VAULT.SKILL.name),+ description: z.string().describe(AGENT_VAULT.SKILL.description),+ latestVersion: z.number().describe(AGENT_VAULT.SKILL.latestVersion)+});diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-skill-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-skill-router.tsnew file mode 100644index 0000000000..1d78314481--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-session-skill-router.ts@@ -0,0 +1,124 @@+import { z } from "zod";++import { TAgentVaultSessions } from "@app/db/schemas";+import { AGENT_VAULT_SESSION_TOKEN_PREFIX } from "@app/ee/services/agent-vault-session/agent-vault-session-fns";+import { EventType, IdentityActor, UserActor, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";+import { AGENT_VAULT } from "@app/lib/api-docs";+import { ApiDocsTags } from "@app/lib/api-docs/constants";+import { UnauthorizedError } from "@app/lib/errors";+import { readLimit } from "@app/server/config/rateLimiter";+import { ActorType } from "@app/services/auth/auth-type";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++import { AgentVaultSkillFilesResponseSchema } from "./agent-vault-schemas";++const BEARER_PREFIX = "Bearer ";+const SESSION_TOKEN_MAX_LENGTH = 128;++const SessionTokenAuthorizationSchema = z+ .string()+ .max(BEARER_PREFIX.length + SESSION_TOKEN_MAX_LENGTH)+ .startsWith(BEARER_PREFIX)+ .transform((header) => header.slice(BEARER_PREFIX.length).trim())+ .pipe(+ z+ .string()+ .min(AGENT_VAULT_SESSION_TOKEN_PREFIX.length + 1)+ .max(SESSION_TOKEN_MAX_LENGTH)+ .startsWith(AGENT_VAULT_SESSION_TOKEN_PREFIX)+ );++const SessionSkillSchema = z.object({+ id: z.string().uuid().describe(AGENT_VAULT.SKILL.skillId),+ name: z.string().describe(AGENT_VAULT.SKILL.name),+ version: z.number().describe(AGENT_VAULT.SKILL.version),+ sha256: z.string().describe(AGENT_VAULT.SKILL.sha256),+ files: AgentVaultSkillFilesResponseSchema+});++const sessionOwnerActor = (+ session: TAgentVaultSessions,+ ownerUser: { username: string; email: string | null } | null+): UserActor | IdentityActor =>+ session.userId && ownerUser+ ? { type: ActorType.USER, metadata: { userId: session.userId, ...ownerUser } }+ : { type: ActorType.IDENTITY, metadata: { identityId: session.identityId!, name: session.actorName } };++export const registerAgentVaultSessionSkillRouter = async (server: FastifyZodProvider) => {+ // Authenticated by the session token alone, which inject-identity skips for this path: the CLI holds no+ // other credential when it starts an agent from a `--session-token`.+ server.route({+ method: "GET",+ url: "/skills",+ config: { rateLimit: readLimit },+ schema: {+ hide: true,+ operationId: "listAgentVaultSessionSkills",+ description:+ "Get the latest files of every skill on the calling session's access bundles, ordered by name. Authenticate with the session token as `Authorization: Bearer agv_...`. Called once when an agent starts.",+ tags: [ApiDocsTags.AgentVaultSkills],+ response: {+ 200: z.object({+ skills: SessionSkillSchema.array().describe(AGENT_VAULT.SKILL.sessionSkills)+ })+ }+ },+ handler: async (req) => {+ const authorization = SessionTokenAuthorizationSchema.safeParse(req.headers.authorization);+ if (!authorization.success) {+ throw new UnauthorizedError({+ message: "Send an Agent Vault session token in the Authorization header, as 'Bearer agv_...'."+ });+ }++ const { skills, session, ownerUser, orgId } = await server.services.agentVaultProxy.getSessionSkills({+ sessionToken: authorization.data+ });++ const actor = sessionOwnerActor(session, ownerUser);+ if (skills.length > 0) {+ // A session carries one access bundle today, so every skill is credited to the same one.+ const [{ accessBundleId, accessBundleName }] = skills;+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ actor,+ orgId,+ projectId: session.projectId,+ event: {+ type: EventType.AGENT_VAULT_SKILLS_DELIVERED,+ metadata: {+ sessionId: session.id,+ accessBundleId,+ accessBundleName,+ skills: skills.map((skill) => ({+ skillId: skill.id,+ skillName: skill.name,+ version: skill.version,+ sha256: skill.sha256+ }))+ }+ }+ });++ void server.services.telemetry+ .sendPostHogEvents({+ event: PostHogEventTypes.AgentVaultSkillsDelivered,+ distinctId: `agent-vault-session-${session.id}`,+ organizationId: orgId,+ anonymous: true,+ properties: {+ orgId,+ channel: req.auditLogInfo.userAgentType ?? UserAgentType.OTHER,+ actorType: actor.type,+ skillCount: skills.length+ }+ })+ .catch(() => {});+ }++ return {+ skills: skills.map(({ id, name, version, sha256, files }) => ({ id, name, version, sha256, files }))+ };+ }+ });+};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-skill-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-skill-router.tsnew file mode 100644index 0000000000..87f2e51142--- /dev/null+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-skill-router.ts@@ -0,0 +1,389 @@+import { z } from "zod";++import {+ AGENT_VAULT_SKILL_NAME_MAX_LENGTH,+ AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT,+ skillSizeBucket+} from "@app/ee/services/agent-vault-skill/agent-vault-skill-fns";+import { EventType } from "@app/ee/services/audit-log/audit-log-types";+import { AGENT_VAULT } from "@app/lib/api-docs";+import { ApiDocsTags } from "@app/lib/api-docs/constants";+import { readLimit, writeLimit } from "@app/server/config/rateLimiter";+import { emitAgentVaultTelemetry } from "@app/server/lib/telemetry";+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";+import { AuthMode } from "@app/services/auth/auth-type";+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";++import { actorContext } from "./agent-vault-router-fns";+import {+ agentVaultListQuery,+ AgentVaultSkillDetailSchema,+ AgentVaultSkillFilesResponseSchema,+ AgentVaultSkillSchema,+ AgentVaultSkillUpdateSchema,+ AgentVaultSkillUploadSchema,+ AgentVaultSkillVersionParamSchema,+ AgentVaultSkillVersionSchema,+ AgentVaultSkillVersionWithFilesSchema+} from "./agent-vault-schemas";++const SkillIdParamsSchema = z.object({+ skillId: z.string().uuid().describe(AGENT_VAULT.SKILL.skillId)+});++const SkillVersionParamsSchema = SkillIdParamsSchema.extend({ version: AgentVaultSkillVersionParamSchema });++export const registerAgentVaultSkillRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "POST",+ url: "/",+ bodyLimit: AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT,+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "createAgentVaultSkill",+ description:+ "Add a skill to Agent Vault from its folder of files. The name comes from the `name` in SKILL.md, and the files become version 1.",+ tags: [ApiDocsTags.AgentVaultSkills],+ body: AgentVaultSkillUploadSchema,+ response: { 200: z.object({ skill: AgentVaultSkillSchema, version: AgentVaultSkillVersionSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, version } = await server.services.agentVaultSkill.createSkill({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ files: req.body.files+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SKILL_CREATE,+ metadata: { skillId: skill.id, skillName: skill.name, version: version.version, sha256: version.sha256 }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultSkillCreated,+ properties: {+ skillId: skill.id,+ fileCount: version.fileCount,+ sizeBucket: skillSizeBucket(version.sizeBytes)+ }+ });++ return { skill, version };+ }+ });++ server.route({+ method: "GET",+ url: "/",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listAgentVaultSkills",+ description:+ "List the skills in Agent Vault and the access bundles each is in, ordered by name. A member sees only the skills on access bundles they have been granted.",+ tags: [ApiDocsTags.AgentVaultSkills],+ querystring: z.object({+ name: z+ .string()+ .trim()+ .min(1)+ .max(AGENT_VAULT_SKILL_NAME_MAX_LENGTH)+ .optional()+ .describe(AGENT_VAULT.SKILL.nameFilter),+ ...agentVaultListQuery(AGENT_VAULT.SKILL)+ }),+ response: {+ 200: z.object({+ skills: AgentVaultSkillDetailSchema.array(),+ totalCount: z.number().describe(AGENT_VAULT.SKILL.totalCount)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) =>+ server.services.agentVaultSkill.listSkills({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ ...req.query+ })+ });++ server.route({+ method: "GET",+ url: "/:skillId",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "getAgentVaultSkill",+ description:+ "Get a skill in Agent Vault, the access bundles it is in, and the files of its latest version. A member can get only a skill on an access bundle they have been granted.",+ tags: [ApiDocsTags.AgentVaultSkills],+ params: SkillIdParamsSchema,+ response: {+ 200: z.object({+ skill: AgentVaultSkillDetailSchema.extend({+ files: AgentVaultSkillFilesResponseSchema.describe(AGENT_VAULT.SKILL.latestFiles)+ })+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, version } = await server.services.agentVaultSkill.getSkill({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ skillId: req.params.skillId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SKILL_VERSION_VIEW,+ metadata: { skillId: skill.id, skillName: skill.name, version }+ }+ });++ return { skill };+ }+ });++ server.route({+ method: "PATCH",+ url: "/:skillId",+ bodyLimit: AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT,+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "updateAgentVaultSkill",+ description:+ "Update a skill's files. Each change is saved as a new version; if the files match the latest version, nothing is saved and that version is returned. If the `name` in SKILL.md differs, the skill is renamed, unless another skill already has that name.",+ tags: [ApiDocsTags.AgentVaultSkills],+ params: SkillIdParamsSchema,+ body: AgentVaultSkillUpdateSchema,+ response: {+ 200: z.object({+ skill: AgentVaultSkillSchema,+ version: AgentVaultSkillVersionSchema,+ unchanged: z.boolean().describe(AGENT_VAULT.SKILL.unchanged)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, version, unchanged, previousName } = await server.services.agentVaultSkill.updateSkill({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ skillId: req.params.skillId,+ files: req.body.files,+ baseVersion: req.body.baseVersion+ });++ if (!unchanged) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SKILL_VERSION_CREATE,+ metadata: { skillId: skill.id, skillName: skill.name, version: version.version, sha256: version.sha256 }+ }+ });++ if (previousName) {+ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SKILL_RENAME,+ metadata: { skillId: skill.id, oldName: previousName, newName: skill.name }+ }+ });+ }++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultSkillVersionPublished,+ properties: {+ skillId: skill.id,+ version: version.version,+ isRestore: false,+ fileCount: version.fileCount,+ sizeBucket: skillSizeBucket(version.sizeBytes)+ }+ });+ }++ return { skill, version, unchanged };+ }+ });++ server.route({+ method: "DELETE",+ url: "/:skillId",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "deleteAgentVaultSkill",+ description: "Delete a skill from Agent Vault. It is removed from every access bundle.",+ tags: [ApiDocsTags.AgentVaultSkills],+ params: SkillIdParamsSchema,+ response: { 200: z.object({ skill: AgentVaultSkillSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, removedFromBundles } = await server.services.agentVaultSkill.deleteSkill({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ skillId: req.params.skillId+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SKILL_DELETE,+ metadata: {+ skillId: skill.id,+ skillName: skill.name,+ removedFromBundles: removedFromBundles.map((bundle) => ({ id: bundle.id, name: bundle.name }))+ }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultSkillDeleted,+ properties: { skillId: skill.id, removedBundleCount: removedFromBundles.length }+ });++ return { skill };+ }+ });++ server.route({+ method: "GET",+ url: "/:skillId/versions",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "listAgentVaultSkillVersions",+ description: "List the kept versions of a skill, newest first. Only admins can list versions.",+ tags: [ApiDocsTags.AgentVaultSkills],+ params: SkillIdParamsSchema,+ response: { 200: z.object({ versions: AgentVaultSkillVersionSchema.array() }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) =>+ server.services.agentVaultSkill.listVersions({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ skillId: req.params.skillId+ })+ });++ server.route({+ method: "GET",+ url: "/:skillId/versions/:version",+ config: { rateLimit: readLimit },+ schema: {+ hide: false,+ operationId: "getAgentVaultSkillVersion",+ description:+ "Get one version of a skill with its files. A member can get only the latest version of a skill on an access bundle they have been granted.",+ tags: [ApiDocsTags.AgentVaultSkills],+ params: SkillVersionParamsSchema,+ response: { 200: z.object({ version: AgentVaultSkillVersionWithFilesSchema }) }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, version } = await server.services.agentVaultSkill.getVersionFiles({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ skillId: req.params.skillId,+ version: req.params.version+ });++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SKILL_VERSION_VIEW,+ metadata: { skillId: skill.id, skillName: skill.name, version: version.version }+ }+ });++ return { version };+ }+ });++ server.route({+ method: "POST",+ url: "/:skillId/versions/:version/restore",+ config: { rateLimit: writeLimit },+ schema: {+ hide: false,+ operationId: "restoreAgentVaultSkillVersion",+ description:+ "Restore an earlier version of a skill by publishing a copy of its files as a new version. The versions in between are kept. The skill keeps its current name: if the restored SKILL.md names it differently, its `name` line is changed to the current name. If the files match the latest version, nothing is published and that version is returned.",+ tags: [ApiDocsTags.AgentVaultSkills],+ params: SkillVersionParamsSchema,+ response: {+ 200: z.object({+ skill: AgentVaultSkillSchema,+ version: AgentVaultSkillVersionSchema,+ unchanged: z.boolean().describe(AGENT_VAULT.SKILL.restoreUnchanged)+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),+ handler: async (req) => {+ const { skill, version, fromVersion, unchanged } = await server.services.agentVaultSkill.restoreVersion({+ projectId: req.internalAgentVaultProjectId,+ ctx: actorContext(req),+ skillId: req.params.skillId,+ version: req.params.version+ });++ if (unchanged) return { skill, version, unchanged };++ await server.services.auditLog.createAuditLog({+ ...req.auditLogInfo,+ orgId: req.permission.orgId,+ projectId: req.internalAgentVaultProjectId,+ event: {+ type: EventType.AGENT_VAULT_SKILL_VERSION_RESTORE,+ metadata: {+ skillId: skill.id,+ skillName: skill.name,+ version: version.version,+ restoredFromVersion: fromVersion,+ sha256: version.sha256+ }+ }+ });++ emitAgentVaultTelemetry(server.services.telemetry, req, {+ event: PostHogEventTypes.AgentVaultSkillVersionPublished,+ properties: {+ skillId: skill.id,+ version: version.version,+ isRestore: true,+ fileCount: version.fileCount,+ sizeBucket: skillSizeBucket(version.sizeBytes)+ }+ });++ return { skill, version, unchanged };+ }+ });+};diff --git a/backend/src/ee/routes/v1/agent-vault-routers/index.ts b/backend/src/ee/routes/v1/agent-vault-routers/index.tsindex 114bdc527d..fc02e1df03 100644--- a/backend/src/ee/routes/v1/agent-vault-routers/index.ts+++ b/backend/src/ee/routes/v1/agent-vault-routers/index.ts@@ -7,13 +7,16 @@ import { registerAgentVaultProxyAgentRouter } from "./agent-vault-proxy-agent-roimport { registerAgentVaultProxyRouter } from "./agent-vault-proxy-router";import { registerAgentVaultSessionLogRouter } from "./agent-vault-session-log-router";import { registerAgentVaultSessionRouter } from "./agent-vault-session-router";+import { registerAgentVaultSessionSkillRouter } from "./agent-vault-session-skill-router";import { registerAgentVaultSettingsRouter } from "./agent-vault-settings-router";+import { registerAgentVaultSkillRouter } from "./agent-vault-skill-router";import { registerAgentVaultVariableRouter } from "./agent-vault-variable-router";export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {await server.register(registerAgentVaultProjectRouter, { prefix: "/project" });await server.register(registerAgentVaultAccessBundleRouter, { prefix: "/access-bundles" });await server.register(registerAgentVaultVariableRouter, { prefix: "/variables" });+ await server.register(registerAgentVaultSkillRouter, { prefix: "/skills" });await server.register(async (sessionServer) => {await sessionServer.register(registerAgentVaultSessionRouter);@@ -21,6 +24,7 @@ export const registerAgentVaultRouters = async (server: FastifyZodProvider) => {},{ prefix: "/sessions" });+ await server.register(registerAgentVaultSessionSkillRouter, { prefix: "/session" });await server.register(registerAgentVaultSettingsRouter, { prefix: "/settings" });await server.register(registerAgentVaultAppConnectionRouter, { prefix: "/app-connections/aws" });await server.register(registerAgentVaultProxyRouter, { prefix: "/proxies" });diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.tsindex 00f94f3e52..7856a06150 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.test.ts@@ -70,7 +70,7 @@ const setup = (agentVaultProxyDAL: {findByIdWithOrg: async () => ({ projectId: PROJECT_ID, orgId: "org-1", pollInterval: 60 })} as never,- agentVaultResolveDAL: { findResolvableServices: async () => rows },+ agentVaultResolveDAL: { findResolvableServices: async () => rows, findSessionSkills: async () => [] },agentVaultServiceCustomHeaderDAL: { findByServiceIds: async () => [] },agentVaultServiceSubstitutionDAL: { findByServiceIds: async () => [] },agentVaultVariableDAL: { findValuesForResolve: async () => variables },@@ -85,6 +85,8 @@ const setup = (},membershipDAL: { findResourceMembershipsForActor: async () => [] },orgDAL: { findEffectiveOrgMembership: async () => ({ isActive: true }) as never },+ projectDAL: { findById: async () => ({ id: PROJECT_ID, orgId: "org-1" }) as never },+ userDAL: { findById: async () => undefined as never },permissionService: {getProjectPermission: async () =>({diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 26f9e084df..8239b3387a 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@ -1,6 +1,12 @@import { ForbiddenError } from "@casl/ability";-import { ActionProjectType, OrgMembershipStatus, ProjectMembershipRole, TAgentVaultProxies } from "@app/db/schemas";+import {+ ActionProjectType,+ OrgMembershipStatus,+ ProjectMembershipRole,+ TAgentVaultProxies,+ TAgentVaultSessions+} from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {ProjectPermissionAgentVaultProxyActions,@@ -22,6 +28,8 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { KmsDataKey } from "@app/services/kms/kms-types";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TOrgDALFactory } from "@app/services/org/org-dal";+import { TProjectDALFactory } from "@app/services/project/project-dal";+import { TUserDALFactory } from "@app/services/user/user-dal";import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";@@ -41,6 +49,7 @@ import { openSessionLogKey } from "../agent-vault-session-log/agent-vault-sessioimport { getEffectiveSessionLogConfig } from "../agent-vault-session-log/agent-vault-session-log-storage-fns";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";+import { deserializeSkillFiles } from "../agent-vault-skill/agent-vault-skill-fns";import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";import {@@ -65,8 +74,10 @@ import { TAgentVaultProxyDALFactory } from "./agent-vault-proxy-dal";import {TAgentVaultProxyConfig,TAgentVaultProxyScoped,+ TAuthorizeSessionDTO,TBootstrapProxyDTO,TCreateProxyDTO,+ TGetSessionSkillsDTO,THeartbeatDTO,TListProxiesDTO,TProxyByIdDTO,@@ -97,6 +108,8 @@ type TAgentVaultProxyServiceFactoryDep = {agentVaultSessionLogConfigDAL: Pick<TAgentVaultSessionLogConfigDALFactory, "findOne" | "findByProjectIdFromPrimary">;membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;+ projectDAL: Pick<TProjectDALFactory, "findById">;+ userDAL: Pick<TUserDALFactory, "findById">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;licenseService: TSessionLogLicenseService;@@ -142,6 +155,8 @@ export const agentVaultProxyServiceFactory = ({agentVaultSessionLogConfigDAL,membershipDAL,orgDAL,+ projectDAL,+ userDAL,permissionService,kmsService,licenseService,@@ -650,21 +665,9 @@ export const agentVaultProxyServiceFactory = ({return resolved;};- // Shared by resolve and credential refresh, so a refresh can never reach a service resolve would not.- const $authorizeSession = async ({- proxyId,- orgId,- sessionToken- }: Pick<TResolveSessionDTO, "proxyId" | "orgId" | "sessionToken">) => {- const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));- if (!session) throw new NotFoundError({ message: "Session not found" });-- // A mismatch is 404, not 403, so a proxy cannot probe another tenant for session ids.- const proxy = await agentVaultProxyDAL.findByIdWithOrg(proxyId);- if (!proxy || proxy.projectId !== session.projectId || proxy.orgId !== orgId) {- throw new NotFoundError({ message: "Session not found" });- }-+ // Shared by the proxy's session routes and the CLI's skills fetch, so none of them can reach a bundle resolve+ // would not. Returns the bundles the session's owner reaches now, null for an admin.+ const $authorizeSessionOwner = async (session: TAgentVaultSessions, orgId: string) => {if (session.revokedAt) throw new UnauthorizedError({ message: "This session has been revoked" });if (session.expiresAt && session.expiresAt <= new Date()) {throw new UnauthorizedError({ message: "This session has expired" });@@ -721,14 +724,26 @@ export const agentVaultProxyServiceFactory = ({throw error;}- const accessBundleIds = isAdmin+ return isAdmin? null- : await findReachableAccessBundleIds(membershipDAL, {+ : findReachableAccessBundleIds(membershipDAL, {projectId: session.projectId,actor,groupIds: liveGroupIds});+ };++ const $authorizeSession = async ({ proxyId, orgId, sessionToken }: TAuthorizeSessionDTO) => {+ const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));+ if (!session) throw new NotFoundError({ message: "Session not found" });++ // A mismatch is 404, not 403, so a proxy cannot probe another tenant for session ids.+ const proxy = await agentVaultProxyDAL.findByIdWithOrg(proxyId);+ if (!proxy || proxy.projectId !== session.projectId || proxy.orgId !== orgId) {+ throw new NotFoundError({ message: "Session not found" });+ }+ const accessBundleIds = await $authorizeSessionOwner(session, orgId);return { session, proxy, accessBundleIds };};@@ -973,6 +988,55 @@ export const agentVaultProxyServiceFactory = ({);};+ // Called by the CLI once when an agent starts: the latest files of every skill on the session's reachable bundles.+ // The session token is the only credential, so an unknown one gets the same 401 as any other refusal.+ const getSessionSkills = async ({ sessionToken }: TGetSessionSkillsDTO) => {+ const session = await agentVaultSessionDAL.findByTokenHash(hashSessionToken(sessionToken));+ const project = session ? await projectDAL.findById(session.projectId) : undefined;+ if (!session || !project) {+ throw new UnauthorizedError({ message: "This Agent Vault session token is not valid" });+ }++ const accessBundleIds = await $authorizeSessionOwner(session, project.orgId);++ const rows = await agentVaultResolveDAL.findSessionSkills({+ sessionId: session.id,+ projectId: session.projectId,+ accessBundleIds+ });++ const decryptor = rows.length+ ? (+ await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: session.projectId+ })+ ).decryptor+ : null;++ const skills = rows.map((row) => ({+ id: row.id,+ name: row.name,+ version: row.version,+ sha256: row.sha256,+ files: deserializeSkillFiles(decryptor!({ cipherTextBlob: row.encryptedFiles })),+ accessBundleId: row.accessBundleId,+ accessBundleName: row.accessBundleName+ }));++ // The session snapshots its owner at mint. Name a user as they are now, as PAM does, and fall back to the+ // snapshot for one who is gone.+ let ownerUser: { username: string; email: string | null } | null = null;+ if (session.userId) {+ const user = await userDAL.findById(session.userId);+ ownerUser = user+ ? { username: user.username, email: user.email ?? null }+ : { username: session.actorEmail ?? session.actorName, email: session.actorEmail ?? null };+ }++ return { skills, session, ownerUser, orgId: project.orgId };+ };+return {getProxyForAuth,listProxies,@@ -985,6 +1049,7 @@ export const agentVaultProxyServiceFactory = ({heartbeat,resolveSession,refreshCredential,- reportMissingScopes+ reportMissingScopes,+ getSessionSkills};};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.tsindex 82c7326408..7df4143d49 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-types.ts@@ -54,10 +54,17 @@ export type THeartbeatDTO = {proxyId: string;};-export type TResolveSessionDTO = {+export type TAuthorizeSessionDTO = {proxyId: string;orgId: string;sessionToken: string;+};++export type TGetSessionSkillsDTO = {+ sessionToken: string;+};++export type TResolveSessionDTO = TAuthorizeSessionDTO & {hasSessionLogKey: boolean;};diff --git a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.tsindex ff1fff4566..f2a39fecb4 100644--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-resolve-dal.ts@@ -22,7 +22,37 @@ export type TResolveServiceRow = {position: number;};+export type TResolveSkillRow = {+ id: string;+ name: string;+ version: number;+ sha256: string;+ encryptedFiles: Buffer;+ accessBundleId: string;+ accessBundleName: string;+};++type TResolveScope = { sessionId: string; projectId: string; accessBundleIds: string[] | null };+export const agentVaultResolveDALFactory = (db: TDbClient) => {+ // The session's bundles that the actor can still reach: the bundle set fixed at mint, intersected with the bundles+ // the actor's live grants allow (accessBundleIds, null when every bundle in the project is allowed). Services and+ // skills both hang off this, so a lost grant takes both away together.+ const reachableSessionBundles = (conn: Knex, { sessionId, projectId, accessBundleIds }: TResolveScope) => {+ const query = conn(TableName.AgentVaultSessionAccessBundle)+ .where(`${TableName.AgentVaultSessionAccessBundle}.sessionId`, sessionId)+ .whereNotNull(`${TableName.AgentVaultSessionAccessBundle}.accessBundleId`)+ .join(+ TableName.AgentVaultAccessBundle,+ `${TableName.AgentVaultSessionAccessBundle}.accessBundleId`,+ `${TableName.AgentVaultAccessBundle}.id`+ )+ .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId);++ if (accessBundleIds) void query.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);+ return query;+ };+/*** The hot path, and an intersection: a session's bundle set is a ceiling fixed at mint, re-checked against* live grants on every resolve, so losing a grant empties a running session without touching its row.@@ -31,39 +61,22 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {*/const findResolvableServices = async ({- sessionId,- projectId,- accessBundleIds,- serviceId- }: {- sessionId: string;- projectId: string;- accessBundleIds: string[] | null;+ serviceId,+ ...scope+ }: TResolveScope & {// Narrows to one service, for a credential refresh that must stay inside the session's resolved set.serviceId?: string;},tx?: Knex): Promise<TResolveServiceRow[]> => {- if (accessBundleIds?.length === 0) return [];+ if (scope.accessBundleIds?.length === 0) return [];try {- const conn = tx || db.replicaNode();+ const query = reachableSessionBundles(tx || db.replicaNode(), scope).join(+ TableName.AgentVaultService,+ `${TableName.AgentVaultService}.accessBundleId`,+ `${TableName.AgentVaultAccessBundle}.id`+ );- const query = conn(TableName.AgentVaultSessionAccessBundle)- .where(`${TableName.AgentVaultSessionAccessBundle}.sessionId`, sessionId)- .whereNotNull(`${TableName.AgentVaultSessionAccessBundle}.accessBundleId`)- .join(- TableName.AgentVaultAccessBundle,- `${TableName.AgentVaultSessionAccessBundle}.accessBundleId`,- `${TableName.AgentVaultAccessBundle}.id`- )- .where(`${TableName.AgentVaultAccessBundle}.projectId`, projectId)- .join(- TableName.AgentVaultService,- `${TableName.AgentVaultService}.accessBundleId`,- `${TableName.AgentVaultAccessBundle}.id`- );-- if (accessBundleIds) void query.whereIn(`${TableName.AgentVaultAccessBundle}.id`, accessBundleIds);if (serviceId) void query.where(`${TableName.AgentVaultService}.id`, serviceId);return (await query@@ -90,5 +103,51 @@ export const agentVaultResolveDALFactory = (db: TDbClient) => {}};- return { findResolvableServices };+ // The latest version of each skill, once, credited to the first of the session's bundles that carries it. Reads the+ // primary: this runs once per agent start, and a skill published a moment before must not arrive a version late.+ const findSessionSkills = async (scope: TResolveScope, tx?: Knex): Promise<TResolveSkillRow[]> => {+ if (scope.accessBundleIds?.length === 0) return [];+ try {+ const rows = (await reachableSessionBundles(tx || db, scope)+ .join(+ TableName.AgentVaultAccessBundleSkill,+ `${TableName.AgentVaultAccessBundleSkill}.accessBundleId`,+ `${TableName.AgentVaultAccessBundle}.id`+ )+ .join(+ TableName.AgentVaultSkill,+ `${TableName.AgentVaultAccessBundleSkill}.skillId`,+ `${TableName.AgentVaultSkill}.id`+ )+ .where(`${TableName.AgentVaultSkill}.projectId`, scope.projectId)+ .join(TableName.AgentVaultSkillVersion, function joinLatestVersion() {+ this.on(`${TableName.AgentVaultSkillVersion}.skillId`, `${TableName.AgentVaultSkill}.id`).andOn(+ `${TableName.AgentVaultSkillVersion}.version`,+ db.raw(`(SELECT MAX(v."version") FROM ?? v WHERE v."skillId" = ??.id)`, [+ TableName.AgentVaultSkillVersion,+ TableName.AgentVaultSkill+ ])+ );+ })+ .distinctOn(`${TableName.AgentVaultSkill}.id`)+ .select(+ db.ref("id").withSchema(TableName.AgentVaultSkill),+ db.ref("name").withSchema(TableName.AgentVaultSkill),+ db.ref("version").withSchema(TableName.AgentVaultSkillVersion),+ db.ref("sha256").withSchema(TableName.AgentVaultSkillVersion),+ db.ref("encryptedFiles").withSchema(TableName.AgentVaultSkillVersion),+ db.ref("id").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleId"),+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle).as("accessBundleName")+ )+ .orderBy([+ { column: `${TableName.AgentVaultSkill}.id` },+ { column: `${TableName.AgentVaultSessionAccessBundle}.position`, order: "asc" }+ ])) as TResolveSkillRow[];+ return rows.sort((a, b) => (a.name < b.name ? -1 : 1));+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault session skills" });+ }+ };++ return { findResolvableServices, findSessionSkills };};diff --git a/backend/src/ee/services/agent-vault-skill/agent-vault-skill-bundle-dal.ts b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-bundle-dal.tsnew file mode 100644index 0000000000..249059a589--- /dev/null+++ b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-bundle-dal.ts@@ -0,0 +1,137 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++import { TAgentVaultBundleSkill, TAgentVaultSkillBundleRef } from "./agent-vault-skill-types";++export type TAgentVaultSkillBundleDALFactory = ReturnType<typeof agentVaultSkillBundleDALFactory>;++export const agentVaultSkillBundleDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultAccessBundleSkill);++ // Reads the primary even without a tx, so a skill added a moment ago is listed.+ const findSkillsForBundle = async (accessBundleId: string, tx?: Knex): Promise<TAgentVaultBundleSkill[]> => {+ try {+ const rows = (await (tx || db)(TableName.AgentVaultAccessBundleSkill)+ .join(+ TableName.AgentVaultSkill,+ `${TableName.AgentVaultAccessBundleSkill}.skillId`,+ `${TableName.AgentVaultSkill}.id`+ )+ .where(`${TableName.AgentVaultAccessBundleSkill}.accessBundleId`, accessBundleId)+ .select(+ db.ref("id").withSchema(TableName.AgentVaultSkill),+ db.ref("name").withSchema(TableName.AgentVaultSkill),+ db.ref("description").withSchema(TableName.AgentVaultSkill),+ db.raw(`(SELECT MAX(v."version") FROM ?? v WHERE v."skillId" = ??.id) AS "latestVersion"`, [+ TableName.AgentVaultSkillVersion,+ TableName.AgentVaultSkill+ ])+ )+ .orderBy(`${TableName.AgentVaultSkill}.name`, "asc")) as unknown as (Omit<+ TAgentVaultBundleSkill,+ "latestVersion"+ > & { latestVersion: number | string })[];+ return rows.map((row) => ({ ...row, latestVersion: Number(row.latestVersion) }));+ } catch (error) {+ throw new DatabaseError({ error, name: "List agent vault access bundle skills" });+ }+ };++ // accessBundleIds null returns every bundle; otherwise only those of them the skill is in.+ const findBundlesForSkill = async (+ skillId: string,+ accessBundleIds: string[] | null,+ tx?: Knex+ ): Promise<TAgentVaultSkillBundleRef[]> => {+ if (accessBundleIds?.length === 0) return [];+ try {+ const query = (tx || db)(TableName.AgentVaultAccessBundleSkill)+ .join(+ TableName.AgentVaultAccessBundle,+ `${TableName.AgentVaultAccessBundleSkill}.accessBundleId`,+ `${TableName.AgentVaultAccessBundle}.id`+ )+ .where(`${TableName.AgentVaultAccessBundleSkill}.skillId`, skillId);+ if (accessBundleIds)+ void query.whereIn(`${TableName.AgentVaultAccessBundleSkill}.accessBundleId`, accessBundleIds);+ return (await query+ .select(+ db.ref("id").withSchema(TableName.AgentVaultAccessBundle),+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle)+ )+ .orderBy(`${TableName.AgentVaultAccessBundle}.name`, "asc")) as TAgentVaultSkillBundleRef[];+ } catch (error) {+ throw new DatabaseError({ error, name: "List agent vault skill access bundles" });+ }+ };++ // Reads the primary even without a tx, so a bundle added a moment ago is listed. accessBundleIds null returns+ // every bundle; otherwise only those of them.+ const findBundlesForSkills = async (+ skillIds: string[],+ accessBundleIds: string[] | null,+ tx?: Knex+ ): Promise<Map<string, TAgentVaultSkillBundleRef[]>> => {+ const bundlesBySkill = new Map<string, TAgentVaultSkillBundleRef[]>();+ if (!skillIds.length || accessBundleIds?.length === 0) return bundlesBySkill;+ try {+ const query = (tx || db)(TableName.AgentVaultAccessBundleSkill)+ .join(+ TableName.AgentVaultAccessBundle,+ `${TableName.AgentVaultAccessBundleSkill}.accessBundleId`,+ `${TableName.AgentVaultAccessBundle}.id`+ )+ .whereIn(`${TableName.AgentVaultAccessBundleSkill}.skillId`, skillIds);+ if (accessBundleIds)+ void query.whereIn(`${TableName.AgentVaultAccessBundleSkill}.accessBundleId`, accessBundleIds);+ const rows = (await query+ .select(+ db.ref("skillId").withSchema(TableName.AgentVaultAccessBundleSkill),+ db.ref("id").withSchema(TableName.AgentVaultAccessBundle),+ db.ref("name").withSchema(TableName.AgentVaultAccessBundle)+ )+ .orderBy(`${TableName.AgentVaultAccessBundle}.name`, "asc")) as (TAgentVaultSkillBundleRef & {+ skillId: string;+ })[];+ for (const { skillId, id, name } of rows) {+ const bundles = bundlesBySkill.get(skillId);+ if (bundles) bundles.push({ id, name });+ else bundlesBySkill.set(skillId, [{ id, name }]);+ }+ return bundlesBySkill;+ } catch (error) {+ throw new DatabaseError({ error, name: "List agent vault skills' access bundles" });+ }+ };++ const countForBundle = async (accessBundleId: string, tx?: Knex): Promise<number> => {+ try {+ const result = (await (tx || db)(TableName.AgentVaultAccessBundleSkill)+ .where({ accessBundleId })+ .count("skillId as count")+ .first()) as { count: string | number } | undefined;+ return Number(result?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "Count agent vault access bundle skills" });+ }+ };++ const isSkillReachable = async (skillId: string, accessBundleIds: string[], tx?: Knex): Promise<boolean> => {+ if (!accessBundleIds.length) return false;+ try {+ const row = (await (tx || db)(TableName.AgentVaultAccessBundleSkill)+ .where({ skillId })+ .whereIn("accessBundleId", accessBundleIds)+ .first("skillId")) as { skillId: string } | undefined;+ return Boolean(row);+ } catch (error) {+ throw new DatabaseError({ error, name: "Check agent vault skill reachability" });+ }+ };++ return { ...orm, findSkillsForBundle, isSkillReachable, findBundlesForSkill, findBundlesForSkills, countForBundle };+};diff --git a/backend/src/ee/services/agent-vault-skill/agent-vault-skill-dal.ts b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-dal.tsnew file mode 100644index 0000000000..382bf60fbe--- /dev/null+++ b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-dal.ts@@ -0,0 +1,152 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultSkills } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { sanitizeSqlLikeString } from "@app/lib/fn/string";+import { ormify } from "@app/lib/knex";++export type TAgentVaultSkillDALFactory = ReturnType<typeof agentVaultSkillDALFactory>;++export type TAgentVaultSkillSummaryRow = TAgentVaultSkills & { latestVersion: number };++type TSummaryQueryRow = TAgentVaultSkills & { latestVersion: number | string };++const SKILL_COLUMNS = ["id", "projectId", "name", "description", "createdAt", "updatedAt"] as const;++export const agentVaultSkillDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultSkill);++ const columns = SKILL_COLUMNS.map((column) => `${TableName.AgentVaultSkill}.${column}`);++ const summaryQuery = (conn: Knex) =>+ conn(TableName.AgentVaultSkill).select(+ ...columns,+ db.raw(`(SELECT MAX(v."version") FROM ?? v WHERE v."skillId" = ??.id) AS "latestVersion"`, [+ TableName.AgentVaultSkillVersion,+ TableName.AgentVaultSkill+ ])+ );++ const toSummary = (row: TSummaryQueryRow): TAgentVaultSkillSummaryRow => ({+ ...row,+ latestVersion: Number(row.latestVersion)+ });++ // Reads the primary even without a tx, so a skill created or published a moment ago is listed as it now is.+ // accessBundleIds null lists every skill; otherwise only skills in one of those bundles.+ const findForList = async (+ {+ projectId,+ accessBundleIds,+ search,+ name,+ limit,+ offset+ }: {+ projectId: string;+ accessBundleIds: string[] | null;+ search?: string;+ name?: string;+ limit: number;+ offset: number;+ },+ tx?: Knex+ ): Promise<{ skills: TAgentVaultSkillSummaryRow[]; totalCount: number }> => {+ if (accessBundleIds?.length === 0) return { skills: [], totalCount: 0 };++ try {+ const conn = tx || db;+ const applyFilters = (query: Knex.QueryBuilder) => {+ void query.where(`${TableName.AgentVaultSkill}.projectId`, projectId);+ if (accessBundleIds) {+ void query.whereExists(+ conn(TableName.AgentVaultAccessBundleSkill)+ .select(db.raw("1"))+ .whereRaw(`??."skillId" = ??.id`, [TableName.AgentVaultAccessBundleSkill, TableName.AgentVaultSkill])+ .whereIn(`${TableName.AgentVaultAccessBundleSkill}.accessBundleId`, accessBundleIds)+ );+ }+ if (name !== undefined) void query.where(`${TableName.AgentVaultSkill}.name`, name);+ if (search) {+ const term = `%${sanitizeSqlLikeString(search)}%`;+ void query.where((qb) => {+ void qb+ .orWhereILike(`${TableName.AgentVaultSkill}.name`, term)+ .orWhereILike(`${TableName.AgentVaultSkill}.description`, term);+ });+ }+ return query;+ };++ const [countResult, rows] = await Promise.all([+ applyFilters(conn(TableName.AgentVaultSkill))+ .count(`${TableName.AgentVaultSkill}.id as count`)+ .first() as Promise<{ count: string } | undefined>,+ applyFilters(summaryQuery(conn))+ .orderBy(`${TableName.AgentVaultSkill}.name`, "asc")+ .limit(limit)+ .offset(offset) as Promise<TSummaryQueryRow[]>+ ]);+ return { skills: rows.map(toSummary), totalCount: parseInt(countResult?.count || "0", 10) };+ } catch (error) {+ throw new DatabaseError({ error, name: "List agent vault skills" });+ }+ };++ const findSummaryByIdInProject = async (+ { id, projectId }: { id: string; projectId: string },+ tx?: Knex+ ): Promise<TAgentVaultSkillSummaryRow | undefined> => {+ try {+ const row = (await summaryQuery(tx || db)+ .where(`${TableName.AgentVaultSkill}.id`, id)+ .where(`${TableName.AgentVaultSkill}.projectId`, projectId)+ .first()) as TSummaryQueryRow | undefined;+ return row ? toSummary(row) : undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault skill" });+ }+ };++ const findByNameInProject = async (+ { name, projectId }: { name: string; projectId: string },+ tx?: Knex+ ): Promise<TAgentVaultSkills | undefined> => {+ try {+ return (await (tx || db)(TableName.AgentVaultSkill).where({ name, projectId }).first(columns)) as+ | TAgentVaultSkills+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault skill by name" });+ }+ };++ const countInProject = async (projectId: string, tx?: Knex): Promise<number> => {+ try {+ const result = (await (tx || db)(TableName.AgentVaultSkill).where({ projectId }).count("id as count").first()) as+ | { count: string | number }+ | undefined;+ return Number(result?.count ?? 0);+ } catch (error) {+ throw new DatabaseError({ error, name: "Count agent vault skills" });+ }+ };++ // Taken by a delete, by a publish or restore, and by an add so a skill being deleted can't gain a bundle on+ // its way out.+ const lockByIdInProject = async (+ { id, projectId }: { id: string; projectId: string },+ tx: Knex+ ): Promise<TAgentVaultSkills | undefined> => {+ try {+ return (await tx(TableName.AgentVaultSkill).where({ id, projectId }).forUpdate().first(columns)) as+ | TAgentVaultSkills+ | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Lock agent vault skill" });+ }+ };++ return { ...orm, findForList, findSummaryByIdInProject, findByNameInProject, countInProject, lockByIdInProject };+};diff --git a/backend/src/ee/services/agent-vault-skill/agent-vault-skill-fns.test.ts b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-fns.test.tsnew file mode 100644index 0000000000..fd2e96c9f0--- /dev/null+++ b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-fns.test.ts@@ -0,0 +1,557 @@+import { describe, expect, test } from "vitest";++import { BadRequestError } from "@app/lib/errors";++import {+ AGENT_VAULT_SKILL_MAX_FILE_BYTES,+ AGENT_VAULT_SKILL_MAX_FILES,+ AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT,+ parseSkillHeader,+ replaceSkillHeaderName,+ sha256Hex,+ skillSizeBucket,+ validateSkillFiles+} from "./agent-vault-skill-fns";+import { AgentVaultSkillFileMode } from "./agent-vault-skill-types";++const b64 = (text: string | Buffer) => Buffer.from(text).toString("base64");++const manifest = (header: string, body = "Do the thing.\n") => `---\n${header}\n---\n${body}`;++const file = (path: string, content: string | Buffer, mode = AgentVaultSkillFileMode.Regular) => ({+ path,+ mode,+ contentBase64: b64(content)+});++const skillMd = (header = "name: code-review\ndescription: Reviews code") => file("SKILL.md", manifest(header));++const expectBadRequest = (fn: () => unknown, message: string | RegExp) => {+ let thrown: unknown;+ try {+ fn();+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(BadRequestError);+ expect((thrown as Error).message).toMatch(message);+};++describe("validateSkillFiles limits", () => {+ test("accepts a minimal skill", () => {+ const result = validateSkillFiles([skillMd()]);+ expect(result.name).toBe("code-review");+ expect(result.description).toBe("Reviews code");+ expect(result.fileCount).toBe(1);+ });++ test("requires SKILL.md at the root", () => {+ expectBadRequest(+ () => validateSkillFiles([file("docs/SKILL.md", manifest("name: a\ndescription: b"))]),+ "SKILL.md is missing."+ );+ expectBadRequest(+ () => validateSkillFiles([file("skill.md", manifest("name: a\ndescription: b"))]),+ "SKILL.md is missing."+ );+ });++ test("refuses a file over the per-file cap and names it", () => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("scripts/x.sh", Buffer.alloc(AGENT_VAULT_SKILL_MAX_FILE_BYTES + 1))]),+ "File 'scripts/x.sh' is larger than 256 KB."+ );+ });++ test("accepts a file at exactly the per-file cap", () => {+ expect(() =>+ validateSkillFiles([skillMd(), file("big.bin", Buffer.alloc(AGENT_VAULT_SKILL_MAX_FILE_BYTES))])+ ).not.toThrow();+ });++ test("refuses a skill over the total cap", () => {+ const files = [0, 1, 2, 3, 4].map((i) => file(`part-${i}.bin`, Buffer.alloc(AGENT_VAULT_SKILL_MAX_FILE_BYTES)));+ expectBadRequest(() => validateSkillFiles([skillMd(), ...files]), /add up to more than 1 MB/);+ });++ test("refuses more files than the cap", () => {+ const files = Array.from({ length: AGENT_VAULT_SKILL_MAX_FILES }, (_, i) => file(`f${i}.txt`, "x"));+ expectBadRequest(() => validateSkillFiles([skillMd(), ...files]), /at most 50 files/);+ });++ test("a single 1.05 MB file fits the upload body and gets the 400 that names it", () => {+ const big = file("big.bin", Buffer.alloc(Math.round(1.05 * 1024 * 1024)));+ expect(big.contentBase64.length).toBeLessThan(AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT);+ expectBadRequest(() => validateSkillFiles([skillMd(), big]), "File 'big.bin' is larger than 256 KB.");+ });++ test("refuses content that is not base64", () => {+ expectBadRequest(+ () =>+ validateSkillFiles([skillMd(), { path: "a.txt", mode: AgentVaultSkillFileMode.Regular, contentBase64: "@@@" }]),+ "File 'a.txt' is not valid base64."+ );+ });+});++describe("validateSkillFiles paths", () => {+ test.each(["/etc/passwd", "../escape.sh", "a/../../b", "a//b", "./a", "a/"])("refuses '%s'", (path) => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(path, "x")]),+ `File path '${path}' must be a relative path inside the skill folder`+ );+ });++ test("refuses an empty path", () => {+ expectBadRequest(() => validateSkillFiles([skillMd(), file("", "x")]), "A file has an empty path.");+ });++ test("refuses a backslash and a control character, naming the file", () => {+ expectBadRequest(() => validateSkillFiles([skillMd(), file("a\\b", "x")]), "File path 'a\\b' uses a backslash.");+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("a\nb", "x")]),+ 'File path "a\\nb" contains a control character.'+ );+ });++ test.each(["C:/x", "a:b.md", "a<b", "a>b", 'a"b', "a|b", "a?b", "docs/a*.md"])(+ "refuses a character Windows does not allow in '%s'",+ (path) => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(path, "x")]),+ `File path '${path}' can't contain any of`+ );+ }+ );++ test.each([+ ["notes.", "notes."],+ ["docs./a.md", "docs."],+ ["a /b.md", "a "],+ ["b.md ", "b.md "]+ ])("refuses '%s', which has a part ending in a dot or space", (path, part) => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(path, "x")]),+ `File path '${path}' has a part ending in a dot or a space ('${part}')`+ );+ });++ test.each([+ ["CON", "CON"],+ ["con.txt", "con.txt"],+ ["docs/nul.md", "nul.md"],+ ["Aux", "Aux"],+ ["PRN.tar.gz", "PRN.tar.gz"],+ ["com1", "com1"],+ ["LPT9.log", "LPT9.log"],+ ["COM3/a.md", "COM3"]+ ])("refuses the Windows device name in '%s'", (path, device) => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(path, "x")]),+ `File path '${path}' uses '${device}', which is a reserved name.`+ );+ });++ test.each(["console.md", "com10", "lpt0.txt", "nullable.md", "docs/con-notes.md"])(+ "accepts '%s', which only looks like a device name",+ (path) => {+ expect(() => validateSkillFiles([skillMd(), file(path, "x")])).not.toThrow();+ }+ );++ test("refuses a lone surrogate", () => {+ expectBadRequest(() => validateSkillFiles([skillMd(), file("a\uD800b.md", "x")]), /is not valid Unicode/);+ expectBadRequest(() => validateSkillFiles([skillMd(), file("a\uDC00.md", "x")]), /is not valid Unicode/);+ });++ test("refuses paths that differ only in case or Unicode form", () => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("Docs/a.md", "x"), file("docs/A.md", "y")]),+ "Files 'Docs/a.md' and 'docs/A.md' would be the same file on disk."+ );+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("caf\u00e9.md", "x"), file("cafe\u0301.md", "y")]),+ /would be the same file on disk/+ );+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("CAF\u00c9.md", "x"), file("cafe\u0301.md", "y")]),+ /would be the same file on disk/+ );+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("a.md", "x"), file("a.md", "y")]),+ "File 'a.md' is listed twice."+ );+ });++ test("refuses a path that is also a folder of another path", () => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("docs", "x"), file("docs/a.md", "y")]),+ "'docs' is a file, but 'docs/a.md' puts it inside a folder of the same name."+ );+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("a/b/c.md", "y"), file("A/B", "x")]),+ "'A/B' is a file, but 'a/b/c.md' puts it inside a folder of the same name."+ );+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file("SKILL.md/x", "y")]),+ "'SKILL.md' is a file, but 'SKILL.md/x' puts it inside a folder of the same name."+ );+ });++ test("refuses a path over 255 characters and accepts one at 255", () => {+ const atLimit = `${"a".repeat(200)}/${"b".repeat(54)}`;+ expect(atLimit.length).toBe(255);+ expect(() => validateSkillFiles([skillMd(), file(atLimit, "x")])).not.toThrow();+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(`${atLimit}c`, "x")]),+ `File path '${"a".repeat(64)}...' is longer than 255 characters.`+ );+ });++ test("refuses a file or folder name over 255 bytes, counting UTF-8 bytes", () => {+ const ascii = "a".repeat(255);+ expect(() => validateSkillFiles([skillMd(), file(ascii, "x")])).not.toThrow();++ // 128 two-byte characters: 128 characters but 256 bytes.+ const wide = "\u00e9".repeat(128);+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(`docs/${wide}.md`, "x")]),+ `File name '${"\u00e9".repeat(64)}…' in 'docs/${wide}.md' is too long. Shorten it.`+ );+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(`${wide}/a.md`, "x")]),+ /^File name '[^']+…' in '[^']+' is too long\. Shorten it\.$/+ );+ expect(() => validateSkillFiles([skillMd(), file(`${"\u00e9".repeat(127)}a`, "x")])).not.toThrow();++ // 64 four-byte characters are 256 bytes, so the whole name is shown with no ellipsis.+ const emoji = "\u{1F600}".repeat(64);+ expectBadRequest(+ () => validateSkillFiles([skillMd(), file(emoji, "x")]),+ `File name '${emoji}' in '${emoji}' is too long. Shorten it.`+ );+ });++ test("accepts nested relative paths", () => {+ expect(+ validateSkillFiles([skillMd(), file("scripts/run.sh", "x", AgentVaultSkillFileMode.Executable)]).fileCount+ ).toBe(2);+ });+});++describe("parseSkillHeader", () => {+ const parse = (text: string) => parseSkillHeader(Buffer.from(text));++ test("reads multi-line and quoted values", () => {+ expect(parse(manifest("name: code-review\ndescription: >-\n Reviews code\n in two lines")).description).toBe(+ "Reviews code in two lines"+ );+ expect(parse(manifest("name: 'code-review'\ndescription: \"Uses *bold* & more\"")).name).toBe("code-review");+ });++ test("lets plain prose with asterisks through", () => {+ expect(parse(manifest("name: a\ndescription: Use *bold* text")).description).toBe("Use *bold* text");+ });++ test("accepts CRLF line endings and a byte order mark", () => {+ expect(parse(`\uFEFF---\r\nname: a\r\ndescription: b\r\n---\r\nbody`).name).toBe("a");+ });++ test("resolves an alias under the JSON schema", () => {+ expect(parse(manifest("base: &x a\nname: *x\ndescription: b")).name).toBe("a");+ });++ test("reads a block scalar that starts with an asterisk", () => {+ expect(parse(manifest("name: a\ndescription: |\n *Important*: reviews code")).description).toBe(+ "*Important*: reviews code"+ );+ });++ test("measures the description after trimming it", () => {+ const atLimit = "d".repeat(1024);+ expect(parse(manifest(`name: a\ndescription: |\n ${atLimit}`)).description).toBe(atLimit);+ expectBadRequest(() => parse(manifest(`name: a\ndescription: |\n ${"d".repeat(1025)}`)), /longer than 1024/);+ });++ test("refuses a header that is not valid YAML and names the line", () => {+ expectBadRequest(+ () => parse(manifest("name: a\ndescription: [unclosed")),+ "Line 3 of SKILL.md: the 'description' value opens a '[' that never closes."+ );+ expectBadRequest(+ () => parse(manifest("name: a\nname: b\ndescription: c")),+ "Line 3 of SKILL.md: the header is not valid YAML (duplicated mapping key)."+ );+ expectBadRequest(+ () => parse(manifest("name: !!js/function 'x'\ndescription: b")),+ "Line 2 of SKILL.md: the header is not valid YAML (unknown tag !<tag:yaml.org,2002:js/function>)."+ );+ });++ test.each([+ [+ "audit",+ 'name: audit\ndescription: Audit a large multi-repo change set for coherence: reverse-engineer what it was built to do\ndisable-model-invocation: true\nargument-hint: [repo paths and/or head ref, e.g. "../cli feat/x"]'+ ],+ [+ "infi",+ "name: infi\ndescription: Drive a local Infisical dev stack: print an org-scoped user JWT\nargument-hint: login | relay <name>"+ ],+ [+ "scrutinize",+ "name: scrutinize\ndescription: Saif's full PR review. Leaves its own pointer questions: every file and suspicious line\ndisable-model-invocation: true"+ ]+ ])("names the unquoted ': ' in the %s skill's description", (_, header) => {+ expectBadRequest(+ () => parse(manifest(header)),+ "Line 3 of SKILL.md: the 'description' value contains ': '. Put the value in double quotes."+ );+ });++ test("ignores ': ' in quoted values and comments when naming the broken line", () => {+ expectBadRequest(+ () => parse(manifest('name: a\ndescription: "x: y" # see: below\nhint: one: two')),+ "Line 4 of SKILL.md: the 'hint' value contains ': '. Put the value in double quotes."+ );+ });++ test("counts lines from the opening '---' with a byte order mark and CRLF line endings", () => {+ const header = "name: a\r\ndescription: Review: then fix";+ expectBadRequest(+ () => parse(`\uFEFF---\r\n${header}\r\n---\r\nbody\r\n`),+ "Line 3 of SKILL.md: the 'description' value contains ': '. Put the value in double quotes."+ );+ expectBadRequest(+ () => parse("\uFEFF---\r\nname: a\r\nname: b\r\n---\r\n"),+ "Line 3 of SKILL.md: the header is not valid YAML (duplicated mapping key)."+ );+ });++ test.each([+ ["---\nname: a\ndescription: d\nx: 1\nhint: [x\n---\n", "opens a '[' that never closes"],+ ["---\nname: a\ndescription: d\nx: 1\nhint: {x\n---\n", "opens a '{' that never closes"],+ ['---\nname: a\ndescription: d\nx: 1\nhint: "x\n---\n', "opens a double quote that never closes"],+ ["---\nname: a\ndescription: d\nx: 1\nhint: 'x\n---\n", "opens a single quote that never closes"],+ ["---\nname: a\nlist: [a,\n b]\nhint: {x\n---\n", "opens a '{' that never closes"],+ ["---\r\nname: a\r\ndescription: d\r\nx: 1\r\nhint: [x\r\n---\r\n", "opens a '[' that never closes"],+ ["\uFEFF---\nname: a\ndescription: d\nx: 1\nhint: [x\n---\n", "opens a '[' that never closes"]+ ])("names the line of a value that never closes in %j", (text, problem) => {+ expectBadRequest(() => parse(text), `Line 5 of SKILL.md: the 'hint' value ${problem}.`);+ });++ test.each([+ '---\ndescription: "first\nsecond"\nname: a\nname: b\n---\n',+ "---\nhint: [a,\n# note\n b]\nname: a\nname: b\n---\n"+ ])("does not blame a value that continues at column zero in %j", (text) => {+ expectBadRequest(() => parse(text), /duplicated mapping key/);+ });++ test("still names a quote left open before the next key", () => {+ expectBadRequest(+ () => parse('---\nname: "oops\ndescription: y\n---\n'),+ "Line 2 of SKILL.md: the 'name' value opens a double quote that never closes."+ );+ });++ test("accepts a CRLF header without seeing control characters", () => {+ expect(parse("---\r\nname: a\r\ndescription: |\r\n one\r\n two\r\n---\r\n")).toEqual({+ name: "a",+ description: "one\ntwo"+ });+ });++ test.each([+ ["NUL", "\\0"],+ ["ESC", "\\e"],+ ["BEL", "\\a"],+ ["CR", "\\r"],+ ["DEL", "\\x7f"]+ ])("refuses a %s control character in the name and the description", (_, escape) => {+ expectBadRequest(+ () => parse(manifest(`name: "a${escape}"\ndescription: b`)),+ "The 'name' in SKILL.md contains a control character."+ );+ expectBadRequest(+ () => parse(manifest(`name: a\ndescription: "x${escape}y"`)),+ "The 'description' in SKILL.md contains a control character."+ );+ });++ test("allows tabs and newlines in the description", () => {+ expect(parse(manifest('name: a\ndescription: "x\\ty\\nz"')).description).toBe("x\ty\nz");+ });++ test("refuses a raw control character as invalid YAML", () => {+ expectBadRequest(+ () => parse(manifest("name: a\ndescription: x\u0007y")),+ "Line 3 of SKILL.md: the header is not valid YAML (the stream contains non-printable characters)."+ );+ });++ test("refuses a missing header", () => {+ expectBadRequest(() => parse("# Just markdown"), /must start with a YAML header/);+ expectBadRequest(() => parse("---\nname: a\ndescription: b\n"), /must start with a YAML header/);+ });++ test("refuses an oversize header", () => {+ expectBadRequest(() => parse(manifest(`name: a\ndescription: b\npad: ${"x".repeat(5000)}`)), /larger than 4 KB/);+ });++ test("checks name and description", () => {+ expectBadRequest(() => parse(manifest("description: b")), "SKILL.md header needs a 'name'.");+ expectBadRequest(+ () => parse(manifest("name: 12\ndescription: b")),+ "The 'name' in SKILL.md must be text. Put it in quotes."+ );+ expectBadRequest(+ () => parse(manifest("name: true\ndescription: b")),+ "The 'name' in SKILL.md must be text. Put it in quotes."+ );+ expect(parse(manifest("name: '12'\ndescription: b")).name).toBe("12");+ expectBadRequest(+ () => parse(manifest("name: a\ndescription: 42")),+ "The 'description' in SKILL.md must be text. Put it in quotes."+ );+ expectBadRequest(+ () => parse(manifest("name: Code Review\ndescription: b")),+ "A skill name can only use lowercase letters, numbers and single hyphens, and can't start or end with a hyphen."+ );+ expectBadRequest(() => parse(manifest("name: code--review\ndescription: b")), /single hyphens/);+ expectBadRequest(() => parse(manifest("name: -code\ndescription: b")), /can't start or end with a hyphen/);+ expectBadRequest(() => parse(manifest(`name: ${"a".repeat(65)}\ndescription: b`)), /longer than 64/);+ expectBadRequest(() => parse(manifest("name: a")), "SKILL.md header needs a 'description'.");+ expectBadRequest(() => parse(manifest(`name: a\ndescription: ${"d".repeat(1025)}`)), /longer than 1024/);+ expectBadRequest(() => parse(manifest("- a\n- b")), /key: value/);+ });++ test("refuses a Windows device name as the skill name", () => {+ ["con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"].forEach((name) => {+ expectBadRequest(+ () => parse(manifest(`name: ${name}\ndescription: b`)),+ `'${name}' is a reserved name and can't be used as a skill name.`+ );+ });+ expect(parse(manifest("name: aux-tools\ndescription: b")).name).toBe("aux-tools");+ expect(parse(manifest("name: com10\ndescription: b")).name).toBe("com10");+ });+});++describe("replaceSkillHeaderName", () => {+ const rename = (text: string, name = "new-name") => {+ const result = replaceSkillHeaderName(Buffer.from(text), name);+ return result === null ? null : result.toString("utf8");+ };++ test("rewrites a plain value and nothing else", () => {+ const before = manifest("name: old-name\ndescription: Reviews code", "# old-name\n\nname: old-name\n");+ const after = rename(before);+ expect(after).toBe(manifest("name: new-name\ndescription: Reviews code", "# old-name\n\nname: old-name\n"));+ expect(parseSkillHeader(Buffer.from(after!)).name).toBe("new-name");+ });++ test("keeps the quoting style", () => {+ expect(rename(manifest("name: 'old-name'\ndescription: b"))).toBe(manifest("name: 'new-name'\ndescription: b"));+ expect(rename(manifest('name: "old-name" \ndescription: b'))).toBe(+ manifest('name: "new-name" \ndescription: b')+ );+ });++ test("keeps a trailing comment and comment lines", () => {+ const before = manifest("# the skill\nname: old-name # set by the CLI\ndescription: b");+ expect(rename(before)).toBe(manifest("# the skill\nname: new-name # set by the CLI\ndescription: b"));+ expect(rename(manifest("name: 'old-name' # quoted\ndescription: b"))).toBe(+ manifest("name: 'new-name' # quoted\ndescription: b")+ );+ });++ test("keeps CRLF line endings", () => {+ const before = "---\r\nname: old-name\r\ndescription: b\r\n---\r\nbody\r\n";+ expect(rename(before)).toBe("---\r\nname: new-name\r\ndescription: b\r\n---\r\nbody\r\n");+ });++ test("keeps a byte order mark", () => {+ const result = replaceSkillHeaderName(Buffer.from("\uFEFF---\nname: old-name\ndescription: b\n---\n"), "x");+ expect(result!.subarray(0, 3)).toEqual(Buffer.from([0xef, 0xbb, 0xbf]));+ expect(result!.toString("utf8")).toBe("\uFEFF---\nname: x\ndescription: b\n---\n");+ expect(parseSkillHeader(result!).name).toBe("x");+ });++ test("ignores an indented name and anything after the header", () => {+ const before = manifest("meta:\n name: inner\nname: old-name\ndescription: b", "name: in-body\n");+ expect(rename(before)).toBe(manifest("meta:\n name: inner\nname: new-name\ndescription: b", "name: in-body\n"));+ });++ test("quotes a name that would otherwise read back as a number, boolean or null", () => {+ ["12", "1e5", "true", "null"].forEach((name) => {+ const after = rename(manifest("name: old-name # kept\ndescription: b"), name);+ expect(after).toBe(manifest(`name: "${name}" # kept\ndescription: b`));+ expect(parseSkillHeader(Buffer.from(after!)).name).toBe(name);+ });+ expect(rename(manifest("name: 'old-name'\ndescription: b"), "12")).toBe(manifest("name: '12'\ndescription: b"));+ });++ test("returns null when there is no name line it can rewrite", () => {+ expect(rename(manifest("description: b"))).toBeNull();+ expect(rename(manifest("name: >-\n old-name\ndescription: b"))).toBeNull();+ expect(rename(manifest("base: &x old-name\nname: *x\ndescription: b"))).toBeNull();+ expect(rename(manifest("description: b", "name: old-name\n"))).toBeNull();+ expect(rename("# no header\nname: old-name\n")).toBeNull();+ });+});++describe("hashing", () => {+ test("the version hash is over the files sorted by path with content re-encoded", () => {+ const a = validateSkillFiles([file("b.txt", "two"), skillMd(), file("a.txt", "one")]);+ const b = validateSkillFiles([file("a.txt", "one"), skillMd(), file("b.txt", "two")]);+ expect(a.sha256).toBe(b.sha256);+ expect(a.files.map((f) => f.path)).toEqual(["SKILL.md", "a.txt", "b.txt"]);+ expect(a.sha256).toBe(sha256Hex(JSON.stringify(a.files)));+ expect(Object.keys(a.files[0])).toEqual(["path", "mode", "contentBase64"]);++ const changedMode = validateSkillFiles([+ file("a.txt", "one", AgentVaultSkillFileMode.Executable),+ skillMd(),+ file("b.txt", "two")+ ]);+ expect(changedMode.sha256).not.toBe(a.sha256);+ });++ test("sorts paths by UTF-8 bytes, as Go does, so the hash matches", () => {+ // U+FF21 sorts before U+1F600 in UTF-16 code units but after it in UTF-8 bytes.+ const result = validateSkillFiles([+ skillMd(),+ file("\uFF21.md", "x"),+ file("\u{1F600}.md", "y"),+ file("b.md", "z")+ ]);+ expect(result.files.map((f) => f.path)).toEqual(["SKILL.md", "b.md", "\uFF21.md", "\u{1F600}.md"]);+ expect(result.sha256).toBe(sha256Hex(JSON.stringify(result.files)));+ });++ test("size buckets", () => {+ expect(skillSizeBucket(0)).toBe("lt-10kb");+ expect(skillSizeBucket(50 * 1024)).toBe("10kb-100kb");+ expect(skillSizeBucket(1024 * 1024)).toBe("100kb-1mb");+ });+});++describe("validateSkillFiles name line", () => {+ test.each([+ "name: code-review\ndescription: Reviews code",+ 'name: "code-review"\ndescription: Reviews code',+ "name: 'code-review' # main\ndescription: Reviews code"+ ])("accepts a name on its own line: %s", (header) => {+ expect(validateSkillFiles([skillMd(header)]).name).toBe("code-review");+ });++ test.each([+ "name: >-\n code-review\ndescription: Reviews code",+ "{name: code-review, description: Reviews code}",+ "name: &n code-review\ndescription: Reviews code"+ ])("refuses a name a restore could not rewrite: %s", (header) => {+ expectBadRequest(+ () => validateSkillFiles([skillMd(header)]),+ "Write the name as a plain line in SKILL.md, like 'name: code-review'."+ );+ });+});diff --git a/backend/src/ee/services/agent-vault-skill/agent-vault-skill-fns.ts b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-fns.tsnew file mode 100644index 0000000000..8ed2938e79--- /dev/null+++ b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-fns.ts@@ -0,0 +1,490 @@+import { JSON_SCHEMA, load, YAMLException } from "js-yaml";++import { crypto } from "@app/lib/crypto/cryptography";+import { BadRequestError } from "@app/lib/errors";+import { slugSchema } from "@app/server/lib/schemas";++import { AgentVaultSkillFileMode, TAgentVaultSkillFile } from "./agent-vault-skill-types";++export const AGENT_VAULT_SKILL_MANIFEST = "SKILL.md";+export const AGENT_VAULT_SKILL_MAX_FILES = 50;+export const AGENT_VAULT_SKILL_MAX_FILE_BYTES = 256 * 1024;+export const AGENT_VAULT_SKILL_MAX_TOTAL_BYTES = 1024 * 1024;+export const AGENT_VAULT_SKILL_MAX_HEADER_BYTES = 4 * 1024;+export const AGENT_VAULT_SKILL_MAX_PATH_LENGTH = 255;+// Most file systems cap one file or folder name at 255 bytes, not characters.+export const AGENT_VAULT_SKILL_MAX_PATH_SEGMENT_BYTES = 255;+export const AGENT_VAULT_SKILL_NAME_MAX_LENGTH = 64;+export const AGENT_VAULT_SKILL_DESCRIPTION_MAX_LENGTH = 1024;+export const AGENT_VAULT_SKILL_VERSIONS_KEPT = 20;+export const AGENT_VAULT_MAX_SKILLS_PER_BUNDLE = 25;+export const AGENT_VAULT_MAX_SKILLS = 250;++// Files travel as base64, so a proxy in front of Infisical must accept bodies this large (nginx defaults to 1m).+// The schema caps content only at the body limit, so an oversize file in a request of up to about 1.5 MB of file+// content (base64 adds a third) gets the 400 that names it. A larger request gets "Request body is too large".+export const AGENT_VAULT_SKILL_UPLOAD_BODY_LIMIT = 2 * 1024 * 1024;++const BASE64_RE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;+// eslint-disable-next-line no-control-regex+const CONTROL_CHARS_RE = /[\x00-\x1f\x7f]/;+// Characters Windows refuses in a file name, so a skill installs the same way on every platform.+const WINDOWS_INVALID_CHARS_RE = /[:<>"|?*]/;+const WINDOWS_DEVICE_NAME_RE = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i;++const SkillNameSchema = slugSchema({ max: AGENT_VAULT_SKILL_NAME_MAX_LENGTH, field: "Name", trim: false });++export type TValidatedSkill = {+ name: string;+ description: string;+ files: TAgentVaultSkillFile[];+ serialized: Buffer;+ sha256: string;+ sizeBytes: number;+ fileCount: number;+};++const assertValidPath = (path: string) => {+ if (!path.length) {+ throw new BadRequestError({ message: "A file has an empty path." });+ }+ if (!path.isWellFormed()) {+ throw new BadRequestError({ message: `File path ${JSON.stringify(path)} is not valid Unicode.` });+ }+ if (path.length > AGENT_VAULT_SKILL_MAX_PATH_LENGTH) {+ throw new BadRequestError({+ message: `File path '${path.slice(0, 64)}...' is longer than ${AGENT_VAULT_SKILL_MAX_PATH_LENGTH} characters.`+ });+ }+ if (CONTROL_CHARS_RE.test(path)) {+ throw new BadRequestError({ message: `File path ${JSON.stringify(path)} contains a control character.` });+ }+ if (path.includes("\\")) {+ throw new BadRequestError({ message: `File path '${path}' uses a backslash. Separate folders with '/'.` });+ }+ const segments = path.split("/");+ if (path.startsWith("/") || segments.some((segment) => segment === "" || segment === "." || segment === "..")) {+ throw new BadRequestError({+ message: `File path '${path}' must be a relative path inside the skill folder, with no empty, '.' or '..' parts.`+ });+ }+ const long = segments.find(+ (segment) => Buffer.byteLength(segment, "utf8") > AGENT_VAULT_SKILL_MAX_PATH_SEGMENT_BYTES+ );+ if (long !== undefined) {+ const shown = Array.from(long).slice(0, 64).join("");+ throw new BadRequestError({+ message: `File name '${shown}${shown.length < long.length ? "…" : ""}' in '${path}' is too long. Shorten it.`+ });+ }+ if (WINDOWS_INVALID_CHARS_RE.test(path)) {+ throw new BadRequestError({+ message: `File path '${path}' can't contain any of : < > " | ? *`+ });+ }+ const trailing = segments.find((segment) => segment.endsWith(".") || segment.endsWith(" "));+ if (trailing !== undefined) {+ throw new BadRequestError({+ message: `File path '${path}' has a part ending in a dot or a space ('${trailing}'), which isn't allowed.`+ });+ }+ const device = segments.find((segment) => WINDOWS_DEVICE_NAME_RE.test(segment));+ if (device !== undefined) {+ throw new BadRequestError({+ message: `File path '${path}' uses '${device}', which is a reserved name. Rename that file or folder.`+ });+ }+};++const decodeContent = (file: { path: string; contentBase64: string }) => {+ if (!BASE64_RE.test(file.contentBase64)) {+ throw new BadRequestError({ message: `File '${file.path}' is not valid base64.` });+ }+ return Buffer.from(file.contentBase64, "base64");+};++const extractHeader = (content: Buffer) => {+ let text: string;+ try {+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: false }).decode(content);+ } catch {+ throw new BadRequestError({ message: `${AGENT_VAULT_SKILL_MANIFEST} is not UTF-8 text.` });+ }++ const lines = text.split(/\r?\n/);+ const closing = lines[0]?.trimEnd() === "---" ? lines.findIndex((line, i) => i > 0 && line.trimEnd() === "---") : -1;+ if (closing === -1) {+ throw new BadRequestError({+ message: `${AGENT_VAULT_SKILL_MANIFEST} must start with a YAML header between two '---' lines.`+ });+ }++ const header = lines.slice(1, closing).join("\n");+ if (Buffer.byteLength(header, "utf8") > AGENT_VAULT_SKILL_MAX_HEADER_BYTES) {+ throw new BadRequestError({+ message: `${AGENT_VAULT_SKILL_MANIFEST} header is larger than ${AGENT_VAULT_SKILL_MAX_HEADER_BYTES / 1024} KB.`+ });+ }+ return header;+};++const FLOW_OR_QUOTED_START = ['"', "'", "|", ">", "[", "{"];++// The usual way a hand-written header breaks: an unquoted value such as `description: Review: then fix`.+const findUnquotedColonValue = (headerLines: string[]) => {+ for (let i = 0; i < headerLines.length; i += 1) {+ const line = headerLines[i];+ const first = line[0];+ if (first !== undefined && first !== " " && first !== "\t" && first !== "#" && first !== "-") {+ const separator = line.indexOf(": ");+ if (separator > 0) {+ const value = line.slice(separator + 2).trimStart();+ const comment = value.indexOf(" #");+ const scalar = comment === -1 ? value : value.slice(0, comment);+ if (scalar.length && !FLOW_OR_QUOTED_START.includes(scalar[0]) && scalar.includes(": ")) {+ return { line: i, key: line.slice(0, separator).trimEnd() };+ }+ }+ }+ }+ return null;+};++const UNCLOSED_VALUE_OPENERS = ["[", "{", '"', "'"];+const QUOTE_MAY_FOLLOW = ["", "[", "{", ",", ":"];++const isBlank = (char: string | undefined) => char === " " || char === "\t" || char === "\n";++// A flow or quoted value may continue on indented lines, so its whole block is scanned before calling it unclosed.+const valueCloses = (text: string) => {+ let depth = 0;+ let quote = "";+ let previous = "";+ for (let i = 0; i < text.length; i += 1) {+ const char = text[i];+ if (quote === '"') {+ if (char === "\\") {+ i += 1;+ } else if (char === '"') {+ if (depth === 0) return true;+ quote = "";+ previous = char;+ }+ } else if (quote === "'") {+ if (char === "'" && text[i + 1] === "'") {+ i += 1;+ } else if (char === "'") {+ if (depth === 0) return true;+ quote = "";+ previous = char;+ }+ } else if (char === "#" && (i === 0 || isBlank(text[i - 1]))) {+ const newline = text.indexOf("\n", i);+ if (newline === -1) return false;+ i = newline;+ } else if ((char === '"' || char === "'") && QUOTE_MAY_FOLLOW.includes(previous)) {+ quote = char;+ } else {+ if (char === "[" || char === "{") depth += 1;+ if (char === "]" || char === "}") {+ depth -= 1;+ if (depth === 0) return true;+ }+ if (!isBlank(char)) previous = char;+ }+ }+ return false;+};++// A quoted or flow value may continue on lines that start at column zero, and comments may sit between its lines,+// so only the next top-level key ends it.+const startsTopLevelKey = (line: string) => {+ const first = line[0];+ if (first === undefined || first === " " || first === "\t" || first === "#" || first === "-") return false;+ const colon = line.indexOf(":");+ return colon > 0 && (colon === line.length - 1 || line[colon + 1] === " " || line[colon + 1] === "\t");+};++const findUnclosedValue = (headerLines: string[]) => {+ for (let i = 0; i < headerLines.length; i += 1) {+ const line = headerLines[i];+ const first = line[0];+ if (first !== undefined && first !== " " && first !== "\t" && first !== "#" && first !== "-") {+ const separator = line.indexOf(": ");+ if (separator > 0) {+ const value = line.slice(separator + 2).trimStart();+ if (UNCLOSED_VALUE_OPENERS.includes(value[0])) {+ let end = i + 1;+ while (end < headerLines.length && !startsTopLevelKey(headerLines[end])) end += 1;+ if (!valueCloses([value, ...headerLines.slice(i + 1, end)].join("\n"))) {+ return { line: i, key: line.slice(0, separator).trimEnd(), opener: value[0] };+ }+ }+ }+ }+ }+ return null;+};++const describeOpener = (opener: string) => {+ if (opener === '"') return "a double quote";+ if (opener === "'") return "a single quote";+ return `a '${opener}'`;+};++const yamlErrorMessage = (header: string, error: unknown) => {+ // The header starts on the line after the opening '---', so its first line is line 2 of the file.+ const unquoted = findUnquotedColonValue(header.split("\n"));+ if (unquoted) {+ return `Line ${unquoted.line + 2} of ${AGENT_VAULT_SKILL_MANIFEST}: the '${unquoted.key}' value contains ': '. Put the value in double quotes.`;+ }+ const unclosed = findUnclosedValue(header.split("\n"));+ if (unclosed) {+ return `Line ${unclosed.line + 2} of ${AGENT_VAULT_SKILL_MANIFEST}: the '${unclosed.key}' value opens ${describeOpener(unclosed.opener)} that never closes.`;+ }+ if (error instanceof YAMLException && typeof error.mark?.line === "number") {+ let reason = (error.reason ?? "").split("\n")[0].trim();+ while (reason.endsWith(".")) reason = reason.slice(0, -1);+ if (reason.length) {+ return `Line ${error.mark.line + 2} of ${AGENT_VAULT_SKILL_MANIFEST}: the header is not valid YAML (${reason}).`;+ }+ }+ return `${AGENT_VAULT_SKILL_MANIFEST} header is not valid YAML.`;+};++// Tab and newline are allowed; a CRLF file is fine because its line endings are dropped before parsing.+const hasControlCharacter = (value: string) => {+ for (let i = 0; i < value.length; i += 1) {+ const code = value.charCodeAt(i);+ if ((code <= 0x1f && code !== 0x09 && code !== 0x0a) || code === 0x7f) return true;+ }+ return false;+};++export const parseSkillHeader = (content: Buffer): { name: string; description: string } => {+ const header = extractHeader(content);++ let parsed: unknown;+ try {+ parsed = load(header, { schema: JSON_SCHEMA });+ } catch (error) {+ throw new BadRequestError({ message: yamlErrorMessage(header, error) });+ }+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new BadRequestError({+ message: `${AGENT_VAULT_SKILL_MANIFEST} header must be a list of 'key: value' lines.`+ });+ }++ const { name, description } = parsed as Record<string, unknown>;++ if (name === undefined || name === null || name === "") {+ throw new BadRequestError({ message: `${AGENT_VAULT_SKILL_MANIFEST} header needs a 'name'.` });+ }+ if (typeof name !== "string") {+ throw new BadRequestError({+ message: `The 'name' in ${AGENT_VAULT_SKILL_MANIFEST} must be text. Put it in quotes.`+ });+ }+ if (hasControlCharacter(name)) {+ throw new BadRequestError({ message: `The 'name' in ${AGENT_VAULT_SKILL_MANIFEST} contains a control character.` });+ }+ if (name.length > AGENT_VAULT_SKILL_NAME_MAX_LENGTH) {+ throw new BadRequestError({+ message: `The 'name' in ${AGENT_VAULT_SKILL_MANIFEST} is longer than ${AGENT_VAULT_SKILL_NAME_MAX_LENGTH} characters.`+ });+ }+ if (!SkillNameSchema.safeParse(name).success) {+ throw new BadRequestError({+ message: `The 'name' in ${AGENT_VAULT_SKILL_MANIFEST} is '${name}'. A skill name can only use lowercase letters, numbers and single hyphens, and can't start or end with a hyphen.`+ });+ }+ // The skill installs as a folder of this name, and Windows can't create one named after a device.+ if (WINDOWS_DEVICE_NAME_RE.test(name)) {+ throw new BadRequestError({ message: `'${name}' is a reserved name and can't be used as a skill name.` });+ }++ if (description === undefined || description === null) {+ throw new BadRequestError({ message: `${AGENT_VAULT_SKILL_MANIFEST} header needs a 'description'.` });+ }+ if (typeof description !== "string") {+ throw new BadRequestError({+ message: `The 'description' in ${AGENT_VAULT_SKILL_MANIFEST} must be text. Put it in quotes.`+ });+ }+ if (hasControlCharacter(description)) {+ throw new BadRequestError({+ message: `The 'description' in ${AGENT_VAULT_SKILL_MANIFEST} contains a control character.`+ });+ }+ const trimmedDescription = description.trim();+ if (!trimmedDescription.length) {+ throw new BadRequestError({ message: `${AGENT_VAULT_SKILL_MANIFEST} header needs a 'description'.` });+ }+ if (trimmedDescription.length > AGENT_VAULT_SKILL_DESCRIPTION_MAX_LENGTH) {+ throw new BadRequestError({+ message: `The 'description' in ${AGENT_VAULT_SKILL_MANIFEST} is longer than ${AGENT_VAULT_SKILL_DESCRIPTION_MAX_LENGTH} characters.`+ });+ }++ return { name, description: trimmedDescription };+};++const NAME_LINE_RE = /^(name[ \t]*:[ \t]*)(.*)$/;++// A plain `12`, `1e5`, `true` or `null` reads back as a number, boolean or null, which the header check refuses.+const loadsAsText = (name: string) => {+ try {+ return load(name, { schema: JSON_SCHEMA }) === name;+ } catch {+ return false;+ }+};++/**+ * Rewrites the value on the top-level `name:` line of a SKILL.md header and leaves every other byte alone (line+ * endings, a byte order mark, quoting and a trailing comment). Returns null when the header has no such line, for+ * example a name written as a block scalar or an alias, so the caller can refuse rather than guess.+ */+export const replaceSkillHeaderName = (content: Buffer, name: string): Buffer | null => {+ let text: string;+ try {+ text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content);+ } catch {+ return null;+ }++ const lines = text.split(/(?<=\n)/);+ const bare = (line: string) => line.replace(/^\uFEFF/, "").replace(/\r?\n$/, "");+ if (bare(lines[0] ?? "").trimEnd() !== "---") return null;++ for (let i = 1; i < lines.length; i += 1) {+ const ending = lines[i].match(/\r?\n$/)?.[0] ?? "";+ const line = lines[i].slice(0, lines[i].length - ending.length);+ if (line.trimEnd() === "---") return null;++ const match = NAME_LINE_RE.exec(line);+ if (match) {+ const [, prefix, rest] = match;+ let value: string;+ const quote = rest[0];+ if (quote === "'" || quote === '"') {+ const close = rest.indexOf(quote, 1);+ if (close === -1) return null;+ value = `${quote}${name}${quote}${rest.slice(close + 1)}`;+ } else {+ const comment = rest.search(/[ \t]#/);+ const end = comment === -1 ? rest.trimEnd().length : comment;+ const scalar = rest.slice(0, end).trimEnd();+ if (!scalar || /^[|>&*!{[]/.test(scalar)) return null;+ value = `${loadsAsText(name) ? name : JSON.stringify(name)}${rest.slice(scalar.length)}`;+ }+ lines[i] = `${prefix}${value}${ending}`;+ return Buffer.from(lines.join(""), "utf8");+ }+ }+ return null;+};++export const sha256Hex = (data: Buffer | string) => crypto.nativeCrypto.createHash("sha256").update(data).digest("hex");++/**+ * Checks a skill folder against the limits and returns it in canonical form: files sorted by path bytes and content+ * re-encoded, so the same folder always serializes, and hashes, the same way however the client encoded it.+ */+export const validateSkillFiles = (+ files: { path: string; mode: AgentVaultSkillFileMode; contentBase64: string }[]+): TValidatedSkill => {+ if (!files.length) {+ throw new BadRequestError({ message: `${AGENT_VAULT_SKILL_MANIFEST} is missing.` });+ }+ if (files.length > AGENT_VAULT_SKILL_MAX_FILES) {+ throw new BadRequestError({ message: `A skill can have at most ${AGENT_VAULT_SKILL_MAX_FILES} files.` });+ }++ // NFC and lowercase, so two paths that one file system would write to the same file can't both be listed.+ const fold = (path: string) => path.normalize("NFC").toLowerCase();+ const seen = new Map<string, string>();+ const folders = new Map<string, string>();+ let sizeBytes = 0;+ const decoded = files.map((file) => {+ assertValidPath(file.path);++ const folded = fold(file.path);+ const clash = seen.get(folded);+ if (clash !== undefined) {+ throw new BadRequestError({+ message:+ clash === file.path+ ? `File '${file.path}' is listed twice.`+ : `Files '${clash}' and '${file.path}' would be the same file on disk. File paths must be unique ignoring case.`+ });+ }+ seen.set(folded, file.path);+ const segments = file.path.split("/");+ segments.slice(0, -1).forEach((_, i) => {+ const folder = segments.slice(0, i + 1).join("/");+ if (!folders.has(fold(folder))) folders.set(fold(folder), file.path);+ });++ const content = decodeContent(file);+ if (content.length > AGENT_VAULT_SKILL_MAX_FILE_BYTES) {+ throw new BadRequestError({+ message: `File '${file.path}' is larger than ${AGENT_VAULT_SKILL_MAX_FILE_BYTES / 1024} KB.`+ });+ }+ sizeBytes += content.length;+ if (sizeBytes > AGENT_VAULT_SKILL_MAX_TOTAL_BYTES) {+ throw new BadRequestError({+ message: `The skill's files add up to more than ${AGENT_VAULT_SKILL_MAX_TOTAL_BYTES / (1024 * 1024)} MB.`+ });+ }+ return { path: file.path, mode: file.mode, content };+ });++ decoded.forEach((file) => {+ const inside = folders.get(fold(file.path));+ if (inside !== undefined) {+ throw new BadRequestError({+ message: `'${file.path}' is a file, but '${inside}' puts it inside a folder of the same name. Rename one of them.`+ });+ }+ });++ const manifest = decoded.find((file) => file.path === AGENT_VAULT_SKILL_MANIFEST);+ if (!manifest) {+ throw new BadRequestError({ message: `${AGENT_VAULT_SKILL_MANIFEST} is missing.` });+ }+ const { name, description } = parseSkillHeader(manifest.content);+ // A restore rewrites this line to keep the skill's current name, so every stored version must have one it can find.+ if (!replaceSkillHeaderName(manifest.content, name)) {+ throw new BadRequestError({+ message: `Write the name as a plain line in ${AGENT_VAULT_SKILL_MANIFEST}, like 'name: ${name}'.`+ });+ }++ const canonical: TAgentVaultSkillFile[] = decoded+ // By UTF-8 bytes, the order Go sorts strings in, so the CLI's recomputed hash matches.+ .sort((a, b) => Buffer.compare(Buffer.from(a.path, "utf8"), Buffer.from(b.path, "utf8")))+ .map((file) => ({ path: file.path, mode: file.mode, contentBase64: file.content.toString("base64") }));+ const serialized = Buffer.from(JSON.stringify(canonical));++ return {+ name,+ description,+ files: canonical,+ serialized,+ sha256: sha256Hex(serialized),+ sizeBytes,+ fileCount: canonical.length+ };+};++export const deserializeSkillFiles = (serialized: Buffer) =>+ JSON.parse(serialized.toString("utf8")) as TAgentVaultSkillFile[];++export const skillSizeBucket = (sizeBytes: number) => {+ if (sizeBytes < 10 * 1024) return "lt-10kb";+ if (sizeBytes < 100 * 1024) return "10kb-100kb";+ return "100kb-1mb";+};diff --git a/backend/src/ee/services/agent-vault-skill/agent-vault-skill-service.ts b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-service.tsnew file mode 100644index 0000000000..3581990862--- /dev/null+++ b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-service.ts@@ -0,0 +1,597 @@+import { ForbiddenError } from "@casl/ability";++import { TAgentVaultSkillVersions } from "@app/db/schemas";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionAgentVaultAccessBundleActions,+ ProjectPermissionAgentVaultSkillActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { PgSqlLock } from "@app/keystore/keystore";+import { BadRequestError, ConflictError, NotFoundError } from "@app/lib/errors";+import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";++import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";+import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";+import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import { TAgentVaultSkillBundleDALFactory } from "./agent-vault-skill-bundle-dal";+import { TAgentVaultSkillDALFactory, TAgentVaultSkillSummaryRow } from "./agent-vault-skill-dal";+import {+ AGENT_VAULT_MAX_SKILLS,+ AGENT_VAULT_MAX_SKILLS_PER_BUNDLE,+ AGENT_VAULT_SKILL_MANIFEST,+ AGENT_VAULT_SKILL_VERSIONS_KEPT,+ deserializeSkillFiles,+ parseSkillHeader,+ replaceSkillHeaderName,+ validateSkillFiles+} from "./agent-vault-skill-fns";+import {+ TAgentVaultBundleSkill,+ TAgentVaultSkill,+ TAgentVaultSkillScoped,+ TAgentVaultSkillVersion,+ TAgentVaultSkillWithBundles,+ TBundleSkillDTO,+ TBundleSkillsDTO,+ TCreateSkillDTO,+ TListSkillsDTO,+ TSkillByIdDTO,+ TSkillVersionDTO,+ TUpdateSkillDTO+} from "./agent-vault-skill-types";+import { TAgentVaultSkillVersionDALFactory, TAgentVaultSkillVersionRow } from "./agent-vault-skill-version-dal";++type TAgentVaultSkillServiceFactoryDep = {+ agentVaultSkillDAL: TAgentVaultSkillDALFactory;+ agentVaultSkillVersionDAL: TAgentVaultSkillVersionDALFactory;+ agentVaultSkillBundleDAL: TAgentVaultSkillBundleDALFactory;+ agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "findByIdInProject" | "lockByIdInProject">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+};++export type TAgentVaultSkillServiceFactory = ReturnType<typeof agentVaultSkillServiceFactory>;++export const agentVaultSkillServiceFactory = ({+ agentVaultSkillDAL,+ agentVaultSkillVersionDAL,+ agentVaultSkillBundleDAL,+ agentVaultAccessBundleDAL,+ permissionService,+ membershipDAL,+ kmsService+}: TAgentVaultSkillServiceFactoryDep) => {+ const getProjectCipher = (projectId: string) =>+ kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });++ const $getPermission = async (scoped: TAgentVaultSkillScoped) =>+ (await getAgentVaultPermission({ permissionService }, scoped)).permission;++ const $authorize = async (scoped: TAgentVaultSkillScoped, action: ProjectPermissionAgentVaultSkillActions) => {+ const permission = await $getPermission(scoped);+ ForbiddenError.from(permission).throwUnlessCan(action, ProjectPermissionSub.AgentVaultSkills);+ };++ // A member sees only the skills on bundles they can reach, so accessBundleIds is null for an admin and the+ // reachable bundles otherwise.+ const $authorizeRead = async (scoped: TAgentVaultSkillScoped) => {+ const { permission, accessBundleIds } = await getAgentVaultReachability(+ { permissionService, membershipDAL },+ scoped+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultSkillActions.Read,+ ProjectPermissionSub.AgentVaultSkills+ );+ return accessBundleIds;+ };++ // Adding a skill changes what a bundle hands out, so it is a bundle edit, and the skill has to be one the caller can see.+ const $authorizeBundleLink = async (scoped: TAgentVaultSkillScoped) => {+ const permission = await $getPermission(scoped);+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultSkillActions.Read,+ ProjectPermissionSub.AgentVaultSkills+ );+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionAgentVaultAccessBundleActions.Edit,+ ProjectPermissionSub.AgentVaultAccessBundles+ );+ };++ const projectSkill = (row: TAgentVaultSkillSummaryRow): TAgentVaultSkill => ({+ id: row.id,+ name: row.name,+ description: row.description,+ latestVersion: row.latestVersion,+ createdAt: row.createdAt,+ updatedAt: row.updatedAt+ });++ const projectVersion = (row: TAgentVaultSkillVersionRow): TAgentVaultSkillVersion => ({+ id: row.id,+ version: row.version,+ sha256: row.sha256,+ sizeBytes: row.sizeBytes,+ fileCount: row.fileCount,+ createdAt: row.createdAt+ });++ const skillNotFound = (skillId: string) => new NotFoundError({ message: `Skill with ID '${skillId}' not found` });++ const bundleNotFound = (accessBundleId: string) =>+ new NotFoundError({ message: `Access bundle with ID '${accessBundleId}' not found` });++ const duplicateNameMessage = (name: string) => `A skill named '${name}' already exists.`;++ const $findSkill = async ({ skillId, projectId }: { skillId: string; projectId: string }) => {+ const skill = await agentVaultSkillDAL.findSummaryByIdInProject({ id: skillId, projectId });+ if (!skill) throw skillNotFound(skillId);+ return skill;+ };++ const createSkill = async ({ files, ...scoped }: TCreateSkillDTO) => {+ await $authorize(scoped, ProjectPermissionAgentVaultSkillActions.Create);++ const validated = validateSkillFiles(files);+ const { encryptor } = await getProjectCipher(scoped.projectId);+ const encryptedFiles = encryptor({ plainText: validated.serialized }).cipherTextBlob;++ // Serialised per project so the count is authoritative. The unique index backs the name check.+ const write = () =>+ agentVaultSkillDAL.transaction(async (tx) => {+ // eslint-disable-next-line @typescript-eslint/no-unsafe-call+ await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.CreateAgentVaultSkill(scoped.projectId)]);++ const existing = await agentVaultSkillDAL.findByNameInProject(+ { name: validated.name, projectId: scoped.projectId },+ tx+ );+ if (existing) throw new ConflictError({ message: duplicateNameMessage(validated.name) });++ const skillCount = await agentVaultSkillDAL.countInProject(scoped.projectId, tx);+ if (skillCount >= AGENT_VAULT_MAX_SKILLS) {+ throw new BadRequestError({+ message: `This organization already has ${AGENT_VAULT_MAX_SKILLS} skills, the most allowed. Delete an unused one first.`+ });+ }++ const skill = await agentVaultSkillDAL.create(+ { projectId: scoped.projectId, name: validated.name, description: validated.description },+ tx+ );+ const version = await agentVaultSkillVersionDAL.create(+ {+ skillId: skill.id,+ version: 1,+ encryptedFiles,+ sha256: validated.sha256,+ sizeBytes: validated.sizeBytes,+ fileCount: validated.fileCount+ },+ tx+ );+ return { skill, version };+ });++ let result;+ try {+ result = await write();+ } catch (err) {+ if (isUniqueViolation(err)) throw new ConflictError({ message: duplicateNameMessage(validated.name) });+ throw err;+ }++ return {+ skill: projectSkill({ ...result.skill, latestVersion: result.version.version }),+ version: projectVersion(result.version)+ };+ };++ // The skill row lock serialises publishes and restores per skill, so two can't take the same number and the+ // unchanged check is authoritative. A skill deleted while this waited is gone once the lock is granted, so the+ // caller gets a 404. The name is read under the lock too, so previousName is the name this write replaced, and a+ // restore, which must never rename, can tell that a publish renamed the skill after it read the name.+ const $writeVersion = async ({+ skillId,+ projectId,+ allowRename,+ baseVersion,+ content+ }: {+ skillId: string;+ projectId: string;+ allowRename: boolean;+ baseVersion?: number;+ content: Pick<TAgentVaultSkillVersions, "encryptedFiles" | "sha256" | "sizeBytes" | "fileCount"> & {+ name: string;+ description: string;+ };+ }) => {+ const write = () =>+ agentVaultSkillDAL.transaction(async (tx) => {+ const current = await agentVaultSkillDAL.lockByIdInProject({ id: skillId, projectId }, tx);+ if (!current) throw skillNotFound(skillId);++ const latest = await agentVaultSkillVersionDAL.findLatest(skillId, tx);+ if (latest?.sha256 === content.sha256) {+ const skill = await agentVaultSkillDAL.findSummaryByIdInProject({ id: skillId, projectId }, tx);+ return { skill: skill!, version: latest, unchanged: true, previousName: undefined };+ }++ const latestVersion = latest?.version ?? 0;+ if (baseVersion !== undefined && latestVersion !== baseVersion) {+ throw new ConflictError({+ message: `Version ${latestVersion} was published after you opened this skill. Review it, then save again.`+ });+ }++ const renamed = current.name !== content.name;+ if (renamed && !allowRename) {+ throw new ConflictError({+ message: `Skill '${content.name}' was renamed to '${current.name}' while this version was being restored. Try again.`+ });+ }+ if (renamed) {+ const taken = await agentVaultSkillDAL.findByNameInProject({ name: content.name, projectId }, tx);+ if (taken) throw new ConflictError({ message: duplicateNameMessage(content.name) });+ }++ const next = latestVersion + 1;+ const version = await agentVaultSkillVersionDAL.create(+ {+ skillId,+ version: next,+ encryptedFiles: content.encryptedFiles,+ sha256: content.sha256,+ sizeBytes: content.sizeBytes,+ fileCount: content.fileCount+ },+ tx+ );+ await agentVaultSkillDAL.updateById(+ skillId,+ renamed ? { name: content.name, description: content.description } : { description: content.description },+ tx+ );+ await agentVaultSkillVersionDAL.deleteOlderThan(+ { skillId, version: next - AGENT_VAULT_SKILL_VERSIONS_KEPT + 1 },+ tx+ );+ const skill = await agentVaultSkillDAL.findSummaryByIdInProject({ id: skillId, projectId }, tx);+ return { skill: skill!, version, unchanged: false, previousName: renamed ? current.name : undefined };+ });++ try {+ return await write();+ } catch (err) {+ if (isUniqueViolation(err)) throw new ConflictError({ message: duplicateNameMessage(content.name) });+ throw err;+ }+ };++ const updateSkill = async ({ skillId, files, baseVersion, ...scoped }: TUpdateSkillDTO) => {+ await $authorize(scoped, ProjectPermissionAgentVaultSkillActions.Edit);++ const skill = await $findSkill({ skillId, projectId: scoped.projectId });+ const validated = validateSkillFiles(files);++ // Checked again under the lock. This read only spares an unchanged upload the encrypt.+ const latest = await agentVaultSkillVersionDAL.findLatest(skill.id);+ if (latest?.sha256 === validated.sha256) {+ return { skill: projectSkill(skill), version: projectVersion(latest), unchanged: true };+ }++ const { encryptor } = await getProjectCipher(scoped.projectId);+ const encryptedFiles = encryptor({ plainText: validated.serialized }).cipherTextBlob;++ const written = await $writeVersion({+ skillId: skill.id,+ projectId: scoped.projectId,+ allowRename: true,+ baseVersion,+ content: {+ encryptedFiles,+ sha256: validated.sha256,+ sizeBytes: validated.sizeBytes,+ fileCount: validated.fileCount,+ name: validated.name,+ description: validated.description+ }+ });++ return {+ skill: projectSkill(written.skill),+ version: projectVersion(written.version),+ unchanged: written.unchanged,+ previousName: written.previousName+ };+ };++ const $findVersion = async ({ skill, version }: { skill: TAgentVaultSkillSummaryRow; version: number }) => {+ const row = await agentVaultSkillVersionDAL.findByVersion({ skillId: skill.id, version });+ if (!row) throw new NotFoundError({ message: `Version ${version} of skill '${skill.name}' not found` });+ return row;+ };++ const restoreVersion = async ({ skillId, version, ...scoped }: TSkillVersionDTO) => {+ await $authorize(scoped, ProjectPermissionAgentVaultSkillActions.Edit);++ const skill = await $findSkill({ skillId, projectId: scoped.projectId });+ const source = await $findVersion({ skill, version });++ // Checked again under the lock. This read only spares restoring the latest content the decrypt.+ const latest = await agentVaultSkillVersionDAL.findLatest(skill.id);+ if (latest?.sha256 === source.sha256) {+ return {+ skill: projectSkill(skill),+ version: projectVersion(latest),+ fromVersion: source.version,+ unchanged: true+ };+ }++ // The description lives on the skill, not the version, so it is read back out of the restored SKILL.md. A+ // version saved under older header rules may no longer parse, and that must not block restoring it.+ const { decryptor, encryptor } = await getProjectCipher(scoped.projectId);+ const files = deserializeSkillFiles(decryptor({ cipherTextBlob: source.encryptedFiles }));+ const manifest = files.find((file) => file.path === AGENT_VAULT_SKILL_MANIFEST);+ let header: { name: string; description: string } | undefined;+ if (manifest) {+ try {+ header = parseSkillHeader(Buffer.from(manifest.contentBase64, "base64"));+ } catch {+ header = undefined;+ }+ }++ let content: Parameters<typeof $writeVersion>[0]["content"] = {+ encryptedFiles: source.encryptedFiles,+ sha256: source.sha256,+ sizeBytes: source.sizeBytes,+ fileCount: source.fileCount,+ name: skill.name,+ description: header?.description ?? skill.description+ };++ // A restore never renames: a version saved under an earlier name gets the current name written into its+ // SKILL.md, so the files an agent installs agree with the skill they came from.+ if (manifest && header && header.name !== skill.name) {+ const rewritten = replaceSkillHeaderName(Buffer.from(manifest.contentBase64, "base64"), skill.name);+ if (!rewritten) {+ throw new BadRequestError({+ message: `Version ${source.version} of skill '${skill.name}' names '${header.name}' in ${AGENT_VAULT_SKILL_MANIFEST}, and its 'name' line could not be changed to '${skill.name}'. Publish a new version instead.`+ });+ }+ const validated = validateSkillFiles(+ files.map((file) => (file === manifest ? { ...file, contentBase64: rewritten.toString("base64") } : file))+ );+ if (validated.name !== skill.name) {+ throw new BadRequestError({+ message: `Version ${source.version} of skill '${skill.name}' could not be restored under its current name. Publish a new version instead.`+ });+ }+ content = {+ encryptedFiles: encryptor({ plainText: validated.serialized }).cipherTextBlob,+ sha256: validated.sha256,+ sizeBytes: validated.sizeBytes,+ fileCount: validated.fileCount,+ name: skill.name,+ description: validated.description+ };+ }++ const written = await $writeVersion({+ skillId: skill.id,+ projectId: scoped.projectId,+ allowRename: false,+ content+ });++ return {+ skill: projectSkill(written.skill),+ version: projectVersion(written.version),+ fromVersion: source.version,+ unchanged: written.unchanged+ };+ };++ const listSkills = async ({ search, name, limit, offset, ...scoped }: TListSkillsDTO) => {+ const accessBundleIds = await $authorizeRead(scoped);++ const { skills, totalCount } = await agentVaultSkillDAL.findForList({+ projectId: scoped.projectId,+ accessBundleIds,+ search,+ name,+ limit,+ offset+ });+ const bundlesBySkill = await agentVaultSkillBundleDAL.findBundlesForSkills(+ skills.map((skill) => skill.id),+ accessBundleIds+ );+ return {+ skills: skills.map((skill): TAgentVaultSkillWithBundles => ({+ ...projectSkill(skill),+ accessBundles: bundlesBySkill.get(skill.id) ?? []+ })),+ totalCount+ };+ };++ // A skill on no bundle the member can reach is a 404, never a 403, which would confirm the id exists.+ const getSkill = async ({ skillId, ...scoped }: TSkillByIdDTO) => {+ const accessBundleIds = await $authorizeRead(scoped);++ const skill = await $findSkill({ skillId, projectId: scoped.projectId });+ const accessBundles = await agentVaultSkillBundleDAL.findBundlesForSkill(skill.id, accessBundleIds);+ if (accessBundleIds && !accessBundles.length) throw skillNotFound(skillId);+ const latest = await $findVersion({ skill, version: skill.latestVersion });++ const { decryptor } = await getProjectCipher(scoped.projectId);+ const files = deserializeSkillFiles(decryptor({ cipherTextBlob: latest.encryptedFiles }));+ return { skill: { ...projectSkill(skill), accessBundles, files }, version: latest.version };+ };++ // Version history is for the people who can publish and restore, so it checks Edit rather than Read.+ const listVersions = async ({ skillId, ...scoped }: TSkillByIdDTO) => {+ await $authorize(scoped, ProjectPermissionAgentVaultSkillActions.Edit);++ const skill = await $findSkill({ skillId, projectId: scoped.projectId });+ const versions = await agentVaultSkillVersionDAL.findBySkillId(skill.id);+ return { versions: versions.map(projectVersion) };+ };++ // A member reads only the latest version of a skill they can reach; anything else is a 404, as for a skill or+ // version that does not exist.+ const getVersionFiles = async ({ skillId, version, ...scoped }: TSkillVersionDTO) => {+ const accessBundleIds = await $authorizeRead(scoped);++ const skill = await $findSkill({ skillId, projectId: scoped.projectId });+ if (accessBundleIds) {+ if (!(await agentVaultSkillBundleDAL.isSkillReachable(skill.id, accessBundleIds))) throw skillNotFound(skillId);+ if (version !== skill.latestVersion) {+ throw new NotFoundError({ message: `Version ${version} of skill '${skill.name}' not found` });+ }+ }+ const row = await $findVersion({ skill, version });++ const { decryptor } = await getProjectCipher(scoped.projectId);+ const files = deserializeSkillFiles(decryptor({ cipherTextBlob: row.encryptedFiles }));+ return { skill: projectSkill(skill), version: { ...projectVersion(row), files } };+ };++ // The bundle links go with the skill through the foreign key; their names are returned for the audit event.+ const deleteSkill = async ({ skillId, ...scoped }: TSkillByIdDTO) => {+ await $authorize(scoped, ProjectPermissionAgentVaultSkillActions.Delete);++ return agentVaultSkillDAL.transaction(async (tx) => {+ const locked = await agentVaultSkillDAL.lockByIdInProject({ id: skillId, projectId: scoped.projectId }, tx);+ if (!locked) throw skillNotFound(skillId);++ const skill = await agentVaultSkillDAL.findSummaryByIdInProject(+ { id: locked.id, projectId: scoped.projectId },+ tx+ );+ const accessBundles = await agentVaultSkillBundleDAL.findBundlesForSkill(locked.id, null, tx);+ await agentVaultSkillDAL.deleteById(locked.id, tx);++ return { skill: projectSkill(skill!), removedFromBundles: accessBundles };+ });+ };++ const toBundleSkill = (+ skill: { id: string; name: string; description: string },+ latest: TAgentVaultSkillVersionRow | undefined+ ): TAgentVaultBundleSkill => ({+ id: skill.id,+ name: skill.name,+ description: skill.description,+ latestVersion: latest?.version ?? 0+ });++ // A bundle the caller cannot reach is a 404, as in the access bundle service.+ const listBundleSkills = async ({ accessBundleId, ...scoped }: TBundleSkillsDTO) => {+ const accessBundleIds = await $authorizeRead(scoped);++ const bundle = await agentVaultAccessBundleDAL.findByIdInProject({+ id: accessBundleId,+ projectId: scoped.projectId+ });+ // Postgres compares uuids case-insensitively but this list does not, so an uppercase id would miss.+ if (!bundle || (accessBundleIds && !accessBundleIds.includes(accessBundleId.toLowerCase()))) {+ throw bundleNotFound(accessBundleId);+ }++ return { skills: await agentVaultSkillBundleDAL.findSkillsForBundle(bundle.id) };+ };++ // The bundle is locked first, as every other bundle write does, then the skill, so a skill delete can't run+ // between the check and the insert.+ const addToBundle = async ({ accessBundleId, skillId, ...scoped }: TBundleSkillDTO) => {+ await $authorizeBundleLink(scoped);++ const add = () =>+ agentVaultSkillDAL.transaction(async (tx) => {+ const bundle = await agentVaultAccessBundleDAL.lockByIdInProject(+ { id: accessBundleId, projectId: scoped.projectId },+ tx+ );+ if (!bundle) throw bundleNotFound(accessBundleId);++ const skill = await agentVaultSkillDAL.lockByIdInProject({ id: skillId, projectId: scoped.projectId }, tx);+ if (!skill) throw skillNotFound(skillId);++ const existing = await agentVaultSkillBundleDAL.findOne({ accessBundleId: bundle.id, skillId: skill.id }, tx);+ if (existing) {+ throw new ConflictError({+ message: `The skill '${skill.name}' is already in the access bundle '${bundle.name}'.`+ });+ }++ const bundleSkillCount = await agentVaultSkillBundleDAL.countForBundle(bundle.id, tx);+ if (bundleSkillCount >= AGENT_VAULT_MAX_SKILLS_PER_BUNDLE) {+ throw new BadRequestError({+ message: `This access bundle already has ${AGENT_VAULT_MAX_SKILLS_PER_BUNDLE} skills, the maximum. Remove one to add another.`+ });+ }++ await agentVaultSkillBundleDAL.create({ accessBundleId: bundle.id, skillId: skill.id }, tx);+ const latest = await agentVaultSkillVersionDAL.findLatest(skill.id, tx);+ return { skill: toBundleSkill(skill, latest), accessBundle: { id: bundle.id, name: bundle.name } };+ });++ try {+ return await add();+ } catch (err) {+ if (isUniqueViolation(err)) {+ throw new ConflictError({ message: "This skill is already in this access bundle." });+ }+ throw err;+ }+ };++ const removeFromBundle = async ({ accessBundleId, skillId, ...scoped }: TBundleSkillDTO) => {+ await $authorizeBundleLink(scoped);++ return agentVaultSkillDAL.transaction(async (tx) => {+ const bundle = await agentVaultAccessBundleDAL.lockByIdInProject(+ { id: accessBundleId, projectId: scoped.projectId },+ tx+ );+ if (!bundle) throw bundleNotFound(accessBundleId);++ const skill = await agentVaultSkillDAL.findOne({ id: skillId, projectId: scoped.projectId }, tx);+ if (!skill) throw skillNotFound(skillId);++ const [removed] = await agentVaultSkillBundleDAL.delete({ accessBundleId: bundle.id, skillId: skill.id }, tx);+ if (!removed) {+ throw new NotFoundError({+ message: `The skill '${skill.name}' isn't in the access bundle '${bundle.name}'.`+ });+ }++ const latest = await agentVaultSkillVersionDAL.findLatest(skill.id, tx);+ return { skill: toBundleSkill(skill, latest), accessBundle: { id: bundle.id, name: bundle.name } };+ });+ };++ return {+ createSkill,+ updateSkill,+ restoreVersion,+ listSkills,+ getSkill,+ listVersions,+ getVersionFiles,+ deleteSkill,+ listBundleSkills,+ addToBundle,+ removeFromBundle+ };+};diff --git a/backend/src/ee/services/agent-vault-skill/agent-vault-skill-types.ts b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-types.tsnew file mode 100644index 0000000000..6af14cd9a0--- /dev/null+++ b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-types.ts@@ -0,0 +1,53 @@+import { TGenericPermission } from "@app/lib/types";++export enum AgentVaultSkillFileMode {+ Regular = "0644",+ Executable = "0755"+}++export type TAgentVaultSkillFile = { path: string; mode: AgentVaultSkillFileMode; contentBase64: string };++export type TAgentVaultSkillScoped = { projectId: string; ctx: TGenericPermission };++export type TCreateSkillDTO = TAgentVaultSkillScoped & { files: TAgentVaultSkillFile[] };++export type TListSkillsDTO = TAgentVaultSkillScoped & {+ search?: string;+ name?: string;+ limit: number;+ offset: number;+};++export type TSkillByIdDTO = TAgentVaultSkillScoped & { skillId: string };++export type TUpdateSkillDTO = TSkillByIdDTO & { files: TAgentVaultSkillFile[]; baseVersion?: number };++export type TSkillVersionDTO = TSkillByIdDTO & { version: number };++export type TBundleSkillsDTO = TAgentVaultSkillScoped & { accessBundleId: string };++export type TBundleSkillDTO = TBundleSkillsDTO & { skillId: string };++export type TAgentVaultSkill = {+ id: string;+ name: string;+ description: string;+ latestVersion: number;+ createdAt: Date;+ updatedAt: Date;+};++export type TAgentVaultSkillBundleRef = { id: string; name: string };++export type TAgentVaultSkillWithBundles = TAgentVaultSkill & { accessBundles: TAgentVaultSkillBundleRef[] };++export type TAgentVaultSkillVersion = {+ id: string;+ version: number;+ sha256: string;+ sizeBytes: number;+ fileCount: number;+ createdAt: Date;+};++export type TAgentVaultBundleSkill = { id: string; name: string; description: string; latestVersion: number };diff --git a/backend/src/ee/services/agent-vault-skill/agent-vault-skill-version-dal.ts b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-version-dal.tsnew file mode 100644index 0000000000..507d555418--- /dev/null+++ b/backend/src/ee/services/agent-vault-skill/agent-vault-skill-version-dal.ts@@ -0,0 +1,61 @@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { TableName, TAgentVaultSkillVersions } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify } from "@app/lib/knex";++export type TAgentVaultSkillVersionDALFactory = ReturnType<typeof agentVaultSkillVersionDALFactory>;++export type TAgentVaultSkillVersionRow = Omit<TAgentVaultSkillVersions, "encryptedFiles">;++const VERSION_COLUMNS = ["id", "skillId", "version", "sha256", "sizeBytes", "fileCount", "createdAt"] as const;++export const agentVaultSkillVersionDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultSkillVersion);++ // Reads the primary even without a tx: publish compares against it to skip an unchanged upload, and a replica+ // behind the last publish would write a duplicate.+ const findLatest = async (skillId: string, tx?: Knex): Promise<TAgentVaultSkillVersionRow | undefined> => {+ try {+ return (await (tx || db)(TableName.AgentVaultSkillVersion)+ .where({ skillId })+ .orderBy("version", "desc")+ .first(VERSION_COLUMNS)) as TAgentVaultSkillVersionRow | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find latest agent vault skill version" });+ }+ };++ const findBySkillId = async (skillId: string, tx?: Knex): Promise<TAgentVaultSkillVersionRow[]> => {+ try {+ return (await (tx || db)(TableName.AgentVaultSkillVersion)+ .where({ skillId })+ .orderBy("version", "desc")+ .select(VERSION_COLUMNS)) as TAgentVaultSkillVersionRow[];+ } catch (error) {+ throw new DatabaseError({ error, name: "List agent vault skill versions" });+ }+ };++ const findByVersion = async (+ { skillId, version }: { skillId: string; version: number },+ tx?: Knex+ ): Promise<TAgentVaultSkillVersions | undefined> => {+ try {+ return await (tx || db)(TableName.AgentVaultSkillVersion).where({ skillId, version }).first();+ } catch (error) {+ throw new DatabaseError({ error, name: "Find agent vault skill version" });+ }+ };++ const deleteOlderThan = async ({ skillId, version }: { skillId: string; version: number }, tx: Knex) => {+ try {+ return await tx(TableName.AgentVaultSkillVersion).where({ skillId }).where("version", "<", version).delete();+ } catch (error) {+ throw new DatabaseError({ error, name: "Prune agent vault skill versions" });+ }+ };++ return { ...orm, findLatest, findBySkillId, findByVersion, deleteOlderThan };+};diff --git a/backend/src/ee/services/agent-vault/AGENTS.md b/backend/src/ee/services/agent-vault/AGENTS.mdindex cf14cedb83..5721d03150 100644--- a/backend/src/ee/services/agent-vault/AGENTS.md+++ b/backend/src/ee/services/agent-vault/AGENTS.md@@ -21,9 +21,10 @@ agent-vault-access-bundle/ bundles, services, credential encryption, grantsagent-vault-variable/ global and personal variables and the reads behind Used Byagent-vault-member/ product membership (list, add, role, remove)agent-vault-personal-value/ each actor's own values for the fields a service leaves to members+agent-vault-skill/ the skill library, versions, bundle links, file validation and hashingagent-vault-session/ mint, revoke, list, get, edit labelagent-vault-project/ the per-org project's lazy bootstrap and resolver-agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolve, credential refresh+agent-vault-proxy/ create/rotate (proxy token + CA), bootstrap, heartbeat, resolve, credential refresh, session skillsagent-vault-oauth/ OAuth for MCP services: discovery, client registration, authorizations, refreshagent-vault-session-log/ storage settings, chunk ingest, playback```@@ -119,6 +120,7 @@ and `packages/agentvault/` in the CLI repo. Frontend: `frontend/src/pages/agent-is enforced against the clock on every resolve; there is no expiry audit event, matching every other product.- **Sessions are never deleted**, so the Sessions page is a full history and a session's row keeps the key itslogs need. Settled with the product owner.+- Anyone with a session token can download its skills from Infisical with only the token (`GET /session/skills`).## Proxies@@ -326,6 +328,62 @@ reference.The sidebar asks for `requiresSetup=true&granted=true` and reads the count, so an admin isn't nagged in the navabout bundles they reach only by role, while the page's banner and badges still show them.+## Skills++A skill is an Agent Skills folder (`SKILL.md` plus files) kept per project and added to bundles. When an agent+starts, the CLI fetches the session's skills from Infisical once, with the session token, and installs them in the user's home+(`~/.agents/skills/<name>`, linked for Claude Code and Hermes, or `--skills-dir`), where they stay after the run.+There are no live updates: a running agent keeps what it got until it restarts, and nothing on the server removes+an installed copy.++- **Files change through `PATCH /skills/:skillId`** (`updateSkill`), which saves them as a new version; there is no+ `POST /skills/:skillId/versions`. The version routes are only list, get one, and restore.+- **The name comes from the latest version's `SKILL.md`.** An update whose `SKILL.md` names something else renames+ the skill in the same transaction (409 if the name is taken) and writes an `agent-vault-skill-rename` audit event+ beside the version event. A restore never renames: if the old `SKILL.md` names something else, only the value on+ its top-level `name:` line is rewritten to the current name (`replaceSkillHeaderName`) and the files are+ re-validated, re-hashed and re-sealed, so the stored `SKILL.md` always agrees with the skill row. A restore that+ meets a rename made after it read the name is a 409, not a rename back. The description is the latest version's,+ stored on the skill row; a restore re-reads it from the files and keeps the current one if that old `SKILL.md` no+ longer parses.+- **The server is the authority** on validation (`agent-vault-skill-fns.ts`): the limits, the paths and the YAML+ header. The upload body limit is 2 MB and the schema caps content only at that, so an oversize file in a request+ of up to about 1.5 MB of file content (base64 adds a third) gets the 400 that names it; a larger request gets+ "Request body is too large". The header is parsed with `JSON_SCHEMA` (no custom types; aliases are harmless under it and the 4 KB cap).+- **Paths must install on every OS:** relative, at most 255 characters with no part over 255 UTF-8 bytes, no+ `.`/`..`/empty parts, no backslash, control character, lone surrogate or `: < > " | ? *`, no part ending in a dot+ or space, no Windows device name (`CON`, `COM1`, `nul.txt`...), and no path that is also a folder of another.+ Duplicates compare by NFC plus lowercase.+- **A version's `sha256` is over the canonical JSON** (files sorted by UTF-8 path bytes, which is Go's string+ order, `{ path, mode, contentBase64 }`, content re-encoded). The CLI recomputes it from the files and refuses a+ mismatch, so the serialization is a contract with the CLI.+- Files are one sealed blob per version (project `SecretManager` key), encrypted before the transaction. Update+ and restore lock the skill row, so version numbers are unique, the unchanged check is authoritative, and an+ update racing a delete gets a 404. An update may send `baseVersion`, the version its edits started from; if the+ latest version under the lock is a different one, it is a 409 so a stale editor can't silently overwrite a newer+ version (an unchanged update still answers `unchanged: true`). Restore takes no base. The newest 20 versions+ are kept. An update or a restore whose files match the+ latest version writes nothing and answers `unchanged: true` with that version, and records no audit or PostHog event.+- Reading one version's files (`GET /skills/:skillId/versions/:version`) writes an `agent-vault-skill-version-view`+ audit event (data-access class). So does `GET /skills/:skillId`, which returns the latest version's files with the+ skill (for that version); the list routes return no files and write none.+- **`GET /session/skills`** returns the latest files of every skill on the session's reachable bundles (the same+ intersection as the services), sorted by name, read from the primary. The proxy is not involved: the CLI calls it+ with `Authorization: Bearer agv_...` and no other credential, so `inject-identity` skips the path and the route+ parses the header itself. Any refusal is a 401, an unknown token included. It shares the owner checks of resolve+ and credential refresh (`$authorizeSessionOwner`), with the org taken from the session's project instead of a+ proxy. A call that returns at least one skill writes one `agent-vault-skills-delivered` audit event+ (data-access class) listing every skill delivered (id, name, version, sha256), with the session's owner as the+ actor (a user named as they are now, or from the session's snapshot if they are gone) and the session's access+ bundle (sessions carry one today), plus one anonymous `Agent Vault Skills Delivered` PostHog event with the+ count. A call with no skills records neither. Nothing caches; the route uses `readLimit`.+- Skills use the `agent-vault-skills` CASL subject. Members keep CASL `Read`, narrowed by reachability+ (`getAgentVaultReachability`): they see only skills in a bundle they can reach, each with only those+ bundles, and only the latest version's files. Anything else, an unreachable bundle's skill list included, is a 404.+ Listing versions checks `Edit`, so it is admin only. Creating, updating, restoring and deleting are admin only. Adding a skill to a bundle or removing it needs `Edit` on access bundles and `Read` on skills, and a+ bundle holds at most 25 skills (`AGENT_VAULT_MAX_SKILLS_PER_BUNDLE`, checked under the bundle lock). Agent Vault+ holds at most 250 skills (`AGENT_VAULT_MAX_SKILLS`, checked under a per-project advisory lock on create).+## Credentials at rest- The KMS cipher pair is project-scoped (`KmsDataKey.SecretManager`) and built once per resolve.diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.test.tsindex 6ad57fba62..9135d53b9d 100644--- a/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.test.ts@@ -43,6 +43,8 @@ describe("audit log event classes", () => {[EventType.PKI_SIGNER_SIGN, AuditLogEventClass.DataAccess],[EventType.DASHBOARD_LIST_SECRETS, AuditLogEventClass.DataAccess],[EventType.VIEW_INSIGHTS_AUTH_METHODS, AuditLogEventClass.DataAccess],+ [EventType.AGENT_VAULT_SKILLS_DELIVERED, AuditLogEventClass.DataAccess],+ [EventType.AGENT_VAULT_SKILL_VERSION_VIEW, AuditLogEventClass.DataAccess],[EventType.UPDATE_SECRET, AuditLogEventClass.Management],[EventType.CREATE_CMEK, AuditLogEventClass.Management],[EventType.VIEW_AUDIT_LOGS, AuditLogEventClass.Management],diff --git a/backend/src/ee/services/audit-log/audit-log-event-classes.ts b/backend/src/ee/services/audit-log/audit-log-event-classes.tsindex 0df31a673d..30de33ca8f 100644--- a/backend/src/ee/services/audit-log/audit-log-event-classes.ts+++ b/backend/src/ee/services/audit-log/audit-log-event-classes.ts@@ -237,6 +237,8 @@ const DATA_ACCESS_EVENT_TYPES: readonly EventType[] = [EventType.VIEW_INSIGHTS_PAM_ROTATION_CALENDAR,EventType.PAM_SESSION_CREDENTIALS_GET,EventType.PAM_ACCOUNT_CREDENTIALS_VIEW,+ EventType.AGENT_VAULT_SKILLS_DELIVERED,+ EventType.AGENT_VAULT_SKILL_VERSION_VIEW,EventType.APPROVAL_POLICY_LIST,EventType.APPROVAL_POLICY_GET,EventType.APPROVAL_REQUEST_GET,diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 5b7389729c..a4cb5c3750 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -828,6 +828,15 @@ export enum EventType {AGENT_VAULT_VARIABLE_VALUE_VIEW = "agent-vault-variable-value-view",AGENT_VAULT_PERSONAL_VALUES_SET = "agent-vault-personal-values-set",AGENT_VAULT_PERSONAL_VALUES_DELETE = "agent-vault-personal-values-delete",+ AGENT_VAULT_SKILL_CREATE = "agent-vault-skill-create",+ AGENT_VAULT_SKILL_VERSION_CREATE = "agent-vault-skill-version-create",+ AGENT_VAULT_SKILL_RENAME = "agent-vault-skill-rename",+ AGENT_VAULT_SKILL_VERSION_RESTORE = "agent-vault-skill-version-restore",+ AGENT_VAULT_SKILL_VERSION_VIEW = "agent-vault-skill-version-view",+ AGENT_VAULT_SKILL_DELETE = "agent-vault-skill-delete",+ AGENT_VAULT_ACCESS_BUNDLE_SKILL_ADD = "agent-vault-access-bundle-skill-add",+ AGENT_VAULT_ACCESS_BUNDLE_SKILL_REMOVE = "agent-vault-access-bundle-skill-remove",+ AGENT_VAULT_SKILLS_DELIVERED = "agent-vault-skills-delivered",AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",@@ -6729,6 +6738,96 @@ interface AgentVaultPersonalValuesDeleteEvent {};}+interface AgentVaultSkillCreateEvent {+ type: EventType.AGENT_VAULT_SKILL_CREATE;+ metadata: {+ skillId: string;+ skillName: string;+ version: number;+ sha256: string;+ };+}++interface AgentVaultSkillVersionCreateEvent {+ type: EventType.AGENT_VAULT_SKILL_VERSION_CREATE;+ metadata: {+ skillId: string;+ skillName: string;+ version: number;+ sha256: string;+ };+}++interface AgentVaultSkillRenameEvent {+ type: EventType.AGENT_VAULT_SKILL_RENAME;+ metadata: {+ skillId: string;+ oldName: string;+ newName: string;+ };+}++interface AgentVaultSkillVersionRestoreEvent {+ type: EventType.AGENT_VAULT_SKILL_VERSION_RESTORE;+ metadata: {+ skillId: string;+ skillName: string;+ version: number;+ restoredFromVersion: number;+ sha256: string;+ };+}++interface AgentVaultSkillVersionViewEvent {+ type: EventType.AGENT_VAULT_SKILL_VERSION_VIEW;+ metadata: {+ skillId: string;+ skillName: string;+ version: number;+ };+}++interface AgentVaultSkillDeleteEvent {+ type: EventType.AGENT_VAULT_SKILL_DELETE;+ metadata: {+ skillId: string;+ skillName: string;+ // The access bundles the skill was in when it was deleted.+ removedFromBundles: { id: string; name: string }[];+ };+}++interface AgentVaultAccessBundleSkillAddEvent {+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_ADD;+ metadata: {+ skillId: string;+ skillName: string;+ accessBundleId: string;+ accessBundleName: string;+ };+}++interface AgentVaultAccessBundleSkillRemoveEvent {+ type: EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_REMOVE;+ metadata: {+ skillId: string;+ skillName: string;+ accessBundleId: string;+ accessBundleName: string;+ };+}++// Recorded once per fetch when the CLI gets a session's skills at agent start, not when the agent reads them.+interface AgentVaultSkillsDeliveredEvent {+ type: EventType.AGENT_VAULT_SKILLS_DELIVERED;+ metadata: {+ sessionId: string;+ accessBundleId: string;+ accessBundleName: string;+ skills: { skillId: string; skillName: string; version: number; sha256: string }[];+ };+}+interface AgentVaultProductMemberAddEvent {type: EventType.AGENT_VAULT_MEMBER_ADD;metadata: {@@ -8825,6 +8924,15 @@ export type Event =| AgentVaultVariableValueViewEvent| AgentVaultPersonalValuesSetEvent| AgentVaultPersonalValuesDeleteEvent+ | AgentVaultSkillCreateEvent+ | AgentVaultSkillVersionCreateEvent+ | AgentVaultSkillVersionRestoreEvent+ | AgentVaultSkillVersionViewEvent+ | AgentVaultSkillRenameEvent+ | AgentVaultSkillDeleteEvent+ | AgentVaultAccessBundleSkillAddEvent+ | AgentVaultAccessBundleSkillRemoveEvent+ | AgentVaultSkillsDeliveredEvent| AgentVaultProductMemberAddEvent| AgentVaultProductMemberUpdateEvent| AgentVaultProductMemberRemoveEventdiff --git a/backend/src/ee/services/permission/agent-vault-project-roles.test.ts b/backend/src/ee/services/permission/agent-vault-project-roles.test.tsindex 0bfb6dffa6..4a5bdf335b 100644--- a/backend/src/ee/services/permission/agent-vault-project-roles.test.ts+++ b/backend/src/ee/services/permission/agent-vault-project-roles.test.ts@@ -19,6 +19,7 @@ import {ProjectPermissionAgentVaultAccessBundleActions,ProjectPermissionAgentVaultProxyActions,ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionAgentVaultSkillActions,ProjectPermissionCmekActions,ProjectPermissionGroupActions,ProjectPermissionIdentityActions,@@ -50,13 +51,15 @@ describe("agent vault project roles", () => {true);expect(admin.can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project)).toBe(true);+ expect(admin.can(ProjectPermissionAgentVaultSkillActions.Create, ProjectPermissionSub.AgentVaultSkills)).toBe(true);+ expect(admin.can(ProjectPermissionAgentVaultSkillActions.Delete, ProjectPermissionSub.AgentVaultSkills)).toBe(true);expect(admin.can(ProjectPermissionCmekActions.Rotate, ProjectPermissionSub.Cmek)).toBe(false);expect(admin.can(ProjectPermissionSecretSyncActions.Create, ProjectPermissionSub.SecretSyncs)).toBe(false);expect(admin.can(ProjectPermissionActions.Create, ProjectPermissionSub.ServiceTokens)).toBe(false);});- test("a member can mint, label and revoke sessions and read a proxy fingerprint, and nothing more", () => {+ test("a member can mint, label and revoke sessions and read a proxy fingerprint and skills, and nothing more", () => {const member = abilityFor(ProjectMembershipRole.Member);expect(member.can(ProjectPermissionAgentVaultSessionActions.Create, ProjectPermissionSub.AgentVaultSessions)).toBe(@@ -83,6 +86,14 @@ describe("agent vault project roles", () => {)).toBe(false);expect(member.can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project)).toBe(false);+ expect(member.can(ProjectPermissionAgentVaultSkillActions.Read, ProjectPermissionSub.AgentVaultSkills)).toBe(true);+ expect(member.can(ProjectPermissionAgentVaultSkillActions.Create, ProjectPermissionSub.AgentVaultSkills)).toBe(+ false+ );+ expect(member.can(ProjectPermissionAgentVaultSkillActions.Edit, ProjectPermissionSub.AgentVaultSkills)).toBe(false);+ expect(member.can(ProjectPermissionAgentVaultSkillActions.Delete, ProjectPermissionSub.AgentVaultSkills)).toBe(+ false+ );expect(member.can(ProjectPermissionMemberActions.Read, ProjectPermissionSub.Member)).toBe(false);expect(member.can(ProjectPermissionGroupActions.Read, ProjectPermissionSub.Groups)).toBe(false);@@ -108,6 +119,8 @@ describe("agent vault project roles", () => {false);expect(custom.can(ProjectPermissionActions.Edit, ProjectPermissionSub.Project)).toBe(false);+ expect(custom.can(ProjectPermissionAgentVaultSkillActions.Read, ProjectPermissionSub.AgentVaultSkills)).toBe(true);+ expect(custom.can(ProjectPermissionAgentVaultSkillActions.Edit, ProjectPermissionSub.AgentVaultSkills)).toBe(false);});});diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.tsindex 3d96d75b1d..a4db9c57e2 100644--- a/backend/src/ee/services/permission/default-roles.ts+++ b/backend/src/ee/services/permission/default-roles.ts@@ -5,6 +5,7 @@ import {ProjectPermissionAgentVaultAccessBundleActions,ProjectPermissionAgentVaultProxyActions,ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionAgentVaultSkillActions,ProjectPermissionAppConnectionActions,ProjectPermissionApplicationActions,ProjectPermissionApprovalRequestActions,@@ -833,6 +834,16 @@ const buildAgentVaultProjectAdminPermissionRules = () => {ProjectPermissionSub.AgentVaultProxies);+ can(+ [+ ProjectPermissionAgentVaultSkillActions.Read,+ ProjectPermissionAgentVaultSkillActions.Create,+ ProjectPermissionAgentVaultSkillActions.Edit,+ ProjectPermissionAgentVaultSkillActions.Delete+ ],+ ProjectPermissionSub.AgentVaultSkills+ );+can([ProjectPermissionAppConnectionActions.Read,@@ -924,6 +935,7 @@ const buildAgentVaultProjectMemberPermissionRules = () => {ProjectPermissionSub.AgentVaultSessions);can([ProjectPermissionAgentVaultProxyActions.Read], ProjectPermissionSub.AgentVaultProxies);+ can([ProjectPermissionAgentVaultSkillActions.Read], ProjectPermissionSub.AgentVaultSkills);return rules;};diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.tsindex 014daad042..e6d6f57a76 100644--- a/backend/src/ee/services/permission/project-permission.ts+++ b/backend/src/ee/services/permission/project-permission.ts@@ -324,6 +324,13 @@ export enum ProjectPermissionAgentVaultProxyActions {Revoke = "revoke"}+export enum ProjectPermissionAgentVaultSkillActions {+ Read = "read",+ Create = "create",+ Edit = "edit",+ Delete = "delete"+}+export enum ProjectPermissionApprovalRequestActions {Read = "read",Create = "create"@@ -403,6 +410,7 @@ export enum ProjectPermissionSub {AgentVaultAccessBundles = "agent-vault-access-bundles",AgentVaultSessions = "agent-vault-sessions",AgentVaultProxies = "agent-vault-proxies",+ AgentVaultSkills = "agent-vault-skills",Insights = "insights"}@@ -725,6 +733,7 @@ export type ProjectPermissionSet =| [ProjectPermissionAgentVaultAccessBundleActions, ProjectPermissionSub.AgentVaultAccessBundles]| [ProjectPermissionAgentVaultSessionActions, ProjectPermissionSub.AgentVaultSessions]| [ProjectPermissionAgentVaultProxyActions, ProjectPermissionSub.AgentVaultProxies]+ | [ProjectPermissionAgentVaultSkillActions, ProjectPermissionSub.AgentVaultSkills]| [ProjectPermissionCertificateProfileActions,(@@ -1679,6 +1688,13 @@ const GeneralPermissionSchema = ["Describe what action an entity can take.")}),+ z.object({+ subject: z.literal(ProjectPermissionSub.AgentVaultSkills).describe("The entity this permission pertains to."),+ inverted: z.boolean().optional().describe("Whether rule allows or forbids."),+ action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionAgentVaultSkillActions).describe(+ "Describe what action an entity can take."+ )+ }),z.object({subject: z.literal(ProjectPermissionSub.ApprovalRequests).describe("The entity this permission pertains to."),action: CASL_ACTION_SCHEMA_NATIVE_ENUM(ProjectPermissionApprovalRequestActions).describe(diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 4619b25b5f..f1ca593af2 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -32,6 +32,7 @@ export const PgSqlLock = {CreateGateway: (orgId: string) => pgAdvisoryLockHashText(`create-gateway:${orgId}`),CreateAgentVaultProxy: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-proxy:${projectId}`),CreateAgentVaultVariable: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-variable:${projectId}`),+ CreateAgentVaultSkill: (projectId: string) => pgAdvisoryLockHashText(`create-agent-vault-skill:${projectId}`),CreateAgentVaultPersonalVariable: (projectId: string, ownerId: string) =>pgAdvisoryLockHashText(`create-agent-vault-personal-variable:${projectId}:${ownerId}`),ClearAgentVaultPersonalValues: (projectId: string) =>diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.tsindex a5dbebdb20..6bf0c530fe 100644--- a/backend/src/lib/api-docs/constants.ts+++ b/backend/src/lib/api-docs/constants.ts@@ -106,6 +106,7 @@ export enum ApiDocsTags {AgentVault = "Agent Vault",AgentVaultAccessBundles = "Agent Vault Access Bundles",AgentVaultVariables = "Agent Vault Variables",+ AgentVaultSkills = "Agent Vault Skills",AgentVaultSessions = "Agent Vault Sessions",AgentVaultProxies = "Agent Vault Proxies",AgentVaultMembers = "Agent Vault Members",@@ -4760,6 +4761,45 @@ export const AGENT_VAULT = {createdAt: "When the variable was added.",updatedAt: "When the variable was last changed."},+ SKILL: {+ skillId: "The ID of the skill.",+ name: "The name of the skill, taken from the `name` in the SKILL.md of its latest version. Lowercase letters, numbers and hyphens.",+ description: "What the skill is for, taken from the `description` in the SKILL.md of its latest version.",+ latestVersion: "The number of the skill's newest version.",+ accessBundles:+ "The access bundles the skill is in, ordered by name. A member sees only the bundles they have been granted.",+ accessBundleId: "The ID of an access bundle the skill is in.",+ accessBundleName: "The name of the access bundle.",+ createdAt: "When the skill was added.",+ updatedAt: "When the skill was last changed.",+ files:+ "Every file in the skill folder. One must be `SKILL.md` at the root, starting with a YAML header that sets `name` and `description`. At most 50 files, 256 KB per file and 1 MB in total.",+ filePath:+ "The file's path inside the skill folder, using `/` between folders. No leading `/`, and no `.` or `..` parts. At most 255 characters, and each file or folder name at most 255 bytes.",+ fileMode: "The file's permissions: `0644` for a regular file, `0755` for one that can be run.",+ fileContent: "The file's content, encoded as base64.",+ latestFiles: "The files of the latest version.",+ versionId: "The ID of the version.",+ version: "The version number. Versions count up from 1, and the newest 20 are kept.",+ sha256: "The SHA-256 digest of the version's files, as hex.",+ sizeBytes: "The total size of the version's files in bytes.",+ fileCount: "How many files the version has.",+ versionCreatedAt: "When the version was saved.",+ unchanged:+ "True if the files match the latest version, in which case no new version was made and that version is returned.",+ baseVersion:+ "The version these files were edited from. If a newer version has been saved since, nothing is saved and the request fails with 409. Omit it to update regardless.",+ restoreUnchanged:+ "True if the version being restored has the same files as the latest version, in which case no new version was made and the latest version is returned.",+ addSkillId: "The ID of the skill to add to the access bundle.",+ search: "Match skills whose name or description contains this text.",+ nameFilter: "Return only the skill with exactly this name.",+ limit: "The maximum number of skills to return. Defaults to 20.",+ offset: "How many skills to skip.",+ totalCount: "How many skills match the filters, across every page.",+ sessionSkills:+ "The latest version of each skill on the session's access bundles that the session's owner can still reach, ordered by name."+ },MEMBER: {grantedAt: "When the access bundle was granted.",userId: "The ID of the user whose Agent Vault membership this is.",diff --git a/backend/src/server/plugins/auth/inject-identity.ts b/backend/src/server/plugins/auth/inject-identity.tsindex d39caaebaa..75d4f811fe 100644--- a/backend/src/server/plugins/auth/inject-identity.ts+++ b/backend/src/server/plugins/auth/inject-identity.ts@@ -297,6 +297,11 @@ export const injectIdentity = fp(return;}+ // Authenticated on the route by an Agent Vault session token, which is not a JWT.+ if (pathname === "/api/v1/agent-vault/session/skills") {+ return;+ }+// Authentication is handled on a route-level here.if (pathname.startsWith("/api/v1/workflow-integrations/microsoft-teams/message-endpoint")) {return;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex a13ab6b9c7..c5f582dfcb 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -47,6 +47,10 @@ import { agentVaultSessionLogServiceFactory } from "@app/ee/services/agent-vaultimport { agentVaultSessionAccessBundleDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-access-bundle-dal";import { agentVaultSessionDALFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-dal";import { agentVaultSessionServiceFactory } from "@app/ee/services/agent-vault-session/agent-vault-session-service";+import { agentVaultSkillBundleDALFactory } from "@app/ee/services/agent-vault-skill/agent-vault-skill-bundle-dal";+import { agentVaultSkillDALFactory } from "@app/ee/services/agent-vault-skill/agent-vault-skill-dal";+import { agentVaultSkillServiceFactory } from "@app/ee/services/agent-vault-skill/agent-vault-skill-service";+import { agentVaultSkillVersionDALFactory } from "@app/ee/services/agent-vault-skill/agent-vault-skill-version-dal";import { agentVaultVariableDALFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-dal";import { agentVaultVariableServiceFactory } from "@app/ee/services/agent-vault-variable/agent-vault-variable-service";import { assumePrivilegeServiceFactory } from "@app/ee/services/assume-privilege/assume-privilege-service";@@ -2061,6 +2065,9 @@ export const registerRoutes = async (const agentVaultProxyDAL = agentVaultProxyDALFactory(db);const agentVaultResolveDAL = agentVaultResolveDALFactory(db);const agentVaultSessionLogConfigDAL = agentVaultSessionLogConfigDALFactory(db);+ const agentVaultSkillDAL = agentVaultSkillDALFactory(db);+ const agentVaultSkillVersionDAL = agentVaultSkillVersionDALFactory(db);+ const agentVaultSkillBundleDAL = agentVaultSkillBundleDALFactory(db);const agentVaultOauthService = agentVaultOauthServiceFactory({keyStore,@@ -2089,6 +2096,16 @@ export const registerRoutes = async (kmsService});+ const agentVaultSkillService = agentVaultSkillServiceFactory({+ agentVaultSkillDAL,+ agentVaultSkillVersionDAL,+ agentVaultSkillBundleDAL,+ agentVaultAccessBundleDAL,+ permissionService,+ membershipDAL,+ kmsService+ });+const agentVaultAccessBundleService = agentVaultAccessBundleServiceFactory({agentVaultAccessBundleDAL,agentVaultServiceDAL,@@ -2235,6 +2252,8 @@ export const registerRoutes = async (agentVaultSessionLogConfigDAL,membershipDAL,orgDAL,+ projectDAL,+ userDAL,permissionService,kmsService,licenseService,@@ -4933,6 +4952,7 @@ export const registerRoutes = async (agentVaultOauth: agentVaultOauthService,agentVaultVariable: agentVaultVariableService,agentVaultPersonalValue: agentVaultPersonalValueService,+ agentVaultSkill: agentVaultSkillService,agentVaultProxy: agentVaultProxyService,agentVaultSession: agentVaultSessionService,agentVaultSessionLog: agentVaultSessionLogService,diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.tsindex c9435c897b..dc50c2ca30 100644--- a/backend/src/services/telemetry/telemetry-types.ts+++ b/backend/src/services/telemetry/telemetry-types.ts@@ -329,6 +329,12 @@ export enum PostHogEventTypes {AgentVaultVariableCreated = "Agent Vault Variable Created",AgentVaultVariableUpdated = "Agent Vault Variable Updated",AgentVaultVariableDeleted = "Agent Vault Variable Deleted",+ AgentVaultSkillCreated = "Agent Vault Skill Created",+ AgentVaultSkillVersionPublished = "Agent Vault Skill Version Published",+ AgentVaultSkillDeleted = "Agent Vault Skill Deleted",+ AgentVaultAccessBundleSkillAdded = "Agent Vault Access Bundle Skill Added",+ AgentVaultAccessBundleSkillRemoved = "Agent Vault Access Bundle Skill Removed",+ AgentVaultSkillsDelivered = "Agent Vault Skills Delivered",AgentVaultAccessBundleMemberAdded = "Agent Vault Access Bundle Member Added",AgentVaultAccessBundleMemberRemoved = "Agent Vault Access Bundle Member Removed",AgentVaultSessionCreated = "Agent Vault Session Created",@@ -2519,6 +2525,49 @@ export type TAgentVaultVariableDeletedEvent = {properties: TAgentVaultEventBase & { variableId: string; scope: string };};+// sizeBucket keeps the size a breakdown.+type TAgentVaultSkillContentProperties = {+ skillId: string;+ fileCount: number;+ sizeBucket: string;+};++export type TAgentVaultSkillCreatedEvent = {+ event: PostHogEventTypes.AgentVaultSkillCreated;+ properties: TAgentVaultEventBase & TAgentVaultSkillContentProperties;+};++export type TAgentVaultSkillVersionPublishedEvent = {+ event: PostHogEventTypes.AgentVaultSkillVersionPublished;+ properties: TAgentVaultEventBase & TAgentVaultSkillContentProperties & { version: number; isRestore: boolean };+};++export type TAgentVaultSkillDeletedEvent = {+ event: PostHogEventTypes.AgentVaultSkillDeleted;+ properties: TAgentVaultEventBase & { skillId: string; removedBundleCount: number };+};++export type TAgentVaultAccessBundleSkillAddedEvent = {+ event: PostHogEventTypes.AgentVaultAccessBundleSkillAdded;+ properties: TAgentVaultEventBase & { skillId: string; accessBundleId: string };+};++export type TAgentVaultAccessBundleSkillRemovedEvent = {+ event: PostHogEventTypes.AgentVaultAccessBundleSkillRemoved;+ properties: TAgentVaultEventBase & { skillId: string; accessBundleId: string };+};++// Fired once per agent start by the route the CLI calls with a session token, which has no request actor.+export type TAgentVaultSkillsDeliveredEvent = {+ event: PostHogEventTypes.AgentVaultSkillsDelivered;+ properties: {+ orgId: string;+ channel: string;+ actorType: string;+ skillCount: number;+ };+};+export type TAgentVaultAccessBundleMemberAddedEvent = {event: PostHogEventTypes.AgentVaultAccessBundleMemberAdded;properties: TAgentVaultEventBase & { accessBundleId: string; memberType: AgentVaultMemberType };@@ -2622,6 +2671,12 @@ export type TAgentVaultPostHogEvent =| TAgentVaultVariableCreatedEvent| TAgentVaultVariableUpdatedEvent| TAgentVaultVariableDeletedEvent+ | TAgentVaultSkillCreatedEvent+ | TAgentVaultSkillVersionPublishedEvent+ | TAgentVaultSkillDeletedEvent+ | TAgentVaultAccessBundleSkillAddedEvent+ | TAgentVaultAccessBundleSkillRemovedEvent+ | TAgentVaultSkillsDeliveredEvent| TAgentVaultAccessBundleMemberAddedEvent| TAgentVaultAccessBundleMemberRemovedEvent| TAgentVaultSessionCreatedEvent@@ -2637,7 +2692,10 @@ export type TAgentVaultPostHogEvent =| TAgentVaultProductMemberUpdatedEvent| TAgentVaultProductMemberRemovedEvent;-export type TAgentVaultActorPostHogEvent = Exclude<TAgentVaultPostHogEvent, TAgentVaultSessionLogChunkAcceptedEvent>;+export type TAgentVaultActorPostHogEvent = Exclude<+ TAgentVaultPostHogEvent,+ TAgentVaultSessionLogChunkAcceptedEvent | TAgentVaultSkillsDeliveredEvent+>;// A trial is burned per PRODUCT, not per (product, plan): the trial-history gate discards plan_key// (see licenseV2Service.getOverview), and the license server 409s a repeat. So TrialStarted fires atdiff --git a/docs/api-reference/endpoints/agent-vault-skills/add.mdx b/docs/api-reference/endpoints/agent-vault-skills/add.mdxnew file mode 100644index 0000000000..e975f00fa2--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/add.mdx@@ -0,0 +1,4 @@+---+title: "Add skill to access bundle"+openapi: "POST /api/v1/agent-vault/access-bundles/{accessBundleId}/skills"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/create.mdx b/docs/api-reference/endpoints/agent-vault-skills/create.mdxnew file mode 100644index 0000000000..277746071e--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/create.mdx@@ -0,0 +1,4 @@+---+title: "Create skill"+openapi: "POST /api/v1/agent-vault/skills"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/delete.mdx b/docs/api-reference/endpoints/agent-vault-skills/delete.mdxnew file mode 100644index 0000000000..766f0c169d--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/delete.mdx@@ -0,0 +1,4 @@+---+title: "Delete skill"+openapi: "DELETE /api/v1/agent-vault/skills/{skillId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/get-version.mdx b/docs/api-reference/endpoints/agent-vault-skills/get-version.mdxnew file mode 100644index 0000000000..4784dccab5--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/get-version.mdx@@ -0,0 +1,4 @@+---+title: "Get skill version"+openapi: "GET /api/v1/agent-vault/skills/{skillId}/versions/{version}"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/get.mdx b/docs/api-reference/endpoints/agent-vault-skills/get.mdxnew file mode 100644index 0000000000..519295a16c--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/get.mdx@@ -0,0 +1,4 @@+---+title: "Get skill"+openapi: "GET /api/v1/agent-vault/skills/{skillId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/list-bundle-skills.mdx b/docs/api-reference/endpoints/agent-vault-skills/list-bundle-skills.mdxnew file mode 100644index 0000000000..4ea613ac1d--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/list-bundle-skills.mdx@@ -0,0 +1,4 @@+---+title: "List access bundle skills"+openapi: "GET /api/v1/agent-vault/access-bundles/{accessBundleId}/skills"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/list-versions.mdx b/docs/api-reference/endpoints/agent-vault-skills/list-versions.mdxnew file mode 100644index 0000000000..9c88f76cc6--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/list-versions.mdx@@ -0,0 +1,4 @@+---+title: "List skill versions"+openapi: "GET /api/v1/agent-vault/skills/{skillId}/versions"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/list.mdx b/docs/api-reference/endpoints/agent-vault-skills/list.mdxnew file mode 100644index 0000000000..a9e30f1d1a--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/list.mdx@@ -0,0 +1,4 @@+---+title: "List skills"+openapi: "GET /api/v1/agent-vault/skills"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/remove.mdx b/docs/api-reference/endpoints/agent-vault-skills/remove.mdxnew file mode 100644index 0000000000..3842d184ee--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/remove.mdx@@ -0,0 +1,4 @@+---+title: "Remove skill from access bundle"+openapi: "DELETE /api/v1/agent-vault/access-bundles/{accessBundleId}/skills/{skillId}"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/restore-version.mdx b/docs/api-reference/endpoints/agent-vault-skills/restore-version.mdxnew file mode 100644index 0000000000..ef1989ca84--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/restore-version.mdx@@ -0,0 +1,4 @@+---+title: "Restore skill version"+openapi: "POST /api/v1/agent-vault/skills/{skillId}/versions/{version}/restore"+---diff --git a/docs/api-reference/endpoints/agent-vault-skills/update.mdx b/docs/api-reference/endpoints/agent-vault-skills/update.mdxnew file mode 100644index 0000000000..a8dd887434--- /dev/null+++ b/docs/api-reference/endpoints/agent-vault-skills/update.mdx@@ -0,0 +1,4 @@+---+title: "Update skill"+openapi: "PATCH /api/v1/agent-vault/skills/{skillId}"+---diff --git a/docs/cli/reference.mdx b/docs/cli/reference.mdxindex a350a67bfc..83dd67b0fc 100644--- a/docs/cli/reference.mdx+++ b/docs/cli/reference.mdx@@ -173,7 +173,7 @@ Run the agent in the foreground, as [infisical agent](/cli/reference#agent) doescommand="agent-vault">-Run [Agent Vault](/documentation/platform/agent-vault/overview), which lets AI agents call services such as LLM providers, GitHub, and Slack without holding the credentials. A proxy adds the real credential to each request the agent sends. Run the proxy with [infisical agent-vault proxy](/cli/reference#agent-vault-proxy), usually where agent traffic leaves your network, and launch agents through it with [infisical agent-vault run](/cli/reference#agent-vault-run).+Run [Agent Vault](/documentation/platform/agent-vault/overview), which lets AI agents call services such as LLM providers, GitHub, and Slack without holding the credentials. A proxy adds the real credential to each request the agent sends. Run the proxy with [infisical agent-vault proxy](/cli/reference#agent-vault-proxy), usually where agent traffic leaves your network, and launch agents through it with [infisical agent-vault run](/cli/reference#agent-vault-run). Upload skills for those agents with [infisical agent-vault skills push](/cli/reference#agent-vault-skills-push).`av` is an alias, so `infisical av run` works wherever `infisical agent-vault run` does. Agent Vault is a different product from the agent proxy that [infisical sm agent-proxy](/cli/reference#sm-agent-proxy) runs.@@ -224,8 +224,10 @@ You set the proxy's traffic policy, exceptions, and poll interval in Infisical,{ name: "--label", value: "<string>", type: "string", description: "A short description of what a session created with `--access-bundle` is for, shown on the **Sessions** page, such as `nightly deploy`. Up to 128 characters, without line breaks, tabs, or invisible characters. Can't be combined with `--session-token`." },{ name: "--no-ca-trust", type: "bool", description: "Skip writing the certificate authority, setting the trust variables, and adding it to the macOS keychain, for a machine that already trusts this proxy. `--ca-fingerprint` is still checked." },{ name: "--no-proxy", value: "<string>", type: "string", description: "More hosts for the agent to reach directly instead of through the proxy, separated by commas. Always merged with `localhost,127.0.0.1` and any `NO_PROXY` in your environment." },+ { name: "--no-skills", type: "bool", description: "Start the agent without installing the session's [skills](/documentation/platform/agent-vault/skills), so the command doesn't contact Infisical for them. Use it if the agent's host can't reach Infisical. Can't be combined with `--skills-dir`." },{ name: "--proxy", value: "<string>", type: "string", description: "The Agent Vault proxy's address as `host:port`, such as `10.0.1.5:17323`. A leading `http://` or `https://` is dropped. Required unless `INFISICAL_AGENT_VAULT_PROXY_ADDRESS` is set." },{ name: "--session-token", value: "<string>", type: "string", description: "A session token created in Infisical. The command never revokes this session. Can't be combined with `--access-bundle`. Can also be set with `INFISICAL_AGENT_VAULT_SESSION_TOKEN`, which keeps it off the command line." },+ { name: "--skills-dir", value: "<string>", type: "string", description: "The folder to install the session's [skills](/documentation/platform/agent-vault/skills) in, instead of `~/.agents/skills`. The CLI doesn't link skills in this folder for Claude Code or Hermes. Can't be empty, and can't be combined with `--no-skills`." },{ name: "--ttl", value: "<string>", type: "string", default: "never", description: "How long a session created with `--access-bundle` lasts: one number and one unit, such as `30m`, `8h`, or `7d` (not `2h30m`), or `never`. Defaults to `never` because the session is revoked when the agent exits, so an expiry only governs one that outlives the command. Can't be combined with `--session-token`." },]}env={[@@ -259,6 +261,50 @@ The command also needs the proxy's address. You can provide it either by passingThe command starts the agent with `HTTP_PROXY` and `HTTPS_PROXY` set to the proxy's address, and sets the [variables that make the agent's HTTP clients trust the proxy's certificate](/documentation/platform/agent-vault/proxies#certificate-trust). The agent inherits the rest of your environment, and the command exits with the agent's exit code.+Before the agent starts, the command installs the [skills](/documentation/platform/agent-vault/skills) in the session's access bundle in `~/.agents/skills`, and links them for Claude Code and Hermes. To install the skills in another folder, pass `--skills-dir`, and to start the agent without them, pass `--no-skills`. The installed skills stay after the agent exits. To pick up skills that changed while the agent runs, restart the agent. For which folders the command links and replaces, see [How agents get skills](/documentation/platform/agent-vault/skills#how-agents-get-skills).++</CLICommand>++<CLICommand+ id="agent-vault-skills"+ command="agent-vault skills"+>++Manage the [skills](/documentation/platform/agent-vault/skills) that Agent Vault installs for agents. [infisical agent-vault skills push](/cli/reference#agent-vault-skills-push) adds a skill from a folder or publishes a new version of it.++</CLICommand>++<CLICommand+ id="agent-vault-skills-push"+ command="agent-vault skills push"+ usage="<folder> [flags]"+ args={[+ { name: "folder", usage: "<folder>", required: true, description: "The folder that holds one skill, with `SKILL.md` at its root." },+ ]}+ flags={[+ { name: "--client-id", value: "<string>", type: "string", description: "The client ID of the machine identity to push as. Can also be set with `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID`." },+ { name: "--client-secret", value: "<string>", type: "string", description: "The client secret of the machine identity to push as. Can also be set with `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET`." },+ ]}+ env={[+ { name: "INFISICAL_UNIVERSAL_AUTH_CLIENT_ID", description: "The client ID of the machine identity to push as. Used if `--client-id` isn't passed." },+ { name: "INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET", description: "The client secret of the machine identity to push as. Used if `--client-secret` isn't passed." },+ { name: "INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN", description: "A machine identity access token to push as. Used if no client ID and client secret are set." },+ { name: "INFISICAL_TOKEN", description: "A machine identity access token to push as. Used if no client ID and client secret are set and `INFISICAL_UNIVERSAL_AUTH_ACCESS_TOKEN` isn't set." },+ ]}+ examples={[+ { title: "Push a skill as the logged-in user", code: "infisical agent-vault skills push ./skills/code-review" },+ { title: "Push a skill as a machine identity", code: "infisical agent-vault skills push ./skills/code-review \\\n --client-id=<client-id> \\\n --client-secret=<client-secret>" },+ ]}+>++Upload a skill folder to Agent Vault. Each command pushes one folder, and the `name` in the folder's `SKILL.md` decides which skill the folder updates:++- If no skill has that name, the command creates the skill+- If a skill has that name, the command publishes the folder as the skill's next version+- If the files match the skill's latest version, the command prints `unchanged` and doesn't create a version++The command skips hidden files and folders, such as `.DS_Store`, and refuses a folder that holds a symbolic link. To push as a machine identity from a script or CI, pass `--client-id` and `--client-secret`, or set `INFISICAL_TOKEN` to the identity's access token. The user or machine identity needs the Admin role in Agent Vault.+</CLICommand><CLICommanddiff --git a/docs/docs.json b/docs/docs.jsonindex aebd45e7b2..f8c3d668d6 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -744,6 +744,7 @@]},"documentation/platform/agent-vault/variables",+ "documentation/platform/agent-vault/skills",{"group": "Sessions","root": "documentation/platform/agent-vault/sessions",@@ -4569,6 +4570,22 @@"api-reference/endpoints/agent-vault-variables/get-value"]},+ {+ "group": "Skills",+ "pages": [+ "api-reference/endpoints/agent-vault-skills/list",+ "api-reference/endpoints/agent-vault-skills/get",+ "api-reference/endpoints/agent-vault-skills/create",+ "api-reference/endpoints/agent-vault-skills/delete",+ "api-reference/endpoints/agent-vault-skills/list-versions",+ "api-reference/endpoints/agent-vault-skills/get-version",+ "api-reference/endpoints/agent-vault-skills/update",+ "api-reference/endpoints/agent-vault-skills/restore-version",+ "api-reference/endpoints/agent-vault-skills/list-bundle-skills",+ "api-reference/endpoints/agent-vault-skills/add",+ "api-reference/endpoints/agent-vault-skills/remove"+ ]+ },{"group": "Access bundle members","pages": [diff --git a/docs/documentation/platform/agent-vault/access-bundles.mdx b/docs/documentation/platform/agent-vault/access-bundles.mdxindex 4770dbb966..f2d9bc09e9 100644--- a/docs/documentation/platform/agent-vault/access-bundles.mdx+++ b/docs/documentation/platform/agent-vault/access-bundles.mdx@@ -31,7 +31,7 @@ To create a new access bundle:</Step></Steps>-Now you can [add services](/documentation/platform/agent-vault/services) to the access bundle so agents using it can make authenticated requests.+Now you can [add services](/documentation/platform/agent-vault/services) to the access bundle so agents using it can make authenticated requests. You can also [add skills](/documentation/platform/agent-vault/skills#add-a-skill-to-an-access-bundle) to the access bundle, so the CLI installs your team's instructions for every agent that starts with it.## Manage access to access bundlesdiff --git a/docs/documentation/platform/agent-vault/access-control.mdx b/docs/documentation/platform/agent-vault/access-control.mdxindex 04329d197d..2852fc278d 100644--- a/docs/documentation/platform/agent-vault/access-control.mdx+++ b/docs/documentation/platform/agent-vault/access-control.mdx@@ -25,8 +25,8 @@ Agent Vault has one member list for your whole organization, instead of one per| Role | What they can do ||------|------------------|-| **Admin** | <ul><li>Create and manage access bundles, services, variables, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Read audit logs</li></ul> |-| **Member** | <ul><li>Create sessions with the access bundles granted to them</li><li>Revoke their own sessions</li><li>Set up their [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) and keep [personal variables](/documentation/platform/agent-vault/variables#personal-variables)</li></ul> |+| **Admin** | <ul><li>Create and manage access bundles, services, variables, skills, and proxies</li><li>Grant access bundles</li><li>Manage membership</li><li>Read audit logs</li></ul> |+| **Member** | <ul><li>Create sessions with the access bundles granted to them</li><li>Revoke their own sessions</li><li>Set up their [personal values](/documentation/platform/agent-vault/access-bundles#set-up-your-personal-values) and keep [personal variables](/documentation/platform/agent-vault/variables#personal-variables)</li><li>View the latest version of the skills in the access bundles granted to them</li></ul> |An admin can use every access bundle without a grant. A member can't use an access bundle until an admin grants it, and only sees the bundles granted to them. On the **Sessions** page, members see their own sessions, and admins can switch between **All Sessions** and **My Sessions**.diff --git a/docs/documentation/platform/agent-vault/guides/modal.mdx b/docs/documentation/platform/agent-vault/guides/modal.mdxindex 7238637736..b46588c854 100644--- a/docs/documentation/platform/agent-vault/guides/modal.mdx+++ b/docs/documentation/platform/agent-vault/guides/modal.mdx@@ -205,7 +205,7 @@ WAIT_FOR_PROXY = (START_AGENT = r"""IFS= read -r INFISICAL_AGENT_VAULT_SESSION_TOKENexport INFISICAL_AGENT_VAULT_SESSION_TOKEN-exec infisical agent-vault run --telemetry=false --proxy agent-proxy:17323 \+exec infisical agent-vault run --telemetry=false --no-skills --proxy agent-proxy:17323 \-- claude -p --permission-mode bypassPermissions"""@@ -319,7 +319,7 @@ const WAIT_FOR_PROXY =const START_AGENT = String.raw`IFS= read -r INFISICAL_AGENT_VAULT_SESSION_TOKENexport INFISICAL_AGENT_VAULT_SESSION_TOKEN-exec infisical agent-vault run --telemetry=false --proxy agent-proxy:17323 \+exec infisical agent-vault run --telemetry=false --no-skills --proxy agent-proxy:17323 \-- claude -p --permission-mode bypassPermissions`;@@ -443,7 +443,7 @@ const waitForProxy = "for i in $(seq 60); do " +const startAgent = `IFS= read -r INFISICAL_AGENT_VAULT_SESSION_TOKENexport INFISICAL_AGENT_VAULT_SESSION_TOKEN-exec infisical agent-vault run --telemetry=false --proxy agent-proxy:17323 \+exec infisical agent-vault run --telemetry=false --no-skills --proxy agent-proxy:17323 \-- claude -p --permission-mode bypassPermissions`@@ -606,7 +606,7 @@ func runAgent(ctx context.Context, mc *modal.Client, app *modal.App, image *moda</CodeGroup>-For more about creating sessions from code, see [Create sessions with the API](/documentation/platform/agent-vault/sessions-api). For the flags the agent starts with, see the [`agent-vault run` CLI reference](/cli/reference#agent-vault-run).+For more about creating sessions from code, see [Create sessions with the API](/documentation/platform/agent-vault/sessions-api). For the flags the agent starts with, see the [`agent-vault run` CLI reference](/cli/reference#agent-vault-run). The script that starts the agent passes `--no-skills`, because the agent's container can't reach Infisical to download [skills](/documentation/platform/agent-vault/skills).To run a different agent, install it in [the image](#step-3-build-the-sandbox-image), replace the `claude` command in the script that starts the agent with the agent's non-interactive command, such as `codex exec`, and replace the Claude Code settings in the agent's environment variables. For an agent you built yourself, run it the same way, or set the proxy in its HTTP client as [Connect your own agent](/documentation/platform/agent-vault/guides/custom-agent#step-4-send-requests-through-the-proxy) describes.diff --git a/docs/documentation/platform/agent-vault/overview.mdx b/docs/documentation/platform/agent-vault/overview.mdxindex 0182ceefaf..69fa8b5d7c 100644--- a/docs/documentation/platform/agent-vault/overview.mdx+++ b/docs/documentation/platform/agent-vault/overview.mdx@@ -78,6 +78,9 @@ Set up Agent Vault for where your agents run.<Card title="Variables" icon="braces" href="/documentation/platform/agent-vault/variables">Values you store once and use in any service in Agent Vault.</Card>+ <Card title="Skills" icon="book-open-text" href="/documentation/platform/agent-vault/skills">+ Instructions you keep in Agent Vault and install for agents you start with an access bundle.+ </Card><Card title="Sessions" icon="monitor" href="/documentation/platform/agent-vault/sessions">Time-bound grants that let AI agents access services without holding real credentials.</Card>diff --git a/docs/documentation/platform/agent-vault/sessions.mdx b/docs/documentation/platform/agent-vault/sessions.mdxindex fbca7230b4..45688757c3 100644--- a/docs/documentation/platform/agent-vault/sessions.mdx+++ b/docs/documentation/platform/agent-vault/sessions.mdx@@ -111,6 +111,8 @@ The access bundle is chosen when you create the session and can't be changed aft- If you delete an access bundle, every session scoped to it stops getting credentials (the session still lists the bundle's name, so you can see what it was)- If you remove someone from Agent Vault, the proxy refuses every request on their sessions+None of these changes removes the [skills](/documentation/platform/agent-vault/skills) that the CLI already installed on the agent's host. To stop agents from using those skills, [delete the installed copies](/documentation/platform/agent-vault/skills#remove-installed-skills).+<Note>If a session stops getting credentials because of a lost grant or a deleted bundle, the proxy still forwards the agent's requests, without credentials. Whether those requests reach the upstream host depends on the proxy's [traffic policy](/documentation/platform/agent-vault/proxies#traffic-policy).</Note>diff --git a/docs/documentation/platform/agent-vault/skills.mdx b/docs/documentation/platform/agent-vault/skills.mdxnew file mode 100644index 0000000000..df5cd9dd99--- /dev/null+++ b/docs/documentation/platform/agent-vault/skills.mdx@@ -0,0 +1,285 @@+---+title: "Skills"+description: "Instructions you keep in Agent Vault and install for agents you start with an access bundle."+---++A skill is a folder of instructions that an AI agent loads when a task needs it, such as how your team reviews pull requests or how to cut a release. Skills follow the [Agent Skills](https://agentskills.io) format, so the same folder works in Claude Code, Codex, and other agents that support it.++An [access bundle](/documentation/platform/agent-vault/access-bundles) defines the services, such as external APIs or MCP servers, that an agent can access during a session. If you add a skill to an access bundle, the CLI installs the skill for each agent that you start with that access bundle through `infisical agent-vault run`. Agents that use the proxy without `infisical agent-vault run`, such as the [Hermes gateway](/documentation/platform/agent-vault/guides/hermes-gateway) and [OpenClaw gateway](/documentation/platform/agent-vault/guides/openclaw-gateway) setups, don't get skills.++<Info>+ [Agent Vault members](/documentation/platform/agent-vault/access-control#product-membership) can view the latest version of each skill in the access bundles granted to them.+</Info>++## Prerequisites++- The **Admin** role in [Agent Vault](/documentation/platform/agent-vault/access-control#product-membership), to add, change, and delete skills, and to add them to access bundles+- The [Infisical CLI](/cli/install) on each host where you start agents++## Skill format++A skill is a folder with a `SKILL.md` file at its root. `SKILL.md` starts with a header that names and describes the skill, followed by the instructions in Markdown:++```markdown+---+name: code-review+description: Reviews a pull request against the team checklist. Use when asked to review code.+---++# Code review++1. Read the diff and the linked issue.+2. Check each item in checklist.md.+```++- `name`: the name agents know the skill by, with up to 64 lowercase letters, numbers, and single hyphens, not starting or ending with a hyphen+- `description`: the text an agent reads to decide when to use the skill (up to 1,024 characters)++The folder can also hold other files that the instructions refer to, such as scripts, templates, or reference documents. Each skill can hold:++- Up to 50 files+- Up to 256 KB per file+- Up to 1 MB in total++If you self-host Infisical behind your own proxy, allow request bodies of at least 2 MB.++Each organization can have up to 250 skills.++<Warning>+ Don't put API keys, tokens, or other secrets in a skill. Anyone with a session token can download the session's skills, and the CLI saves them as plain files on each agent's host. To let an agent use a credential, add the credential to a [service](/documentation/platform/agent-vault/services) instead.+</Warning>++### Scripts in a skill++If you push a skill with the CLI, its scripts stay executable, even after you edit the skill or upload a new version in Infisical. A zipped folder that you upload also keeps its executable files. To make a file executable in the editor, right-click it or select its three-dot button, then select **Make Executable**.++From Windows, push from WSL or CI, or have `SKILL.md` tell the agent to run each script with an interpreter, such as `bash scripts/check.sh`.++## Add a skill++You can push a skill folder with the CLI, or create the skill in Infisical.++<Tabs>+ <Tab title="CLI">+ Log in to the CLI as an Agent Vault admin, then run the following command on the host that has the skill folder:++ ```bash+ infisical agent-vault skills push ./skills/code-review+ ```++ The CLI finds the skill by the `name` in `SKILL.md`. It creates the skill if it doesn't exist yet, and adds a new version if it does.++ In a script or CI, authenticate as a [machine identity](/documentation/platform/identities/machine-identities) with the [Admin role in Agent Vault](/documentation/platform/agent-vault/access-control#product-membership), in one of these ways:++ - Pass `--client-id` and `--client-secret`+ - Set `INFISICAL_UNIVERSAL_AUTH_CLIENT_ID` and `INFISICAL_UNIVERSAL_AUTH_CLIENT_SECRET`+ - Set `INFISICAL_TOKEN` to the identity's access token++ For the flags, see [infisical agent-vault skills push](/cli/reference#agent-vault-skills-push).+ </Tab>+ <Tab title="Infisical">+ <Steps>+ <Step>+ In Agent Vault, go to **Skills** and select **Create Skill**.+ </Step>+ <Step>+ To start from a skill you already have, select **Upload** and drop a zipped skill folder or a Markdown file into the dialog. Infisical fills in the **Name**, the **Description**, and the files from the upload.++ To write the skill instead, enter a **Name** and a **Description**, then write the instructions in `SKILL.md`. To add more files, follow the steps in [Change the files](#change-the-files).++ The header at the top of `SKILL.md` always matches the **Name** and **Description** fields, so you can change the name and the description in either place.+ </Step>+ <Step>+ Check the files, then select **Create Skill**.+ </Step>+ </Steps>+ </Tab>+</Tabs>++## Add a skill to an access bundle++To install skills for agents, add them to an access bundle:++<Steps>+ <Step>+ In Agent Vault, go to **Access Bundles** and select the access bundle.+ </Step>+ <Step>+ In the **Skills** section, select **Add Skills**.+ </Step>+ <Step>+ Pick one or more skills from the list, then select the **Add** button. You can also create a skill from here with **Create New Skill** at the end of the list, and it's added to the access bundle.+ </Step>+</Steps>++An access bundle can have up to 25 skills.++To remove a skill from an access bundle, open its actions menu in the **Skills** section and select **Remove From Bundle**, then type the skill's name and select **Remove**. The CLI doesn't delete copies of the skill that it already installed, so to stop agents from using the skill, [delete the installed copies](#remove-installed-skills).++## How agents get skills++When you start an agent with [`infisical agent-vault run`](/cli/reference#agent-vault-run), the CLI downloads the latest version of each skill in the session's access bundle, and installs the skills before the agent starts. If you publish a new version or add a skill to the access bundle, restart the agent to pick up the change. Starting another agent on the same host also updates the skills there, including for agents already running.++### Reaching Infisical from the agent's host++The CLI downloads the skills from Infisical with the session's token, so the agent's host needs to reach your Infisical instance:++- If the host can't reach Infisical, or you don't want skills, pass [`--no-skills`](/cli/reference#agent-vault-run--flag-no-skills) to start the agent without them+- If you start the agent with a session token and you use EU Cloud or self-host Infisical, pass your instance's URL to the CLI with [`--domain`](/cli/reference#global-flags--flag-domain)++### Where the CLI installs skills++The CLI installs each skill in `~/.agents/skills/<skill-name>`, where Codex, OpenCode, and OpenClaw look for skills.++The CLI also links each skill into the `skills` folder of Claude Code and of Hermes, if that agent's folder exists on the host. If the agent's command is `claude`, the CLI links the skills for Claude Code even if its folder doesn't exist yet:++- Claude Code: `$CLAUDE_CONFIG_DIR`, or `~/.claude` if `CLAUDE_CONFIG_DIR` isn't set+- Hermes: `$HERMES_HOME`, or `~/.hermes` if `HERMES_HOME` isn't set++If the CLI can't create links on the host, such as on Windows without permission to create symbolic links, it copies the skill's folder instead.++To install the skills in a different folder, pass [`--skills-dir`](/cli/reference#agent-vault-run--flag-skills-dir) with the folder's path. The CLI then installs the skills only in that folder.++### Hermes and OpenClaw profiles++In some setups, Hermes and OpenClaw don't read the folders that the CLI installs skills in:++- If you run Hermes with a profile, or on Windows, Hermes doesn't read `~/.hermes/skills`, so add `~/.agents/skills` to `skills.external_dirs` in the `config.yaml` that Hermes uses+- If you run OpenClaw with `OPENCLAW_PROFILE` or `OPENCLAW_STATE_DIR` set, OpenClaw doesn't read `~/.agents/skills`, so pass `--skills-dir` with the `skills` folder in OpenClaw's state folder++For Hermes, the setting in `config.yaml` looks like this:++```yaml+skills:+ external_dirs:+ - ~/.agents/skills+```++### Installed skills stay on the host++The CLI doesn't delete the skills it installs when the agent exits, so later runs of any agent on the host can still use them.++<Note>+ The CLI only replaces skill folders it installed. If a folder with the same name as a skill in the access bundle already exists and the CLI didn't install it, the CLI leaves it alone and warns you.+</Note>++### Remove installed skills++If you remove a skill from an access bundle, delete it, or rename it, the CLI doesn't delete the copies it already installed. On each host that ran an agent with the skill, delete the skill's folder from `~/.agents/skills`, or from the folder you passed to `--skills-dir`. Also delete the skill's link or copy from the Claude Code and Hermes `skills` folders, if the CLI created one there.++If you renamed the skill, the installed folder has the skill's old name.++### If an agent starts without skills++The CLI always starts the agent, even if it can't install the skills. If it can't download or install them, it prints why the agent started without them.++## Manage skills++### View a skill++To open a skill, go to **Skills** in Agent Vault and select the skill. You can also open it from an access bundle: in the **Skills** section, open the skill's actions menu and select **View Skill**.++If you're an Agent Vault member, open the skill from an access bundle that's granted to you. The **Skills** page is only for admins.++The skill opens in a side panel that shows the latest version of its files. To get a copy of the files, select **Options** in the panel, then select **Download**. Infisical downloads the files as a zip file, and scripts that are executable in Infisical stay executable.++### Edit a skill++To change a skill's files in Infisical:++<Steps>+ <Step>+ In Agent Vault, go to **Skills** and select the skill. To edit a Markdown file, select **Code**.+ </Step>+ <Step>+ Change the files in the editor, as described in [Change the files](#change-the-files).+ </Step>+ <Step>+ Select **Save Version** at the bottom, check the changes to each file, and select **Save Version** again. To throw your changes away instead, select **Discard**.+ </Step>+</Steps>++Each time you save, push, or upload a skill with different files, Infisical saves the files as a new version. Infisical keeps the last 20 versions of each skill.++#### Change the files++The editor lists the skill's files on the left and shows the selected file on the right:++- To change a file, select the file and edit its content (for Markdown files, select **Code** first)+- To add a file or a folder, select **New File** or **New Folder**, or right-click an empty part of the file list, then type the name and press Enter+- To add a file or a folder inside a folder, right-click the folder or select its three-dot button, then select **New File** or **New Folder**+- To rename or remove a file or a folder, right-click it or select its three-dot button, then select **Rename**, **Delete File**, or **Delete Folder**++You can't rename or delete `SKILL.md`. The editor doesn't show binary files, such as images, and keeps them as they are.++### Upload a new version++To replace a skill's files with a zipped folder or a Markdown file:++<Steps>+ <Step>+ In Agent Vault, go to **Skills** and select the skill.+ </Step>+ <Step>+ Select **Options**, then select **Upload New Version**, and drop the zipped folder or the Markdown file into the dialog.+ </Step>+ <Step>+ Select **Save Version**.+ </Step>+</Steps>++A zipped folder replaces every file in the skill. A Markdown file replaces only `SKILL.md` and keeps the skill's other files.++You can also publish a new version from the CLI with [infisical agent-vault skills push](/cli/reference#agent-vault-skills-push).++### Rename a skill++To rename a skill, change the `name` in its `SKILL.md`, then [save the change](#edit-a-skill) or [upload](#upload-a-new-version) the new `SKILL.md`.++You can't rename a skill with the CLI. If you push a folder whose `SKILL.md` has a new name, the CLI creates a new skill with that name.++Agents that start after the rename get the skill under its new name. The CLI doesn't delete the copy it installed under the old name, so [delete the installed copies](#remove-installed-skills) on each host.++### Restore a previous version++To roll a skill back:++<Steps>+ <Step>+ In Agent Vault, go to **Skills** and select the skill.+ </Step>+ <Step>+ Select **Options**, then select **Version History**.+ </Step>+ <Step>+ Select the version you want, check its files, and select **Roll Back**. Select **Roll Back** again to confirm.+ </Step>+</Steps>++Infisical publishes a copy of that version as the new latest version. Agents that start after the rollback get that version. If the version you roll back to has the same files as the latest version, Infisical doesn't create a new version.++A rollback keeps the skill's current name. If the older version has a different name, Infisical changes the `name` in that version's `SKILL.md` to the current name.++### Delete a skill++To delete a skill and every version of it:++<Steps>+ <Step>+ In Agent Vault, go to **Skills** and select the skill.+ </Step>+ <Step>+ Select **Options**, then select **Delete Skill**. The dialog lists the access bundles the skill is in.+ </Step>+ <Step>+ Type the skill's name and select **Delete**.+ </Step>+</Steps>++Infisical removes the skill from every access bundle. The CLI doesn't delete copies of the skill that it already installed, so to stop agents from using the skill, [delete the installed copies](#remove-installed-skills).++## Audit trail++Infisical writes an audit event when someone creates, edits, renames, rolls back, or deletes a skill, adds a skill to an access bundle or removes it, or opens a version of a skill. When the CLI downloads a session's skills, Infisical also writes one event for the session that lists each skill's version and the version's SHA-256 checksum, so you can see which version each agent got.++To review these events, open **Audit Logs** in Agent Vault, or scope an [audit log stream](/documentation/platform/audit-log-streams/audit-log-streams) to the Agent Vault product.diff --git a/docs/snippets/agent-vault/QuickstartBody.mdx b/docs/snippets/agent-vault/QuickstartBody.mdxindex f059b79517..80796bed1b 100644--- a/docs/snippets/agent-vault/QuickstartBody.mdx+++ b/docs/snippets/agent-vault/QuickstartBody.mdx@@ -142,4 +142,7 @@ The CLI adds the proxy's certificate authority to the agent process' trusted CAs<Card title="Create sessions with the API" icon="calendar-clock" href="/documentation/platform/agent-vault/sessions-api">Create sessions from code every time you start your agent.</Card>+ <Card title="Skills" icon="book-open-text" href="/documentation/platform/agent-vault/skills">+ Give your agent your team's instructions each time it starts.+ </Card></CardGroup>diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex ce9b7e638c..282027b726 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -12,6 +12,7 @@"@casl/ability": "^6.7.5","@casl/react": "^6.0.0","@codemirror/commands": "^6.10.3",+ "@codemirror/lang-markdown": "^6.5.2","@codemirror/lang-sql": "^6.10.0","@codemirror/language": "^6.12.3","@codemirror/state": "^6.6.0",@@ -74,9 +75,11 @@"date-fns": "^4.1.0","diff": "^8.0.3","dompurify": "^3.2.4",+ "fflate": "^0.8.3","file-saver": "^2.0.5","i18next": "^24.1.0","i18next-http-backend": "^3.0.1",+ "js-yaml": "^4.1.1","jwt-decode": "^4.0.0","lucide-react": "^0.544.0","motion": "^13.2.0",@@ -100,6 +103,7 @@"react-markdown": "^10.0.1","recharts": "^3.8.1","rehype-raw": "^7.0.0",+ "remark-gfm": "^4.0.1","sonner": "^2.0.7","tailwind-merge": "^2.5.5","xterm-readline": "^1.1.2",@@ -114,6 +118,7 @@"@tailwindcss/postcss": "^4.1.14","@tanstack/router-plugin": "^1.95.1","@types/file-saver": "^2.0.7",+ "@types/js-yaml": "^4.0.9","@types/ms": "^0.7.34","@types/node": "^22.12.0","@types/picomatch": "^3.0.1",@@ -618,6 +623,66 @@"@lezer/common": "^1.1.0"}},+ "node_modules/@codemirror/lang-css": {+ "version": "6.3.1",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",+ "integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@lezer/common": "^1.0.2",+ "@lezer/css": "^1.1.7"+ }+ },+ "node_modules/@codemirror/lang-html": {+ "version": "6.4.12",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.12.tgz",+ "integrity": "sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/lang-css": "^6.0.0",+ "@codemirror/lang-javascript": "^6.0.0",+ "@codemirror/language": "^6.4.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.17.0",+ "@lezer/common": "^1.0.0",+ "@lezer/css": "^1.1.0",+ "@lezer/html": "^1.3.12"+ }+ },+ "node_modules/@codemirror/lang-javascript": {+ "version": "6.2.5",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.5.tgz",+ "integrity": "sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.0.0",+ "@codemirror/language": "^6.6.0",+ "@codemirror/lint": "^6.0.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.17.0",+ "@lezer/common": "^1.0.0",+ "@lezer/javascript": "^1.0.0"+ }+ },+ "node_modules/@codemirror/lang-markdown": {+ "version": "6.5.2",+ "resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.2.tgz",+ "integrity": "sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/autocomplete": "^6.7.1",+ "@codemirror/lang-html": "^6.0.0",+ "@codemirror/language": "^6.3.0",+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.0.0",+ "@lezer/common": "^1.2.1",+ "@lezer/markdown": "^1.0.0"+ }+ },"node_modules/@codemirror/lang-sql": {"version": "6.10.0","resolved": "https://registry.npmjs.org/@codemirror/lang-sql/-/lang-sql-6.10.0.tgz",@@ -646,6 +711,17 @@"style-mod": "^4.0.0"}},+ "node_modules/@codemirror/lint": {+ "version": "6.9.5",+ "resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.5.tgz",+ "integrity": "sha512-GElsbU9G7QT9xXhpUg1zWGmftA/7jamh+7+ydKRuT0ORpWS3wOSP0yT1FOlIZa7mIJjpVPipErsyvVqB9cfTFA==",+ "license": "MIT",+ "dependencies": {+ "@codemirror/state": "^6.0.0",+ "@codemirror/view": "^6.35.0",+ "crelt": "^1.0.5"+ }+ },"node_modules/@codemirror/state": {"version": "6.6.0","resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.6.0.tgz",@@ -1545,6 +1621,17 @@"integrity": "sha512-6YRVG9vBkaY7p1IVxL4s44n5nUnaNnGM2/AckNgYOnxTG2kWh1vR8BMxPseWPjRNpb5VtXnMpeYAEAADoRV1Iw==","license": "MIT"},+ "node_modules/@lezer/css": {+ "version": "1.3.9",+ "resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.9.tgz",+ "integrity": "sha512-ZmzgvTOBdJWGIsY/ItAfN7UW8DV802oZG+jeG6E508SwEzz5YhuAajptpWPICvIyqYAD2+VjMdOS40GgGkyEOQ==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.3.0"+ }+ },"node_modules/@lezer/highlight": {"version": "1.2.3","resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",@@ -1554,6 +1641,28 @@"@lezer/common": "^1.3.0"}},+ "node_modules/@lezer/html": {+ "version": "1.3.13",+ "resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.13.tgz",+ "integrity": "sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.0.0",+ "@lezer/lr": "^1.0.0"+ }+ },+ "node_modules/@lezer/javascript": {+ "version": "1.5.6",+ "resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.6.tgz",+ "integrity": "sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.2.0",+ "@lezer/highlight": "^1.1.3",+ "@lezer/lr": "^1.3.0"+ }+ },"node_modules/@lezer/lr": {"version": "1.4.8","resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.8.tgz",@@ -1563,6 +1672,16 @@"@lezer/common": "^1.0.0"}},+ "node_modules/@lezer/markdown": {+ "version": "1.8.0",+ "resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.8.0.tgz",+ "integrity": "sha512-X6w3A2NpyhdtGqTWRJB8gR4QDXBaFMbTOs780ZdZ15KKCfBXOQTKcB3Vr+W6tqJHVlealt53tLmHRvOqPTQgYA==",+ "license": "MIT",+ "dependencies": {+ "@lezer/common": "^1.5.0",+ "@lezer/highlight": "^1.0.0"+ }+ },"node_modules/@lottiefiles/dotlottie-react": {"version": "0.12.0","resolved": "https://registry.npmjs.org/@lottiefiles/dotlottie-react/-/dotlottie-react-0.12.0.tgz",@@ -6638,6 +6757,13 @@"@types/unist": "*"}},+ "node_modules/@types/js-yaml": {+ "version": "4.0.9",+ "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",+ "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/mdast": {"version": "4.0.4","resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz",@@ -7507,6 +7633,12 @@"url": "https://github.com/sponsors/jonschlinkert"}},+ "node_modules/argparse": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",+ "license": "Python-2.0"+ },"node_modules/aria-hidden": {"version": "1.2.4","resolved": "https://registry.npmjs.org/aria-hidden/-/aria-hidden-1.2.4.tgz",@@ -9154,6 +9286,18 @@"node": ">=6"}},+ "node_modules/escape-string-regexp": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-5.0.0.tgz",+ "integrity": "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },"node_modules/esprima": {"version": "4.0.1","resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",@@ -9254,6 +9398,12 @@}}},+ "node_modules/fflate": {+ "version": "0.8.3",+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",+ "license": "MIT"+ },"node_modules/file-saver": {"version": "2.0.5","resolved": "https://registry.npmjs.org/file-saver/-/file-saver-2.0.5.tgz",@@ -10280,6 +10430,18 @@"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==","license": "MIT"},+ "node_modules/js-yaml": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",+ "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",+ "license": "MIT",+ "dependencies": {+ "argparse": "^2.0.1"+ },+ "bin": {+ "js-yaml": "bin/js-yaml.js"+ }+ },"node_modules/jsesc": {"version": "3.1.0","resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",@@ -10664,6 +10826,16 @@"dev": true,"license": "MIT"},+ "node_modules/markdown-table": {+ "version": "3.0.4",+ "resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",+ "integrity": "sha512-wiYz4+JrLyb/DqW2hkFJxP7Vd7JuTDm77fvbM8VfEQdmSMqcImWeeRbHwZjBjIFki/VaMK2BhFi7oUUZeM5bqw==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/math-intrinsics": {"version": "1.1.0","resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",@@ -10685,6 +10857,36 @@"safe-buffer": "^5.1.2"}},+ "node_modules/mdast-util-find-and-replace": {+ "version": "3.0.3",+ "resolved": "https://registry.npmjs.org/mdast-util-find-and-replace/-/mdast-util-find-and-replace-3.0.3.tgz",+ "integrity": "sha512-xPgpDNl0/OXHsI7TlaIs22lWnH3KlpvZdXG1ET/m/YT2Hhdkx8lJV4kLphE6l9simyM4KPDFBwas08BgEob6Jw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "escape-string-regexp": "^5.0.0",+ "unist-util-is": "^6.0.0",+ "unist-util-visit-parents": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-find-and-replace/node_modules/unist-util-visit-parents": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/unist-util-visit-parents/-/unist-util-visit-parents-6.1.0.tgz",+ "integrity": "sha512-vKXxz6O38sKDj1mtx/k2cWvkkFBuYGx6uGrlzBkVeWCRF/F8sdI0j3Wbkz/5rVNRRuVc8UrgRdbCxNhmYXgP3w==",+ "license": "MIT",+ "dependencies": {+ "@types/unist": "^3.0.0",+ "unist-util-is": "^6.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/mdast-util-from-markdown": {"version": "2.0.2","resolved": "https://registry.npmjs.org/mdast-util-from-markdown/-/mdast-util-from-markdown-2.0.2.tgz",@@ -10708,6 +10910,107 @@"url": "https://opencollective.com/unified"}},+ "node_modules/mdast-util-gfm": {+ "version": "3.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm/-/mdast-util-gfm-3.1.0.tgz",+ "integrity": "sha512-0ulfdQOM3ysHhCJ1p06l0b0VKlhU0wuQs3thxZQagjcjPrlFRqY215uZGHHJan9GEAXd9MbfPjFJz+qMkVR6zQ==",+ "license": "MIT",+ "dependencies": {+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-gfm-autolink-literal": "^2.0.0",+ "mdast-util-gfm-footnote": "^2.0.0",+ "mdast-util-gfm-strikethrough": "^2.0.0",+ "mdast-util-gfm-table": "^2.0.0",+ "mdast-util-gfm-task-list-item": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-autolink-literal": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-autolink-literal/-/mdast-util-gfm-autolink-literal-2.0.1.tgz",+ "integrity": "sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "ccount": "^2.0.0",+ "devlop": "^1.0.0",+ "mdast-util-find-and-replace": "^3.0.0",+ "micromark-util-character": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-footnote/-/mdast-util-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-sqpDWlsHn7Ac9GNZQMeUzPQSMzR6Wv0WKRNvQRg0KqHh02fpTz69Qc1QSseNX29bhz1ROIyNyxExfawVKTm1GQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.1.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-strikethrough": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-strikethrough/-/mdast-util-gfm-strikethrough-2.0.1.tgz",+ "integrity": "sha512-OuJHqvr455pwu2OaOrir7dbzqs4jlWKOtlu9L6GjcIjjQwNyw02VntQsr/Ek6/A13vgnXfUhBekWRUP1OkNivw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-table": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-table/-/mdast-util-gfm-table-2.0.0.tgz",+ "integrity": "sha512-78UEvebzz/rJIxLvE7ZtDd/vIQ0RHv+3Mh5DR96p7cS7HsBhYIICDBCu8csTNWNO6tBWfqXPWekRuj2FNOGOZg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "markdown-table": "^3.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/mdast-util-gfm-task-list-item": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/mdast-util-gfm-task-list-item/-/mdast-util-gfm-task-list-item-2.0.0.tgz",+ "integrity": "sha512-IrtvNvjxC1o06taBAVJznEnkiHxLFTzgonUdy8hzFVeDun0uTjxxrRGVaNFqkU1wJR3RBPEfsxmU6jDWPofrTQ==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "devlop": "^1.0.0",+ "mdast-util-from-markdown": "^2.0.0",+ "mdast-util-to-markdown": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/mdast-util-mdx-expression": {"version": "2.0.1","resolved": "https://registry.npmjs.org/mdast-util-mdx-expression/-/mdast-util-mdx-expression-2.0.1.tgz",@@ -10908,6 +11211,127 @@"micromark-util-types": "^2.0.0"}},+ "node_modules/micromark-extension-gfm": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz",+ "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==",+ "license": "MIT",+ "dependencies": {+ "micromark-extension-gfm-autolink-literal": "^2.0.0",+ "micromark-extension-gfm-footnote": "^2.0.0",+ "micromark-extension-gfm-strikethrough": "^2.0.0",+ "micromark-extension-gfm-table": "^2.0.0",+ "micromark-extension-gfm-tagfilter": "^2.0.0",+ "micromark-extension-gfm-task-list-item": "^2.0.0",+ "micromark-util-combine-extensions": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-autolink-literal": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz",+ "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-character": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-footnote": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz",+ "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-core-commonmark": "^2.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-normalize-identifier": "^2.0.0",+ "micromark-util-sanitize-uri": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-strikethrough": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz",+ "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-util-chunked": "^2.0.0",+ "micromark-util-classify-character": "^2.0.0",+ "micromark-util-resolve-all": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-table": {+ "version": "2.1.2",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.2.tgz",+ "integrity": "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-tagfilter": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz",+ "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==",+ "license": "MIT",+ "dependencies": {+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },+ "node_modules/micromark-extension-gfm-task-list-item": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz",+ "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==",+ "license": "MIT",+ "dependencies": {+ "devlop": "^1.0.0",+ "micromark-factory-space": "^2.0.0",+ "micromark-util-character": "^2.0.0",+ "micromark-util-symbol": "^2.0.0",+ "micromark-util-types": "^2.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/micromark-factory-destination": {"version": "2.0.1","resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz",@@ -12892,6 +13316,24 @@"url": "https://opencollective.com/unified"}},+ "node_modules/remark-gfm": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",+ "integrity": "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-gfm": "^3.0.0",+ "micromark-extension-gfm": "^3.0.0",+ "remark-parse": "^11.0.0",+ "remark-stringify": "^11.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/remark-parse": {"version": "11.0.0","resolved": "https://registry.npmjs.org/remark-parse/-/remark-parse-11.0.0.tgz",@@ -12923,6 +13365,21 @@"url": "https://opencollective.com/unified"}},+ "node_modules/remark-stringify": {+ "version": "11.0.0",+ "resolved": "https://registry.npmjs.org/remark-stringify/-/remark-stringify-11.0.0.tgz",+ "integrity": "sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==",+ "license": "MIT",+ "dependencies": {+ "@types/mdast": "^4.0.0",+ "mdast-util-to-markdown": "^2.0.0",+ "unified": "^11.0.0"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/require-directory": {"version": "2.1.1","resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 518786a3a5..69ee7e5588 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -45,6 +45,7 @@"@casl/ability": "^6.7.5","@casl/react": "^6.0.0","@codemirror/commands": "^6.10.3",+ "@codemirror/lang-markdown": "^6.5.2","@codemirror/lang-sql": "^6.10.0","@codemirror/language": "^6.12.3","@codemirror/state": "^6.6.0",@@ -107,9 +108,11 @@"date-fns": "^4.1.0","diff": "^8.0.3","dompurify": "^3.2.4",+ "fflate": "^0.8.3","file-saver": "^2.0.5","i18next": "^24.1.0","i18next-http-backend": "^3.0.1",+ "js-yaml": "^4.1.1","jwt-decode": "^4.0.0","lucide-react": "^0.544.0","motion": "^13.2.0",@@ -133,6 +136,7 @@"react-markdown": "^10.0.1","recharts": "^3.8.1","rehype-raw": "^7.0.0",+ "remark-gfm": "^4.0.1","sonner": "^2.0.7","tailwind-merge": "^2.5.5","xterm-readline": "^1.1.2",@@ -147,6 +151,7 @@"@tailwindcss/postcss": "^4.1.14","@tanstack/router-plugin": "^1.95.1","@types/file-saver": "^2.0.7",+ "@types/js-yaml": "^4.0.9","@types/ms": "^0.7.34","@types/node": "^22.12.0","@types/picomatch": "^3.0.1",diff --git a/frontend/src/components/agent-vault/skills/CreateSkillSheet.tsx b/frontend/src/components/agent-vault/skills/CreateSkillSheet.tsxnew file mode 100644index 0000000000..9f91470694--- /dev/null+++ b/frontend/src/components/agent-vault/skills/CreateSkillSheet.tsx@@ -0,0 +1,402 @@+import { FormEvent, useEffect, useMemo, useState } from "react";+import { Controller, useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import { UploadIcon } from "lucide-react";+import { z } from "zod";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ DiscardChangesAlertDialog,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel,+ Input,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle+} from "@app/components/v3";+import {+ fromDraftFiles,+ getReservedSkillNameMessage,+ getSkillHeaderError,+ getSkillHeaderText,+ isReservedSkillName,+ newDraftFile,+ parseSkillHeader,+ setSkillHeaderValue,+ SKILL_DESCRIPTION_MAX_LENGTH,+ SKILL_ENTRY_FILE,+ SKILL_NAME_MAX_LENGTH,+ SKILL_NAME_MESSAGE,+ SKILL_NAME_RE,+ sortSkillFiles,+ splitFrontmatter,+ toDraftFiles,+ TSkillDraftFile+} from "@app/helpers/agentVaultSkills";+import { useDiscardChangesGuard } from "@app/hooks";+import { useCreateAgentVaultSkill } from "@app/hooks/api/agentVault";+import { TAgentVaultSkillSummary } from "@app/hooks/api/agentVault/types";++import { handleSkillEditorEscape, SkillFilesEditor } from "./SkillFilesEditor";+import { SkillUploadDialog, TSkillUpload } from "./SkillUploadDialog";++const schema = z.object({+ name: z+ .string()+ .min(1, "Required")+ .max(SKILL_NAME_MAX_LENGTH, `A name can be at most ${SKILL_NAME_MAX_LENGTH} characters.`)+ .regex(SKILL_NAME_RE, SKILL_NAME_MESSAGE)+ .refine(+ (name) => !isReservedSkillName(name),+ (name) => ({ message: getReservedSkillNameMessage(name) })+ ),+ description: z+ .string()+ .trim()+ .min(1, "Required")+ .max(+ SKILL_DESCRIPTION_MAX_LENGTH,+ `A description can be at most ${SKILL_DESCRIPTION_MAX_LENGTH} characters.`+ )+});++type FormData = z.infer<typeof schema>;++const HEADER_KEYS = ["name", "description"] as const;++const withHeader = (text: string, values: FormData) =>+ HEADER_KEYS.reduce((next, key) => setSkillHeaderValue(next, key, values[key]), text);++// The fields are single-line inputs, which drop line breaks, so a description written over several lines shows its+// line breaks as spaces.+const toFieldText = (value: unknown) =>+ getSkillHeaderText(value)+ .replace(/\n+$/, "")+ .replace(/[ \t]*\n[ \t]*/g, " ");++/** The header's name and description, or null when the text has no header or it can't be read. */+const readHeaderFields = (text: string): FormData | null => {+ const { frontmatter } = splitFrontmatter(text);+ const header = frontmatter === null ? null : parseSkillHeader(frontmatter);+ if (!header) return null;+ return {+ name: getSkillHeaderText(header.name),+ description: toFieldText(header.description)+ };+};++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ initialName?: string;+ description?: string;+ /** Awaited before the sheet closes, so the skill can't be created twice meanwhile. */+ onCreated?: (skill: TAgentVaultSkillSummary) => void | Promise<void>;+ /** Whether the sheet confirms the new skill with a toast. Turn it off when the caller confirms it instead. */+ shouldNotify?: boolean;+};++export const CreateSkillSheet = ({+ isOpen,+ onOpenChange,+ initialName = "",+ description = `Write the instructions in ${SKILL_ENTRY_FILE} and add any files the skill needs, or upload a skill to start from.`,+ onCreated,+ shouldNotify = true+}: Props) => {+ const createSkill = useCreateAgentVaultSkill();+ const initialFiles = useMemo(+ () => [newDraftFile(SKILL_ENTRY_FILE, withHeader("", { name: initialName, description: "" }))],+ [initialName]+ );+ const [files, setFiles] = useState<TSkillDraftFile[]>(initialFiles);+ const [selectedPath, setSelectedPath] = useState<string>(SKILL_ENTRY_FILE);+ const [bodyError, setBodyError] = useState<string | null>(null);+ const [isUploadOpen, setIsUploadOpen] = useState(false);+ const [uploadCount, setUploadCount] = useState(0);++ const {+ control,+ handleSubmit,+ getValues,+ setValue,+ reset,+ formState: { isDirty, isSubmitting, isSubmitted }+ } = useForm<FormData>({+ resolver: zodResolver(schema),+ defaultValues: { name: initialName, description: "" }+ });++ useEffect(() => {+ if (!isOpen) return;+ reset({ name: initialName, description: "" });+ setFiles(initialFiles);+ setSelectedPath(SKILL_ENTRY_FILE);+ setBodyError(null);+ }, [isOpen, initialName, initialFiles, reset]);++ const areFilesDirty = files !== initialFiles;+ const changedPaths = useMemo(+ () =>+ new Set(+ files+ .filter((file) => file.path !== SKILL_ENTRY_FILE || file.text !== initialFiles[0].text)+ .map((file) => file.path)+ ),+ [files, initialFiles]+ );++ const close = () => onOpenChange(false);++ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({ isDirty: isDirty || areFilesDirty, onDiscard: close });++ const getEntryText = (from = files) =>+ from.find((file) => file.path === SKILL_ENTRY_FILE)?.text ?? "";++ const entryHeader = splitFrontmatter(getEntryText()).frontmatter;+ const headerError = useMemo(+ () => (entryHeader === null ? null : getSkillHeaderError(entryHeader)),+ [entryHeader]+ );++ const setEntryText = (from: TSkillDraftFile[], text: string) =>+ from.map((file) => (file.path === SKILL_ENTRY_FILE ? { ...file, text } : file));++ const syncFieldsFromHeader = (text: string) => {+ const fields = readHeaderFields(text);+ if (!fields) return;+ const current = getValues();+ HEADER_KEYS.forEach((key) => {+ if (fields[key] !== current[key])+ setValue(key, fields[key], { shouldDirty: true, shouldValidate: isSubmitted });+ });+ };++ const handleFieldChange = (key: (typeof HEADER_KEYS)[number], value: string) => {+ // While the header was broken the other field couldn't follow it, so it catches up once this edit repairs it.+ if (headerError) syncFieldsFromHeader(setSkillHeaderValue(getEntryText(), key, value));+ setFiles((prev) => setEntryText(prev, setSkillHeaderValue(getEntryText(prev), key, value)));+ setBodyError(null);+ };++ const handleFilesChange = (next: TSkillDraftFile[]) => {+ const text = getEntryText(next);+ if (text !== getEntryText()) syncFieldsFromHeader(text);+ setFiles(next);+ setBodyError(null);+ };++ const handleUpload = ({ files: uploaded, isEntryOnly }: TSkillUpload) => {+ const drafts = toDraftFiles(uploaded);+ const next = isEntryOnly+ ? [drafts[0], ...files.filter((file) => file.path !== SKILL_ENTRY_FILE)]+ : drafts;+ const entry = next.find((file) => file.path === SKILL_ENTRY_FILE);+ let entryFiles: TSkillDraftFile[];+ if (entry?.text && splitFrontmatter(entry.text).frontmatter !== null) {+ syncFieldsFromHeader(entry.text);+ entryFiles = next;+ } else if (entry && entry.text !== null) {+ entryFiles = setEntryText(next, withHeader(entry.text, getValues()));+ } else {+ entryFiles = [+ newDraftFile(SKILL_ENTRY_FILE, withHeader("", getValues())),+ ...next.filter((file) => file.path !== SKILL_ENTRY_FILE)+ ];+ }+ setFiles(sortSkillFiles(entryFiles));+ setSelectedPath(SKILL_ENTRY_FILE);+ setBodyError(null);+ setUploadCount((count) => count + 1);+ };++ const onSubmit = async () => {+ const text = getEntryText();+ const { frontmatter, body } = splitFrontmatter(text);+ const header = frontmatter === null ? {} : parseSkillHeader(frontmatter);+ if (!header) return;+ if (!body.trim()) {+ setSelectedPath(SKILL_ENTRY_FILE);+ setBodyError(`Write the instructions in ${SKILL_ENTRY_FILE}.`);+ return;+ }++ // Only where the header disagrees with the fields (no header, or a name written as `12`), so a header that+ // already matches, such as a folded description, keeps its exact text.+ const values = getValues();+ const entryText = HEADER_KEYS.reduce(+ (next, key) =>+ header[key] === values[key] ||+ (key === "description" &&+ typeof header[key] === "string" &&+ toFieldText(header[key]) === values[key])+ ? next+ : setSkillHeaderValue(next, key, values[key]),+ text+ );++ let skill: TAgentVaultSkillSummary;+ try {+ ({ skill } = await createSkill.mutateAsync({+ files: fromDraftFiles(setEntryText(files, entryText))+ }));+ } catch {+ return;+ }+ if (shouldNotify)+ createNotification({ text: `Skill "${skill.name}" created`, type: "success" });+ await onCreated?.(skill);+ close();+ };++ // A broken header is reported before the fields' checks, since the fields can't show what it holds.+ const handleCreate = (event: FormEvent<HTMLFormElement>) => {+ if (headerError) {+ event.preventDefault();+ setSelectedPath(SKILL_ENTRY_FILE);+ return;+ }+ handleSubmit(onSubmit)(event);+ };++ return (+ <>+ <Sheet open={isOpen} onOpenChange={(open) => !open && requestDiscard()}>+ <SheetContent+ size="wide"+ className="flex h-full max-h-full w-full flex-col gap-y-0"+ isPending={isSubmitting}+ onOpenAutoFocus={(event) => event.preventDefault()}+ onEscapeKeyDown={handleSkillEditorEscape}+ >+ <form onSubmit={handleCreate} className="flex min-h-0 flex-1 flex-col">+ <SheetHeader className="pr-12">+ <div className="flex flex-wrap items-start gap-3">+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <SheetTitle>Create Skill</SheetTitle>+ <SheetDescription>{description}</SheetDescription>+ </div>+ <Button+ type="button"+ variant="outline"+ isDisabled={isSubmitting}+ onClick={() => setIsUploadOpen(true)}+ >+ <UploadIcon />+ Upload+ </Button>+ </div>+ </SheetHeader>++ <div className="flex min-h-0 thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto p-4">+ <div className="grid gap-4 md:grid-cols-[minmax(0,1fr)_minmax(0,2fr)]">+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Name</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ onChange={(event) => {+ field.onChange(event);+ handleFieldChange("name", event.target.value);+ }}+ placeholder="code-review"+ autoComplete="off"+ spellCheck={false}+ isError={Boolean(fieldState.error)}+ />+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="description"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Description</FieldLabel>+ <FieldContent>+ <Input+ {...field}+ onChange={(event) => {+ field.onChange(event);+ handleFieldChange("description", event.target.value);+ }}+ placeholder="Reviews a pull request against the team's checklist. Use when asked to review code."+ isError={Boolean(fieldState.error)}+ />+ <FieldDescription>+ Agents read this to decide when to use the skill.+ </FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ </div>++ <Field>+ <FieldLabel>Files</FieldLabel>+ <FieldContent>+ <FieldError>{headerError ?? bodyError}</FieldError>+ <SkillFilesEditor+ files={files}+ selectedPath={selectedPath}+ onSelect={setSelectedPath}+ isEditing+ defaultView="code"+ onChange={handleFilesChange}+ changedPaths={changedPaths}+ requiredPaths={[SKILL_ENTRY_FILE]}+ historyKey={uploadCount}+ className="h-[calc(100dvh-14rem)] min-h-96"+ />+ </FieldContent>+ </Field>+ </div>++ <SheetFooter className="justify-end border-t">+ <Button+ type="button"+ variant="ghost"+ onClick={requestDiscard}+ isDisabled={isSubmitting}+ >+ Cancel+ </Button>+ <Button type="submit" variant="av" isPending={isSubmitting}>+ Create Skill+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>++ <SkillUploadDialog+ isOpen={isUploadOpen}+ onOpenChange={setIsUploadOpen}+ onLoad={handleUpload}+ />++ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Skill?"+ description="The skill you are writing will be lost."+ />+ </>+ );+};diff --git a/frontend/src/components/agent-vault/skills/DeleteSkillDialog.tsx b/frontend/src/components/agent-vault/skills/DeleteSkillDialog.tsxnew file mode 100644index 0000000000..54a4c557c8--- /dev/null+++ b/frontend/src/components/agent-vault/skills/DeleteSkillDialog.tsx@@ -0,0 +1,61 @@+import { PackageIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { ConfirmationAlertDialog } from "@app/components/v3";+import { useDeleteAgentVaultSkill } from "@app/hooks/api/agentVault";+import { TAgentVaultSkill } from "@app/hooks/api/agentVault/types";++type Props = {+ skill: Pick<TAgentVaultSkill, "id" | "name" | "accessBundles"> | null;+ onOpenChange: (isOpen: boolean) => void;+ onDeleted?: () => void | Promise<void>;+};++export const DeleteSkillDialog = ({ skill, onOpenChange, onDeleted }: Props) => {+ const deleteSkill = useDeleteAgentVaultSkill();+ const accessBundles = skill?.accessBundles ?? [];++ const handleDelete = async () => {+ if (!skill) return;+ try {+ await deleteSkill.mutateAsync(skill.id);+ } catch {+ return;+ }+ createNotification({ text: `Skill "${skill.name}" deleted`, type: "success" });+ onOpenChange(false);+ await onDeleted?.();+ };++ return (+ <ConfirmationAlertDialog+ isOpen={Boolean(skill)}+ onOpenChange={onOpenChange}+ title={`Delete "${skill?.name}"`}+ description={+ accessBundles.length > 0+ ? "Deleting it removes it from every access bundle below and deletes every version. This cannot be undone."+ : "This skill isn't in any access bundle. Every version of it is deleted. This cannot be undone."+ }+ confirmKey={skill?.name ?? ""}+ isPending={deleteSkill.isPending}+ onConfirm={handleDelete}+ >+ {accessBundles.length > 0 && (+ <div className="flex flex-col gap-2">+ <p className="text-sm font-medium">+ Used by {accessBundles.length} access bundle{accessBundles.length === 1 ? "" : "s"}+ </p>+ <ul className="flex max-h-48 thin-scrollbar flex-col gap-2 overflow-y-auto rounded-md border border-border bg-container/50 p-3">+ {accessBundles.map((bundle) => (+ <li key={bundle.id} className="flex items-center gap-2 text-sm">+ <PackageIcon className="size-3.5 shrink-0 text-muted" />+ <span className="truncate">{bundle.name}</span>+ </li>+ ))}+ </ul>+ </div>+ )}+ </ConfirmationAlertDialog>+ );+};diff --git a/frontend/src/components/agent-vault/skills/RollBackSkillAlertDialog.tsx b/frontend/src/components/agent-vault/skills/RollBackSkillAlertDialog.tsxnew file mode 100644index 0000000000..90b32bedf7--- /dev/null+++ b/frontend/src/components/agent-vault/skills/RollBackSkillAlertDialog.tsx@@ -0,0 +1,51 @@+import { useRef } from "react";++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle+} from "@app/components/v3";++type Props = {+ /** The version to roll back to, or null while closed. */+ version: number | null;+ onOpenChange: (isOpen: boolean) => void;+ onConfirm: (version: number) => void;+};++// Radix focuses Cancel when an alert dialog opens, so an Enter meant for the Roll Back button underneath can't publish.+export const RollBackSkillAlertDialog = ({ version, onOpenChange, onConfirm }: Props) => {+ // Kept while the dialog animates closed, so its title doesn't lose the number.+ const shownRef = useRef(version);+ if (version !== null) shownRef.current = version;+ const shown = shownRef.current;++ return (+ <AlertDialog open={version !== null} onOpenChange={onOpenChange}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Roll Back to v{shown}?</AlertDialogTitle>+ <AlertDialogDescription>+ This publishes a copy of v{shown} as the new latest version.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="av"+ onClick={() => {+ if (version !== null) onConfirm(version);+ }}+ >+ Roll Back+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+};diff --git a/frontend/src/components/agent-vault/skills/SaveSkillVersionSheet.tsx b/frontend/src/components/agent-vault/skills/SaveSkillVersionSheet.tsxnew file mode 100644index 0000000000..3eb3e7cf87--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SaveSkillVersionSheet.tsx@@ -0,0 +1,151 @@+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+ Alert,+ AlertDescription,+ Badge,+ Button,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle+} from "@app/components/v3";+import {+ getSkillEntryName,+ SKILL_ENTRY_FILE,+ TSkillFileChange+} from "@app/helpers/agentVaultSkills";++import { SkillFileDiff } from "./SkillFileDiff";++const STATUS_BADGE = {+ added: { label: "Added", variant: "success" },+ modified: { label: "Modified", variant: "warning" },+ deleted: { label: "Deleted", variant: "danger" }+} as const;++const ChangeBody = ({ change }: { change: TSkillFileChange }) => {+ const isContentChanged = change.oldText !== change.newText;+ const isModeChanged =+ change.status === "modified" && change.oldMode !== undefined && change.newMode !== undefined;+ return (+ <div className="flex flex-col border-t border-border">+ {isModeChanged && (+ <p className="px-3 py-2 font-mono text-xs text-label">+ {change.oldMode} → {change.newMode}+ </p>+ )}+ {change.isBinary && (+ <p className="px-3 py-2 text-xs text-muted">Binary file. Its contents are not shown.</p>+ )}+ {!change.isBinary && isContentChanged && change.isTooLarge && (+ <p className="px-3 py-2 text-xs text-muted">Too large to show a diff</p>+ )}+ {!change.isBinary && isContentChanged && !change.isTooLarge && (+ <SkillFileDiff oldText={change.oldText ?? ""} newText={change.newText ?? ""} />+ )}+ </div>+ );+};++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ skillName: string;+ nextVersion: number;+ /** The latest version, when it is newer than the one editing started from. */+ newerVersion?: number | null;+ changes: TSkillFileChange[];+ isPending: boolean;+ onSave: () => void;+};++export const SaveSkillVersionSheet = ({+ isOpen,+ onOpenChange,+ skillName,+ nextVersion,+ newerVersion,+ changes,+ isPending,+ onSave+}: Props) => {+ const entryChange = changes.find((change) => change.path === SKILL_ENTRY_FILE);+ const newName = getSkillEntryName(entryChange?.newText);+ const renamedTo = newName && newName !== skillName ? newName : null;++ return (+ <Sheet open={isOpen} onOpenChange={onOpenChange}>+ <SheetContent+ size="wide"+ className="flex h-full max-h-full w-full flex-col gap-y-0"+ isPending={isPending}+ >+ <SheetHeader className="border-b pr-12">+ <SheetTitle>+ Save v{nextVersion} of {skillName}+ </SheetTitle>+ <SheetDescription>+ Review the changes. Agents get the new version the next time they start.+ </SheetDescription>+ </SheetHeader>++ <div className="flex min-h-0 thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto p-4">+ {renamedTo && (+ <Alert variant="info">+ <AlertDescription>+ This will rename the skill from {skillName} to {renamedTo}.+ </AlertDescription>+ </Alert>+ )}++ {newerVersion && (+ <Alert variant="warning">+ <AlertDescription>+ A newer version (v{newerVersion}) was published while you were editing. Saving will+ make your version the latest.+ </AlertDescription>+ </Alert>+ )}++ <Accordion type="multiple" defaultValue={changes.map((change) => change.path)}>+ {changes.map((change) => (+ <AccordionItem key={change.path} value={change.path}>+ <AccordionTrigger className="min-h-10 px-3">+ <span className="min-w-0 flex-1 truncate text-left text-sm" title={change.path}>+ {change.path}+ </span>+ {!(change.status === "modified" && change.isTooLarge) && (+ <span className="shrink-0 text-xs tabular-nums">+ <span className="text-success">+{change.additions}</span>{" "}+ <span className="text-danger">-{change.deletions}</span>+ </span>+ )}+ <Badge variant={STATUS_BADGE[change.status].variant}>+ {STATUS_BADGE[change.status].label}+ </Badge>+ </AccordionTrigger>+ <AccordionContent>+ <ChangeBody change={change} />+ </AccordionContent>+ </AccordionItem>+ ))}+ </Accordion>+ </div>++ <SheetFooter className="justify-end border-t">+ <Button variant="ghost" onClick={() => onOpenChange(false)} isDisabled={isPending}>+ Back to Editing+ </Button>+ <Button variant="av" isPending={isPending} onClick={onSave}>+ {newerVersion ? "Save Anyway" : "Save Version"}+ </Button>+ </SheetFooter>+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/components/agent-vault/skills/SkillBundleBadges.tsx b/frontend/src/components/agent-vault/skills/SkillBundleBadges.tsxnew file mode 100644index 0000000000..f6e9d19f83--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SkillBundleBadges.tsx@@ -0,0 +1,56 @@+import { Link } from "@tanstack/react-router";+import { PackageIcon } from "lucide-react";++import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";+import { useOrganization } from "@app/context";+import { TAgentVaultSkill } from "@app/hooks/api/agentVault/types";++const MAX_VISIBLE = 3;++export const SkillBundleBadges = ({+ accessBundles+}: {+ accessBundles: TAgentVaultSkill["accessBundles"];+}) => {+ const { currentOrg } = useOrganization();++ if (accessBundles.length === 0) return <span className="text-sm text-muted">Unused</span>;++ const visible = accessBundles.slice(0, MAX_VISIBLE);+ const hidden = accessBundles.slice(MAX_VISIBLE);++ return (+ <div className="flex min-w-0 items-center gap-2">+ {visible.map((bundle) => (+ <Tooltip key={bundle.id}>+ <TooltipTrigger asChild>+ <Badge variant="neutral" isTruncatable iconPosition="left" className="max-w-40" asChild>+ <Link+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"+ params={{ orgId: currentOrg.id, accessBundleId: bundle.id }}+ >+ <PackageIcon />+ <span>{bundle.name}</span>+ </Link>+ </Badge>+ </TooltipTrigger>+ <TooltipContent>{bundle.name}</TooltipContent>+ </Tooltip>+ ))}+ {hidden.length > 0 && (+ <Tooltip>+ <TooltipTrigger asChild data-row-interactive>+ <span className="shrink-0 cursor-default text-xs text-muted">+{hidden.length}</span>+ </TooltipTrigger>+ <TooltipContent>+ <div className="flex flex-col">+ {hidden.map((bundle) => (+ <span key={bundle.id}>{bundle.name}</span>+ ))}+ </div>+ </TooltipContent>+ </Tooltip>+ )}+ </div>+ );+};diff --git a/frontend/src/components/agent-vault/skills/SkillDescription.tsx b/frontend/src/components/agent-vault/skills/SkillDescription.tsxnew file mode 100644index 0000000000..3d07a646e1--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SkillDescription.tsx@@ -0,0 +1,11 @@+import { Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";++/** A skill's description cut to one line, with the full text on hover. */+export const SkillDescription = ({ description }: { description: string }) => (+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="block truncate text-sm">{description}</span>+ </TooltipTrigger>+ <TooltipContent className="max-w-md">{description}</TooltipContent>+ </Tooltip>+);diff --git a/frontend/src/components/agent-vault/skills/SkillFileDiff.tsx b/frontend/src/components/agent-vault/skills/SkillFileDiff.tsxnew file mode 100644index 0000000000..5f3dcc5d96--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SkillFileDiff.tsx@@ -0,0 +1,64 @@+import { useMemo } from "react";+import { twMerge } from "tailwind-merge";++import { buildDiffRows } from "@app/helpers/agentVaultSkills";++type Props = {+ oldText: string;+ newText: string;+};++export const SkillFileDiff = ({ oldText, newText }: Props) => {+ const rows = useMemo(() => buildDiffRows(oldText, newText), [oldText, newText]);++ if (rows.length === 0) {+ return <p className="px-3 py-2 text-xs text-muted">The file is empty.</p>;+ }++ return (+ <div className="thin-scrollbar overflow-x-auto font-mono text-xs leading-relaxed">+ <table className="w-max min-w-full border-collapse">+ <tbody>+ {rows.map((row, index) => {+ if (row.type === "skip") {+ return (+ // eslint-disable-next-line react/no-array-index-key+ <tr key={`skip-${index}`} className="bg-container text-muted">+ <td colSpan={4} className="px-3 py-0.5">+ {row.count} unchanged line{row.count === 1 ? "" : "s"}+ </td>+ </tr>+ );+ }+ let symbol = " ";+ if (row.type === "added") symbol = "+";+ if (row.type === "removed") symbol = "-";+ return (+ <tr+ // eslint-disable-next-line react/no-array-index-key+ key={`line-${index}`}+ className={twMerge(+ row.type === "added" && "bg-success/15",+ row.type === "removed" && "bg-danger/15"+ )}+ >+ <td className="w-10 px-2 text-right text-muted select-none">{row.oldLine ?? ""}</td>+ <td className="w-10 px-2 text-right text-muted select-none">{row.newLine ?? ""}</td>+ <td+ className={twMerge(+ "w-4 select-none",+ row.type === "added" && "text-success",+ row.type === "removed" && "text-danger"+ )}+ >+ {symbol}+ </td>+ <td className="pr-3 whitespace-pre">{row.text}</td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+};diff --git a/frontend/src/components/agent-vault/skills/SkillFilesEditor.tsx b/frontend/src/components/agent-vault/skills/SkillFilesEditor.tsxnew file mode 100644index 0000000000..dd7c957964--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SkillFilesEditor.tsx@@ -0,0 +1,565 @@+import { useEffect, useMemo, useRef, useState } from "react";+import {+ CodeIcon,+ EyeIcon,+ FilePlusIcon,+ FolderPlusIcon,+ MoreHorizontalIcon,+ PencilIcon,+ SquareTerminalIcon,+ TrashIcon,+ Undo2Icon+} from "lucide-react";+import { twMerge } from "tailwind-merge";++import {+ Badge,+ Button,+ ButtonGroup,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ FileTree,+ type FileTreeInlineEdit,+ type FileTreeItemType,+ IconButton,+ Input,+ Markdown,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import { CodeEditor } from "@app/components/v3/generic/CodeEditor";+import {+ getSkillBaseName,+ getSkillEntryNameError,+ getSkillFolders,+ getSkillParentPath,+ isMarkdownPath,+ joinSkillPath,+ newDraftFile,+ removeSkillPath,+ renameSkillFolders,+ renameSkillPaths,+ SKILL_MAX_FILES,+ splitFrontmatter,+ TSkillDraftFile+} from "@app/helpers/agentVaultSkills";++type TTreeTarget = { path: string; type: FileTreeItemType } | null;++/**+ * For the sheet around the editor: Escape in a file or folder name box cancels only that box, and Escape in the code+ * editor moves the focus out to the sheet, so Tab, which indents inside the editor, can leave it. The sheet listens+ * for Escape on the document before either sees it, so they can't stop it from closing the sheet themselves.+ */+export const handleSkillEditorEscape = (event: KeyboardEvent) => {+ if (!(event.target instanceof Element)) return;+ if (event.target.closest("[data-skill-name-input]")) {+ event.preventDefault();+ return;+ }+ if (event.target.closest('.cm-content[contenteditable="true"]')) {+ event.preventDefault();+ event.target.closest<HTMLElement>('[role="dialog"]')?.focus({ preventScroll: true });+ }+};++type TContextMenu = { x: number; y: number; target: TTreeTarget };++type InlineNameInputProps = {+ initialValue: string;+ isFile: boolean;+ getError: (name: string) => string | null;+ onCommit: (name: string) => void;+ onCancel: () => void;+};++const InlineNameInput = ({+ initialValue,+ isFile,+ getError,+ onCommit,+ onCancel+}: InlineNameInputProps) => {+ const [value, setValue] = useState(initialValue);+ const inputRef = useRef<HTMLInputElement>(null);+ const error = value && value !== initialValue ? getError(value) : null;++ // Focused after the menu that opened it has finished closing, which would otherwise take the focus back.+ useEffect(() => {+ const timer = setTimeout(() => inputRef.current?.focus());+ return () => clearTimeout(timer);+ }, []);++ const commit = () => {+ if (!value || value === initialValue) {+ onCancel();+ return;+ }+ if (getError(value)) return;+ onCommit(value);+ };++ return (+ <div className="flex flex-col gap-1">+ <Input+ ref={inputRef}+ value={value}+ onChange={(event) => setValue(event.target.value)}+ onFocus={(event) => {+ const dot = event.target.value.lastIndexOf(".");+ event.target.setSelectionRange(0, isFile && dot > 0 ? dot : event.target.value.length);+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ commit();+ }+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ onCancel();+ }+ }}+ onBlur={() => {+ if (value && value !== initialValue && !getError(value)) onCommit(value);+ else onCancel();+ }}+ data-skill-name-input+ aria-label={isFile ? "File name" : "Folder name"}+ aria-invalid={Boolean(error)}+ spellCheck={false}+ autoComplete="off"+ size="sm"+ className="font-mono"+ isError={Boolean(error)}+ />+ {error && <p className="text-2xs leading-snug text-danger">{error}</p>}+ </div>+ );+};++type Props = {+ files: TSkillDraftFile[];+ selectedPath: string | null;+ onSelect: (path: string) => void;+ isEditing: boolean;+ onChange?: (files: TSkillDraftFile[]) => void;+ /** Paths marked as changed in the tree. */+ changedPaths?: ReadonlySet<string>;+ /** Changed files whose saved copy has the same path, so "Discard Changes" can put it back. */+ discardablePaths?: ReadonlySet<string>;+ /** Files that can't be renamed or deleted. */+ requiredPaths?: readonly string[];+ /** Which view Markdown files open in. Code is where an editable file is changed. */+ defaultView?: "preview" | "code";+ /** Changing it gives every file a fresh undo history, so undo can't bring back text that was discarded or replaced. */+ historyKey?: string | number;+ /** Like historyKey for one file, so discarding a file's changes resets only that file's undo history. */+ fileHistoryKeys?: Readonly<Record<string, number>>;+ /** Puts back the saved copy of a changed file, offered in that file's menu. */+ onDiscardFile?: (path: string) => void;+ className?: string;+};++export const SkillFilesEditor = ({+ files,+ selectedPath,+ onSelect,+ isEditing,+ onChange,+ changedPaths,+ discardablePaths,+ requiredPaths = [],+ defaultView = "preview",+ historyKey = 0,+ fileHistoryKeys,+ onDiscardFile,+ className+}: Props) => {+ const [view, setView] = useState<"preview" | "code">(defaultView);+ const [emptyFolders, setEmptyFolders] = useState<string[]>([]);+ const [inlineEdit, setInlineEdit] = useState<FileTreeInlineEdit | null>(null);+ const [contextMenu, setContextMenu] = useState<TContextMenu | null>(null);++ useEffect(() => {+ setEmptyFolders([]);+ setInlineEdit(null);+ }, [isEditing]);++ const paths = useMemo(() => files.map((file) => file.path), [files]);+ const folderPaths = useMemo(() => getSkillFolders(paths, emptyFolders), [paths, emptyFolders]);+ const selected = files.find((file) => file.path === selectedPath) ?? files[0];+ const isMarkdown = selected ? isMarkdownPath(selected.path) : false;+ const canPreview = isMarkdown && selected?.text !== null;+ const showRendered = canPreview && view === "preview";+ const isAtFileLimit = files.length >= SKILL_MAX_FILES;+ const modes = useMemo(() => new Map(files.map((file) => [file.path, file.mode])), [files]);+ const hasExecutable = files.some((file) => file.mode === "0755");+ const hasChangedPaths = Boolean(changedPaths?.size);+ const newItemParent = selected ? getSkillParentPath(selected.path) : "";++ const rendered = useMemo(+ () =>+ showRendered && typeof selected?.text === "string" ? splitFrontmatter(selected.text) : null,+ [showRendered, selected?.text]+ );++ const updateFile = (path: string, patch: Partial<TSkillDraftFile>) =>+ onChange?.(files.map((file) => (file.path === path ? { ...file, ...patch } : file)));++ const startCreate = (type: FileTreeItemType, parentPath: string) =>+ setInlineEdit({ action: "create", type, parentPath });++ const deleteEntry = (path: string) => {+ const remaining = removeSkillPath(files, path);+ onChange?.(remaining);+ setEmptyFolders((prev) => removeSkillPath(prev, path));+ if (selected && !remaining.includes(selected) && remaining[0]) onSelect(remaining[0].path);+ };++ const commitInlineEdit = (name: string) => {+ if (!inlineEdit) return;+ if (inlineEdit.action === "create") {+ const path = joinSkillPath(inlineEdit.parentPath, name);+ if (inlineEdit.type === "file") {+ onChange?.([...files, newDraftFile(path)]);+ onSelect(path);+ } else {+ setEmptyFolders((prev) => [...prev, path]);+ }+ } else {+ const from = inlineEdit.path;+ const to = joinSkillPath(getSkillParentPath(from), name);+ onChange?.(renameSkillPaths(files, from, to));+ setEmptyFolders((prev) => renameSkillFolders(prev, from, to));+ if (selected && (selected.path === from || selected.path.startsWith(`${from}/`))) {+ onSelect(to + selected.path.slice(from.length));+ }+ }+ setInlineEdit(null);+ };++ const getInlineError = (name: string) => {+ if (!inlineEdit) return null;+ if (inlineEdit.action === "create") {+ return getSkillEntryNameError({+ name,+ parentPath: inlineEdit.parentPath,+ filePaths: paths,+ folderPaths+ });+ }+ return getSkillEntryNameError({+ name,+ parentPath: getSkillParentPath(inlineEdit.path),+ filePaths: paths,+ folderPaths,+ renamingPath: inlineEdit.path+ });+ };++ const canDiscardFile = (target: TTreeTarget) =>+ Boolean(onDiscardFile && target?.type === "file" && discardablePaths?.has(target.path));++ // New items go in the empty space or inside a folder; a file only changes, discards or deletes itself.+ const hasMenuItems = (target: TTreeTarget) =>+ !target ||+ target.type === "folder" ||+ !requiredPaths.includes(target.path) ||+ canDiscardFile(target);++ const renderMenuItems = (target: TTreeTarget) => {+ const canCreate = !target || target.type === "folder";+ const canChange = target && !requiredPaths.includes(target.path);+ const parentPath = target?.path ?? "";+ const isExecutable = target ? modes.get(target.path) === "0755" : false;+ return (+ <>+ {canCreate && (+ <>+ <DropdownMenuItem+ isDisabled={isAtFileLimit}+ onClick={() => startCreate("file", parentPath)}+ >+ <FilePlusIcon />+ New File+ </DropdownMenuItem>+ <DropdownMenuItem onClick={() => startCreate("folder", parentPath)}>+ <FolderPlusIcon />+ New Folder+ </DropdownMenuItem>+ </>+ )}+ {canCreate && canChange && <DropdownMenuSeparator />}+ {canChange && (+ <>+ <DropdownMenuItem+ onClick={() =>+ setInlineEdit({ action: "rename", type: target.type, path: target.path })+ }+ >+ <PencilIcon />+ Rename+ </DropdownMenuItem>+ {target.type === "file" && (+ <DropdownMenuItem+ onClick={() => updateFile(target.path, { mode: isExecutable ? "0644" : "0755" })}+ >+ <SquareTerminalIcon />+ {isExecutable ? "Make Not Executable" : "Make Executable"}+ </DropdownMenuItem>+ )}+ </>+ )}+ {target && canDiscardFile(target) && (+ <DropdownMenuItem onClick={() => onDiscardFile?.(target.path)}>+ <Undo2Icon />+ Discard Changes+ </DropdownMenuItem>+ )}+ {canChange && (+ <DropdownMenuItem variant="danger" onClick={() => deleteEntry(target.path)}>+ <TrashIcon />+ {target.type === "folder" ? "Delete Folder" : "Delete File"}+ </DropdownMenuItem>+ )}+ </>+ );+ };++ const openContextMenu = (event: React.MouseEvent, target: TTreeTarget) => {+ event.preventDefault();+ if (!hasMenuItems(target)) return;+ setContextMenu({ x: event.clientX, y: event.clientY, target });+ };++ // Not modal: a modal menu keeps the focus while it closes, which blurs and cancels the name input it just opened.+ const renderActions = (path: string, type: FileTreeItemType) => {+ if (!isEditing) return null;+ // A required file still gets the button, disabled, so its unsaved dot lines up with every other row's.+ if (!hasMenuItems({ path, type })) {+ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <IconButton+ variant="ghost"+ size="2xs"+ isDisabled+ aria-label={`No actions for ${path}`}+ >+ <MoreHorizontalIcon />+ </IconButton>+ </span>+ </TooltipTrigger>+ <TooltipContent>{path} can't be renamed or deleted.</TooltipContent>+ </Tooltip>+ );+ }+ return (+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="2xs" aria-label={`Open actions for ${path}`}>+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="end"+ sideOffset={2}+ onCloseAutoFocus={(event) => event.preventDefault()}+ >+ {renderMenuItems({ path, type })}+ </DropdownMenuContent>+ </DropdownMenu>+ );+ };++ return (+ <div+ className={twMerge(+ "grid h-[32rem] min-h-0 min-w-0 grid-rows-[minmax(0,10rem)_minmax(0,1fr)] overflow-hidden rounded-md border border-border md:grid-cols-[minmax(0,16rem)_minmax(0,1fr)] md:grid-rows-1",+ className+ )}+ >+ <FileTree+ paths={paths}+ folders={emptyFolders}+ selectedPath={selected?.path ?? null}+ onSelect={onSelect}+ renderIndicator={(path) =>+ hasExecutable || hasChangedPaths ? (+ <span className="flex shrink-0 items-center gap-1">+ {hasExecutable && (+ <span className="flex w-3.5 justify-center">+ {modes.get(path) === "0755" && (+ <Tooltip>+ <TooltipTrigger asChild>+ <span role="img" aria-label="Executable" className="flex">+ <SquareTerminalIcon className="size-3.5 text-muted" />+ </span>+ </TooltipTrigger>+ <TooltipContent>Executable</TooltipContent>+ </Tooltip>+ )}+ </span>+ )}+ {hasChangedPaths && (+ <span className="mr-1 flex w-1.5 justify-center">+ {changedPaths?.has(path) && (+ <span+ aria-label="Unsaved changes"+ className="size-1.5 rounded-full bg-warning"+ />+ )}+ </span>+ )}+ </span>+ ) : null+ }+ renderActions={isEditing ? renderActions : undefined}+ onItemContextMenu={+ isEditing ? (event, path, type) => openContextMenu(event, { path, type }) : undefined+ }+ onBackgroundContextMenu={isEditing ? (event) => openContextMenu(event, null) : undefined}+ inlineEdit={inlineEdit}+ renderInlineEdit={() =>+ inlineEdit && (+ <InlineNameInput+ key={inlineEdit.action === "rename" ? inlineEdit.path : inlineEdit.parentPath}+ initialValue={inlineEdit.action === "rename" ? getSkillBaseName(inlineEdit.path) : ""}+ isFile={inlineEdit.type === "file"}+ getError={getInlineError}+ onCommit={commitInlineEdit}+ onCancel={() => setInlineEdit(null)}+ />+ )+ }+ footer={+ isEditing ? (+ <div className="flex flex-col gap-1">+ <div className="flex gap-1">+ <Button+ variant="ghost"+ size="xs"+ className="flex-1 justify-start"+ isDisabled={isAtFileLimit}+ onClick={() => startCreate("file", newItemParent)}+ >+ <FilePlusIcon />+ New File+ </Button>+ <Button+ variant="ghost"+ size="xs"+ className="flex-1 justify-start"+ onClick={() => startCreate("folder", newItemParent)}+ >+ <FolderPlusIcon />+ New Folder+ </Button>+ </div>+ {isAtFileLimit && (+ <p className="px-2 text-2xs text-muted">+ A skill can hold at most {SKILL_MAX_FILES} files.+ </p>+ )}+ </div>+ ) : undefined+ }+ className="border-b border-border p-2 md:border-r md:border-b-0"+ />++ {contextMenu && (+ <DropdownMenu modal={false} open onOpenChange={(open) => !open && setContextMenu(null)}>+ <DropdownMenuTrigger+ aria-hidden+ tabIndex={-1}+ className="pointer-events-none fixed size-px opacity-0"+ style={{ left: contextMenu.x, top: contextMenu.y }}+ />+ <DropdownMenuContent align="start" onCloseAutoFocus={(event) => event.preventDefault()}>+ {renderMenuItems(contextMenu.target)}+ </DropdownMenuContent>+ </DropdownMenu>+ )}++ <div className="flex min-h-0 min-w-0 flex-col">+ {selected && (+ <div className="flex min-h-10 shrink-0 items-center gap-2 border-b border-border px-3 py-1.5">+ <span className="min-w-0 flex-1 truncate text-xs text-label" title={selected.path}>+ {selected.path}+ </span>+ {selected.mode === "0755" && <Badge variant="neutral">Executable</Badge>}+ {canPreview && (+ <ButtonGroup aria-label="How to show the file">+ <Button+ size="xs"+ variant={view === "preview" ? "av" : "outline"}+ aria-pressed={view === "preview"}+ onClick={() => setView("preview")}+ >+ <EyeIcon />+ Preview+ </Button>+ <Button+ size="xs"+ variant={view === "code" ? "av" : "outline"}+ aria-pressed={view === "code"}+ onClick={() => setView("code")}+ >+ <CodeIcon />+ Code+ </Button>+ </ButtonGroup>+ )}+ </div>+ )}++ <div className="min-h-0 min-w-0 flex-1">+ {selected && selected.text === null && (+ <Empty className="m-3 border">+ <EmptyHeader>+ <EmptyTitle>Binary file</EmptyTitle>+ <EmptyDescription>+ It can't be shown or edited here. It is kept as it is.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ )}+ {rendered && (+ <div className="h-full thin-scrollbar overflow-y-auto p-4">+ {rendered.frontmatter && (+ <pre className="mb-4 thin-scrollbar overflow-x-auto rounded-md border border-border bg-container p-3 font-mono text-xs leading-relaxed whitespace-pre-wrap text-label">+ {rendered.frontmatter}+ </pre>+ )}+ <Markdown>{rendered.body}</Markdown>+ </div>+ )}+ {/* Stays mounted while hidden, so each file keeps its undo history for as long as the editor is open. */}+ {selected && (+ <CodeEditor+ value={selected.text ?? ""}+ onChange={(text) => updateFile(selected.path, { text })}+ language={isMarkdown ? "markdown" : "plain"}+ isReadOnly={!isEditing}+ hasLineWrapping={isMarkdown}+ stateKey={`${isEditing ? "edit" : "view"}:${historyKey}:${fileHistoryKeys?.[selected.path] ?? 0}:${selected.path}`}+ aria-label={selected.path}+ isBorderless+ className={twMerge("h-full", (selected.text === null || showRendered) && "hidden")}+ />+ )}+ </div>+ </div>+ </div>+ );+};diff --git a/frontend/src/components/agent-vault/skills/SkillSheet.tsx b/frontend/src/components/agent-vault/skills/SkillSheet.tsxnew file mode 100644index 0000000000..c3d5388a3f--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SkillSheet.tsx@@ -0,0 +1,585 @@+import { useEffect, useMemo, useRef, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import axios from "axios";+import { format } from "date-fns";+import {+ DownloadIcon,+ EllipsisIcon,+ HistoryIcon,+ RotateCwIcon,+ TrashIcon,+ UploadIcon+} from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Alert,+ AlertDescription,+ Button,+ DiscardChangesAlertDialog,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Empty,+ EmptyContent,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+ Skeleton,+ Spinner+} from "@app/components/v3";+import {+ ProjectPermissionAgentVaultSkillActions,+ ProjectPermissionSub,+ useOrganization,+ useProjectPermission+} from "@app/context";+import {+ fromDraftFiles,+ getChangedSkillPaths,+ getSkillFileChanges,+ SKILL_ENTRY_FILE,+ toDraftFiles,+ TSkillDraftFile,+ TSkillFileChange+} from "@app/helpers/agentVaultSkills";+import { useDiscardChangesGuard } from "@app/hooks";+import {+ agentVaultKeys,+ SkillVersionConflictError,+ useGetAgentVaultSkill,+ useGetAgentVaultSkillVersion,+ useRestoreAgentVaultSkillVersion,+ useUpdateAgentVaultSkill+} from "@app/hooks/api/agentVault";+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";+import { useAgentVaultSheetState } from "@app/hooks/useAgentVaultSheetState";++import { DeleteSkillDialog } from "./DeleteSkillDialog";+import { downloadSkillVersion } from "./downloadSkillVersion";+import { RollBackSkillAlertDialog } from "./RollBackSkillAlertDialog";+import { SaveSkillVersionSheet } from "./SaveSkillVersionSheet";+import { handleSkillEditorEscape, SkillFilesEditor } from "./SkillFilesEditor";+import { SkillUploadDialog } from "./SkillUploadDialog";+import { SkillVersionHistoryDialog } from "./SkillVersionHistoryDialog";++type TEditState = {+ /** The version editing started from, kept even if a newer one is published meanwhile. */+ baseVersion: number;+ baseFiles: TSkillDraftFile[];+ draft: TSkillDraftFile[];+};++type TSkillDialog = "history" | "upload" | "delete" | "save";++type TSkillSheetBodyProps = {+ shownSkillId: string;+ closeSheet: () => Promise<void>;+ updateSkill: ReturnType<typeof useUpdateAgentVaultSkill>;+ registerRequestClose: (requestClose: () => void) => void;+};++const SkillSheetBody = ({+ shownSkillId,+ closeSheet,+ updateSkill,+ registerRequestClose+}: TSkillSheetBodyProps) => {+ const queryClient = useQueryClient();+ const { currentOrg } = useOrganization();+ const { hasProjectRole, permission } = useProjectPermission();+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);+ const canEdit = permission.can(+ ProjectPermissionAgentVaultSkillActions.Edit,+ ProjectPermissionSub.AgentVaultSkills+ );+ const canDelete = permission.can(+ ProjectPermissionAgentVaultSkillActions.Delete,+ ProjectPermissionSub.AgentVaultSkills+ );++ const {+ data: skill,+ isPending: isSkillPending,+ error: skillError,+ isFetching: isSkillFetching,+ refetch: refetchSkill+ } = useGetAgentVaultSkill(shownSkillId);+ const [viewedVersion, setViewedVersion] = useState<number | null>(null);+ const [edit, setEdit] = useState<TEditState | null>(null);+ const [selectedPath, setSelectedPath] = useState<string | null>(null);+ const [dialog, setDialog] = useState<TSkillDialog | null>(null);+ const [discardCount, setDiscardCount] = useState(0);+ const [fileDiscardCounts, setFileDiscardCounts] = useState<Record<string, number>>({});+ const [rollBackVersion, setRollBackVersion] = useState<number | null>(null);+ // The latest version a refused save reported, shown before the refetched skill arrives.+ const [conflictVersion, setConflictVersion] = useState<number | null>(null);++ // The skill carries the latest version's files, so only an older version is fetched on its own.+ const olderVersionNumber =+ viewedVersion !== null && viewedVersion !== skill?.latestVersion ? viewedVersion : undefined;+ const {+ data: olderVersionData,+ error: versionError,+ isFetching: isVersionFetching,+ refetch: refetchVersion+ } = useGetAgentVaultSkillVersion(shownSkillId, olderVersionNumber);+ const versionData = useMemo(() => {+ if (olderVersionNumber !== undefined) return olderVersionData;+ return skill && { version: skill.latestVersion, files: skill.files };+ }, [olderVersionNumber, olderVersionData, skill]);+ const restoreVersion = useRestoreAgentVaultSkillVersion();++ const original = useMemo(() => toDraftFiles(versionData?.files ?? []), [versionData]);+ // From the picked number, not the loaded data, so the latest draft isn't shown as editable while it loads or fails.+ const isViewingOlder = Boolean(+ skill && viewedVersion !== null && viewedVersion !== skill.latestVersion+ );+ // Admins edit the latest version in place; older versions and members are read-only.+ const isEditing = edit !== null && canEdit && !isViewingOlder;+ const files = isEditing && edit ? edit.draft : original;+ const { changedPaths, hasChanges } = useMemo(+ () =>+ edit+ ? getChangedSkillPaths(edit.baseFiles, edit.draft)+ : { changedPaths: new Set<string>(), hasChanges: false },+ [edit]+ );+ // A renamed or new file has no saved copy under its name, so only files edited in place can be discarded.+ const discardablePaths = useMemo(() => {+ const savedPaths = new Set(edit?.baseFiles.map((file) => file.path));+ return new Set([...changedPaths].filter((path) => savedPaths.has(path)));+ }, [edit, changedPaths]);++ // The line diff is only worked out for the save review, since it is too slow to run on every keystroke.+ const isSaveOpen = dialog === "save";+ const reviewChanges = useMemo(+ () => (isSaveOpen && edit ? getSkillFileChanges(edit.baseFiles, edit.draft) : null),+ [isSaveOpen, edit]+ );+ // Kept while the review animates closed, so its rows don't empty under it.+ const lastReviewChangesRef = useRef<TSkillFileChange[]>([]);+ if (reviewChanges) lastReviewChangesRef.current = reviewChanges;++ const latestKnownVersion = Math.max(skill?.latestVersion ?? 0, conflictVersion ?? 0);+ const newerVersion = edit && latestKnownVersion > edit.baseVersion ? latestKnownVersion : null;++ // The draft follows the latest version until the first change, then keeps the version it started from.+ useEffect(() => {+ if (!canEdit || !skill || !versionData || versionData.version !== skill.latestVersion) return;+ setEdit((prev) =>+ prev &&+ (prev.baseVersion === versionData.version ||+ getChangedSkillPaths(prev.baseFiles, prev.draft).hasChanges)+ ? prev+ : { baseVersion: versionData.version, baseFiles: original, draft: original }+ );+ }, [canEdit, skill, versionData, original]);++ const discardIntent = useRef<"stop" | "close">("stop");+ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({+ isDirty: hasChanges,+ onDiscard: () => {+ const isLatest = Boolean(+ skill && versionData && versionData.version === skill.latestVersion+ );+ setEdit((prev) => {+ if (!prev) return prev;+ return isLatest && versionData+ ? { baseVersion: versionData.version, baseFiles: original, draft: original }+ : { ...prev, draft: prev.baseFiles };+ });+ setDiscardCount((count) => count + 1);+ if (discardIntent.current === "close") closeSheet();+ }+ });++ const requestStopEditing = () => {+ discardIntent.current = "stop";+ requestDiscard();+ };++ const requestClose = () => {+ discardIntent.current = "close";+ requestDiscard();+ };+ registerRequestClose(requestClose);++ // Once the newer version has been shown, saving goes ahead without the version check.+ const handleSave = async () => {+ if (!skill || !edit) return;+ try {+ const {+ skill: saved,+ version: published,+ unchanged+ } = await updateSkill.mutateAsync({+ skillId: skill.id,+ files: fromDraftFiles(edit.draft),+ ...(newerVersion === null && { baseVersion: edit.baseVersion })+ });+ createNotification({+ text: unchanged+ ? `No changes. Version ${published.version} of "${saved.name}" already has these files.`+ : `Saved version ${published.version} of "${saved.name}"`,+ type: unchanged ? "info" : "success"+ });+ setDialog(null);+ setEdit((prev) => prev && { ...prev, baseVersion: published.version, baseFiles: prev.draft });+ setViewedVersion(null);+ } catch (error) {+ if (error instanceof SkillVersionConflictError) setConflictVersion(error.latestVersion);+ // Any other failure is shown by the global mutation handler.+ }+ };++ const handleRollBack = async (target: number) => {+ if (!skill) return;+ try {+ const { version: restored, unchanged } = await restoreVersion.mutateAsync({+ skillId: skill.id,+ version: target+ });+ createNotification(+ unchanged+ ? { text: "This version already matches the latest.", type: "info" }+ : {+ text: `Rolled "${skill.name}" back to version ${target} as version ${restored.version}`,+ type: "success"+ }+ );+ setViewedVersion(null);+ } catch {+ // The global mutation handler shows the server's message.+ }+ };++ const handleDiscardFile = (path: string) => {+ setEdit((prev) => {+ if (!prev) return prev;+ const saved = prev.baseFiles.find((file) => file.path === path);+ if (!saved) return prev;+ return { ...prev, draft: prev.draft.map((file) => (file.path === path ? saved : file)) };+ });+ setFileDiscardCounts((counts) => ({ ...counts, [path]: (counts[path] ?? 0) + 1 }));+ };++ const renderFiles = () => {+ if (versionData || isEditing) {+ return (+ <SkillFilesEditor+ files={files}+ selectedPath={selectedPath}+ onSelect={setSelectedPath}+ isEditing={isEditing}+ onChange={+ isEditing ? (draft) => setEdit((prev) => prev && { ...prev, draft }) : undefined+ }+ changedPaths={changedPaths}+ discardablePaths={discardablePaths}+ requiredPaths={[SKILL_ENTRY_FILE]}+ historyKey={`${discardCount}:${edit?.baseVersion}`}+ fileHistoryKeys={fileDiscardCounts}+ onDiscardFile={isEditing ? handleDiscardFile : undefined}+ className="min-h-96 flex-1"+ />+ );+ }+ if (versionError) {+ return (+ <Empty className="min-h-96 flex-1 border">+ <EmptyHeader>+ <EmptyTitle>Couldn't load this version</EmptyTitle>+ </EmptyHeader>+ <EmptyContent>+ <Button+ variant="outline"+ size="xs"+ isPending={isVersionFetching}+ onClick={() => refetchVersion()}+ >+ <RotateCwIcon />+ Try Again+ </Button>+ </EmptyContent>+ </Empty>+ );+ }+ return <Skeleton className="min-h-96 w-full flex-1" />;+ };++ const renderBody = () => {+ if (!skill && isSkillPending) {+ return (+ <Empty className="m-4 border">+ <EmptyHeader>+ <Spinner size="sm" />+ </EmptyHeader>+ </Empty>+ );+ }+ const isSkillMissing = axios.isAxiosError(skillError) && skillError.response?.status === 404;+ if (!skill && skillError && !isSkillMissing) {+ return (+ <Empty className="m-4 border">+ <EmptyHeader>+ <EmptyTitle>Couldn't load this skill</EmptyTitle>+ </EmptyHeader>+ <EmptyContent>+ <Button+ variant="outline"+ size="xs"+ isPending={isSkillFetching}+ onClick={() => refetchSkill()}+ >+ <RotateCwIcon />+ Try Again+ </Button>+ </EmptyContent>+ </Empty>+ );+ }+ if (!skill) {+ return (+ <Empty className="m-4 border">+ <EmptyHeader>+ <EmptyTitle>Skill not found</EmptyTitle>+ <EmptyDescription>+ This skill was deleted, or you don't have access to it.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ );+ }++ return (+ <>+ <SheetHeader className="pr-12">+ <div className="flex flex-wrap items-start gap-3">+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <SheetTitle className="flex items-center gap-2">+ <span className="truncate">{skill.name}</span>+ </SheetTitle>+ <SheetDescription className="line-clamp-2" title={skill.description}>+ {skill.description}+ </SheetDescription>+ </div>+ <div className="flex shrink-0 items-center gap-2">+ <DropdownMenu>+ <DropdownMenuTrigger asChild disabled={hasChanges}>+ <Button variant="outline">+ Options+ <EllipsisIcon />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {isAdmin && (+ <DropdownMenuItem onClick={() => setDialog("history")}>+ <HistoryIcon />+ Version History+ </DropdownMenuItem>+ )}+ {canEdit && (+ <DropdownMenuItem+ onClick={() => {+ setDialog("upload");+ refetchSkill();+ }}+ >+ <UploadIcon />+ Upload New Version+ </DropdownMenuItem>+ )}+ <DropdownMenuItem+ isDisabled={!versionData}+ onClick={() => versionData && downloadSkillVersion(skill.name, versionData)}+ >+ <DownloadIcon />+ Download+ </DropdownMenuItem>+ {canDelete && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="danger" onClick={() => setDialog("delete")}>+ <TrashIcon />+ Delete Skill+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </div>+ </SheetHeader>++ <div className="flex min-h-0 thin-scrollbar flex-1 flex-col gap-4 overflow-y-auto p-4">+ {isViewingOlder && viewedVersion !== null && (+ <Alert variant="info">+ <AlertDescription className="flex flex-wrap items-center gap-2">+ <span className="flex-1">+ You are viewing v{viewedVersion}+ {olderVersionData &&+ `, published ${format(new Date(olderVersionData.createdAt), "MMM d, yyyy h:mm a")}`}+ . Agents get v{skill.latestVersion}.+ </span>+ <Button variant="outline" size="xs" onClick={() => setViewedVersion(null)}>+ View Latest+ </Button>+ {canEdit && (+ <Button+ variant="av"+ size="xs"+ isPending={restoreVersion.isPending}+ isDisabled={!versionData}+ onClick={() => setRollBackVersion(viewedVersion)}+ >+ <HistoryIcon />+ Roll Back+ </Button>+ )}+ </AlertDescription>+ </Alert>+ )}++ {renderFiles()}+ </div>++ {canEdit && !isViewingOlder && (+ <SheetFooter className="items-center justify-end border-t">+ {hasChanges && <span className="mr-auto text-sm text-accent">Unsaved changes</span>}+ <Button+ variant="ghost"+ onClick={requestStopEditing}+ isDisabled={!hasChanges || updateSkill.isPending}+ >+ Discard+ </Button>+ <Button+ variant="av"+ isDisabled={!hasChanges}+ onClick={() => {+ setDialog("save");+ refetchSkill();+ }}+ >+ Save Version+ </Button>+ </SheetFooter>+ )}+ </>+ );+ };++ return (+ <>+ {renderBody()}++ {skill && (+ <>+ {isAdmin && (+ <SkillVersionHistoryDialog+ isOpen={dialog === "history"}+ onOpenChange={(open) => setDialog(open ? "history" : null)}+ skill={skill}+ viewedVersion={viewedVersion ?? skill.latestVersion}+ canRollBack={canEdit}+ onView={(next) => setViewedVersion(next === skill.latestVersion ? null : next)}+ onRolledBack={() => setViewedVersion(null)}+ />+ )}++ {canEdit && (+ <SkillUploadDialog+ isOpen={dialog === "upload"}+ onOpenChange={(open) => setDialog(open ? "upload" : null)}+ skill={skill}+ onSaved={() => setViewedVersion(null)}+ />+ )}++ <SaveSkillVersionSheet+ isOpen={dialog === "save"}+ onOpenChange={(open) => setDialog(open ? "save" : null)}+ skillName={skill.name}+ nextVersion={skill.latestVersion + 1}+ newerVersion={newerVersion}+ changes={lastReviewChangesRef.current}+ isPending={updateSkill.isPending}+ onSave={handleSave}+ />+ </>+ )}++ <RollBackSkillAlertDialog+ version={rollBackVersion}+ onOpenChange={(open) => !open && setRollBackVersion(null)}+ onConfirm={(target) => {+ setRollBackVersion(null);+ handleRollBack(target);+ }}+ />++ <DeleteSkillDialog+ skill={dialog === "delete" && skill ? skill : null}+ onOpenChange={(open) => setDialog(open ? "delete" : null)}+ onDeleted={async () => {+ if (!skill) return;+ await closeSheet();+ queryClient.removeQueries({ queryKey: agentVaultKeys.skill(currentOrg.id, skill.id) });+ }}+ />++ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Changes?"+ description="Your edits to this skill will be lost."+ />+ </>+ );+};++/** A skill's files, opened from the `skillId` search param of the page it is on. */+export const SkillSheet = () => {+ const { id: skillId, closeSheet } = useAgentVaultSheetState("skillId");++ // Kept while the sheet animates closed, so its contents don't change under it.+ const lastSkillIdRef = useRef(skillId);+ if (skillId) lastSkillIdRef.current = skillId;+ const shownSkillId = skillId ?? lastSkillIdRef.current ?? "";++ const updateSkill = useUpdateAgentVaultSkill();+ const requestCloseRef = useRef<() => void>(closeSheet);++ return (+ <Sheet open={Boolean(skillId)} onOpenChange={(open) => !open && requestCloseRef.current()}>+ <SheetContent+ size="wide"+ className="flex h-full max-h-full w-full flex-col gap-y-0"+ isPending={updateSkill.isPending}+ onOpenAutoFocus={(event) => event.preventDefault()}+ onEscapeKeyDown={handleSkillEditorEscape}+ >+ <SkillSheetBody+ key={shownSkillId}+ shownSkillId={shownSkillId}+ closeSheet={closeSheet}+ updateSkill={updateSkill}+ registerRequestClose={(requestClose) => {+ requestCloseRef.current = requestClose;+ }}+ />+ </SheetContent>+ </Sheet>+ );+};diff --git a/frontend/src/components/agent-vault/skills/SkillUploadDialog.tsx b/frontend/src/components/agent-vault/skills/SkillUploadDialog.tsxnew file mode 100644index 0000000000..60f334a76f--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SkillUploadDialog.tsx@@ -0,0 +1,294 @@+import { useMemo, useRef, useState } from "react";+import { FileTextIcon, RotateCwIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Alert,+ AlertDescription,+ Badge,+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DiscardChangesAlertDialog,+ FileDropzone+} from "@app/components/v3";+import {+ base64ToBytes,+ carrySkillFileModes,+ decodeSkillFile,+ formatSkillBytes,+ getSkillEntryName,+ readSkillUpload,+ replaceSkillEntryFile,+ SKILL_ENTRY_FILE,+ SkillPackageError,+ sortSkillFiles+} from "@app/helpers/agentVaultSkills";+import { useDiscardChangesGuard } from "@app/hooks";+import {+ SkillVersionConflictError,+ useGetAgentVaultSkillVersion,+ useUpdateAgentVaultSkill+} from "@app/hooks/api/agentVault";+import { TAgentVaultSkill, TAgentVaultSkillFile } from "@app/hooks/api/agentVault/types";++type TUploadState =+ | { status: "empty" }+ | { status: "reading"; file: File }+ | { status: "ready"; file: File; files: TAgentVaultSkillFile[]; isEntryOnly: boolean }+ | { status: "invalid"; file: File; message: string };++export type TSkillUpload = { files: TAgentVaultSkillFile[]; isEntryOnly: boolean };++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+} & (+ | {+ /** Publishes the upload as a new version of this skill. */+ skill: Pick<TAgentVaultSkill, "id" | "name" | "latestVersion">;+ onSaved?: () => void;+ onLoad?: never;+ }+ | {+ skill?: never;+ onSaved?: never;+ /** Hands the files back, for an editor to show before anything is saved. */+ onLoad: (upload: TSkillUpload) => void;+ }+);++export const SkillUploadDialog = ({ isOpen, onOpenChange, skill, onSaved, onLoad }: Props) => {+ const updateSkill = useUpdateAgentVaultSkill();+ const latest = useGetAgentVaultSkillVersion(+ isOpen && skill ? skill.id : "",+ skill?.latestVersion+ );+ const [upload, setUpload] = useState<TUploadState>({ status: "empty" });+ // The latest version a refused save reported; saving again then goes ahead without the version check.+ const [conflictVersion, setConflictVersion] = useState<number | null>(null);+ // A file on a cloud or network drive can take seconds to read; a read that outlives its upload is dropped.+ const readIdRef = useRef(0);++ // A new version keeps the modes the previous one gave each path, and a lone .md replaces only SKILL.md.+ const filesToPublish = useMemo(() => {+ if (upload.status !== "ready") return [];+ if (!skill || !latest.data) return upload.files;+ return sortSkillFiles(+ upload.isEntryOnly+ ? replaceSkillEntryFile(latest.data.files, upload.files[0])+ : carrySkillFileModes(upload.files, latest.data.files)+ );+ }, [upload, skill, latest.data]);++ const close = () => {+ readIdRef.current += 1;+ setUpload({ status: "empty" });+ setConflictVersion(null);+ onOpenChange(false);+ };++ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =+ useDiscardChangesGuard({ isDirty: upload.status !== "empty", onDiscard: close });++ const selectFile = async (file?: File) => {+ readIdRef.current += 1;+ setConflictVersion(null);+ const readId = readIdRef.current;+ if (!file) {+ setUpload({ status: "empty" });+ return;+ }+ setUpload({ status: "reading", file });+ try {+ const files = await readSkillUpload(file);+ if (readId !== readIdRef.current) return;+ // Creating: the editor is the review step, so the files go straight there.+ if (!skill) {+ onLoad?.({+ files: sortSkillFiles(files),+ isEntryOnly: file.name.toLowerCase().endsWith(".md")+ });+ close();+ return;+ }+ setUpload({+ status: "ready",+ file,+ files: sortSkillFiles(files),+ isEntryOnly: file.name.toLowerCase().endsWith(".md")+ });+ } catch (error) {+ if (readId !== readIdRef.current) return;+ setUpload({+ status: "invalid",+ file,+ message: error instanceof SkillPackageError ? error.message : "This file could not be read."+ });+ }+ };++ const handleSubmit = async () => {+ if (upload.status !== "ready" || !skill) return;+ try {+ const {+ skill: saved,+ version,+ unchanged+ } = await updateSkill.mutateAsync({+ skillId: skill.id,+ files: filesToPublish,+ ...(conflictVersion === null && latest.data && { baseVersion: latest.data.version })+ });+ createNotification({+ text: unchanged+ ? `No changes. Version ${version.version} of "${saved.name}" already has these files.`+ : `Saved version ${version.version} of "${saved.name}"`,+ type: unchanged ? "info" : "success"+ });+ onSaved?.();+ close();+ } catch (error) {+ if (error instanceof SkillVersionConflictError) setConflictVersion(error.latestVersion);+ // Any other failure is shown by the global mutation handler.+ }+ };++ const uploadedEntry = filesToPublish.find((file) => file.path === SKILL_ENTRY_FILE);+ const uploadedName = uploadedEntry && getSkillEntryName(decodeSkillFile(uploadedEntry));+ const renamedTo = skill && uploadedName && uploadedName !== skill.name ? uploadedName : null;++ const uploadedPaths = new Set(upload.status === "ready" ? upload.files.map((f) => f.path) : []);+ const hasLatestError = Boolean(skill) && latest.isError;+ const isWaitingForLatest = Boolean(skill) && !latest.data;+ const { isPending } = updateSkill;++ return (+ <>+ <Dialog+ open={isOpen}+ onOpenChange={(next) => {+ if (next) onOpenChange(true);+ else requestDiscard();+ }}+ >+ <DialogContent className="sm:max-w-xl" isPending={isPending}>+ <DialogHeader>+ <DialogTitle>{skill ? "Upload New Version" : "Upload Skill"}</DialogTitle>+ {!skill && (+ <DialogDescription>+ Pick a .zip or .md file. Its files fill the editor, and nothing is saved until you+ create the skill.+ </DialogDescription>+ )}+ </DialogHeader>++ {hasLatestError && (+ <Alert variant="danger">+ <AlertDescription className="flex flex-wrap items-center justify-between gap-2">+ Couldn't load the current version of this skill.+ <Button+ variant="outline"+ size="xs"+ isPending={latest.isFetching}+ onClick={() => latest.refetch()}+ >+ <RotateCwIcon />+ Try Again+ </Button>+ </AlertDescription>+ </Alert>+ )}++ <FileDropzone+ accept=".zip,.md"+ files={upload.status === "empty" ? undefined : [upload.file]}+ onFilesSelect={(files) => selectFile(files[0])}+ onFileRemove={() => selectFile()}+ isDisabled={isPending}+ description={+ skill+ ? `A .zip replaces every file. A single .md file replaces only ${SKILL_ENTRY_FILE}.`+ : `A .zip of the skill's folder replaces every file in the editor. A single .md file replaces only ${SKILL_ENTRY_FILE}.`+ }+ />++ {upload.status === "invalid" && (+ <Alert variant="danger">+ <AlertDescription>{upload.message}</AlertDescription>+ </Alert>+ )}++ {upload.status === "ready" && conflictVersion !== null && (+ <Alert variant="warning">+ <AlertDescription>+ A newer version (v{conflictVersion}) was published while you were uploading. Saving+ will make your version the latest.+ </AlertDescription>+ </Alert>+ )}++ {upload.status === "ready" && renamedTo && (+ <Alert variant="info">+ <AlertDescription>+ This will rename the skill from {skill?.name} to {renamedTo}.+ </AlertDescription>+ </Alert>+ )}++ {upload.status === "ready" && (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-accent">+ {filesToPublish.length} file{filesToPublish.length === 1 ? "" : "s"}+ {skill ? " in the new version" : ""}+ </p>+ <ul className="flex max-h-48 thin-scrollbar flex-col gap-1.5 overflow-y-auto rounded-md border border-border bg-container/50 p-3">+ {filesToPublish.map((file) => (+ <li key={file.path} className="flex items-center gap-2 text-sm">+ <FileTextIcon className="size-3.5 shrink-0 text-muted" />+ <span className="min-w-0 flex-1 truncate">{file.path}</span>+ {skill && !uploadedPaths.has(file.path) && (+ <Badge variant="neutral">Kept</Badge>+ )}+ {file.mode === "0755" && <Badge variant="neutral">Executable</Badge>}+ <span className="shrink-0 text-xs text-muted">+ {formatSkillBytes(base64ToBytes(file.contentBase64).length)}+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}++ <DialogFooter>+ <Button variant="ghost" onClick={requestDiscard} isDisabled={isPending}>+ Cancel+ </Button>+ {skill && (+ <Button+ variant="av"+ isPending={isPending}+ isDisabled={upload.status !== "ready" || isWaitingForLatest}+ onClick={handleSubmit}+ >+ {conflictVersion === null ? "Save Version" : "Save Anyway"}+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <DiscardChangesAlertDialog+ open={isDiscardDialogOpen}+ onOpenChange={setIsDiscardDialogOpen}+ onDiscard={confirmDiscard}+ title="Discard Upload?"+ description="The file you picked will not be used."+ />+ </>+ );+};diff --git a/frontend/src/components/agent-vault/skills/SkillVersionHistoryDialog.tsx b/frontend/src/components/agent-vault/skills/SkillVersionHistoryDialog.tsxnew file mode 100644index 0000000000..eb8eb2a274--- /dev/null+++ b/frontend/src/components/agent-vault/skills/SkillVersionHistoryDialog.tsx@@ -0,0 +1,182 @@+import { useState } from "react";+import { format } from "date-fns";+import { HistoryIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import {+ Badge,+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import { formatSkillBytes } from "@app/helpers/agentVaultSkills";+import {+ useListAgentVaultSkillVersions,+ useRestoreAgentVaultSkillVersion+} from "@app/hooks/api/agentVault";+import { TAgentVaultSkill } from "@app/hooks/api/agentVault/types";++import { RollBackSkillAlertDialog } from "./RollBackSkillAlertDialog";++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ skill: Pick<TAgentVaultSkill, "id" | "name" | "latestVersion">;+ viewedVersion: number;+ canRollBack: boolean;+ onView: (version: number) => void;+ onRolledBack: () => void;+};++export const SkillVersionHistoryDialog = ({+ isOpen,+ onOpenChange,+ skill,+ viewedVersion,+ canRollBack,+ onView,+ onRolledBack+}: Props) => {+ const { data: versions = [], isPending } = useListAgentVaultSkillVersions(isOpen ? skill.id : "");+ const restoreVersion = useRestoreAgentVaultSkillVersion();+ const [rollingBack, setRollingBack] = useState<number | null>(null);+ const [confirmVersion, setConfirmVersion] = useState<number | null>(null);++ const handleRollBack = async (version: number) => {+ setRollingBack(version);+ try {+ const { version: restored, unchanged } = await restoreVersion.mutateAsync({+ skillId: skill.id,+ version+ });+ createNotification(+ unchanged+ ? { text: "This version already matches the latest.", type: "info" }+ : {+ text: `Rolled "${skill.name}" back to version ${version} as version ${restored.version}`,+ type: "success"+ }+ );+ onRolledBack();+ onOpenChange(false);+ } catch {+ // The global mutation handler shows the server's message.+ } finally {+ setRollingBack(null);+ }+ };++ return (+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-3xl" isPending={rollingBack !== null}>+ <DialogHeader>+ <DialogTitle>Version History</DialogTitle>+ <DialogDescription>+ Agents get the latest version when they start. Select a version to see its files.+ Rolling back publishes a copy of an older version as the latest.+ </DialogDescription>+ </DialogHeader>++ <div className="max-h-[60vh] thin-scrollbar overflow-y-auto rounded-md border border-border">+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead>Version</TableHead>+ <TableHead>Published</TableHead>+ <TableHead>Files</TableHead>+ <TableHead>Size</TableHead>+ <TableHead variant="action" className="w-28" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {isPending &&+ Array.from({ length: 3 }).map((_, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableRow key={`version-skeleton-${index}`}>+ {Array.from({ length: 4 }).map((__, cell) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableCell key={`version-skeleton-${index}-${cell}`}>+ <Skeleton className="h-4 w-full" />+ </TableCell>+ ))}+ <TableCell variant="action" />+ </TableRow>+ ))}+ {!isPending &&+ versions.map((version) => {+ const isLatest = version.version === skill.latestVersion;+ const view = () => {+ onView(version.version);+ onOpenChange(false);+ };+ return (+ <TableRow+ key={version.id}+ data-state={version.version === viewedVersion ? "selected" : undefined}+ tabIndex={0}+ onClick={view}+ onKeyDown={(event) => {+ if (event.target !== event.currentTarget) return;+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ view();+ }+ }}+ >+ <TableCell>+ <div className="flex items-center gap-2">+ <span>v{version.version}</span>+ {isLatest && <Badge variant="success">Latest</Badge>}+ </div>+ </TableCell>+ <TableCell>+ {format(new Date(version.createdAt), "MMM d, yyyy h:mm a")}+ </TableCell>+ <TableCell>{version.fileCount}</TableCell>+ <TableCell>{formatSkillBytes(version.sizeBytes)}</TableCell>+ <TableCell variant="action">+ {canRollBack && !isLatest && (+ <Button+ variant="ghost"+ size="xs"+ isPending={rollingBack === version.version}+ isDisabled={rollingBack !== null}+ onClick={(event) => {+ event.stopPropagation();+ setConfirmVersion(version.version);+ }}+ >+ <HistoryIcon />+ Roll Back+ </Button>+ )}+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>++ <RollBackSkillAlertDialog+ version={confirmVersion}+ onOpenChange={(open) => !open && setConfirmVersion(null)}+ onConfirm={(version) => {+ setConfirmVersion(null);+ handleRollBack(version);+ }}+ />+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/components/agent-vault/skills/downloadSkillVersion.ts b/frontend/src/components/agent-vault/skills/downloadSkillVersion.tsnew file mode 100644index 0000000000..183867b8e4--- /dev/null+++ b/frontend/src/components/agent-vault/skills/downloadSkillVersion.ts@@ -0,0 +1,23 @@+import FileSaver from "file-saver";++import {+ buildSkillZip,+ decodeSkillFile,+ getSkillEntryName,+ SKILL_ENTRY_FILE,+ SKILL_NAME_RE+} from "@app/helpers/agentVaultSkills";+import { TAgentVaultSkillVersionWithFiles } from "@app/hooks/api/agentVault/types";++export const downloadSkillVersion = (+ skillName: string,+ version: Pick<TAgentVaultSkillVersionWithFiles, "version" | "files">+) => {+ const entry = version.files.find((file) => file.path === SKILL_ENTRY_FILE);+ const entryName = getSkillEntryName(entry && decodeSkillFile(entry));+ const folder = entryName && SKILL_NAME_RE.test(entryName) ? entryName : skillName;+ FileSaver.saveAs(+ new Blob([buildSkillZip(folder, version.files)], { type: "application/zip" }),+ `${skillName}-v${version.version}.zip`+ );+};diff --git a/frontend/src/components/v3/generic/CodeEditor/CodeEditor.stories.tsx b/frontend/src/components/v3/generic/CodeEditor/CodeEditor.stories.tsxnew file mode 100644index 0000000000..95721c53eb--- /dev/null+++ b/frontend/src/components/v3/generic/CodeEditor/CodeEditor.stories.tsx@@ -0,0 +1,75 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";++import { CodeEditor, type CodeEditorProps } from "./CodeEditor";++const MARKDOWN = `# Release checklist++Run these steps **before** tagging a release:++1. Update \`CHANGELOG.md\`.+2. Run the test suite.+3. Open a pull request. See [the guide](https://example.com/guide).++> Ask for review from the owning team.+`;++const ControlledEditor = ({ value: initialValue, ...props }: CodeEditorProps) => {+ const [value, setValue] = useState(initialValue);+ return <CodeEditor {...props} value={value} onChange={setValue} />;+};++const meta = {+ title: "Generic/CodeEditor",+ component: CodeEditor,+ parameters: { layout: "centered" },+ tags: ["autodocs"],+ render: (args) => <ControlledEditor {...args} />,+ decorators: [+ (Story) => (+ <div className="w-[640px]">+ <Story />+ </div>+ )+ ]+} satisfies Meta<typeof CodeEditor>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Markdown: Story = {+ args: { value: MARKDOWN, language: "markdown", className: "h-72", "aria-label": "Notes" }+};++export const PlainText: Story = {+ args: {+ value: '#!/usr/bin/env bash\nset -euo pipefail\n\necho "checking"\n',+ className: "h-48",+ "aria-label": "Script"+ }+};++export const ReadOnly: Story = {+ args: { value: MARKDOWN, language: "markdown", isReadOnly: true, className: "h-72" }+};++export const WithPlaceholder: Story = {+ args: {+ value: "",+ placeholder: "Start writing...",+ hasLineWrapping: true,+ className: "h-40",+ "aria-label": "Draft"+ }+};++export const Borderless: Story = {+ args: { value: MARKDOWN, language: "markdown", isBorderless: true, className: "h-72" },+ decorators: [+ (Story) => (+ <div className="overflow-hidden rounded-md border border-border bg-card">+ <Story />+ </div>+ )+ ]+};diff --git a/frontend/src/components/v3/generic/CodeEditor/CodeEditor.tsx b/frontend/src/components/v3/generic/CodeEditor/CodeEditor.tsxnew file mode 100644index 0000000000..a88dc5bd0b--- /dev/null+++ b/frontend/src/components/v3/generic/CodeEditor/CodeEditor.tsx@@ -0,0 +1,243 @@+import { useEffect, useRef } from "react";+import { history } from "@codemirror/commands";+import { markdown } from "@codemirror/lang-markdown";+import { HighlightStyle, syntaxHighlighting } from "@codemirror/language";+import {+ Annotation,+ Compartment,+ EditorState,+ type Extension,+ Transaction+} from "@codemirror/state";+import {+ EditorView,+ highlightActiveLine,+ highlightActiveLineGutter,+ lineNumbers as lineNumbersGutter,+ placeholder as placeholderText+} from "@codemirror/view";+import { tags } from "@lezer/highlight";++import { cn } from "../../utils";+import { codeEditorEditing, lineEndingsFor } from "./codeEditorExtensions";+import { getValueSync } from "./getChangedRange";++type CodeEditorLanguage = "markdown" | "plain";++type CodeEditorProps = {+ value: string;+ onChange?: (value: string) => void;+ language?: CodeEditorLanguage;+ isReadOnly?: boolean;+ hasLineNumbers?: boolean;+ hasLineWrapping?: boolean;+ placeholder?: string;+ /**+ * Names the document being edited. Changing it puts the current document's undo history and selection aside and+ * brings back the new one's, for as long as the editor stays mounted, so switching between files keeps each one's+ * history. A document whose text changed while it was away starts a fresh history.+ */+ stateKey?: string;+ /** Drops the border, radius and background, for an editor that fills a panel which already draws them. */+ isBorderless?: boolean;+ className?: string;+ "aria-label"?: string;+};++const editorTheme = EditorView.theme({+ "&": { height: "100%", fontSize: "12px", backgroundColor: "transparent" },+ "&.cm-focused": { outline: "none" },+ ".cm-scroller": {+ overflow: "auto",+ fontFamily: "var(--font-mono)",+ lineHeight: "1.6",+ scrollbarWidth: "thin",+ scrollbarColor: "var(--color-scrollbar-track-thumb) transparent"+ },+ ".cm-content": { padding: "8px 0", caretColor: "var(--color-foreground)" },+ ".cm-line": { padding: "0 12px" },+ ".cm-gutters": {+ backgroundColor: "transparent",+ borderRight: "1px solid var(--color-border)",+ color: "var(--color-muted)"+ },+ ".cm-lineNumbers .cm-gutterElement": { padding: "0 10px 0 12px", minWidth: "36px" },+ ".cm-activeLine": {+ backgroundColor: "color-mix(in srgb, var(--color-border-control) 35%, transparent)"+ },+ ".cm-activeLineGutter": {+ backgroundColor: "color-mix(in srgb, var(--color-border-control) 35%, transparent)",+ color: "var(--color-foreground)"+ },+ ".cm-cursor": { borderLeftColor: "var(--color-foreground)" },+ ".cm-selectionBackground": { backgroundColor: "var(--color-border-control) !important" },+ "&.cm-focused .cm-selectionBackground": {+ backgroundColor: "var(--color-border-control) !important"+ },+ ".cm-placeholder": { color: "var(--color-muted)" }+});++const highlightStyle = HighlightStyle.define(+ [+ { tag: tags.heading, color: "var(--color-foreground)", fontWeight: "600" },+ { tag: tags.strong, fontWeight: "600" },+ { tag: tags.emphasis, fontStyle: "italic" },+ { tag: tags.strikethrough, textDecoration: "line-through" },+ { tag: [tags.link, tags.url], color: "var(--color-info)" },+ { tag: tags.monospace, color: "var(--color-success)" },+ { tag: tags.quote, color: "var(--color-label)", fontStyle: "italic" },+ {+ tag: [tags.processingInstruction, tags.contentSeparator, tags.meta],+ color: "var(--color-muted)"+ },+ { tag: tags.list, color: "var(--color-label)" },+ { tag: tags.keyword, color: "var(--color-info)" },+ { tag: tags.string, color: "var(--color-success)" },+ { tag: tags.number, color: "var(--color-warning)" },+ { tag: tags.comment, color: "var(--color-muted)", fontStyle: "italic" },+ { tag: tags.invalid, color: "var(--color-danger)" }+ ],+ { all: { color: "var(--color-foreground)" } }+);++// Marks the dispatch that copies a new `value` prop in, so it is not reported back through `onChange` or undone.+const externalSync = Annotation.define<boolean>();++const languageExtension = (language: CodeEditorLanguage): Extension =>+ language === "markdown" ? markdown() : [];++type TConfigurableOptions = Required<+ Pick<+ CodeEditorProps,+ "language" | "isReadOnly" | "hasLineNumbers" | "hasLineWrapping" | "placeholder"+ >+>;++const configurableExtensions = ({+ language,+ isReadOnly,+ hasLineNumbers,+ hasLineWrapping,+ placeholder+}: TConfigurableOptions): Extension => [+ languageExtension(language),+ EditorState.readOnly.of(isReadOnly),+ EditorView.editable.of(!isReadOnly),+ isReadOnly ? [] : [highlightActiveLine(), highlightActiveLineGutter()],+ hasLineNumbers ? lineNumbersGutter() : [],+ hasLineWrapping ? EditorView.lineWrapping : [],+ placeholder ? placeholderText(placeholder) : []+];++const CodeEditor = ({+ value,+ onChange,+ language = "plain",+ isReadOnly = false,+ hasLineNumbers = true,+ hasLineWrapping = false,+ placeholder = "",+ stateKey,+ isBorderless = false,+ className,+ "aria-label": ariaLabel+}: CodeEditorProps) => {+ const containerRef = useRef<HTMLDivElement>(null);+ const viewRef = useRef<EditorView | null>(null);+ const compartmentRef = useRef(new Compartment());+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;+ const savedStatesRef = useRef(new Map<string, EditorState>());+ const stateKeyRef = useRef(stateKey);++ const options = { language, isReadOnly, hasLineNumbers, hasLineWrapping, placeholder };++ const createState = (doc: string) =>+ EditorState.create({+ doc,+ extensions: [+ history(),+ codeEditorEditing,+ lineEndingsFor(doc),+ editorTheme,+ syntaxHighlighting(highlightStyle),+ compartmentRef.current.of(configurableExtensions(options)),+ EditorView.updateListener.of((update) => {+ if (!update.docChanged) return;+ if (update.transactions.some((tr) => tr.annotation(externalSync))) return;+ onChangeRef.current?.(update.state.sliceDoc());+ })+ ]+ });++ useEffect(() => {+ if (!containerRef.current) return undefined;++ const view = new EditorView({ state: createState(value), parent: containerRef.current });+ viewRef.current = view;++ return () => {+ view.destroy();+ viewRef.current = null;+ };+ // The editor is created once; later prop changes are applied by the effects below.+ }, []);++ useEffect(() => {+ viewRef.current?.dispatch({+ effects: compartmentRef.current.reconfigure(configurableExtensions(options))+ });+ }, [language, isReadOnly, hasLineNumbers, hasLineWrapping, placeholder]);++ // Runs before the value effect below, so a swapped-in document is not then replaced as an edit.+ useEffect(() => {+ const view = viewRef.current;+ if (!view || stateKeyRef.current === stateKey) return;+ if (stateKeyRef.current !== undefined) {+ savedStatesRef.current.set(stateKeyRef.current, view.state);+ }+ stateKeyRef.current = stateKey;+ const saved = stateKey === undefined ? undefined : savedStatesRef.current.get(stateKey);+ view.setState(saved && getValueSync(saved, value) === null ? saved : createState(value));+ // A saved state still holds the options it was put aside with.+ view.dispatch({+ effects: compartmentRef.current.reconfigure(configurableExtensions(options))+ });+ view.contentDOM.setAttribute("aria-label", ariaLabel ?? "");+ }, [stateKey]);++ useEffect(() => {+ const view = viewRef.current;+ if (!view) return;+ const sync = getValueSync(view.state, value);+ if (!sync) return;+ if (sync === "replace") {+ view.setState(createState(value));+ view.contentDOM.setAttribute("aria-label", ariaLabel ?? "");+ return;+ }+ // Only the changed range is replaced, so undo history for the rest of the text still maps to the right places.+ view.dispatch({+ changes: sync,+ annotations: [externalSync.of(true), Transaction.addToHistory.of(false)]+ });+ }, [value]);++ useEffect(() => {+ viewRef.current?.contentDOM.setAttribute("aria-label", ariaLabel ?? "");+ }, [ariaLabel]);++ return (+ <div+ ref={containerRef}+ data-slot="code-editor"+ className={cn(+ "min-h-0 min-w-0 overflow-hidden text-foreground",+ isBorderless ? "bg-transparent" : "rounded-md border border-border bg-container",+ className+ )}+ />+ );+};++export { CodeEditor, type CodeEditorLanguage, type CodeEditorProps };diff --git a/frontend/src/components/v3/generic/CodeEditor/codeEditorExtensions.test.ts b/frontend/src/components/v3/generic/CodeEditor/codeEditorExtensions.test.tsnew file mode 100644index 0000000000..220a6faa15--- /dev/null+++ b/frontend/src/components/v3/generic/CodeEditor/codeEditorExtensions.test.ts@@ -0,0 +1,95 @@+import { indentWithTab } from "@codemirror/commands";+import { EditorState, Transaction } from "@codemirror/state";+import { describe, expect, test } from "vitest";++import { codeEditorEditing, codeEditorKeymap, lineEndingsFor } from "./codeEditorExtensions";+import { getValueSync, isCrlfText } from "./getChangedRange";++const createState = (doc: string, extensions = [codeEditorEditing]) =>+ EditorState.create({ doc, extensions: [...extensions, lineEndingsFor(doc)] });++const runTab = (state: EditorState, readOnly = false) => {+ let next = state;+ const target = readOnly+ ? EditorState.create({+ doc: state.doc,+ selection: state.selection,+ extensions: [codeEditorEditing, EditorState.readOnly.of(true)]+ })+ : state;+ const handled = indentWithTab.run!({+ state: target,+ dispatch: (tr: Transaction) => {+ next = tr.state;+ }+ } as never);+ return { handled, text: next.sliceDoc() };+};++describe("CRLF files", () => {+ const crlf = "---\r\nname: a\r\n---\r\n\r\nline one\r\nline two\r\n";++ test("a one-line edit keeps every other line ending", () => {+ const state = createState(crlf);+ expect(state.doc.lines).toBe(7);+ const at = state.doc.toString().indexOf("line one") + "line one".length;+ const typed = state.update({ changes: { from: at, insert: "X" } }).state;+ expect(typed.sliceDoc()).toBe(crlf.replace("line one", "line oneX"));++ const enter = typed.update({ changes: { from: at, insert: typed.lineBreak } }).state;+ expect(enter.sliceDoc()).toBe(crlf.replace("line one", "line one\r\nX"));+ });++ test("an outside change to one line is applied as that line only", () => {+ const state = createState(crlf);+ const next = crlf.replace("line two", "line two edited");+ const sync = getValueSync(state, next);+ expect(sync).toEqual({+ from: state.doc.toString().indexOf("line two") + 8,+ to: state.doc.toString().indexOf("line two") + 8,+ insert: " edited"+ });+ const synced = state.update({ changes: sync as Exclude<typeof sync, "replace" | null> }).state;+ expect(synced.sliceDoc()).toBe(next);+ expect(getValueSync(synced, next)).toBeNull();+ });++ test("a mixed file keeps today's handling, without merging its \\n lines", () => {+ const mixed = "a\r\nb\nc\r\n";+ expect(isCrlfText(mixed)).toBe(false);+ const state = createState(mixed);+ expect(state.lineBreak).toBe("\n");+ expect(state.doc.lines).toBe(4);+ expect(getValueSync(state, mixed)).toBeNull();+ });++ test("an LF file is unchanged", () => {+ const state = createState("a\nb\n");+ expect(state.lineBreak).toBe("\n");+ const typed = state.update({ changes: { from: 1, insert: "X" } }).state;+ expect(typed.sliceDoc()).toBe("aX\nb\n");+ });++ test("a value whose line endings change needs a new state", () => {+ expect(getValueSync(createState("a\nb\n"), "a\r\nb\r\n")).toBe("replace");+ expect(getValueSync(createState("a\r\nb\r\n"), "a\nb\n")).toBe("replace");+ expect(getValueSync(createState("a\r\nb\r\n"), "ab")).toEqual({ from: 1, to: 4, insert: "b" });+ });+});++describe("Tab", () => {+ test("is bound to indent", () => {+ expect(codeEditorKeymap[0]).toBe(indentWithTab);+ });++ test("indents with two spaces, never a tab character", () => {+ const { handled, text } = runTab(createState("a\nb"));+ expect(handled).toBe(true);+ expect(text).toBe(" a\nb");+ expect(text).not.toContain("\t");+ });++ test("does nothing in a read-only editor, so the focus can move on", () => {+ expect(runTab(createState("a"), true).handled).toBe(false);+ });+});diff --git a/frontend/src/components/v3/generic/CodeEditor/codeEditorExtensions.ts b/frontend/src/components/v3/generic/CodeEditor/codeEditorExtensions.tsnew file mode 100644index 0000000000..9dc7f42aed--- /dev/null+++ b/frontend/src/components/v3/generic/CodeEditor/codeEditorExtensions.ts@@ -0,0 +1,23 @@+import { defaultKeymap, historyKeymap, indentWithTab } from "@codemirror/commands";+import { indentUnit } from "@codemirror/language";+import { EditorState } from "@codemirror/state";+import { EditorView, keymap } from "@codemirror/view";++import { isCrlfText } from "./getChangedRange";++// Tab indents rather than moving the focus; a read-only editor refuses the indent, so Tab still moves on there.+export const codeEditorKeymap = [indentWithTab, ...historyKeymap, ...defaultKeymap];++export const codeEditorEditing = [indentUnit.of(" "), keymap.of(codeEditorKeymap)];++/**+ * Keeps a CRLF file's line endings: lines are joined with \r\n, Enter inserts one, and pasted text is converted to+ * them, so typing one character doesn't rewrite every line ending in the file.+ */+export const lineEndingsFor = (value: string) =>+ isCrlfText(value)+ ? [+ EditorState.lineSeparator.of("\r\n"),+ EditorView.clipboardInputFilter.of((text) => text.replace(/\r\n?|\n/g, "\r\n"))+ ]+ : [];diff --git a/frontend/src/components/v3/generic/CodeEditor/getChangedRange.test.ts b/frontend/src/components/v3/generic/CodeEditor/getChangedRange.test.tsnew file mode 100644index 0000000000..eca9f833b5--- /dev/null+++ b/frontend/src/components/v3/generic/CodeEditor/getChangedRange.test.ts@@ -0,0 +1,76 @@+import { history, undo } from "@codemirror/commands";+import { EditorState, Transaction } from "@codemirror/state";+import { describe, expect, test } from "vitest";++import { getChangedRange, toEditorText } from "./getChangedRange";++const createView = (doc: string) => {+ const view = { state: EditorState.create({ doc, extensions: [history()] }) };+ return {+ view,+ edit: (from: number, to: number, insert = "") => {+ view.state = view.state.update({ changes: { from, to, insert } }).state;+ },+ syncFromOutside: (value: string) => {+ const text = toEditorText(value);+ if (view.state.doc.toString() === text) return undefined;+ const changes = getChangedRange(view.state.doc.toString(), text);+ view.state = view.state.update({+ changes,+ annotations: Transaction.addToHistory.of(false)+ }).state;+ return changes;+ },+ undo: () =>+ undo({+ state: view.state,+ dispatch: (tr) => {+ view.state = tr.state;+ }+ })+ };+};++describe("getChangedRange", () => {+ test("covers only the text between the common prefix and suffix", () => {+ expect(getChangedRange("name: a\nbody", "name: abc\nbody")).toEqual({+ from: 7,+ to: 7,+ insert: "bc"+ });+ expect(getChangedRange("abc", "abc")).toEqual({ from: 3, to: 3, insert: "" });+ expect(getChangedRange("", "new")).toEqual({ from: 0, to: 0, insert: "new" });+ expect(getChangedRange("old", "")).toEqual({ from: 0, to: 3, insert: "" });+ expect(getChangedRange("aaa", "aa")).toEqual({ from: 2, to: 3, insert: "" });+ });++ test("keeps undo of typed text in place after the header is changed from outside", () => {+ const doc = "---\nname: a\ndescription: d\n---\n\n# Title\nbody";+ const editor = createView(doc);+ const end = doc.indexOf("body") + 4;+ editor.edit(end, end, " TYPED");++ editor.syncFromOutside(editor.view.state.doc.toString().replace("name: a", "name: abc"));+ editor.undo();++ expect(editor.view.state.doc.toString()).toBe(doc.replace("name: a", "name: abc"));+ });++ test("syncs a Windows (CRLF) file without adding lines, and an edit to one line as that line only", () => {+ const value = "---\r\nname: a\r\n---\r\n\r\nline one\r\nline two\r\n";+ const editor = createView(value);++ expect(editor.syncFromOutside(value)).toBeUndefined();+ expect(editor.view.state.doc.lines).toBe(7);+ expect(editor.view.state.doc.toString()).toBe(toEditorText(value));++ expect(editor.syncFromOutside(value.replace("line one", "line one edited"))).toEqual({+ from: toEditorText(value).indexOf("line one") + 8,+ to: toEditorText(value).indexOf("line one") + 8,+ insert: " edited"+ });+ expect(editor.view.state.doc.toString()).toBe(+ "---\nname: a\n---\n\nline one edited\nline two\n"+ );+ });+});diff --git a/frontend/src/components/v3/generic/CodeEditor/getChangedRange.ts b/frontend/src/components/v3/generic/CodeEditor/getChangedRange.tsnew file mode 100644index 0000000000..b58c1e7abf--- /dev/null+++ b/frontend/src/components/v3/generic/CodeEditor/getChangedRange.ts@@ -0,0 +1,35 @@+import { EditorState } from "@codemirror/state";++/** The smallest single replacement that turns `current` into `next`: the text between their common prefix and suffix. */+export const getChangedRange = (current: string, next: string) => {+ const max = Math.min(current.length, next.length);+ let start = 0;+ while (start < max && current[start] === next[start]) start += 1;+ let end = 0;+ while (end < max - start && current[current.length - 1 - end] === next[next.length - 1 - end])+ end += 1;+ return { from: start, to: current.length - end, insert: next.slice(start, next.length - end) };+};++// CodeMirror splits lines on \r\n and \r as well and its document joins them with \n, so a value is compared in that form.+export const toEditorText = (value: string) => value.replace(/\r\n?/g, "\n");++const LONE_LINE_BREAK_RE = /\r(?!\n)|(?<!\r)\n/;++/** A value whose every line break is \r\n, such as a file written on Windows. */+export const isCrlfText = (value: string) =>+ value.includes("\r\n") && !LONE_LINE_BREAK_RE.test(value);++/**+ * The change that brings an editor showing `state` to `value`, null when it already shows it, or "replace" when the+ * value's line endings don't fit the ones the state was made for, so it needs a new state.+ */+export const getValueSync = (state: EditorState, value: string) => {+ const isCrlfState = state.lineBreak === "\r\n";+ // A CRLF file edited down to one line keeps its state, so its undo history survives.+ if (isCrlfState ? LONE_LINE_BREAK_RE.test(value) : isCrlfText(value)) return "replace" as const;+ if (state.sliceDoc() === (isCrlfState ? value : toEditorText(value))) return null;+ // Positions count each line break as one character, so the range is found on the \n form of both texts.+ const range = getChangedRange(state.doc.toString(), toEditorText(value));+ return isCrlfState ? { ...range, insert: range.insert.replace(/\n/g, "\r\n") } : range;+};diff --git a/frontend/src/components/v3/generic/CodeEditor/index.ts b/frontend/src/components/v3/generic/CodeEditor/index.tsnew file mode 100644index 0000000000..6bb8194a87--- /dev/null+++ b/frontend/src/components/v3/generic/CodeEditor/index.ts@@ -0,0 +1 @@+export * from "./CodeEditor";diff --git a/frontend/src/components/v3/generic/FileTree/FileTree.stories.tsx b/frontend/src/components/v3/generic/FileTree/FileTree.stories.tsxnew file mode 100644index 0000000000..7bc76d30a4--- /dev/null+++ b/frontend/src/components/v3/generic/FileTree/FileTree.stories.tsx@@ -0,0 +1,71 @@+import { useState } from "react";+import type { Meta, StoryObj } from "@storybook/react-vite";+import { PlusIcon, TrashIcon } from "lucide-react";++import { Button } from "../Button";+import { IconButton } from "../IconButton";+import { FileTree, type FileTreeProps } from "./FileTree";++const PATHS = [+ "README.md",+ "docs/setup.md",+ "docs/reference/api.md",+ "scripts/build.sh",+ "scripts/check.sh"+];++const SelectableTree = ({ paths, ...props }: FileTreeProps) => {+ const [selectedPath, setSelectedPath] = useState<string | null>(paths[0] ?? null);+ return (+ <FileTree {...props} paths={paths} selectedPath={selectedPath} onSelect={setSelectedPath} />+ );+};++const meta = {+ title: "Generic/FileTree",+ component: FileTree,+ parameters: { layout: "centered" },+ tags: ["autodocs"],+ render: (args) => <SelectableTree {...args} />,+ decorators: [+ (Story) => (+ <div className="h-72 w-64 rounded-md border border-border p-2">+ <Story />+ </div>+ )+ ]+} satisfies Meta<typeof FileTree>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ args: { paths: PATHS }+};++export const WithIndicators: Story = {+ args: {+ paths: PATHS,+ renderIndicator: (path) =>+ path.startsWith("scripts/") ? (+ <span aria-label="Changed" className="size-1.5 shrink-0 rounded-full bg-warning" />+ ) : null+ }+};++export const WithActionsAndFooter: Story = {+ args: {+ paths: PATHS,+ renderActions: (path) => (+ <IconButton variant="ghost" size="xs" aria-label={`Delete ${path}`}>+ <TrashIcon />+ </IconButton>+ ),+ footer: (+ <Button variant="ghost" size="xs" isFullWidth>+ <PlusIcon />+ Add File+ </Button>+ )+ }+};diff --git a/frontend/src/components/v3/generic/FileTree/FileTree.tsx b/frontend/src/components/v3/generic/FileTree/FileTree.tsxnew file mode 100644index 0000000000..dcc2ec0047--- /dev/null+++ b/frontend/src/components/v3/generic/FileTree/FileTree.tsx@@ -0,0 +1,217 @@+import { type MouseEvent, type ReactNode, useEffect, useMemo, useState } from "react";+import { ChevronRightIcon, FileTextIcon, FolderIcon, FolderOpenIcon } from "lucide-react";++import { cn } from "../../utils";+import { buildFileTree, type FileTreeNode, getAncestorFolders } from "./file-tree";++type FileTreeItemType = FileTreeNode["type"];++/** A row whose name is being typed: a new item at the top of a folder, or an existing item being renamed. */+type FileTreeInlineEdit =+ | { action: "create"; type: FileTreeItemType; parentPath: string }+ | { action: "rename"; type: FileTreeItemType; path: string };++type FileTreeProps = {+ /** Slash-separated file paths. Folders are derived from them. */+ paths: readonly string[];+ /** Folders to show even though no file is in them. */+ folders?: readonly string[];+ selectedPath?: string | null;+ onSelect?: (path: string) => void;+ /** Shown after a file's name, such as a status dot or a badge. */+ renderIndicator?: (path: string) => ReactNode;+ /** Controls for a file or folder, shown at the end of its row while the row is hovered or focused. */+ renderActions?: (path: string, type: FileTreeItemType) => ReactNode;+ onItemContextMenu?: (event: MouseEvent, path: string, type: FileTreeItemType) => void;+ /** Right-click on the tree's empty space, outside any row. */+ onBackgroundContextMenu?: (event: MouseEvent) => void;+ inlineEdit?: FileTreeInlineEdit | null;+ /** The input shown in place of the name of the row in `inlineEdit`. */+ renderInlineEdit?: () => ReactNode;+ footer?: ReactNode;+ className?: string;+ "aria-label"?: string;+};++const ROW_CLASSNAME =+ "group/file-tree-row flex h-7 min-w-0 items-center gap-1 rounded-md pr-1 text-sm text-label hover:bg-container-hover hover:text-foreground";++const INDENT_PX = 12;+const CHEVRON_PX = 18;++const getFolderPathsToOpen = (inlineEdit?: FileTreeInlineEdit | null) => {+ if (!inlineEdit) return [];+ if (inlineEdit.action === "create") {+ return inlineEdit.parentPath+ ? [...getAncestorFolders(inlineEdit.parentPath), inlineEdit.parentPath]+ : [];+ }+ return getAncestorFolders(inlineEdit.path);+};++const FileTree = ({+ paths,+ folders,+ selectedPath,+ onSelect,+ renderIndicator,+ renderActions,+ onItemContextMenu,+ onBackgroundContextMenu,+ inlineEdit,+ renderInlineEdit,+ footer,+ className,+ "aria-label": ariaLabel = "Files"+}: FileTreeProps) => {+ const tree = useMemo(() => buildFileTree(paths, folders), [paths, folders]);+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());++ const expand = (toOpen: string[]) =>+ setCollapsed((prev) =>+ toOpen.some((folder) => prev.has(folder))+ ? new Set([...prev].filter((folder) => !toOpen.includes(folder)))+ : prev+ );++ useEffect(() => {+ if (selectedPath) expand(getAncestorFolders(selectedPath));+ }, [selectedPath]);++ useEffect(() => {+ expand(getFolderPathsToOpen(inlineEdit));+ }, [inlineEdit]);++ const toggleFolder = (path: string) =>+ setCollapsed((prev) => {+ const next = new Set(prev);+ if (next.has(path)) next.delete(path);+ else next.add(path);+ return next;+ });++ const renderEditRow = (key: string, type: FileTreeItemType, depth: number) => {+ const Icon = type === "folder" ? FolderIcon : FileTextIcon;+ return (+ <li+ key={key}+ className="flex min-w-0 items-start gap-1 py-0.5 pr-1"+ style={{ paddingLeft: 4 + depth * INDENT_PX + CHEVRON_PX }}+ >+ <Icon aria-hidden className="mt-2 size-3.5 shrink-0 text-muted" />+ <div className="min-w-0 flex-1">{renderInlineEdit?.()}</div>+ </li>+ );+ };++ const renderActionSlot = (path: string, type: FileTreeItemType) => {+ const actions = renderActions?.(path, type);+ if (!actions) return null;+ return (+ <div className="flex shrink-0 items-center opacity-0 group-focus-within/file-tree-row:opacity-100 group-hover/file-tree-row:opacity-100 has-[[data-state=open]]:opacity-100">+ {actions}+ </div>+ );+ };++ const renderNodes = (nodes: FileTreeNode[], depth: number, parentPath: string): ReactNode => {+ const createRow =+ inlineEdit?.action === "create" && inlineEdit.parentPath === parentPath+ ? renderEditRow(`create:${parentPath}`, inlineEdit.type, depth)+ : null;++ const rows = nodes.map((node) => {+ const paddingLeft = 4 + depth * INDENT_PX;+ const isRenaming = inlineEdit?.action === "rename" && inlineEdit.path === node.path;+ const onContextMenu = onItemContextMenu+ ? (event: MouseEvent) => {+ event.stopPropagation();+ onItemContextMenu(event, node.path, node.type);+ }+ : undefined;++ if (node.type === "folder") {+ const isOpen = !collapsed.has(node.path);+ const children = isOpen ? renderNodes(node.children, depth + 1, node.path) : null;+ if (isRenaming) {+ return (+ <li key={`folder:${node.path}`}>+ <ul>{renderEditRow(`rename:${node.path}`, "folder", depth)}</ul>+ {children && <ul>{children}</ul>}+ </li>+ );+ }+ const Icon = isOpen ? FolderOpenIcon : FolderIcon;+ return (+ <li key={`folder:${node.path}`}>+ <div className={ROW_CLASSNAME} onContextMenu={onContextMenu}>+ <button+ type="button"+ aria-expanded={isOpen}+ onClick={() => toggleFolder(node.path)}+ className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"+ style={{ paddingLeft }}+ >+ <ChevronRightIcon+ aria-hidden+ className={cn(+ "size-3.5 shrink-0 text-muted transition-transform",+ isOpen && "rotate-90"+ )}+ />+ <Icon aria-hidden className="size-3.5 shrink-0 text-muted" />+ <span className="min-w-0 flex-1 truncate font-mono text-xs" title={node.path}>+ {node.name}+ </span>+ </button>+ {renderActionSlot(node.path, "folder")}+ </div>+ {children && <ul>{children}</ul>}+ </li>+ );+ }++ if (isRenaming) return renderEditRow(`rename:${node.path}`, "file", depth);++ const isSelected = node.path === selectedPath;+ return (+ <li+ key={`file:${node.path}`}+ className={cn(ROW_CLASSNAME, isSelected && "bg-container-hover text-foreground")}+ onContextMenu={onContextMenu}+ >+ <button+ type="button"+ aria-current={isSelected || undefined}+ onClick={() => onSelect?.(node.path)}+ className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"+ style={{ paddingLeft: paddingLeft + CHEVRON_PX }}+ >+ <FileTextIcon aria-hidden className="size-3.5 shrink-0 text-muted" />+ <span className="min-w-0 flex-1 truncate font-mono text-xs" title={node.path}>+ {node.name}+ </span>+ {renderIndicator?.(node.path)}+ </button>+ {renderActionSlot(node.path, "file")}+ </li>+ );+ });++ return createRow ? [createRow, ...rows] : rows;+ };++ return (+ <nav+ aria-label={ariaLabel}+ data-slot="file-tree"+ className={cn("flex min-h-0 min-w-0 flex-col", className)}+ onContextMenu={onBackgroundContextMenu}+ >+ <ul className="min-h-0 thin-scrollbar flex-1 overflow-y-auto">{renderNodes(tree, 0, "")}</ul>+ {footer && <div className="shrink-0 pt-1">{footer}</div>}+ </nav>+ );+};++export { FileTree, type FileTreeInlineEdit, type FileTreeItemType, type FileTreeProps };diff --git a/frontend/src/components/v3/generic/FileTree/file-tree.test.ts b/frontend/src/components/v3/generic/FileTree/file-tree.test.tsnew file mode 100644index 0000000000..fa91c23416--- /dev/null+++ b/frontend/src/components/v3/generic/FileTree/file-tree.test.ts@@ -0,0 +1,59 @@+import { describe, expect, test } from "vitest";++import { buildFileTree, getAncestorFolders } from "./file-tree";++describe("buildFileTree", () => {+ test("nests files in folders, folders first and files in the given order", () => {+ expect(+ buildFileTree(["SKILL.md", "scripts/check.sh", "docs/b.md", "docs/a.md", "README.md"])+ ).toEqual([+ {+ type: "folder",+ name: "docs",+ path: "docs",+ children: [+ { type: "file", name: "b.md", path: "docs/b.md" },+ { type: "file", name: "a.md", path: "docs/a.md" }+ ]+ },+ {+ type: "folder",+ name: "scripts",+ path: "scripts",+ children: [{ type: "file", name: "check.sh", path: "scripts/check.sh" }]+ },+ { type: "file", name: "SKILL.md", path: "SKILL.md" },+ { type: "file", name: "README.md", path: "README.md" }+ ]);+ });++ test("shares folders between deep paths", () => {+ const [folder] = buildFileTree(["a/b/one.txt", "a/two.txt", "a/b/c/three.txt"]);+ expect(folder).toMatchObject({ path: "a" });+ expect(folder.type === "folder" && folder.children.map((node) => node.path)).toEqual([+ "a/b",+ "a/two.txt"+ ]);+ });++ test("adds empty folders, nested or not", () => {+ const tree = buildFileTree(["a/one.txt"], ["a/empty", "top"]);+ expect(tree.map((node) => node.path)).toEqual(["a", "top"]);+ const [folder] = tree;+ expect(folder.type === "folder" && folder.children.map((node) => node.path)).toEqual([+ "a/empty",+ "a/one.txt"+ ]);+ });++ test("returns nothing for no paths", () => {+ expect(buildFileTree([])).toEqual([]);+ });+});++describe("getAncestorFolders", () => {+ test("lists each containing folder, outermost first", () => {+ expect(getAncestorFolders("a/b/c.txt")).toEqual(["a", "a/b"]);+ expect(getAncestorFolders("top.txt")).toEqual([]);+ });+});diff --git a/frontend/src/components/v3/generic/FileTree/file-tree.ts b/frontend/src/components/v3/generic/FileTree/file-tree.tsnew file mode 100644index 0000000000..c691617794--- /dev/null+++ b/frontend/src/components/v3/generic/FileTree/file-tree.ts@@ -0,0 +1,56 @@+export type FileTreeNode =+ | { type: "folder"; name: string; path: string; children: FileTreeNode[] }+ | { type: "file"; name: string; path: string };++type FolderNode = Extract<FileTreeNode, { type: "folder" }>;++/**+ * Turns slash-separated file paths into nested folders. Folders come first, sorted by name; files keep the order they+ * were given in. `emptyFolders` adds folders that hold no file.+ */+export const buildFileTree = (+ paths: readonly string[],+ emptyFolders: readonly string[] = []+): FileTreeNode[] => {+ const root: FolderNode = { type: "folder", name: "", path: "", children: [] };+ const folders = new Map<string, FolderNode>([["", root]]);++ const addFolders = (segments: string[]) => {+ let parent = root;+ segments.forEach((name) => {+ const folderPath = parent.path ? `${parent.path}/${name}` : name;+ let folder = folders.get(folderPath);+ if (!folder) {+ folder = { type: "folder", name, path: folderPath, children: [] };+ folders.set(folderPath, folder);+ parent.children.push(folder);+ }+ parent = folder;+ });+ return parent;+ };++ emptyFolders.forEach((path) => addFolders(path.split("/").filter(Boolean)));+ paths.forEach((path) => {+ const segments = path.split("/").filter(Boolean);+ const parent = addFolders(segments.slice(0, -1));+ const name = segments[segments.length - 1];+ if (name) parent.children.push({ type: "file", name, path });+ });++ const order = (nodes: FileTreeNode[]): FileTreeNode[] => {+ const folderNodes = nodes+ .filter((node): node is FolderNode => node.type === "folder")+ .sort((a, b) => a.name.localeCompare(b.name))+ .map((folder) => ({ ...folder, children: order(folder.children) }));+ return [...folderNodes, ...nodes.filter((node) => node.type === "file")];+ };++ return order(root.children);+};++/** The folders that contain a path, outermost first: `a/b/c.txt` gives `a` and `a/b`. */+export const getAncestorFolders = (path: string) => {+ const segments = path.split("/").filter(Boolean);+ return segments.slice(0, -1).map((_, index) => segments.slice(0, index + 1).join("/"));+};diff --git a/frontend/src/components/v3/generic/FileTree/index.ts b/frontend/src/components/v3/generic/FileTree/index.tsnew file mode 100644index 0000000000..8f5bb28c91--- /dev/null+++ b/frontend/src/components/v3/generic/FileTree/index.ts@@ -0,0 +1,2 @@+export * from "./file-tree";+export * from "./FileTree";diff --git a/frontend/src/components/v3/generic/Input/Input.stories.tsx b/frontend/src/components/v3/generic/Input/Input.stories.tsxindex c931608875..d2045a1565 100644--- a/frontend/src/components/v3/generic/Input/Input.stories.tsx+++ b/frontend/src/components/v3/generic/Input/Input.stories.tsx@@ -40,6 +40,10 @@ const meta = {control: "select",options: ["default", "outlined"]},+ size: {+ control: "select",+ options: ["default", "sm"]+ },isError: {control: "boolean"},@@ -59,6 +63,7 @@ const meta = {args: {type: "text",variant: "default",+ size: "default",placeholder: "Enter text...",isError: false,disabled: false,@@ -104,6 +109,21 @@ export const Outlined: Story = {}};+export const Small: Story = {+ args: {+ size: "sm",+ placeholder: "File name"+ },+ parameters: {+ docs: {+ description: {+ story:+ "Compact 24px input for inline editing inside dense UI, such as renaming an entry in a file tree. Use the default size in forms."+ }+ }+ }+};+export const Disabled: Story = {name: "State: Disabled",args: {diff --git a/frontend/src/components/v3/generic/Input/Input.tsx b/frontend/src/components/v3/generic/Input/Input.tsxindex 815d978453..4beb1767e9 100644--- a/frontend/src/components/v3/generic/Input/Input.tsx+++ b/frontend/src/components/v3/generic/Input/Input.tsx@@ -5,7 +5,7 @@ import { cn } from "../../utils";import { Kbd } from "../Kbd";const inputVariants = cva(- "h-9 w-full min-w-0 rounded-md border border-border bg-transparent px-2.5 text-sm text-foreground shadow-xs file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted [&[readonly]]:border-border/50 disabled:pointer-events-none disabled:border-border/50 disabled:text-foreground/50 disabled:placeholder:text-muted/50 selection:bg-foreground selection:text-background",+ "w-full min-w-0 rounded-md border border-border bg-transparent text-foreground shadow-xs file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted [&[readonly]]:border-border/50 disabled:pointer-events-none disabled:border-border/50 disabled:text-foreground/50 disabled:placeholder:text-muted/50 selection:bg-foreground selection:text-background",{variants: {variant: {@@ -13,15 +13,20 @@ const inputVariants = cva("outline-none transition-[color,box-shadow] focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-invalid:border-danger aria-invalid:ring-danger/40",outlined:"outline-1 outline-offset-4 outline-transparent transition-colors outline-solid [&:not([readonly]):not(:disabled):hover]:border-foreground/20 focus-visible:border-accent focus-visible:outline-accent/60 aria-invalid:border-danger aria-invalid:focus-visible:outline-danger/60"+ },+ size: {+ default: "h-9 px-2.5 text-sm",+ sm: "h-6 px-1.5 text-xs"}},defaultVariants: {- variant: "default"+ variant: "default",+ size: "default"}});-type InputProps = React.ComponentProps<"input"> &+type InputProps = Omit<React.ComponentProps<"input">, "size"> &VariantProps<typeof inputVariants> & {isError?: boolean;"data-1p-ignore"?: boolean;@@ -34,6 +39,7 @@ const Input = forwardRef<HTMLInputElement, InputProps>(className,type,variant = "default",+ size = "default",isError,autoComplete,"data-1p-ignore": ignorePasswordManager = !/email|password|username/i.test(@@ -67,9 +73,10 @@ const Input = forwardRef<HTMLInputElement, InputProps>(type={type}data-slot="input"data-variant={variant}+ data-size={size}autoComplete={autoComplete}data-1p-ignore={ignorePasswordManager || undefined}- className={cn(inputVariants({ variant, className }), suggestedValue && "peer pr-14")}+ className={cn(inputVariants({ variant, size, className }), suggestedValue && "peer pr-14")}aria-invalid={isError}placeholder={suggestedValue || placeholder}aria-describedby={diff --git a/frontend/src/components/v3/generic/Markdown/Markdown.stories.tsx b/frontend/src/components/v3/generic/Markdown/Markdown.stories.tsxnew file mode 100644index 0000000000..8532242273--- /dev/null+++ b/frontend/src/components/v3/generic/Markdown/Markdown.stories.tsx@@ -0,0 +1,57 @@+import type { Meta, StoryObj } from "@storybook/react-vite";++import { Markdown } from "./Markdown";++const meta = {+ title: "Generic/Markdown",+ component: Markdown,+ parameters: { layout: "centered" },+ tags: ["autodocs"],+ decorators: [+ (Story) => (+ <div className="w-[640px]">+ <Story />+ </div>+ )+ ]+} satisfies Meta<typeof Markdown>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ args: {+ children: `# Release checklist++Run these steps **before** tagging a release, and read [the guide](https://example.com) first.++## Steps++1. Update \`CHANGELOG.md\`.+2. Run the test suite:++ \`\`\`bash+ npm test+ \`\`\`++3. Open a pull request.++> Ask the owning team for review.++---++## Status++| Step | Owner | Done |+| :--- | :---- | ---: |+| Changelog | Docs | yes |+| Tests | Platform | ~~no~~ yes |++- [x] Tag the release+- [ ] Announce it++- Raw <b>HTML</b> is left out.+- Images show their alt text: +`+ }+};diff --git a/frontend/src/components/v3/generic/Markdown/Markdown.test.tsx b/frontend/src/components/v3/generic/Markdown/Markdown.test.tsxnew file mode 100644index 0000000000..d444764ddd--- /dev/null+++ b/frontend/src/components/v3/generic/Markdown/Markdown.test.tsx@@ -0,0 +1,33 @@+import assert from "node:assert/strict";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, it } from "vitest";++import { Markdown } from "./Markdown";++describe("Markdown GitHub additions", () => {+ it("renders tables", () => {+ const markup = renderToStaticMarkup(+ <Markdown>{"| Name | Size |\n| :--- | ---: |\n| a.md | 2 KB |"}</Markdown>+ );+ assert.match(markup, /<table[^>]*>/);+ assert.match(markup, /<th[^>]*>Name<\/th>/);+ assert.match(markup, /<td[^>]*text-align:right[^>]*>2 KB<\/td>/);+ });++ it("renders strikethrough", () => {+ const markup = renderToStaticMarkup(<Markdown>~~old~~ new</Markdown>);+ assert.match(markup, /<del[^>]*>old<\/del>/);+ });++ it("renders task list items as read-only checkboxes", () => {+ const markup = renderToStaticMarkup(<Markdown>{"- [x] done\n- [ ] todo"}</Markdown>);+ assert.match(markup, /role="checkbox" aria-checked="true" aria-disabled="true"/);+ assert.match(markup, /role="checkbox" aria-checked="false" aria-disabled="true"/);+ assert.ok(!markup.includes("<input"));+ });++ it("still leaves raw HTML out", () => {+ const markup = renderToStaticMarkup(<Markdown>{"<script>alert(1)</script>\n\ntext"}</Markdown>);+ assert.ok(!markup.includes("<script"));+ });+});diff --git a/frontend/src/components/v3/generic/Markdown/Markdown.tsx b/frontend/src/components/v3/generic/Markdown/Markdown.tsxnew file mode 100644index 0000000000..43262bee6b--- /dev/null+++ b/frontend/src/components/v3/generic/Markdown/Markdown.tsx@@ -0,0 +1,160 @@+import ReactMarkdown, { type Components } from "react-markdown";+import { CheckIcon } from "lucide-react";+import remarkGfm from "remark-gfm";++import { cn } from "../../utils";++type MarkdownProps = {+ /**+ * Markdown source, with GitHub's additions (tables, strikethrough, task lists, autolinks). Raw HTML in it is left+ * out, and images show their alt text rather than loading.+ */+ children: string;+ className?: string;+};++const components: Components = {+ h1: ({ node, className, children, ...props }) => (+ <h1 className={cn("mt-6 mb-3 font-alliance text-2xl first:mt-0", className)} {...props}>+ {children}+ </h1>+ ),+ h2: ({ node, className, children, ...props }) => (+ <h2 className={cn("mt-6 mb-3 font-alliance text-xl first:mt-0", className)} {...props}>+ {children}+ </h2>+ ),+ h3: ({ node, className, children, ...props }) => (+ <h3 className={cn("mt-5 mb-2 font-alliance text-lg first:mt-0", className)} {...props}>+ {children}+ </h3>+ ),+ h4: ({ node, className, children, ...props }) => (+ <h4 className={cn("mt-4 mb-2 font-alliance text-base first:mt-0", className)} {...props}>+ {children}+ </h4>+ ),+ h5: ({ node, className, children, ...props }) => (+ <h5 className={cn("mt-4 mb-2 font-alliance text-sm first:mt-0", className)} {...props}>+ {children}+ </h5>+ ),+ h6: ({ node, className, children, ...props }) => (+ <h6+ className={cn("mt-4 mb-2 font-alliance text-sm text-label first:mt-0", className)}+ {...props}+ >+ {children}+ </h6>+ ),+ p: ({ node, className, ...props }) => (+ <p className={cn("my-3 leading-relaxed first:mt-0 last:mb-0", className)} {...props} />+ ),+ a: ({ node, className, children, ...props }) => (+ <a+ className={cn("text-info underline underline-offset-4 hover:text-info/80", className)}+ target="_blank"+ rel="noopener noreferrer"+ {...props}+ >+ {children}+ </a>+ ),+ ul: ({ node, className, ...props }) => (+ <ul+ className={cn(+ "my-3 list-disc space-y-1 pl-6 [&.contains-task-list]:list-none [&.contains-task-list]:pl-1",+ className+ )}+ {...props}+ />+ ),+ ol: ({ node, className, ...props }) => (+ <ol className={cn("my-3 list-decimal space-y-1 pl-6", className)} {...props} />+ ),+ li: ({ node, className, ...props }) => (+ <li+ className={cn("leading-relaxed marker:text-muted [&.task-list-item]:list-none", className)}+ {...props}+ />+ ),+ input: ({ node, type, checked, className, ...props }) =>+ type === "checkbox" ? (+ <span+ role="checkbox"+ aria-checked={Boolean(checked)}+ aria-disabled+ className={cn(+ "mr-2 inline-flex size-3.5 translate-y-0.5 items-center justify-center rounded-[4px] border border-foreground/15 align-baseline text-foreground",+ checked && "border-foreground/25 bg-foreground/10",+ className+ )}+ >+ {checked && <CheckIcon className="size-3" />}+ </span>+ ) : (+ <input type={type} checked={checked} className={className} {...props} />+ ),+ del: ({ node, className, ...props }) => (+ <del className={cn("text-label line-through", className)} {...props} />+ ),+ table: ({ node, className, ...props }) => (+ <div className="my-3 thin-scrollbar overflow-x-auto rounded-md border border-border">+ <table className={cn("w-max min-w-full text-start text-sm", className)} {...props} />+ </div>+ ),+ thead: ({ node, className, ...props }) => (+ <thead className={cn("bg-container", className)} {...props} />+ ),+ tr: ({ node, className, ...props }) => (+ <tr className={cn("border-b border-border last:border-b-0", className)} {...props} />+ ),+ th: ({ node, className, ...props }) => (+ <th+ className={cn("px-3 py-2 text-start align-bottom text-xs font-medium text-accent", className)}+ {...props}+ />+ ),+ td: ({ node, className, ...props }) => (+ <td className={cn("px-3 py-2 align-top", className)} {...props} />+ ),+ blockquote: ({ node, className, ...props }) => (+ <blockquote+ className={cn("my-3 border-l-2 border-border pl-4 text-label italic", className)}+ {...props}+ />+ ),+ hr: ({ node, className, ...props }) => (+ <hr className={cn("my-6 border-border", className)} {...props} />+ ),+ pre: ({ node, className, ...props }) => (+ <pre+ className={cn(+ "my-3 thin-scrollbar overflow-x-auto rounded-md border border-border bg-container p-3 font-mono text-xs leading-relaxed [&>code]:bg-transparent [&>code]:p-0",+ className+ )}+ {...props}+ />+ ),+ code: ({ node, className, ...props }) => (+ <code+ className={cn("rounded-sm bg-container px-1 py-0.5 font-mono text-[0.85em]", className)}+ {...props}+ />+ ),+ img: ({ alt, src }) => (+ <span className="text-muted" title={typeof src === "string" ? src : undefined}>+ [{alt || "image"}]+ </span>+ )+};++const Markdown = ({ children, className }: MarkdownProps) => (+ <div data-slot="markdown" className={cn("min-w-0 text-sm text-foreground", className)}>+ <ReactMarkdown components={components} remarkPlugins={[remarkGfm]} skipHtml>+ {children}+ </ReactMarkdown>+ </div>+);++export { Markdown, type MarkdownProps };diff --git a/frontend/src/components/v3/generic/Markdown/index.ts b/frontend/src/components/v3/generic/Markdown/index.tsnew file mode 100644index 0000000000..3306b09006--- /dev/null+++ b/frontend/src/components/v3/generic/Markdown/index.ts@@ -0,0 +1 @@+export * from "./Markdown";diff --git a/frontend/src/components/v3/generic/index.ts b/frontend/src/components/v3/generic/index.tsindex d7fa050ce3..89bb0f7dfd 100644--- a/frontend/src/components/v3/generic/index.ts+++ b/frontend/src/components/v3/generic/index.ts@@ -12,6 +12,7 @@ export * from "./Card";export * from "./Checkbox";export * from "./Code";export * from "./CodeBlock";+// CodeMirror stays out of the shared v3 chunk that every page preloads; import it from ./CodeEditor directly.export * from "./ColorPicker";export * from "./Combobox";export * from "./Command";@@ -24,6 +25,7 @@ export * from "./DurationInput";export * from "./Empty";export * from "./Field";export * from "./FileDropzone";+export * from "./FileTree";export * from "./HoverCard";export * from "./IconButton";export * from "./Input";@@ -32,6 +34,7 @@ export * from "./Item";export * from "./Kbd";export * from "./Label";export * from "./Loader";+export * from "./Markdown";export * from "./Pagination";export * from "./Popover";export * from "./RadioGroup";diff --git a/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts b/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.tsindex 7f7ad442e7..609d618b5e 100644--- a/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts+++ b/frontend/src/components/v3/platform/ProjectPermissionSubjects/ProjectPermissionSubjects.ts@@ -1,6 +1,7 @@import {BarChart3Icon,BellIcon,+ BookOpenTextIcon,BoxIcon,CableIcon,ChevronsLeftRightEllipsisIcon,@@ -231,7 +232,8 @@ export const PROJECT_PERMISSION_SUBJECT_PRESENTATION = {[ProjectPermissionSub.SecretScanningConfigs]: scanning(SlidersHorizontalIcon),[ProjectPermissionSub.AgentVaultAccessBundles]: agentVault(PackageIcon),[ProjectPermissionSub.AgentVaultSessions]: agentVault(TicketIcon),- [ProjectPermissionSub.AgentVaultProxies]: agentVault(RouteIcon)+ [ProjectPermissionSub.AgentVaultProxies]: agentVault(RouteIcon),+ [ProjectPermissionSub.AgentVaultSkills]: agentVault(BookOpenTextIcon)} as const satisfies Record<ProjectPermissionSub, ProjectPermissionSubjectPresentation>;export const getProjectPermissionSubjectPresentation = (diff --git a/frontend/src/context/ProjectPermissionContext/index.tsx b/frontend/src/context/ProjectPermissionContext/index.tsxindex 106d5b7f61..b1d7b2c123 100644--- a/frontend/src/context/ProjectPermissionContext/index.tsx+++ b/frontend/src/context/ProjectPermissionContext/index.tsx@@ -5,6 +5,7 @@ export {ProjectPermissionAgentVaultAccessBundleActions,ProjectPermissionAgentVaultProxyActions,ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionAgentVaultSkillActions,ProjectPermissionAuditLogsActions,ProjectPermissionCertificateActions,ProjectPermissionCertificateAuthorityActions,diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.tsindex dbc51c1202..b18fc1b5c7 100644--- a/frontend/src/context/ProjectPermissionContext/types.ts+++ b/frontend/src/context/ProjectPermissionContext/types.ts@@ -306,6 +306,13 @@ export enum ProjectPermissionAgentVaultAccessBundleActions {ManageMembers = "manage-members"}+export enum ProjectPermissionAgentVaultSkillActions {+ Read = "read",+ Create = "create",+ Edit = "edit",+ Delete = "delete"+}+export enum ProjectPermissionAgentVaultSessionActions {Read = "read",Create = "create",@@ -478,6 +485,7 @@ export enum ProjectPermissionSub {AgentVaultAccessBundles = "agent-vault-access-bundles",AgentVaultSessions = "agent-vault-sessions",AgentVaultProxies = "agent-vault-proxies",+ AgentVaultSkills = "agent-vault-skills",ApprovalRequests = "approval-requests",ApprovalRequestGrants = "approval-request-grants",ProjectFolderGrant = "project-folder-grant",@@ -762,6 +770,7 @@ export type ProjectPermissionSet =| [ProjectPermissionAgentVaultAccessBundleActions, ProjectPermissionSub.AgentVaultAccessBundles]| [ProjectPermissionAgentVaultSessionActions, ProjectPermissionSub.AgentVaultSessions]| [ProjectPermissionAgentVaultProxyActions, ProjectPermissionSub.AgentVaultProxies]+ | [ProjectPermissionAgentVaultSkillActions, ProjectPermissionSub.AgentVaultSkills]| [ProjectPermissionProjectFolderGrantActions,(diff --git a/frontend/src/context/index.tsx b/frontend/src/context/index.tsxindex c9023e1936..ee16aa646f 100644--- a/frontend/src/context/index.tsx+++ b/frontend/src/context/index.tsx@@ -21,6 +21,7 @@ export {ProjectPermissionAgentVaultAccessBundleActions,ProjectPermissionAgentVaultProxyActions,ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionAgentVaultSkillActions,ProjectPermissionAuditLogsActions,ProjectPermissionCertificateActions,ProjectPermissionCertificateAuthorityActions,diff --git a/frontend/src/helpers/agentVaultSkills.test.ts b/frontend/src/helpers/agentVaultSkills.test.tsnew file mode 100644index 0000000000..f89719eda6--- /dev/null+++ b/frontend/src/helpers/agentVaultSkills.test.ts@@ -0,0 +1,803 @@+import { strToU8, unzipSync, zipSync } from "fflate";+import { describe, expect, test } from "vitest";++import {+ buildDiffRows,+ buildSkillZip,+ bytesToBase64,+ carrySkillFileModes,+ countLineChanges,+ decodeSkillFile,+ formatSkillHeaderValue,+ fromDraftFiles,+ getChangedSkillPaths,+ getReservedSkillNameMessage,+ getSkillBaseName,+ getSkillEntryNameError,+ getSkillFileChanges,+ getSkillFolders,+ getSkillHeaderError,+ getSkillHeaderText,+ getSkillParentPath,+ getSkillPathError,+ isReservedSkillName,+ joinSkillPath,+ newDraftFile,+ normalizeSkillPath,+ parseSkillHeader,+ readSkillUpload,+ removeSkillPath,+ renameSkillFolders,+ renameSkillPaths,+ replaceSkillEntryFile,+ setSkillHeaderValue,+ SkillPackageError,+ sortSkillFiles,+ splitFrontmatter,+ toDraftFiles,+ toSkillFile+} from "./agentVaultSkills";++const zipFile = (entries: Record<string, Uint8Array>, name = "skill.zip") =>+ new File([zipSync(entries)], name);++const decoded = (files: Awaited<ReturnType<typeof readSkillUpload>>) =>+ Object.fromEntries(files.map((file) => [file.path, decodeSkillFile(file)]));++describe("readSkillUpload", () => {+ test("turns a single Markdown file into SKILL.md", async () => {+ const files = await readSkillUpload(new File(["# Review"], "review.md"));+ expect(decoded(files)).toEqual({ "SKILL.md": "# Review" });+ });++ test("strips a single top-level folder and archive noise", async () => {+ const files = await readSkillUpload(+ zipFile({+ "code-review/SKILL.md": strToU8("---\nname: code-review\n---"),+ "code-review/scripts/run.sh": strToU8("echo hi"),+ "code-review/.DS_Store": strToU8("x"),+ "__MACOSX/code-review/._SKILL.md": strToU8("x")+ })+ );+ expect(sortSkillFiles(files).map((file) => file.path)).toEqual(["SKILL.md", "scripts/run.sh"]);+ });++ test("skips hidden files and folders", async () => {+ const files = await readSkillUpload(+ zipFile({+ "code-review/SKILL.md": strToU8("a"),+ "code-review/.env": strToU8("x"),+ "code-review/.git/config": strToU8("x"),+ "code-review/docs/.notes/a.md": strToU8("x"),+ "code-review/docs/guide.md": strToU8("b")+ })+ );+ expect(sortSkillFiles(files).map((file) => file.path)).toEqual(["SKILL.md", "docs/guide.md"]);+ });++ test("keeps paths when the files are at the archive root", async () => {+ const files = await readSkillUpload(+ zipFile({ "SKILL.md": strToU8("a"), "docs/guide.md": strToU8("b") })+ );+ expect(sortSkillFiles(files).map((file) => file.path)).toEqual(["SKILL.md", "docs/guide.md"]);+ });++ test("reads Windows-style backslash paths as folders", async () => {+ const files = await readSkillUpload(+ zipFile({+ "review\\SKILL.md": strToU8("a"),+ "review\\scripts\\run.sh": strToU8("b")+ })+ );+ expect(sortSkillFiles(files).map((file) => file.path)).toEqual(["SKILL.md", "scripts/run.sh"]);+ });++ test("reads UTF-8 names from a macOS zip that doesn't flag them as UTF-8", async () => {+ const archive = zipSync({+ "café/SKILL.md": strToU8("a"),+ "café/docs/日本語.md": strToU8("b"),+ "café/Ünïcödé 🎉.txt": strToU8("c")+ });+ // Clears the UTF-8 flag (bit 11) in each local and central header, as macOS's zip and Finder write them.+ const view = new DataView(archive.buffer);+ const clearUtf8Flag = (offset: number) => {+ const flags = view.getUint16(offset, true);+ if (Math.floor(flags / 0x800) % 2 === 1) view.setUint16(offset, flags - 0x800, true);+ };+ for (let i = 0; i + 4 <= archive.length; i += 1) {+ const signature = view.getUint32(i, true);+ if (signature === 0x04034b50) clearUtf8Flag(i + 6);+ if (signature === 0x02014b50) clearUtf8Flag(i + 8);+ }+ const files = await readSkillUpload(new File([archive], "skill.zip"));+ expect(sortSkillFiles(files).map((file) => file.path)).toEqual([+ "SKILL.md",+ "docs/日本語.md",+ "Ünïcödé 🎉.txt"+ ]);+ });++ test("keeps a Latin-1 name that isn't valid UTF-8", async () => {+ const archive = zipSync({ "SKILL.md": strToU8("a"), "caf\u00e9.md": strToU8("b") });+ const files = await readSkillUpload(new File([archive], "skill.zip"));+ expect(sortSkillFiles(files).map((file) => file.path)).toEqual(["SKILL.md", "caf\u00e9.md"]);+ });++ test("refuses an entry over the file limit before inflating it", async () => {+ await expect(+ readSkillUpload(zipFile({ "SKILL.md": new Uint8Array(256 * 1024 + 1) }))+ ).rejects.toThrow("File 'SKILL.md' is larger than 256 KB.");+ });++ test("refuses more than 50 files", async () => {+ const entries = Object.fromEntries(+ Array.from({ length: 51 }, (_, index) => [`f${index}.md`, strToU8("x")])+ );+ await expect(readSkillUpload(zipFile(entries))).rejects.toThrow(+ "A skill can hold at most 50 files."+ );+ });++ test("explains a file that is not a zip", async () => {+ await expect(readSkillUpload(new File(["nope"], "skill.zip"))).rejects.toBeInstanceOf(+ SkillPackageError+ );+ await expect(readSkillUpload(new File(["x"], "skill.txt"))).rejects.toThrow(+ "Upload a .zip of the skill's folder, or a single .md file."+ );+ });+});++describe("formatSkillHeaderValue", () => {+ test("writes a value plain when YAML reads it back as the same string", () => {+ expect(formatSkillHeaderValue("code-review")).toBe("code-review");+ expect(formatSkillHeaderValue("Reviews code. Use when asked.")).toBe(+ "Reviews code. Use when asked."+ );+ });++ test("quotes values YAML would read as something else", () => {+ expect(formatSkillHeaderValue("12")).toBe('"12"');+ expect(formatSkillHeaderValue("1e5")).toBe('"1e5"');+ expect(formatSkillHeaderValue("true")).toBe('"true"');+ expect(formatSkillHeaderValue("null")).toBe('"null"');+ expect(formatSkillHeaderValue("")).toBe('""');+ expect(formatSkillHeaderValue("Use when: reviewing")).toBe('"Use when: reviewing"');+ expect(formatSkillHeaderValue("a # not a comment")).toBe('"a # not a comment"');+ expect(formatSkillHeaderValue("'quoted'")).toBe("\"'quoted'\"");+ expect(formatSkillHeaderValue(" padded ")).toBe('" padded "');+ });++ test("quotes words YAML 1.1 reads as booleans or null", () => {+ ["yes", "no", "on", "off", "y", "N", "True", "NULL", "~"].forEach((value) =>+ expect(formatSkillHeaderValue(value)).toBe(`"${value}"`)+ );+ expect(formatSkillHeaderValue("yesterday")).toBe("yesterday");+ });+});++describe("setSkillHeaderValue", () => {+ test("rewrites only the key's value and keeps every other header key and the body", () => {+ const text = "---\nname: old\nlicense: MIT\ndescription: Old.\n---\n\n# Steps\n";+ expect(setSkillHeaderValue(text, "name", "new-name")).toBe(+ "---\nname: new-name\nlicense: MIT\ndescription: Old.\n---\n\n# Steps\n"+ );+ });++ test("replaces a value written over several lines", () => {+ const text = "---\ndescription: >\n First line\n\n second line\nname: a\n---\nBody\n";+ expect(setSkillHeaderValue(text, "description", "New.")).toBe(+ "---\ndescription: New.\nname: a\n---\nBody\n"+ );+ });++ test("adds a missing key, and a header when there is none", () => {+ expect(setSkillHeaderValue("---\nname: a\n---\nBody", "description", "true")).toBe(+ '---\nname: a\ndescription: "true"\n---\nBody'+ );+ expect(setSkillHeaderValue("---\n---\nBody", "name", "a")).toBe("---\nname: a\n---\nBody");+ expect(setSkillHeaderValue("Body", "name", "a")).toBe("---\nname: a\n---\n\nBody");+ });++ test("rewrites a quoted key instead of adding a second one", () => {+ expect(setSkillHeaderValue('---\n"name": a\n---\nBody', "name", "b")).toBe(+ "---\nname: b\n---\nBody"+ );+ expect(setSkillHeaderValue("---\n'name' : a\n---\nBody", "name", "b")).toBe(+ "---\nname: b\n---\nBody"+ );+ });++ test("keeps a double-quoted value quoted", () => {+ expect(setSkillHeaderValue("---\ndescription: Hi\n---\n", "description", "Hi ")).toBe(+ '---\ndescription: "Hi "\n---\n'+ );+ expect(setSkillHeaderValue('---\ndescription: "Hi "\n---\n', "description", "Hi t")).toBe(+ '---\ndescription: "Hi t"\n---\n'+ );+ });++ test("keeps Windows line endings", () => {+ expect(setSkillHeaderValue("---\r\nname: a\r\nx: 1\r\n---\r\nBody", "name", "b")).toBe(+ "---\r\nname: b\r\nx: 1\r\n---\r\nBody"+ );+ });++ test("reads back as the value it was given", () => {+ ["12", 'Says "hi" # twice', "a: b", "line\nbreak"].forEach((value) => {+ const { frontmatter } = splitFrontmatter(setSkillHeaderValue("", "description", value));+ expect(parseSkillHeader(frontmatter ?? "")?.description).toBe(value);+ });+ });+});++describe("isReservedSkillName", () => {+ test("refuses Windows device names", () => {+ ["con", "prn", "aux", "nul", "com1", "com9", "lpt1", "lpt9"].forEach((name) =>+ expect(isReservedSkillName(name)).toBe(true)+ );+ ["console", "com0", "aux-tools", "code-review"].forEach((name) =>+ expect(isReservedSkillName(name)).toBe(false)+ );+ expect(getReservedSkillNameMessage("aux")).toBe(+ "'aux' is a reserved name and can't be used as a skill name."+ );+ });+});++describe("fromDraftFiles", () => {+ test("keeps the original bytes of a file whose text is unchanged", () => {+ const withBom = new Uint8Array([0xef, 0xbb, 0xbf, ...new TextEncoder().encode("# Hi\n")]);+ const [draft] = toDraftFiles([+ { path: "SKILL.md", mode: "0644", contentBase64: bytesToBase64(withBom) }+ ]);+ expect(draft.text).toBe("# Hi\n");+ expect(fromDraftFiles([draft])[0].contentBase64).toBe(bytesToBase64(withBom));+ });++ test("re-encodes a file whose text changed, and keeps its mode", () => {+ const [draft] = toDraftFiles([+ { path: "run.sh", mode: "0755", contentBase64: bytesToBase64(strToU8("echo a\n")) }+ ]);+ expect(fromDraftFiles([{ ...draft, text: "echo b\n" }])).toEqual([+ { path: "run.sh", mode: "0755", contentBase64: bytesToBase64(strToU8("echo b\n")) }+ ]);+ });+});++describe("normalizeSkillPath", () => {+ test("uses forward slashes and drops leading ./ and /", () => {+ expect(normalizeSkillPath(" ./scripts\\check.sh ")).toBe("scripts/check.sh");+ expect(normalizeSkillPath("/docs//guide.md")).toBe("docs/guide.md");+ });+});++describe("getSkillPathError", () => {+ test("accepts ordinary relative paths", () => {+ expect(getSkillPathError("SKILL.md")).toBeNull();+ expect(getSkillPathError("scripts/check.sh")).toBeNull();+ expect(getSkillPathError("docs/.env.example")).toBeNull();+ expect(getSkillPathError("CONSOLE.md")).toBeNull();+ });++ test("refuses what the server refuses", () => {+ expect(getSkillPathError("")).toBe("Enter a name.");+ expect(getSkillPathError("a\\b")).toBe("A name can't contain a backslash.");+ expect(getSkillPathError("a\u0001b")).toBe("A name can't contain control characters.");+ expect(getSkillPathError("a\uD800")).toBe("A name must be valid Unicode text.");+ expect(getSkillPathError("/abs")).toBe("A name can't be empty, '.' or '..'.");+ expect(getSkillPathError("a//b")).toBe("A name can't be empty, '.' or '..'.");+ expect(getSkillPathError("../x")).toBe("A name can't be empty, '.' or '..'.");+ ["a:b", "a<b", "a>b", 'a"b', "a|b", "a?b", "a*b"].forEach((path) =>+ expect(getSkillPathError(path)).toMatch(/can't contain any of/)+ );+ expect(getSkillPathError("docs./a.md")).toBe("'docs.' can't end in a dot or a space.");+ expect(getSkillPathError("a /b")).toMatch(/can't end in a dot or a space/);+ });++ test("limits each file or folder name to 255 UTF-8 bytes", () => {+ expect(getSkillPathError("é".repeat(127))).toBeNull();+ const long = "é".repeat(128);+ expect(getSkillPathError(`docs/${long}`)).toBe(+ `File name '${long.slice(0, 64)}…' in 'docs/${long}' is too long. Shorten it.`+ );+ });++ test("refuses Windows device names with or without an extension", () => {+ ["CON", "prn", "Aux.txt", "nul.tar.gz", "COM1", "lpt9.md", "scripts/com3"].forEach((path) =>+ expect(getSkillPathError(path)).toMatch(/is a reserved name/)+ );+ expect(getSkillPathError("COM0")).toBeNull();+ expect(getSkillPathError("LPT10")).toBeNull();+ });++ test("refuses paths longer than 255 characters", () => {+ expect(getSkillPathError("a".repeat(255))).toBeNull();+ expect(getSkillPathError("a".repeat(256))).toMatch(/at most 255 characters/);+ });+});++describe("getSkillEntryNameError", () => {+ const filePaths = ["SKILL.md", "docs/guide.md", "scripts/run.sh"];+ const folderPaths = getSkillFolders(filePaths, ["empty"]);+ const check = (name: string, parentPath = "", renamingPath?: string) =>+ getSkillEntryNameError({ name, parentPath, filePaths, folderPaths, renamingPath });++ test("accepts a new name in the root or a folder", () => {+ expect(check("README.md")).toBeNull();+ expect(check("other.md", "docs")).toBeNull();+ expect(check("nested", "empty")).toBeNull();+ });++ test("refuses slashes, since folders are made one at a time", () => {+ expect(check("a/b.md")).toMatch(/can't contain '\/'/);+ });++ test("refuses a name already used, ignoring case and Unicode form", () => {+ expect(check("skill.md")).toBe(+ "A file named 'SKILL.md' is already here. Names must be unique ignoring case."+ );+ expect(check("guide.md", "docs")).toBe("A file named 'guide.md' is already here.");+ expect(+ getSkillEntryNameError({+ name: "café.md",+ parentPath: "",+ filePaths: ["café.md"],+ folderPaths: []+ })+ ).toMatch(/already here/);+ });++ test("refuses a file where a folder is, and a folder where a file is", () => {+ expect(check("Docs")).toBe(+ "A folder named 'docs' is already here. Names must be unique ignoring case."+ );+ expect(check("empty")).toBe("A folder named 'empty' is already here.");+ expect(check("run.sh", "scripts")).toBe("A file named 'run.sh' is already here.");+ });++ test("lets a rename change only the case of its own name", () => {+ expect(check("Guide.md", "docs", "docs/guide.md")).toBeNull();+ expect(check("Scripts", "", "scripts")).toBeNull();+ expect(check("docs", "", "scripts")).toMatch(/already here/);+ });++ test("checks the longest path a renamed folder would give its files", () => {+ expect(check("x".repeat(250), "", "scripts")).toMatch(/longer than 255/);+ });++ test("checks the joined path against the server rules", () => {+ expect(check("nul.md", "docs")).toMatch(/is a reserved name/);+ expect(check("trailing.", "docs")).toMatch(/can't end in a dot/);+ });+});++describe("file tree edits", () => {+ const files = [+ { path: "SKILL.md" },+ { path: "docs/a.md" },+ { path: "docs/deep/b.md" },+ { path: "docsx.md" }+ ];++ test("renames a folder with everything in it, and nothing that only shares a prefix", () => {+ expect(renameSkillPaths(files, "docs", "guides").map((file) => file.path)).toEqual([+ "SKILL.md",+ "guides/a.md",+ "guides/deep/b.md",+ "docsx.md"+ ]);+ expect(renameSkillFolders(["docs", "docs/deep", "docsx"], "docs", "g")).toEqual([+ "g",+ "g/deep",+ "docsx"+ ]);+ });++ test("renames a single file", () => {+ expect(renameSkillPaths(files, "docs/a.md", "docs/c.md").map((file) => file.path)).toContain(+ "docs/c.md"+ );+ });++ test("removes a folder with everything in it", () => {+ expect(removeSkillPath(files, "docs").map((file) => file.path)).toEqual([+ "SKILL.md",+ "docsx.md"+ ]);+ expect(removeSkillPath(["docs", "docs/deep", "docsx"], "docs")).toEqual(["docsx"]);+ });++ test("lists every folder that holds a file, plus empty ones", () => {+ expect(getSkillFolders(["a/b/c.md", "d.md"], ["e"]).sort()).toEqual(["a", "a/b", "e"]);+ });++ test("splits and joins paths", () => {+ expect(joinSkillPath("", "a.md")).toBe("a.md");+ expect(joinSkillPath("docs", "a.md")).toBe("docs/a.md");+ expect(getSkillParentPath("docs/deep/b.md")).toBe("docs/deep");+ expect(getSkillParentPath("SKILL.md")).toBe("");+ expect(getSkillBaseName("docs/deep/b.md")).toBe("b.md");+ });+});++describe("parseSkillHeader", () => {+ test("reads the header as the server does", () => {+ expect(parseSkillHeader("name: code-review\ndescription: Reviews code.")).toEqual({+ name: "code-review",+ description: "Reviews code."+ });+ expect(parseSkillHeader("name: 'a'\ndescription: 'It''s fine.'\nlicense: MIT")).toEqual({+ name: "a",+ description: "It's fine.",+ license: "MIT"+ });+ expect(parseSkillHeader("name: 12\ndescription: >\n First line\n second line\n")).toEqual({+ name: 12,+ description: "First line second line\n"+ });+ expect(parseSkillHeader("")).toEqual({});+ });++ test("returns null when the header can't be read", () => {+ expect(parseSkillHeader("name: [unclosed")).toBeNull();+ expect(parseSkillHeader("- a\n- b")).toBeNull();+ expect(parseSkillHeader("just text")).toBeNull();+ });+});++describe("getSkillHeaderError", () => {+ test("names the line and key of an unquoted value with ': ', as in real skills", () => {+ expect(+ getSkillHeaderError(+ "name: audit\ndescription: Audit a large multi-repo change set for coherence: reverse-engineer what it was built to do\ndisable-model-invocation: true\nargument-hint: [repo paths and/or head ref]"+ )+ ).toBe(+ "Line 3 of SKILL.md: the 'description' value contains ': '. Put the value in double quotes."+ );+ expect(+ getSkillHeaderError(+ "name: infi\ndescription: Drive a local Infisical dev stack: print an org-scoped user JWT\nargument-hint: login | relay <name>"+ )+ ).toBe(+ "Line 3 of SKILL.md: the 'description' value contains ': '. Put the value in double quotes."+ );+ expect(+ getSkillHeaderError(+ "name: scrutinize\r\ndescription: Saif's full PR review. Verifies: every claim\r\ndisable-model-invocation: true"+ )+ ).toBe(+ "Line 3 of SKILL.md: the 'description' value contains ': '. Put the value in double quotes."+ );+ });++ test("gives the parser's reason and the line for other broken YAML", () => {+ expect(getSkillHeaderError("name: a\ndescription: d\n bad: indent")).toBe(+ "Line 4 of SKILL.md: the header is not valid YAML (bad indentation of a mapping entry)."+ );+ expect(getSkillHeaderError("name: a\r\ndescription: d\r\n bad: indent")).toBe(+ "Line 4 of SKILL.md: the header is not valid YAML (bad indentation of a mapping entry)."+ );+ });++ test.each([+ ["---\nname: a\ndescription: d\nx: 1\nhint: [x\n---\n", "opens a '[' that never closes"],+ ["---\nname: a\ndescription: d\nx: 1\nhint: {x\n---\n", "opens a '{' that never closes"],+ [+ '---\nname: a\ndescription: d\nx: 1\nhint: "x\n---\n',+ "opens a double quote that never closes"+ ],+ [+ "---\nname: a\ndescription: d\nx: 1\nhint: 'x\n---\n",+ "opens a single quote that never closes"+ ],+ ["---\nname: a\nlist: [a,\n b]\nhint: {x\n---\n", "opens a '{' that never closes"],+ [+ "---\r\nname: a\r\ndescription: d\r\nx: 1\r\nhint: [x\r\n---\r\n",+ "opens a '[' that never closes"+ ],+ ["\uFEFF---\nname: a\ndescription: d\nx: 1\nhint: [x\n---\n", "opens a '[' that never closes"]+ ])("names the line of a value that never closes in %j", (text, problem) => {+ const { frontmatter } = splitFrontmatter(new TextDecoder().decode(strToU8(text)));+ expect(getSkillHeaderError(frontmatter ?? "")).toBe(+ `Line 5 of SKILL.md: the 'hint' value ${problem}.`+ );+ });++ test.each([+ '---\ndescription: "first\nsecond"\nname: a\nname: b\n---\n',+ "---\nhint: [a,\n# note\n b]\nname: a\nname: b\n---\n"+ ])("does not blame a value that continues at column zero in %j", (text) => {+ const { frontmatter } = splitFrontmatter(text);+ expect(getSkillHeaderError(frontmatter ?? "")).toMatch(/duplicated mapping key/);+ });++ test("still names a quote left open before the next key", () => {+ const { frontmatter } = splitFrontmatter('---\nname: "oops\ndescription: y\n---\n');+ expect(getSkillHeaderError(frontmatter ?? "")).toBe(+ "Line 2 of SKILL.md: the 'name' value opens a double quote that never closes."+ );+ });++ test("returns null for a header that parses, quoted colons included", () => {+ expect(getSkillHeaderError('name: a\ndescription: "Review: then fix"')).toBeNull();+ expect(getSkillHeaderError("name: a\ndescription: >\n Review: then fix")).toBeNull();+ expect(getSkillHeaderError("")).toBeNull();+ });++ test("keeps the generic message for a header that isn't a list of key: value lines", () => {+ expect(getSkillHeaderError("- a\n- b")).toBe("The header in SKILL.md is not valid YAML.");+ });+});++describe("getSkillHeaderText", () => {+ test("shows scalars as text and anything else as empty", () => {+ expect(getSkillHeaderText("a")).toBe("a");+ expect(getSkillHeaderText(12)).toBe("12");+ expect(getSkillHeaderText(null)).toBe("");+ expect(getSkillHeaderText(undefined)).toBe("");+ });+});++describe("countLineChanges", () => {+ test("counts added and removed lines", () => {+ expect(countLineChanges("a\nb\nc\n", "a\nB\nc\nd\n")).toEqual({+ additions: 2,+ deletions: 1+ });+ expect(countLineChanges("", "one\ntwo")).toEqual({ additions: 2, deletions: 0 });+ expect(countLineChanges("same\n", "same\n")).toEqual({ additions: 0, deletions: 0 });+ });+});++describe("getSkillFileChanges", () => {+ const original = toDraftFiles([+ toSkillFile("SKILL.md", "# Skill\n"),+ { ...toSkillFile("run.sh", "echo hi\n"), mode: "0755" },+ toSkillFile("old.md", "gone\nsoon\n")+ ]);++ test("reports nothing for an untouched draft", () => {+ expect(getSkillFileChanges(original, original)).toEqual([]);+ });++ test("reports added, modified, mode-only and deleted files with line counts", () => {+ const draft = [+ { ...original[0], text: "# Skill\nMore\n" },+ original.find((file) => file.path === "run.sh")!,+ newDraftFile("notes/new.md", "a\nb\n")+ ].map((file) => (file.path === "run.sh" ? { ...file, mode: "0644" as const } : file));++ expect(+ getSkillFileChanges(original, draft).map(+ ({ path, status, additions, deletions, newMode }) => ({+ path,+ status,+ additions,+ deletions,+ newMode+ })+ )+ ).toEqual([+ { path: "SKILL.md", status: "modified", additions: 1, deletions: 0, newMode: undefined },+ { path: "run.sh", status: "modified", additions: 0, deletions: 0, newMode: "0644" },+ { path: "notes/new.md", status: "added", additions: 2, deletions: 0, newMode: "0644" },+ { path: "old.md", status: "deleted", additions: 0, deletions: 2, newMode: undefined }+ ]);+ });+});++describe("buildDiffRows", () => {+ test("numbers lines and folds long unchanged runs", () => {+ const before = `${Array.from({ length: 10 }, (_, i) => `line ${i + 1}`).join("\n")}\n`;+ const after = before.replace("line 9\n", "line nine\n");+ const rows = buildDiffRows(before, after, 2);+ expect(rows[0]).toEqual({ type: "skip", count: 6 });+ expect(rows.slice(1)).toEqual([+ { type: "context", text: "line 7", oldLine: 7, newLine: 7 },+ { type: "context", text: "line 8", oldLine: 8, newLine: 8 },+ { type: "removed", text: "line 9", oldLine: 9, newLine: null },+ { type: "added", text: "line nine", oldLine: null, newLine: 9 },+ { type: "context", text: "line 10", oldLine: 10, newLine: 10 }+ ]);+ });++ test("marks the side without a final newline when only that changed", () => {+ expect(buildDiffRows("a\nb", "a\nb\n")).toEqual([+ { type: "context", text: "a", oldLine: 1, newLine: 1 },+ { type: "removed", text: "b", oldLine: 2, newLine: null },+ { type: "context", text: "\\ No newline at end of file", oldLine: null, newLine: null },+ { type: "added", text: "b", oldLine: null, newLine: 2 }+ ]);+ expect(+ buildDiffRows("a\nb", "a\nc").some((row) => row.type === "context" && row.oldLine === null)+ ).toBe(false);+ });+});++describe("modes and SKILL.md uploads", () => {+ const previous = [+ toSkillFile("SKILL.md", "old"),+ { ...toSkillFile("scripts/run.sh", "echo"), mode: "0755" as const },+ toSkillFile("docs/a.md", "a")+ ];++ test("an uploaded archive keeps each existing path's mode", () => {+ const uploaded = [toSkillFile("SKILL.md", "new"), toSkillFile("scripts/run.sh", "echo 2")];+ expect(carrySkillFileModes(uploaded, previous).map((file) => file.mode)).toEqual([+ "0644",+ "0755"+ ]);+ });++ test("a single SKILL.md replaces only SKILL.md", () => {+ const files = replaceSkillEntryFile(previous, toSkillFile("SKILL.md", "new"));+ expect(Object.fromEntries(files.map((file) => [file.path, decodeSkillFile(file)]))).toEqual({+ "SKILL.md": "new",+ "scripts/run.sh": "echo",+ "docs/a.md": "a"+ });+ expect(files.find((file) => file.path === "scripts/run.sh")?.mode).toBe("0755");+ });++ test("a downloaded zip holds the files under the skill's folder", () => {+ const entries = unzipSync(buildSkillZip("review", previous));+ expect(Object.keys(entries).sort()).toEqual([+ "review/SKILL.md",+ "review/docs/a.md",+ "review/scripts/run.sh"+ ]);+ });++ test("a downloaded zip keeps each file's mode", () => {+ const zip = buildSkillZip("review", previous);+ const view = new DataView(zip.buffer, zip.byteOffset, zip.byteLength);+ const modes: Record<string, number> = {};+ for (let offset = 0; offset + 46 <= zip.length; offset += 1) {+ if (view.getUint32(offset, true) === 0x02014b50) {+ const nameLength = view.getUint16(offset + 28, true);+ const name = new TextDecoder().decode(zip.subarray(offset + 46, offset + 46 + nameLength));+ // eslint-disable-next-line no-bitwise+ modes[name] = (view.getUint32(offset + 38, true) >>> 16) & 0o777;+ }+ }+ expect(modes).toEqual({+ "review/SKILL.md": 0o644,+ "review/scripts/run.sh": 0o755,+ "review/docs/a.md": 0o644+ });+ });+});++describe("splitFrontmatter", () => {+ test("separates a leading YAML header from the body", () => {+ expect(splitFrontmatter("---\nname: a\n---\n\n# Body\n")).toEqual({+ frontmatter: "name: a",+ body: "\n# Body\n"+ });+ expect(splitFrontmatter("# No header")).toEqual({ frontmatter: null, body: "# No header" });+ expect(splitFrontmatter("---\n---\nBody\n---\n")).toEqual({+ frontmatter: "",+ body: "Body\n---\n"+ });+ });++ test("accepts trailing spaces after the opening marker", () => {+ expect(splitFrontmatter("--- \nname: a\n---\nBody")).toEqual({+ frontmatter: "name: a",+ body: "Body"+ });+ expect(splitFrontmatter("---\t\r\nname: a\r\n---\r\nBody")).toEqual({+ frontmatter: "name: a",+ body: "Body"+ });+ expect(setSkillHeaderValue("--- \nname: a\n---\nBody", "name", "b")).toBe(+ "--- \nname: b\n---\nBody"+ );+ });+});++describe("executable files in an uploaded zip", () => {+ test("keeps 0755 for an entry whose Unix mode has an execute bit", async () => {+ const archive = buildSkillZip("review", [+ toSkillFile("SKILL.md", "# Review"),+ { ...toSkillFile("scripts/check.sh", "echo ok"), mode: "0755" }+ ]);+ const files = await readSkillUpload(new File([archive], "review.zip"));+ expect(Object.fromEntries(files.map((file) => [file.path, file.mode]))).toEqual({+ "SKILL.md": "0644",+ "scripts/check.sh": "0755"+ });+ });++ // Browsers decode the "latin1" label as Windows-1252, so 日本語's bytes 0x80-0x9f once named a different file+ // than fflate did. Node decodes it as true Latin-1, so this guards the decoder choice rather than reproducing it.+ test("keeps 0755 for a non-Latin name in a zip that doesn't flag names as UTF-8", async () => {+ const archive = buildSkillZip("review", [+ toSkillFile("SKILL.md", "# Review"),+ { ...toSkillFile("scripts/日本語.sh", "echo ok"), mode: "0755" }+ ]);+ const view = new DataView(archive.buffer, archive.byteOffset, archive.byteLength);+ const clearUtf8Flag = (offset: number) => {+ const flags = view.getUint16(offset, true);+ if (Math.floor(flags / 0x800) % 2 === 1) view.setUint16(offset, flags - 0x800, true);+ };+ for (let i = 0; i + 4 <= archive.length; i += 1) {+ const signature = view.getUint32(i, true);+ if (signature === 0x04034b50) clearUtf8Flag(i + 6);+ if (signature === 0x02014b50) clearUtf8Flag(i + 8);+ }+ const files = await readSkillUpload(new File([archive], "review.zip"));+ expect(Object.fromEntries(files.map((file) => [file.path, file.mode]))).toEqual({+ "SKILL.md": "0644",+ "scripts/日本語.sh": "0755"+ });+ });++ test("reads 0644 when the archive carries no Unix modes", async () => {+ const files = await readSkillUpload(+ zipFile({ "SKILL.md": strToU8("# Review"), "scripts/check.sh": strToU8("echo ok") })+ );+ expect(files.map((file) => file.mode)).toEqual(["0644", "0644"]);+ });++ test("an executable entry stays executable when carrying the previous modes", () => {+ const previous = [toSkillFile("scripts/check.sh", "echo")];+ const uploaded = [{ ...toSkillFile("scripts/check.sh", "echo 2"), mode: "0755" as const }];+ expect(carrySkillFileModes(uploaded, previous)[0].mode).toBe("0755");+ });+});++describe("getChangedSkillPaths", () => {+ const base = toDraftFiles([+ toSkillFile("SKILL.md", "a"),+ toSkillFile("scripts/run.sh", "echo"),+ toSkillFile("docs/a.md", "a")+ ]);++ test("finds edited, added and mode-changed files without diffing", () => {+ const draft = [+ { ...base[0], text: "b" },+ { ...base[1] },+ { ...base[2], mode: "0755" as const },+ newDraftFile("new.md", "x")+ ];+ const { changedPaths, hasChanges } = getChangedSkillPaths(base, draft);+ expect([...changedPaths].sort()).toEqual(["SKILL.md", "new.md", "scripts/run.sh"]);+ expect(hasChanges).toBe(true);+ });++ test("counts a deleted file as a change", () => {+ const { changedPaths, hasChanges } = getChangedSkillPaths(base, base.slice(0, 2));+ expect(changedPaths.size).toBe(0);+ expect(hasChanges).toBe(true);+ });++ test("reports nothing for an unchanged draft", () => {+ expect(+ getChangedSkillPaths(+ base,+ base.map((file) => ({ ...file }))+ ).hasChanges+ ).toBe(false);+ });+});++describe("large files in the save review", () => {+ test("a modified file over 2,000 lines is not diffed", () => {+ const big = Array.from({ length: 2001 }, (_, i) => `line ${i}`).join("\n");+ const [change] = getSkillFileChanges(toDraftFiles([toSkillFile("big.txt", big)]), [+ { ...toDraftFiles([toSkillFile("big.txt", big)])[0], text: `${big}\nmore` }+ ]);+ expect(change.isTooLarge).toBe(true);+ expect([change.additions, change.deletions]).toEqual([0, 0]);+ });++ test("a small modified file is diffed", () => {+ const [change] = getSkillFileChanges(toDraftFiles([toSkillFile("a.txt", "a\n")]), [+ { ...toDraftFiles([toSkillFile("a.txt", "a\n")])[0], text: "b\n" }+ ]);+ expect(change.isTooLarge).toBe(false);+ expect([change.additions, change.deletions]).toEqual([1, 1]);+ });+});diff --git a/frontend/src/helpers/agentVaultSkills.ts b/frontend/src/helpers/agentVaultSkills.tsnew file mode 100644index 0000000000..1743e001a7--- /dev/null+++ b/frontend/src/helpers/agentVaultSkills.ts@@ -0,0 +1,840 @@+import { diffLines } from "diff";+import { strFromU8, unzipSync, zipSync } from "fflate";+import { JSON_SCHEMA, load, YAMLException } from "js-yaml";++import { TAgentVaultSkillFile, TAgentVaultSkillFileMode } from "@app/hooks/api/agentVault/types";++export const SKILL_NAME_MAX_LENGTH = 64;+export const SKILL_DESCRIPTION_MAX_LENGTH = 1024;+export const SKILL_NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;+export const SKILL_NAME_MESSAGE =+ "A skill name uses lower case letters, numbers and single hyphens, like code-review.";++export const SKILL_ENTRY_FILE = "SKILL.md";++// The server enforces these limits. They are repeated here only so an archive is never inflated past them: an entry's+// declared size bounds what fflate writes, so a small archive that would expand to gigabytes is refused unread.+const MAX_FILE_BYTES = 256 * 1024;+const MAX_TOTAL_BYTES = 1024 * 1024;+const MAX_FILES = 50;++export class SkillPackageError extends Error {}++const formatLimit = (bytes: number) =>+ bytes >= 1024 * 1024 ? `${bytes / (1024 * 1024)} MB` : `${bytes / 1024} KB`;++export const formatSkillBytes = (bytes: number) => {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+};++export const bytesToBase64 = (bytes: Uint8Array) => {+ let binary = "";+ for (let i = 0; i < bytes.length; i += 8192) {+ binary += String.fromCharCode(...bytes.subarray(i, i + 8192));+ }+ return btoa(binary);+};++export const base64ToBytes = (value: string) =>+ Uint8Array.from(atob(value), (char) => char.charCodeAt(0));++/** The file's text, or null when it is not valid UTF-8 and so can't be shown. */+export const decodeSkillFile = (file: TAgentVaultSkillFile) => {+ try {+ return new TextDecoder("utf-8", { fatal: true }).decode(base64ToBytes(file.contentBase64));+ } catch {+ return null;+ }+};++/** Uses forward slashes and drops leading `./` and `/`, as Windows archive tools and typed paths may not. */+export const normalizeSkillPath = (path: string) =>+ path+ .trim()+ .replace(/\\/g, "/")+ .replace(/\/{2,}/g, "/")+ .replace(/^(\.\/|\/)+/, "");++// Archive tools add these beside the real files, and they would stop a single top-level folder from being stripped.+// Hidden entries are skipped too, as the CLI skips them on push, so both ways publish the same files.+const isArchiveNoise = (path: string) =>+ path.startsWith("__MACOSX/") || path.split("/").some((segment) => segment.startsWith("."));++const stripSharedFolder = (paths: string[]) => {+ const [first] = paths;+ const slash = first?.indexOf("/") ?? -1;+ if (slash <= 0) return paths;+ const prefix = first.slice(0, slash + 1);+ return paths.every((path) => path.startsWith(prefix))+ ? paths.map((path) => path.slice(prefix.length))+ : paths;+};++// Archive tools on macOS write UTF-8 names without the zip flag that says so, and fflate then reads each byte as a+// Latin-1 character. A name whose characters are all bytes and which decodes as UTF-8 is read as UTF-8 instead.+const decodeZipName = (name: string) => {+ const bytes = new Uint8Array(name.length);+ for (let i = 0; i < name.length; i += 1) {+ const code = name.charCodeAt(i);+ if (code > 0xff) return name;+ bytes[i] = code;+ }+ try {+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ } catch {+ return name;+ }+};++const ZIP_END_OF_DIRECTORY = 0x06054b50;+const ZIP_DIRECTORY_ENTRY = 0x02014b50;+const ZIP_HOST_UNIX = 3;++// fflate doesn't expose an entry's external attributes, so the central directory is read here for the Unix mode bits.+// Names are decoded as fflate decodes them, so they match the names its filter sees.+const readZipExecutableNames = (data: Uint8Array) => {+ const executable = new Set<string>();+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);+ let end = data.length - 22;+ const stop = Math.max(0, end - 0xffff);+ while (end >= stop && view.getUint32(end, true) !== ZIP_END_OF_DIRECTORY) end -= 1;+ if (end < stop) return executable;++ const count = view.getUint16(end + 10, true);+ let offset = view.getUint32(end + 16, true);+ for (let i = 0; i < count; i += 1) {+ if (offset + 46 > data.length || view.getUint32(offset, true) !== ZIP_DIRECTORY_ENTRY) break;+ const host = view.getUint8(offset + 5);+ const flags = view.getUint16(offset + 8, true);+ const nameLength = view.getUint16(offset + 28, true);+ const extraLength = view.getUint16(offset + 30, true);+ const commentLength = view.getUint16(offset + 32, true);+ // The high half of the external attributes holds the Unix mode.+ const unixMode = view.getUint16(offset + 40, true);+ const nameBytes = data.subarray(offset + 46, offset + 46 + nameLength);+ // eslint-disable-next-line no-bitwise+ const name = strFromU8(nameBytes, !(flags & 0x800));+ // eslint-disable-next-line no-bitwise+ if (host === ZIP_HOST_UNIX && unixMode & 0o111) executable.add(name);+ offset += 46 + nameLength + extraLength + commentLength;+ }+ return executable;+};++const readZip = (data: Uint8Array): TAgentVaultSkillFile[] => {+ let count = 0;+ let total = 0;+ let entries: Record<string, Uint8Array>;+ const names: string[] = [];+ try {+ entries = unzipSync(data, {+ filter: ({ name: rawName, originalSize }) => {+ const name = normalizeSkillPath(decodeZipName(rawName));+ if (rawName.endsWith("/") || rawName.endsWith("\\") || isArchiveNoise(name)) return false;+ count += 1;+ total += originalSize;+ if (originalSize > MAX_FILE_BYTES) {+ throw new SkillPackageError(+ `File '${name}' is larger than ${formatLimit(MAX_FILE_BYTES)}.`+ );+ }+ if (count > MAX_FILES) {+ throw new SkillPackageError(`A skill can hold at most ${MAX_FILES} files.`);+ }+ if (total > MAX_TOTAL_BYTES) {+ throw new SkillPackageError(+ `A skill can be at most ${formatLimit(MAX_TOTAL_BYTES)} in total.`+ );+ }+ names.push(rawName);+ return true;+ }+ });+ } catch (error) {+ if (error instanceof SkillPackageError) throw error;+ throw new SkillPackageError("This file is not a valid zip archive.");+ }++ if (names.length === 0) throw new SkillPackageError("This archive holds no files.");+ const paths = stripSharedFolder(names.map((name) => normalizeSkillPath(decodeZipName(name))));++ const executable = readZipExecutableNames(data);++ return names.map((name, index) => ({+ path: paths[index],+ mode: executable.has(name) ? ("0755" as const) : ("0644" as const),+ contentBase64: bytesToBase64(entries[name])+ }));+};++/** SKILL.md first, then the rest by path, as the skill's files are listed. */+export const sortSkillFiles = <T extends { path: string }>(files: T[]) =>+ [...files].sort((a, b) => {+ if (a.path === SKILL_ENTRY_FILE) return -1;+ if (b.path === SKILL_ENTRY_FILE) return 1;+ return a.path.localeCompare(b.path);+ });++/**+ * Reads an uploaded skill: a zip of the skill's folder, or a single Markdown file that becomes its SKILL.md. Only+ * the archive's size is checked here; the server validates everything else and its message is shown as is.+ */+export const readSkillUpload = async (file: File): Promise<TAgentVaultSkillFile[]> => {+ const name = file.name.toLowerCase();++ if (name.endsWith(".md")) {+ if (file.size > MAX_FILE_BYTES) {+ throw new SkillPackageError(+ `File '${file.name}' is larger than ${formatLimit(MAX_FILE_BYTES)}.`+ );+ }+ return [+ {+ path: SKILL_ENTRY_FILE,+ mode: "0644",+ contentBase64: bytesToBase64(new Uint8Array(await file.arrayBuffer()))+ }+ ];+ }++ if (name.endsWith(".zip")) {+ // Stored entries make a zip slightly larger than its files, never by more than the headers.+ if (file.size > MAX_TOTAL_BYTES + 64 * 1024) {+ throw new SkillPackageError(+ `A skill can be at most ${formatLimit(MAX_TOTAL_BYTES)} in total.`+ );+ }+ return readZip(new Uint8Array(await file.arrayBuffer()));+ }++ throw new SkillPackageError("Upload a .zip of the skill's folder, or a single .md file.");+};++export const toSkillFile = (path: string, text: string): TAgentVaultSkillFile => ({+ path,+ mode: "0644",+ contentBase64: bytesToBase64(new TextEncoder().encode(text))+});++export const isMarkdownPath = (path: string) => /\.(md|markdown)$/i.test(path);++/** A file as the editor holds it: text for anything that decodes as UTF-8, else the original bytes, read only. */+export type TSkillDraftFile = {+ path: string;+ mode: TAgentVaultSkillFileMode;+ text: string | null;+ contentBase64: string;+};++export const toDraftFiles = (files: TAgentVaultSkillFile[]): TSkillDraftFile[] =>+ sortSkillFiles(files).map((file) => ({ ...file, text: decodeSkillFile(file) }));++/**+ * A file whose text is unchanged keeps its original bytes, so a byte order mark or an encoding detail the editor+ * doesn't show is not lost and the file doesn't appear changed.+ */+export const fromDraftFiles = (files: TSkillDraftFile[]): TAgentVaultSkillFile[] =>+ files.map(({ path, mode, text, contentBase64 }) =>+ text === null ||+ (contentBase64 !== "" && decodeSkillFile({ path, mode, contentBase64 }) === text)+ ? { path, mode, contentBase64 }+ : { ...toSkillFile(path, text), mode }+ );++export const newDraftFile = (path: string, text = ""): TSkillDraftFile => ({+ path,+ mode: "0644",+ text,+ contentBase64: ""+});++export const SKILL_MAX_FILES = MAX_FILES;+export const SKILL_MAX_PATH_LENGTH = 255;+const SKILL_MAX_SEGMENT_BYTES = 255;+export const AGENT_VAULT_MAX_SKILLS_PER_BUNDLE = 25;++// eslint-disable-next-line no-control-regex+const CONTROL_CHARS_RE = /[\x00-\x1f\x7f]/;+const LONE_SURROGATE_RE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;+const WINDOWS_INVALID_CHARS_RE = /[:<>"|?*]/;+const WINDOWS_DEVICE_NAME_RE = /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?$/i;++export const isReservedSkillName = (name: string) => WINDOWS_DEVICE_NAME_RE.test(name);++export const getReservedSkillNameMessage = (name: string) =>+ `'${name}' is a reserved name and can't be used as a skill name.`;++/** Why the server would refuse a file path, or null. Mirrors assertValidPath in the backend's agent-vault-skill-fns.ts. */+export const getSkillPathError = (path: string): string | null => {+ if (!path.length) return "Enter a name.";+ if (LONE_SURROGATE_RE.test(path)) return "A name must be valid Unicode text.";+ if (path.length > SKILL_MAX_PATH_LENGTH)+ return `A path can be at most ${SKILL_MAX_PATH_LENGTH} characters, including its folders.`;+ if (CONTROL_CHARS_RE.test(path)) return "A name can't contain control characters.";+ if (path.includes("\\")) return "A name can't contain a backslash.";+ const segments = path.split("/");+ if (path.startsWith("/") || segments.some((s) => s === "" || s === "." || s === ".."))+ return "A name can't be empty, '.' or '..'.";+ const encoder = new TextEncoder();+ const tooLong = segments.find((s) => encoder.encode(s).length > SKILL_MAX_SEGMENT_BYTES);+ if (tooLong !== undefined)+ return `File name '${tooLong.slice(0, 64)}…' in '${path}' is too long. Shorten it.`;+ if (WINDOWS_INVALID_CHARS_RE.test(path)) return "A name can't contain any of : < > \" | ? *";+ const trailing = segments.find((s) => s.endsWith(".") || s.endsWith(" "));+ if (trailing !== undefined) return `'${trailing}' can't end in a dot or a space.`;+ const device = segments.find((s) => WINDOWS_DEVICE_NAME_RE.test(s));+ if (device !== undefined) return `'${device}' is a reserved name and can't be used.`;+ return null;+};++// The server compares paths this way, since one file system may write both spellings to the same file.+const foldSkillPath = (path: string) => path.normalize("NFC").toLowerCase();++export const joinSkillPath = (parentPath: string, name: string) =>+ parentPath ? `${parentPath}/${name}` : name;++export const getSkillParentPath = (path: string) => {+ const slash = path.lastIndexOf("/");+ return slash === -1 ? "" : path.slice(0, slash);+};++export const getSkillBaseName = (path: string) => path.slice(path.lastIndexOf("/") + 1);++const isSameOrInside = (path: string, folder: string) =>+ path === folder || path.startsWith(`${folder}/`);++/** Every folder that holds one of the files, plus any empty folders given. */+export const getSkillFolders = (+ filePaths: readonly string[],+ emptyFolders: readonly string[] = []+) => {+ const folders = new Set<string>(emptyFolders);+ filePaths.forEach((path) => {+ const segments = path.split("/");+ segments+ .slice(0, -1)+ .forEach((_, index) => folders.add(segments.slice(0, index + 1).join("/")));+ });+ return [...folders];+};++type TSkillEntryCheck = {+ name: string;+ parentPath: string;+ filePaths: readonly string[];+ folderPaths: readonly string[];+ /** The file or folder being renamed. It and anything inside it don't count as clashes. */+ renamingPath?: string;+};++/** Why a name typed in the file tree can't be used, or null when it can. */+export const getSkillEntryNameError = ({+ name,+ parentPath,+ filePaths,+ folderPaths,+ renamingPath+}: TSkillEntryCheck): string | null => {+ if (!name) return "Enter a name.";+ if (name.includes("/")) return "A name can't contain '/'. Use New Folder to add a folder.";+ const path = joinSkillPath(parentPath, name);+ const pathError = getSkillPathError(path);+ if (pathError) return pathError;++ const isMoved = (existing: string) =>+ renamingPath !== undefined && isSameOrInside(existing, renamingPath);+ if (renamingPath !== undefined) {+ const longest = filePaths+ .filter(isMoved)+ .reduce(+ (max, existing) => Math.max(max, path.length + existing.length - renamingPath.length),+ 0+ );+ if (longest > SKILL_MAX_PATH_LENGTH)+ return `A file inside would have a path longer than ${SKILL_MAX_PATH_LENGTH} characters.`;+ }++ const folded = foldSkillPath(path);+ const clash = (paths: readonly string[]) =>+ paths.find((existing) => !isMoved(existing) && foldSkillPath(existing) === folded);+ const caseNote = (existing: string) =>+ existing === path ? "" : " Names must be unique ignoring case.";+ const file = clash(filePaths);+ if (file) return `A file named '${getSkillBaseName(file)}' is already here.${caseNote(file)}`;+ const folder = clash(folderPaths);+ if (folder)+ return `A folder named '${getSkillBaseName(folder)}' is already here.${caseNote(folder)}`;+ return null;+};++/** Moves a file, or a folder with everything in it, to a new path. */+export const renameSkillPaths = <T extends { path: string }>(+ files: readonly T[],+ from: string,+ to: string+): T[] =>+ files.map((file) =>+ isSameOrInside(file.path, from) ? { ...file, path: to + file.path.slice(from.length) } : file+ );++export const renameSkillFolders = (folders: readonly string[], from: string, to: string) =>+ folders.map((folder) => (isSameOrInside(folder, from) ? to + folder.slice(from.length) : folder));++/** Drops a file, or a folder with everything in it. */+export const removeSkillPath = <T extends string | { path: string }>(+ items: readonly T[],+ path: string+) => items.filter((item) => !isSameOrInside(typeof item === "string" ? item : item.path, path));++/**+ * Reads a SKILL.md YAML header the way the server does, with js-yaml's JSON schema. Returns null when it is not valid+ * YAML or not a list of `key: value` lines.+ */+export const parseSkillHeader = (frontmatter: string): Record<string, unknown> | null => {+ let parsed: unknown;+ try {+ parsed = load(frontmatter, { schema: JSON_SCHEMA });+ } catch {+ return null;+ }+ if (parsed === undefined || parsed === null) return {};+ if (typeof parsed !== "object" || Array.isArray(parsed)) return null;+ return parsed as Record<string, unknown>;+};++const QUOTED_OR_FLOW_START = ['"', "'", "|", ">", "[", "{"];++// The usual way a hand-written header breaks: an unquoted value such as `description: Review: then fix`.+const findUnquotedColonValue = (lines: string[]) => {+ for (let i = 0; i < lines.length; i += 1) {+ const line = lines[i];+ const first = line[0];+ if (first !== undefined && first !== " " && first !== "\t" && first !== "#" && first !== "-") {+ const separator = line.indexOf(": ");+ if (separator > 0) {+ const value = line.slice(separator + 2).trimStart();+ const comment = value.indexOf(" #");+ const scalar = comment === -1 ? value : value.slice(0, comment);+ if (scalar.length && !QUOTED_OR_FLOW_START.includes(scalar[0]) && scalar.includes(": "))+ return { line: i, key: line.slice(0, separator).trimEnd() };+ }+ }+ }+ return null;+};++const UNCLOSED_VALUE_OPENERS = ["[", "{", '"', "'"];+const QUOTE_MAY_FOLLOW = ["", "[", "{", ",", ":"];++const isBlank = (char: string | undefined) => char === " " || char === "\t" || char === "\n";++// A flow or quoted value may continue on indented lines, so its whole block is scanned before calling it unclosed.+const valueCloses = (text: string) => {+ let depth = 0;+ let quote = "";+ let previous = "";+ for (let i = 0; i < text.length; i += 1) {+ const char = text[i];+ if (quote === '"') {+ if (char === "\\") {+ i += 1;+ } else if (char === '"') {+ if (depth === 0) return true;+ quote = "";+ previous = char;+ }+ } else if (quote === "'") {+ if (char === "'" && text[i + 1] === "'") {+ i += 1;+ } else if (char === "'") {+ if (depth === 0) return true;+ quote = "";+ previous = char;+ }+ } else if (char === "#" && (i === 0 || isBlank(text[i - 1]))) {+ const newline = text.indexOf("\n", i);+ if (newline === -1) return false;+ i = newline;+ } else if ((char === '"' || char === "'") && QUOTE_MAY_FOLLOW.includes(previous)) {+ quote = char;+ } else {+ if (char === "[" || char === "{") depth += 1;+ if (char === "]" || char === "}") {+ depth -= 1;+ if (depth === 0) return true;+ }+ if (!isBlank(char)) previous = char;+ }+ }+ return false;+};++// A quoted or flow value may continue on lines that start at column zero, and comments may sit between its lines,+// so only the next top-level key ends it.+const startsTopLevelKey = (line: string) => {+ const first = line[0];+ if (first === undefined || first === " " || first === "\t" || first === "#" || first === "-")+ return false;+ const colon = line.indexOf(":");+ return (+ colon > 0 && (colon === line.length - 1 || line[colon + 1] === " " || line[colon + 1] === "\t")+ );+};++const findUnclosedValue = (headerLines: string[]) => {+ for (let i = 0; i < headerLines.length; i += 1) {+ const line = headerLines[i];+ const first = line[0];+ if (first !== undefined && first !== " " && first !== "\t" && first !== "#" && first !== "-") {+ const separator = line.indexOf(": ");+ if (separator > 0) {+ const value = line.slice(separator + 2).trimStart();+ if (UNCLOSED_VALUE_OPENERS.includes(value[0])) {+ let end = i + 1;+ while (end < headerLines.length && !startsTopLevelKey(headerLines[end])) end += 1;+ if (!valueCloses([value, ...headerLines.slice(i + 1, end)].join("\n"))) {+ return { line: i, key: line.slice(0, separator).trimEnd(), opener: value[0] };+ }+ }+ }+ }+ }+ return null;+};++const describeOpener = (opener: string) => {+ if (opener === '"') return "a double quote";+ if (opener === "'") return "a single quote";+ return `a '${opener}'`;+};++/**+ * Why a SKILL.md header can't be read, in the words the server and CLI use, or null when it can. Mirrors+ * yamlErrorMessage in the backend's agent-vault-skill-fns.ts.+ */+export const getSkillHeaderError = (frontmatter: string): string | null => {+ try {+ load(frontmatter, { schema: JSON_SCHEMA });+ } catch (error) {+ // The header starts on the line after the opening '---', so its first line is line 2 of the file.+ const lines = frontmatter.split(/\r?\n/);+ const unquoted = findUnquotedColonValue(lines);+ if (unquoted)+ return `Line ${unquoted.line + 2} of ${SKILL_ENTRY_FILE}: the '${unquoted.key}' value contains ': '. Put the value in double quotes.`;+ const unclosed = findUnclosedValue(lines);+ if (unclosed)+ return `Line ${unclosed.line + 2} of ${SKILL_ENTRY_FILE}: the '${unclosed.key}' value opens ${describeOpener(unclosed.opener)} that never closes.`;+ if (error instanceof YAMLException && typeof error.mark?.line === "number") {+ const reason = (error.reason ?? "").split("\n")[0].trim().replace(/\.+$/, "");+ if (reason)+ return `Line ${error.mark.line + 2} of ${SKILL_ENTRY_FILE}: the header is not valid YAML (${reason}).`;+ }+ return `The header in ${SKILL_ENTRY_FILE} is not valid YAML.`;+ }+ return parseSkillHeader(frontmatter)+ ? null+ : `The header in ${SKILL_ENTRY_FILE} is not valid YAML.`;+};++/** A header value as a text field shows it: `12` as "12", and a missing or empty value as "". */+export const getSkillHeaderText = (value: unknown) => {+ if (typeof value === "string") return value;+ if (typeof value === "number" || typeof value === "boolean") return String(value);+ return "";+};++// Plain strings that YAML 1.1 parsers, such as Python's, read as booleans or null.+const YAML_1_1_KEYWORD_RE = /^(?:y|n|yes|no|on|off|true|false|null|~)$/i;++/** Writes a header value plain when YAML reads it back as the same string, else as a double-quoted JSON string. */+export const formatSkillHeaderValue = (value: string) => {+ if (YAML_1_1_KEYWORD_RE.test(value)) return JSON.stringify(value);+ try {+ if ((load(`v: ${value}`, { schema: JSON_SCHEMA }) as { v?: unknown } | null)?.v === value)+ return value;+ } catch {+ // Not valid as a plain value, so it is quoted below.+ }+ return JSON.stringify(value);+};++const FRONTMATTER_RE = /^(---[ \t]*\r?\n)(?:([\s\S]*?)\r?\n)??(---[ \t]*(?:\r?\n|$))/;++/**+ * Sets one top-level key in a SKILL.md header and leaves every other line of the file as it was. A value written over+ * several indented lines is replaced as a whole. Adds the key when the header lacks it, and a header when there is none.+ */+export const setSkillHeaderValue = (text: string, key: string, value: string) => {+ const match = FRONTMATTER_RE.exec(text);+ if (!match) return `---\n${key}: ${formatSkillHeaderValue(value)}\n---\n\n${text}`;++ const [whole, open, header, close] = match;+ const eol = open.endsWith("\r\n") ? "\r\n" : "\n";+ const lines = header === undefined ? [] : header.split(/\r?\n/);+ const keyForms = [key, `"${key}"`, `'${key}'`];+ const start = lines.findIndex((line) =>+ keyForms.some((form) => line.startsWith(form) && /^[ \t]*:/.test(line.slice(form.length)))+ );+ // A value already in double quotes stays quoted, so typing a trailing space doesn't flip the line on each keystroke.+ const isQuoted = start !== -1 && /^[^:]*:[ \t]*"/.test(lines[start]);+ const entry = `${key}: ${isQuoted ? JSON.stringify(value) : formatSkillHeaderValue(value)}`;+ if (start === -1) {+ lines.push(entry);+ } else {+ let end = start;+ for (let i = start + 1; i < lines.length; i += 1) {+ if (/^[ \t]/.test(lines[i])) end = i;+ else if (lines[i].trim() !== "") break;+ }+ lines.splice(start, end - start + 1, entry);+ }+ return `${open}${lines.join(eol)}${eol}${close}${text.slice(whole.length)}`;+};++const countLines = (text: string) => {+ if (text === "") return 0;+ const lines = text.split("\n");+ return lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;+};++export const countLineChanges = (oldText: string, newText: string) => {+ let additions = 0;+ let deletions = 0;+ diffLines(oldText, newText).forEach((change) => {+ if (change.added) additions += countLines(change.value);+ if (change.removed) deletions += countLines(change.value);+ });+ return { additions, deletions };+};++export type TSkillFileChange = {+ path: string;+ status: "added" | "modified" | "deleted";+ oldText: string | null;+ newText: string | null;+ isBinary: boolean;+ /** Too large to diff in the browser; its line counts are not known when it was modified. */+ isTooLarge: boolean;+ additions: number;+ deletions: number;+ oldMode?: TAgentVaultSkillFileMode;+ newMode?: TAgentVaultSkillFileMode;+};++const isSameDraftFile = (before: TSkillDraftFile, file: TSkillDraftFile) =>+ before.mode === file.mode &&+ (file.text === null ? before.contentBase64 === file.contentBase64 : before.text === file.text);++/**+ * The paths a draft adds or changes, and whether it changes anything at all, without diffing any text. Cheap enough+ * to run on every keystroke.+ */+export const getChangedSkillPaths = (original: TSkillDraftFile[], draft: TSkillDraftFile[]) => {+ const originalByPath = new Map(original.map((file) => [file.path, file]));+ const changedPaths = new Set<string>();+ draft.forEach((file) => {+ const before = originalByPath.get(file.path);+ if (!before || !isSameDraftFile(before, file)) changedPaths.add(file.path);+ });+ const draftPaths = new Set(draft.map((file) => file.path));+ const hasChanges = changedPaths.size > 0 || original.some((file) => !draftPaths.has(file.path));+ return { changedPaths, hasChanges };+};++const DIFF_MAX_LINES = 2000;+const DIFF_MAX_CHARS = 200 * 1024;++const isTooLargeToDiff = (...texts: (string | null)[]) =>+ texts.some(+ (text) => text !== null && (text.length > DIFF_MAX_CHARS || countLines(text) > DIFF_MAX_LINES)+ );++/** What a draft changes against the files it started from, in the draft's order with deleted files last. */+export const getSkillFileChanges = (+ original: TSkillDraftFile[],+ draft: TSkillDraftFile[]+): TSkillFileChange[] => {+ const originalByPath = new Map(original.map((file) => [file.path, file]));+ const draftPaths = new Set(draft.map((file) => file.path));+ const changes: TSkillFileChange[] = [];++ draft.forEach((file) => {+ const before = originalByPath.get(file.path);+ const isBinary = file.text === null;+ if (!before) {+ changes.push({+ path: file.path,+ status: "added",+ oldText: null,+ newText: file.text,+ isBinary,+ isTooLarge: isTooLargeToDiff(file.text),+ additions: countLines(file.text ?? ""),+ deletions: 0,+ newMode: file.mode+ });+ return;+ }+ const isContentChanged = isBinary+ ? before.contentBase64 !== file.contentBase64+ : before.text !== file.text;+ if (!isContentChanged && before.mode === file.mode) return;+ const isTooLarge = isTooLargeToDiff(before.text, file.text);+ changes.push({+ path: file.path,+ status: "modified",+ oldText: before.text,+ newText: file.text,+ isBinary,+ isTooLarge,+ ...(isBinary || !isContentChanged || isTooLarge+ ? { additions: 0, deletions: 0 }+ : countLineChanges(before.text ?? "", file.text ?? "")),+ ...(before.mode !== file.mode && { oldMode: before.mode, newMode: file.mode })+ });+ });++ original.forEach((file) => {+ if (draftPaths.has(file.path)) return;+ changes.push({+ path: file.path,+ status: "deleted",+ oldText: file.text,+ newText: null,+ isBinary: file.text === null,+ isTooLarge: isTooLargeToDiff(file.text),+ additions: 0,+ deletions: countLines(file.text ?? ""),+ oldMode: file.mode+ });+ });++ return changes;+};++export type TDiffRow =+ | {+ type: "context" | "added" | "removed";+ text: string;+ oldLine: number | null;+ newLine: number | null;+ }+ | { type: "skip"; count: number };++const splitLines = (value: string) => {+ const lines = value.split("\n");+ if (lines[lines.length - 1] === "") lines.pop();+ return lines;+};++const NO_FINAL_NEWLINE = "\\ No newline at end of file";++/** A unified line diff, with unchanged runs longer than twice `context` folded into a skip row. */+export const buildDiffRows = (oldText: string, newText: string, context = 3): TDiffRow[] => {+ const rows: TDiffRow[] = [];+ let oldLine = 1;+ let newLine = 1;++ const endsWithNewline = (text: string) => text === "" || text.endsWith("\n");+ const isFinalNewlineChanged = endsWithNewline(oldText) !== endsWithNewline(newText);++ const changes = diffLines(oldText, newText);+ changes.forEach((change, index) => {+ const lines = splitLines(change.value);+ if (change.added || change.removed) {+ lines.forEach((text) => {+ rows.push({+ type: change.added ? "added" : "removed",+ text,+ oldLine: change.added ? null : oldLine,+ newLine: change.added ? newLine : null+ });+ if (change.added) newLine += 1;+ else oldLine += 1;+ });+ if (isFinalNewlineChanged && !endsWithNewline(change.value))+ rows.push({ type: "context", text: NO_FINAL_NEWLINE, oldLine: null, newLine: null });+ return;+ }++ const head = index === 0 ? 0 : context;+ const tail = index === changes.length - 1 ? 0 : context;+ const toRow = (text: string, offset: number): TDiffRow => ({+ type: "context",+ text,+ oldLine: oldLine + offset,+ newLine: newLine + offset+ });++ if (lines.length <= head + tail + 1) {+ lines.forEach((text, offset) => rows.push(toRow(text, offset)));+ } else {+ lines.slice(0, head).forEach((text, offset) => rows.push(toRow(text, offset)));+ rows.push({ type: "skip", count: lines.length - head - tail });+ lines+ .slice(lines.length - tail)+ .forEach((text, offset) => rows.push(toRow(text, lines.length - tail + offset)));+ }+ oldLine += lines.length;+ newLine += lines.length;+ });++ return rows;+};++/**+ * Keeps a file the archive marks executable as such, and gives every other file the mode the same path had before,+ * since archives made on Windows carry no modes at all.+ */+export const carrySkillFileModes = (+ files: TAgentVaultSkillFile[],+ previous: TAgentVaultSkillFile[]+): TAgentVaultSkillFile[] => {+ const modes = new Map(previous.map((file) => [file.path, file.mode]));+ return files.map((file) =>+ file.mode === "0755" ? file : { ...file, mode: modes.get(file.path) ?? file.mode }+ );+};++/** Swaps in a new SKILL.md and keeps every other file of the previous version as it was. */+export const replaceSkillEntryFile = (+ previous: TAgentVaultSkillFile[],+ entry: TAgentVaultSkillFile+): TAgentVaultSkillFile[] => {+ const existing = previous.find((file) => file.path === SKILL_ENTRY_FILE);+ return [+ { ...entry, mode: existing?.mode ?? entry.mode },+ ...previous.filter((file) => file.path !== SKILL_ENTRY_FILE)+ ];+};++/** The skill's files in a zip under one folder named after it, with executable files marked as such. */+export const buildSkillZip = (folder: string, files: TAgentVaultSkillFile[]) =>+ zipSync(+ Object.fromEntries(+ files.map((file) => [+ `${folder}/${file.path}`,+ [+ base64ToBytes(file.contentBase64),+ { os: 3, attrs: (file.mode === "0755" ? 0o100755 : 0o100644) * 0x10000 }+ ]+ ])+ )+ );++/** Splits a leading YAML header off Markdown, so it can be shown apart from the rendered body. */+export const splitFrontmatter = (text: string) => {+ const match = FRONTMATTER_RE.exec(text);+ if (!match) return { frontmatter: null, body: text };+ return { frontmatter: match[2] ?? "", body: text.slice(match[0].length) };+};++/** The name a SKILL.md's header gives, when its text has a header with one. */+export const getSkillEntryName = (text: string | null | undefined) => {+ if (!text) return undefined;+ const { frontmatter } = splitFrontmatter(text);+ const name = frontmatter === null ? undefined : parseSkillHeader(frontmatter)?.name;+ return typeof name === "string" && name ? name : undefined;+};diff --git a/frontend/src/hooks/api/agentVault/mutations.tsx b/frontend/src/hooks/api/agentVault/mutations.tsxindex 24c5cd4d8f..39c91ce6cf 100644--- a/frontend/src/hooks/api/agentVault/mutations.tsx+++ b/frontend/src/hooks/api/agentVault/mutations.tsx@@ -12,6 +12,7 @@ import {TAgentVaultAccessBundle,TAgentVaultActorIdsDTO,TAgentVaultActorRef,+ TAgentVaultBundleSkill,TAgentVaultGrantedMember,TAgentVaultMemberWriteResult,TAgentVaultMintedSession,@@ -23,6 +24,8 @@ import {TAgentVaultService,TAgentVaultSession,TAgentVaultSessionLogSettingsState,+ TAgentVaultSkillSummary,+ TAgentVaultSkillVersion,TAgentVaultVariable,TAgentVaultWrittenMember,TCompleteAgentVaultOauthAuthorizationDTO,@@ -31,6 +34,7 @@ import {TCreateAgentVaultOauthAuthorizationResponse,TCreateAgentVaultServiceDTO,TCreateAgentVaultSessionDTO,+ TCreateAgentVaultSkillDTO,TCreateAgentVaultVariableDTO,TDeleteAgentVaultPersonalValuesDTO,TSetAgentVaultPersonalValuesDTO,@@ -39,6 +43,7 @@ import {TUpdateAgentVaultServiceDTO,TUpdateAgentVaultSessionLabelDTO,TUpdateAgentVaultSessionLogSettingsDTO,+ TUpdateAgentVaultSkillDTO,TUpdateAgentVaultVariableDTO} from "./types";@@ -77,6 +82,8 @@ export const useUpdateAgentVaultAccessBundle = () => {});// A variable's usedByServices names each service's bundle.queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });+ // A skill lists the bundles it is in by name.+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skills(currentOrg.id) });}});};@@ -95,6 +102,7 @@ export const useDeleteAgentVaultAccessBundle = () => {queryClient.invalidateQueries({ queryKey: agentVaultKeys.accessBundles(currentOrg.id) });queryClient.invalidateQueries({ queryKey: agentVaultKeys.sessions(currentOrg.id) });queryClient.invalidateQueries({ queryKey: agentVaultKeys.variables(currentOrg.id) });+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skills(currentOrg.id) });}});};@@ -573,3 +581,180 @@ export const useDeleteAgentVaultPersonalValues = () => {invalidatePersonalValues(queryClient, currentOrg.id, accessBundleId)});};++// Matches every access bundle's skill list, whose rows show each skill's latest version.+const isAccessBundleSkillsKey = (orgId: string) => (query: { queryKey: readonly unknown[] }) => {+ const [, keyOrgId, scope, , leaf] = query.queryKey;+ return keyOrgId === orgId && scope === "access-bundles" && leaf === "skills";+};++const invalidateSkillVersionChange = (+ queryClient: ReturnType<typeof useQueryClient>,+ orgId: string,+ skillId: string+) =>+ Promise.all([+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skill(orgId, skillId), exact: true }),+ queryClient.invalidateQueries({+ queryKey: agentVaultKeys.skillVersions(orgId, skillId),+ exact: true+ }),+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skillLists(orgId) }),+ queryClient.invalidateQueries({ predicate: isAccessBundleSkillsKey(orgId) })+ ]);++export const useCreateAgentVaultSkill = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (params: TCreateAgentVaultSkillDTO) => {+ const { data } = await apiRequest.post<{+ skill: TAgentVaultSkillSummary;+ version: TAgentVaultSkillVersion;+ }>("/api/v1/agent-vault/skills", params);+ return data;+ },+ onSuccess: () =>+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skillLists(currentOrg.id) })+ });+};++/** A save sent with a `baseVersion` that is no longer the latest. The caller shows it, so no toast is raised. */+export class SkillVersionConflictError extends Error {+ latestVersion: number;++ constructor(message: string, latestVersion: number) {+ super(message);+ this.latestVersion = latestVersion;+ }+}++const STALE_BASE_VERSION_RE = /^Version (\d+) was published after you opened this skill\./;++export const useUpdateAgentVaultSkill = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ skillId, ...params }: TUpdateAgentVaultSkillDTO) => {+ try {+ const { data } = await apiRequest.patch<{+ skill: TAgentVaultSkillSummary;+ version: TAgentVaultSkillVersion;+ unchanged: boolean;+ }>(`/api/v1/agent-vault/skills/${skillId}`, params);+ return data;+ } catch (error) {+ const message: unknown = axios.isAxiosError(error)+ ? error.response?.data?.message+ : undefined;+ const match =+ axios.isAxiosError(error) && error.response?.status === 409 && typeof message === "string"+ ? STALE_BASE_VERSION_RE.exec(message)+ : null;+ if (match) throw new SkillVersionConflictError(message as string, Number(match[1]));+ throw error;+ }+ },+ onSuccess: (_, { skillId }) =>+ invalidateSkillVersionChange(queryClient, currentOrg.id, skillId),+ onError: (error, { skillId }) => {+ if (error instanceof SkillVersionConflictError) {+ invalidateSkillVersionChange(queryClient, currentOrg.id, skillId).catch(() => undefined);+ }+ }+ });+};++export const useRestoreAgentVaultSkillVersion = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({ skillId, version }: { skillId: string; version: number }) => {+ const { data } = await apiRequest.post<{+ version: TAgentVaultSkillVersion;+ unchanged: boolean;+ }>(`/api/v1/agent-vault/skills/${skillId}/versions/${version}/restore`);+ return data;+ },+ onSuccess: (_, { skillId }) => invalidateSkillVersionChange(queryClient, currentOrg.id, skillId)+ });+};++export const useDeleteAgentVaultSkill = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async (skillId: string) => {+ const { data } = await apiRequest.delete<{ skill: TAgentVaultSkillSummary }>(+ `/api/v1/agent-vault/skills/${skillId}`+ );+ return data.skill;+ },+ // The skill's own queries are dropped rather than invalidated, which would refetch them only to get 404s. A page+ // still showing the skill drops its queries once it has navigated away.+ onSuccess: (_, skillId) => {+ queryClient.removeQueries({+ queryKey: agentVaultKeys.skill(currentOrg.id, skillId),+ type: "inactive"+ });+ return Promise.all([+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skillLists(currentOrg.id) }),+ queryClient.invalidateQueries({ predicate: isAccessBundleSkillsKey(currentOrg.id) })+ ]);+ }+ });+};++const invalidateBundleSkillChange = (+ queryClient: ReturnType<typeof useQueryClient>,+ orgId: string,+ { accessBundleId, skillId }: { accessBundleId: string; skillId: string }+) =>+ Promise.all([+ queryClient.invalidateQueries({+ queryKey: agentVaultKeys.accessBundleSkills(orgId, accessBundleId)+ }),+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skill(orgId, skillId), exact: true }),+ queryClient.invalidateQueries({ queryKey: agentVaultKeys.skillLists(orgId) })+ ]);++export const useAddAgentVaultAccessBundleSkill = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({+ accessBundleId,+ skillId+ }: {+ accessBundleId: string;+ skillId: string;+ }) => {+ const { data } = await apiRequest.post<{ skill: TAgentVaultBundleSkill }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/skills`,+ { skillId }+ );+ return data.skill;+ },+ onSuccess: (_, params) => invalidateBundleSkillChange(queryClient, currentOrg.id, params)+ });+};++export const useRemoveAgentVaultAccessBundleSkill = () => {+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: async ({+ accessBundleId,+ skillId+ }: {+ accessBundleId: string;+ skillId: string;+ }) => {+ const { data } = await apiRequest.delete<{ skill: TAgentVaultBundleSkill }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/skills/${skillId}`+ );+ return data.skill;+ },+ onSuccess: (_, params) => invalidateBundleSkillChange(queryClient, currentOrg.id, params)+ });+};diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsxindex 01fd6fa746..693faac81d 100644--- a/frontend/src/hooks/api/agentVault/queries.tsx+++ b/frontend/src/hooks/api/agentVault/queries.tsx@@ -31,6 +31,7 @@ import {import {TAgentVaultAccessBundleDetails,TAgentVaultAccessBundleListItem,+ TAgentVaultBundleSkill,TAgentVaultDecryptedSessionLogPage,TAgentVaultMember,TAgentVaultOauthAuthorization,@@ -45,11 +46,16 @@ import {TAgentVaultSessionLogReadCheck,TAgentVaultSessionLogSettingsState,TAgentVaultSessionLogTailPage,+ TAgentVaultSkillDetail,+ TAgentVaultSkillPage,+ TAgentVaultSkillVersion,+ TAgentVaultSkillVersionWithFiles,TAgentVaultVariable,TListAgentVaultAccessBundlesDTO,TListAgentVaultMembersDTO,TListAgentVaultProxiesDTO,TListAgentVaultSessionsDTO,+ TListAgentVaultSkillsDTO,TListAgentVaultVariablesDTO} from "./types";@@ -119,6 +125,19 @@ export const agentVaultKeys = {[...agentVaultKeys.variables(orgId), "list", params] as const,variableKeyStatus: (orgId: string, scope: AgentVaultVariableScope, keys: string[]) =>[...agentVaultKeys.variables(orgId), "key-status", scope, keys] as const,+ skills: (orgId: string) => [...agentVaultKeys.all(orgId), "skills"] as const,+ skillLists: (orgId: string) => [...agentVaultKeys.skills(orgId), "list"] as const,+ skillList: (orgId: string, params: TListAgentVaultSkillsDTO) =>+ [...agentVaultKeys.skillLists(orgId), params] as const,+ skill: (orgId: string, skillId: string) =>+ [...agentVaultKeys.skills(orgId), "detail", skillId] as const,+ skillVersions: (orgId: string, skillId: string) =>+ [...agentVaultKeys.skill(orgId, skillId), "versions"] as const,+ skillVersion: (orgId: string, skillId: string, version: number) =>+ [...agentVaultKeys.skillVersions(orgId, skillId), version] as const,+ // Nested under accessBundle() so changes to the bundle refresh its skills too.+ accessBundleSkills: (orgId: string, accessBundleId: string) =>+ [...agentVaultKeys.accessBundle(orgId, accessBundleId), "skills"] as const,members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>[...agentVaultKeys.members(orgId), params] as const,@@ -691,3 +710,89 @@ export const useAgentVaultVariableKeyStatus = (};}, [data, keySignature]);};++export const useListAgentVaultSkills = (+ params: TListAgentVaultSkillsDTO = {},+ { enabled = true }: { enabled?: boolean } = {}+) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.skillList(currentOrg.id, params),+ queryFn: async () => {+ const { data } = await apiRequest.get<TAgentVaultSkillPage>("/api/v1/agent-vault/skills", {+ params+ });+ return data;+ },+ placeholderData: (prev) => prev,+ enabled+ });+};++export const useGetAgentVaultSkill = (skillId: string) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.skill(currentOrg.id, skillId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ skill: TAgentVaultSkillDetail }>(+ `/api/v1/agent-vault/skills/${skillId}`+ );+ return data.skill;+ },+ enabled: Boolean(skillId)+ });+};++export const useListAgentVaultSkillVersions = (skillId: string) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.skillVersions(currentOrg.id, skillId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ versions: TAgentVaultSkillVersion[] }>(+ `/api/v1/agent-vault/skills/${skillId}/versions`+ );+ return data.versions;+ },+ enabled: Boolean(skillId)+ });+};++export const fetchAgentVaultSkillVersion = async (skillId: string, version: number) => {+ const { data } = await apiRequest.get<{ version: TAgentVaultSkillVersionWithFiles }>(+ `/api/v1/agent-vault/skills/${skillId}/versions/${version}`+ );+ return data.version;+};++export const useGetAgentVaultSkillVersion = (skillId: string, version?: number) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.skillVersion(currentOrg.id, skillId, version ?? 0),+ queryFn: () => fetchAgentVaultSkillVersion(skillId, version ?? 0),+ enabled: Boolean(skillId) && Boolean(version),+ // A version never changes once published.+ staleTime: Infinity+ });+};++export const useListAgentVaultAccessBundleSkills = (+ accessBundleId: string,+ { enabled = true }: { enabled?: boolean } = {}+) => {+ const { currentOrg } = useOrganization();++ return useQuery({+ queryKey: agentVaultKeys.accessBundleSkills(currentOrg.id, accessBundleId),+ queryFn: async () => {+ const { data } = await apiRequest.get<{ skills: TAgentVaultBundleSkill[] }>(+ `/api/v1/agent-vault/access-bundles/${accessBundleId}/skills`+ );+ return data.skills;+ },+ enabled: enabled && Boolean(accessBundleId)+ });+};diff --git a/frontend/src/hooks/api/agentVault/types.ts b/frontend/src/hooks/api/agentVault/types.tsindex 4ee16f0af4..151212fa2b 100644--- a/frontend/src/hooks/api/agentVault/types.ts+++ b/frontend/src/hooks/api/agentVault/types.ts@@ -606,3 +606,74 @@ export type TSetAgentVaultPersonalValuesDTO = {};export type TDeleteAgentVaultPersonalValuesDTO = { accessBundleId: string; serviceId: string };++export type TAgentVaultSkillFileMode = "0644" | "0755";++export type TAgentVaultSkillFile = {+ path: string;+ mode: TAgentVaultSkillFileMode;+ contentBase64: string;+};++/** A skill as create and delete return it, without its access bundles. */+export type TAgentVaultSkillSummary = {+ id: string;+ name: string;+ description: string;+ latestVersion: number;+ createdAt: string;+ updatedAt: string;+};++export type TAgentVaultSkill = TAgentVaultSkillSummary & {+ /** Sorted by name. */+ accessBundles: { id: string; name: string }[];+};++export type TAgentVaultSkillDetail = TAgentVaultSkill & {+ /** The files of the latest version. */+ files: TAgentVaultSkillFile[];+};++export type TListAgentVaultSkillsDTO = {+ search?: string;+ /** Exact name. */+ name?: string;+ limit?: number;+ offset?: number;+};++export type TAgentVaultSkillPage = {+ skills: TAgentVaultSkill[];+ totalCount: number;+};++export type TAgentVaultSkillVersion = {+ id: string;+ version: number;+ sha256: string;+ sizeBytes: number;+ fileCount: number;+ createdAt: string;+};++export type TAgentVaultSkillVersionWithFiles = TAgentVaultSkillVersion & {+ files: TAgentVaultSkillFile[];+};++export type TAgentVaultBundleSkill = {+ id: string;+ name: string;+ description: string;+ latestVersion: number;+};++export type TCreateAgentVaultSkillDTO = {+ files: TAgentVaultSkillFile[];+};++export type TUpdateAgentVaultSkillDTO = TCreateAgentVaultSkillDTO & {+ skillId: string;+ /** The version the files were edited from. The server refuses the save when a newer one was published since. */+ baseVersion?: number;+};diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsxindex 8527cab9c1..1a3b7c9fd9 100644--- a/frontend/src/hooks/api/auditLogs/constants.tsx+++ b/frontend/src/hooks/api/auditLogs/constants.tsx@@ -490,6 +490,15 @@ export const eventToNameMap: { [K in EventType]: string } = {[EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW]: "View variable value",[EventType.AGENT_VAULT_PERSONAL_VALUES_SET]: "Set personal values",[EventType.AGENT_VAULT_PERSONAL_VALUES_DELETE]: "Remove personal values",+ [EventType.AGENT_VAULT_SKILL_CREATE]: "Create skill",+ [EventType.AGENT_VAULT_SKILL_VERSION_CREATE]: "Save skill version",+ [EventType.AGENT_VAULT_SKILL_VERSION_RESTORE]: "Roll back skill version",+ [EventType.AGENT_VAULT_SKILL_RENAME]: "Rename skill",+ [EventType.AGENT_VAULT_SKILL_VERSION_VIEW]: "View skill version files",+ [EventType.AGENT_VAULT_SKILL_DELETE]: "Delete skill",+ [EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_ADD]: "Add skill to bundle",+ [EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_REMOVE]: "Remove skill from bundle",+ [EventType.AGENT_VAULT_SKILLS_DELIVERED]: "Skills delivered",[EventType.AGENT_VAULT_MEMBER_ADD]: "Add member",[EventType.AGENT_VAULT_MEMBER_UPDATE]: "Change member role",[EventType.AGENT_VAULT_MEMBER_REMOVE]: "Remove member",@@ -576,6 +585,15 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {EventType.AGENT_VAULT_VARIABLE_VALUE_VIEW,EventType.AGENT_VAULT_PERSONAL_VALUES_SET,EventType.AGENT_VAULT_PERSONAL_VALUES_DELETE,+ EventType.AGENT_VAULT_SKILL_CREATE,+ EventType.AGENT_VAULT_SKILL_VERSION_CREATE,+ EventType.AGENT_VAULT_SKILL_VERSION_RESTORE,+ EventType.AGENT_VAULT_SKILL_RENAME,+ EventType.AGENT_VAULT_SKILL_VERSION_VIEW,+ EventType.AGENT_VAULT_SKILL_DELETE,+ EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_ADD,+ EventType.AGENT_VAULT_ACCESS_BUNDLE_SKILL_REMOVE,+ EventType.AGENT_VAULT_SKILLS_DELIVERED,EventType.AGENT_VAULT_MEMBER_ADD,EventType.AGENT_VAULT_MEMBER_UPDATE,EventType.AGENT_VAULT_MEMBER_REMOVE,diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsxindex 7465032017..fce6802ecc 100644--- a/frontend/src/hooks/api/auditLogs/enums.tsx+++ b/frontend/src/hooks/api/auditLogs/enums.tsx@@ -487,6 +487,15 @@ export enum EventType {AGENT_VAULT_VARIABLE_VALUE_VIEW = "agent-vault-variable-value-view",AGENT_VAULT_PERSONAL_VALUES_SET = "agent-vault-personal-values-set",AGENT_VAULT_PERSONAL_VALUES_DELETE = "agent-vault-personal-values-delete",+ AGENT_VAULT_SKILL_CREATE = "agent-vault-skill-create",+ AGENT_VAULT_SKILL_VERSION_CREATE = "agent-vault-skill-version-create",+ AGENT_VAULT_SKILL_VERSION_RESTORE = "agent-vault-skill-version-restore",+ AGENT_VAULT_SKILL_RENAME = "agent-vault-skill-rename",+ AGENT_VAULT_SKILL_VERSION_VIEW = "agent-vault-skill-version-view",+ AGENT_VAULT_SKILL_DELETE = "agent-vault-skill-delete",+ AGENT_VAULT_ACCESS_BUNDLE_SKILL_ADD = "agent-vault-access-bundle-skill-add",+ AGENT_VAULT_ACCESS_BUNDLE_SKILL_REMOVE = "agent-vault-access-bundle-skill-remove",+ AGENT_VAULT_SKILLS_DELIVERED = "agent-vault-skills-delivered",AGENT_VAULT_MEMBER_ADD = "agent-vault-member-add",AGENT_VAULT_MEMBER_UPDATE = "agent-vault-member-update",AGENT_VAULT_MEMBER_REMOVE = "agent-vault-member-remove",diff --git a/frontend/src/hooks/useAgentVaultSheetState.ts b/frontend/src/hooks/useAgentVaultSheetState.tsindex 25956fba66..d0629645df 100644--- a/frontend/src/hooks/useAgentVaultSheetState.ts+++ b/frontend/src/hooks/useAgentVaultSheetState.ts@@ -5,22 +5,24 @@ export const agentVaultSheetSearchParams = z.object({sessionId: z.string().uuid().optional().catch(undefined)});-export const useAgentVaultSheetState = () => {+export const agentVaultSkillSheetSearchParams = z.object({+ skillId: z.string().uuid().optional().catch(undefined)+});++export const useAgentVaultSheetState = (param: "sessionId" | "skillId" = "sessionId") => {const navigate = useNavigate();const search = useSearch({ strict: false }) as Record<string, unknown>;- const sessionId = search.sessionId as string | undefined;+ const id = search[param] as string | undefined;return {- sessionId,- isOpen: Boolean(sessionId),- openSheet: (id: string) => {- navigate({ search: { ...search, sessionId: id } as any });+ id,+ isOpen: Boolean(id),+ openSheet: (nextId: string) => {+ navigate({ search: { ...search, [param]: nextId } as any });},closeSheet: () => {- const rest = Object.fromEntries(- Object.entries(search).filter(([key]) => key !== "sessionId")- );- navigate({ search: rest as any });+ const rest = Object.fromEntries(Object.entries(search).filter(([key]) => key !== param));+ return navigate({ search: rest as any });}};};diff --git a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsxindex c2dd17826c..dd479bb09e 100644--- a/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx+++ b/frontend/src/layouts/OrganizationLayout/components/OrgSidebar/AgentVaultNav.tsx@@ -1,4 +1,5 @@import {+ BookOpenText,Braces,FileText,IdCard,@@ -54,7 +55,8 @@ export const AgentVaultNav = ({ onSubmenuOpen }: { onSubmenuOpen: (submenu: SubmpathSuffix: "access-bundles",alertVariant: needsSetup ? "warning" : undefined},- { label: "Variables", icon: Braces, pathSuffix: "variables" }+ { label: "Variables", icon: Braces, pathSuffix: "variables" },+ { label: "Skills", icon: BookOpenText, pathSuffix: "skills", hidden: !isAdmin }];const infrastructureItems: NavItem[] = [diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsxindex fb8c2ecec8..a29e99f164 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/AgentVaultAccessBundleDetailPage.tsx@@ -32,7 +32,13 @@ import {PageHeader,PageLoader} from "@app/components/v3";-import { useOrganization, useProjectPermission } from "@app/context";+import {+ ProjectPermissionAgentVaultAccessBundleActions,+ ProjectPermissionAgentVaultSkillActions,+ ProjectPermissionSub,+ useOrganization,+ useProjectPermission+} from "@app/context";import {AgentVaultSessionScope,useGetAgentVaultAccessBundle,@@ -45,12 +51,21 @@ import { useAgentVaultCreateIntent } from "@app/hooks/useAgentVaultCreateIntent"import { DeleteAccessBundleDialog } from "@app/pages/agent-vault/AgentVaultAccessBundlesPage/components/DeleteAccessBundleDialog";import { ServicesCard } from "./components/ServicesCard";+import { SkillsCard } from "./components/SkillsCard";export const AgentVaultAccessBundleDetailPage = () => {const navigate = useNavigate();const { currentOrg } = useOrganization();- const { hasProjectRole } = useProjectPermission();+ const { hasProjectRole, permission } = useProjectPermission();const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);+ const canReadSkills = permission.can(+ ProjectPermissionAgentVaultSkillActions.Read,+ ProjectPermissionSub.AgentVaultSkills+ );+ const canEditBundle = permission.can(+ ProjectPermissionAgentVaultAccessBundleActions.Edit,+ ProjectPermissionSub.AgentVaultAccessBundles+ );const accessBundleId = useParams({strict: false,@@ -199,20 +214,29 @@ export const AgentVaultAccessBundleDetailPage = () => {</Alert>)}- <ServicesCard- accessBundleId={accessBundle.id}- onSetUp={setServiceToSetUp}- services={accessBundle.services}- canManage={isAdmin}- onAdd={() => {- setServiceToEdit(null);- setIsServiceSheetOpen(true);- }}- onEdit={(service) => {- setServiceToEdit(service);- setIsServiceSheetOpen(true);- }}- />+ <div className="flex flex-col gap-6">+ <ServicesCard+ accessBundleId={accessBundle.id}+ onSetUp={setServiceToSetUp}+ services={accessBundle.services}+ canManage={isAdmin}+ onAdd={() => {+ setServiceToEdit(null);+ setIsServiceSheetOpen(true);+ }}+ onEdit={(service) => {+ setServiceToEdit(service);+ setIsServiceSheetOpen(true);+ }}+ />+ {canReadSkills && (+ <SkillsCard+ accessBundleId={accessBundle.id}+ accessBundleName={accessBundle.name}+ canManage={canEditBundle}+ />+ )}+ </div><PersonalValuesDialogtarget={diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/AddBundleSkillDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/AddBundleSkillDialog.tsxnew file mode 100644index 0000000000..c1a513c617--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/AddBundleSkillDialog.tsx@@ -0,0 +1,190 @@+import { useMemo, useState } from "react";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ Combobox,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldContent,+ FieldDescription,+ FieldError,+ FieldLabel+} from "@app/components/v3";+import { AGENT_VAULT_MAX_SKILLS_PER_BUNDLE } from "@app/helpers/agentVaultSkills";+import { useDebounce } from "@app/hooks";+import {+ useAddAgentVaultAccessBundleSkill,+ useListAgentVaultSkills+} from "@app/hooks/api/agentVault";+import { TAgentVaultSkill } from "@app/hooks/api/agentVault/types";++const CREATE_LABEL = "Create New Skill";+const PICKER_LIMIT = 100;++type Props = {+ accessBundleId: string;+ bundleSkillIds: string[];+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ canCreateSkills: boolean;+ onCreateNew: (name: string) => void;+};++export const AddBundleSkillDialog = ({+ accessBundleId,+ bundleSkillIds,+ isOpen,+ onOpenChange,+ canCreateSkills,+ onCreateNew+}: Props) => {+ const addSkill = useAddAgentVaultAccessBundleSkill();+ const [skills, setSkills] = useState<TAgentVaultSkill[]>([]);+ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);+ const [isAdding, setIsAdding] = useState(false);++ const { data, isFetching } = useListAgentVaultSkills(+ { search: debouncedSearch.trim() || undefined, limit: PICKER_LIMIT },+ { enabled: isOpen }+ );++ const options = useMemo(() => {+ const inBundle = new Set(bundleSkillIds);+ return (data?.skills ?? []).filter((option) => !inBundle.has(option.id));+ }, [data, bundleSkillIds]);++ const isListTruncated = (data?.totalCount ?? 0) > (data?.skills.length ?? 0);+ const roomLeft = Math.max(0, AGENT_VAULT_MAX_SKILLS_PER_BUNDLE - bundleSkillIds.length);+ const isOverLimit = skills.length > roomLeft;++ const handleClose = () => {+ setSkills([]);+ setSearch("");+ onOpenChange(false);+ };++ const handleAdd = async () => {+ if (skills.length === 0) return;+ setIsAdding(true);+ const added: TAgentVaultSkill[] = [];+ try {+ // One at a time, so the bundle's skill limit stops the rest once it is reached.+ for (const skill of skills) {+ // eslint-disable-next-line no-await-in-loop+ await addSkill.mutateAsync({ accessBundleId, skillId: skill.id });+ added.push(skill);+ }+ } catch {+ // The global mutation handler shows the server's message.+ } finally {+ setIsAdding(false);+ }+ if (added.length > 0) {+ createNotification({+ text:+ added.length === 1 ? `Skill "${added[0].name}" added` : `${added.length} skills added`,+ type: "success"+ });+ }+ if (added.length === skills.length) handleClose();+ else setSkills((prev) => prev.filter((skill) => !added.includes(skill)));+ };++ return (+ <Dialog+ open={isOpen}+ onOpenChange={(open) => {+ if (!open) {+ handleClose();+ return;+ }+ onOpenChange(open);+ }}+ >+ <DialogContent isPending={isAdding}>+ <DialogHeader>+ <DialogTitle>Add Skills</DialogTitle>+ <DialogDescription>+ Agents running with this bundle get the skills the next time they start.+ </DialogDescription>+ </DialogHeader>++ <Field>+ <FieldLabel htmlFor="agent-vault-add-bundle-skills">Skills</FieldLabel>+ <FieldContent>+ <Combobox<TAgentVaultSkill>+ id="agent-vault-add-bundle-skills"+ multiple+ options={options}+ value={skills}+ isLoading={isFetching}+ onSearchChange={setSearch}+ getOptionValue={(option) => option.id}+ getOptionLabel={(option) => option.name}+ getOptionKeywords={(option) => [option.description]}+ renderOption={(option) => (+ <div className="flex min-w-0 flex-col">+ <span className="truncate text-sm">{option.name}</span>+ <span className="truncate text-xs text-muted">{option.description}</span>+ </div>+ )}+ placeholder="Pick skills"+ searchPlaceholder="Search skills..."+ searchAriaLabel="Search skills"+ emptyMessage={search ? "No skills match your search" : "No skills to add"}+ modal+ isError={isOverLimit}+ onValueChange={setSkills}+ creation={+ canCreateSkills+ ? {+ mode: "action",+ emptyLabel: CREATE_LABEL,+ formatLabel: () => CREATE_LABEL,+ onAction: (inputValue) => {+ handleClose();+ onCreateNew(inputValue);+ }+ }+ : undefined+ }+ />+ {isOverLimit ? (+ <FieldError>+ An access bundle can have at most {AGENT_VAULT_MAX_SKILLS_PER_BUNDLE} skills. This+ one has room for {roomLeft} more.+ </FieldError>+ ) : (+ isListTruncated && (+ <FieldDescription>+ Search by name to find skills that are not listed.+ </FieldDescription>+ )+ )}+ </FieldContent>+ </Field>++ <DialogFooter>+ <Button variant="outline" onClick={handleClose} isDisabled={isAdding}>+ Cancel+ </Button>+ <Button+ variant="av"+ isPending={isAdding}+ isDisabled={skills.length === 0 || isOverLimit}+ onClick={handleAdd}+ >+ {skills.length > 1 ? `Add ${skills.length} Skills` : "Add Skill"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/SkillsCard.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/SkillsCard.tsxnew file mode 100644index 0000000000..1c8c03b0da--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/components/SkillsCard.tsx@@ -0,0 +1,247 @@+import { useState } from "react";+import { EyeIcon, MoreHorizontalIcon, PlusIcon, TrashIcon } from "lucide-react";++import { CreateSkillSheet } from "@app/components/agent-vault/skills/CreateSkillSheet";+import { SkillDescription } from "@app/components/agent-vault/skills/SkillDescription";+import { SkillSheet } from "@app/components/agent-vault/skills/SkillSheet";+import { createNotification } from "@app/components/notifications";+import {+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ ConfirmationAlertDialog,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ RowLink,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";+import {+ ProjectPermissionAgentVaultSkillActions,+ ProjectPermissionSub,+ useOrganization,+ useProjectPermission+} from "@app/context";+import {+ useAddAgentVaultAccessBundleSkill,+ useListAgentVaultAccessBundleSkills,+ useRemoveAgentVaultAccessBundleSkill+} from "@app/hooks/api/agentVault";+import { TAgentVaultBundleSkill, TAgentVaultSkillSummary } from "@app/hooks/api/agentVault/types";+import { useAgentVaultSheetState } from "@app/hooks/useAgentVaultSheetState";++import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";+import { AddBundleSkillDialog } from "./AddBundleSkillDialog";++type Props = {+ accessBundleId: string;+ accessBundleName: string;+ canManage: boolean;+};++export const SkillsCard = ({ accessBundleId, accessBundleName, canManage }: Props) => {+ const { permission } = useProjectPermission();+ const { openSheet } = useAgentVaultSheetState("skillId");+ const { currentOrg } = useOrganization();+ const canCreateSkills = permission.can(+ ProjectPermissionAgentVaultSkillActions.Create,+ ProjectPermissionSub.AgentVaultSkills+ );+ const { data: bundleSkills = [], isPending } =+ useListAgentVaultAccessBundleSkills(accessBundleId);+ const addSkill = useAddAgentVaultAccessBundleSkill();+ const removeSkill = useRemoveAgentVaultAccessBundleSkill();+ const [skillToRemove, setSkillToRemove] = useState<TAgentVaultBundleSkill | null>(null);+ const [isAddOpen, setIsAddOpen] = useState(false);+ const [createName, setCreateName] = useState<string | null>(null);++ const addCreated = async (skill: TAgentVaultSkillSummary) => {+ try {+ await addSkill.mutateAsync({ accessBundleId, skillId: skill.id });+ createNotification({+ text: `Skill "${skill.name}" created and added to this access bundle`,+ type: "success"+ });+ } catch {+ // The add error is already a toast; this one says the skill itself exists now+ createNotification({ text: `Skill "${skill.name}" created`, type: "info" });+ }+ };++ const handleRemove = async () => {+ if (!skillToRemove) return;+ try {+ await removeSkill.mutateAsync({ accessBundleId, skillId: skillToRemove.id });+ } catch {+ return;+ }+ createNotification({ text: `Skill "${skillToRemove.name}" removed`, type: "success" });+ setSkillToRemove(null);+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ Skills+ <DocumentationLinkBadge href={AgentVaultDocsUrls.skills} />+ </CardTitle>+ <CardDescription>+ Agents running with this bundle get these skills, at their latest version, when they+ start.+ </CardDescription>+ {canManage && (+ <CardAction>+ <Button variant="av" isDisabled={isPending} onClick={() => setIsAddOpen(true)}>+ <PlusIcon />+ Add Skills+ </Button>+ </CardAction>+ )}+ </CardHeader>++ {!isPending && bundleSkills.length === 0 ? (+ <CardContent>+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>No skills yet</EmptyTitle>+ <EmptyDescription>+ Add skills to give agents running with this bundle instructions for their tasks.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ </CardContent>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead isTruncatable className="w-1/3">+ Name+ </TableHead>+ <TableHead isTruncatable>Description</TableHead>+ <TableHead variant="action" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {isPending &&+ Array.from({ length: 2 }).map((_, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableRow key={`bundle-skill-skeleton-${index}`}>+ <TableCell>+ <Skeleton className="h-4 w-full" />+ </TableCell>+ <TableCell>+ <Skeleton className="h-4 w-full" />+ </TableCell>+ <TableCell variant="action" />+ </TableRow>+ ))}+ {!isPending &&+ bundleSkills.map((skill) => (+ <TableRow key={skill.id} linked>+ <TableCell isTruncatable>+ <RowLink+ to="/organizations/$orgId/agent-vault/access-bundles/$accessBundleId"+ params={{ orgId: currentOrg.id, accessBundleId }}+ search={(prev) => ({ ...prev, skillId: skill.id })}+ title={skill.name}+ >+ {skill.name}+ </RowLink>+ </TableCell>+ <TableCell isTruncatable>+ <SkillDescription description={skill.description} />+ </TableCell>+ <TableCell variant="action">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Open skill actions"+ onClick={(event) => event.stopPropagation()}+ >+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ sideOffset={2}+ align="end"+ onClick={(event) => event.stopPropagation()}+ >+ <DropdownMenuItem onClick={() => openSheet(skill.id)}>+ <EyeIcon />+ View Skill+ </DropdownMenuItem>+ {canManage && (+ <DropdownMenuItem+ variant="danger"+ onClick={() => setSkillToRemove(skill)}+ >+ <TrashIcon />+ Remove From Bundle+ </DropdownMenuItem>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}++ <AddBundleSkillDialog+ accessBundleId={accessBundleId}+ bundleSkillIds={bundleSkills.map((skill) => skill.id)}+ isOpen={isAddOpen}+ onOpenChange={setIsAddOpen}+ canCreateSkills={canCreateSkills}+ onCreateNew={setCreateName}+ />++ <CreateSkillSheet+ isOpen={createName !== null}+ onOpenChange={(isOpen) => {+ if (!isOpen) setCreateName(null);+ }}+ initialName={createName ?? ""}+ description="The new skill is added to this access bundle once it is created."+ onCreated={addCreated}+ shouldNotify={false}+ />++ <ConfirmationAlertDialog+ isOpen={Boolean(skillToRemove)}+ onOpenChange={(isOpen) => {+ if (!isOpen) setSkillToRemove(null);+ }}+ title={`Remove "${skillToRemove?.name}" From "${accessBundleName}"`}+ description="The skill itself is not deleted."+ confirmKey={skillToRemove?.name ?? ""}+ confirmLabel="Remove"+ isPending={removeSkill.isPending}+ onConfirm={handleRemove}+ />++ <SkillSheet />+ </Card>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/route.tsxindex ff1cc88daf..dd89ff2f6c 100644--- a/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/route.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultAccessBundleDetailPage/route.tsx@@ -1,7 +1,8 @@-import { createFileRoute, linkOptions } from "@tanstack/react-router";+import { createFileRoute, linkOptions, stripSearchParams } from "@tanstack/react-router";import { zodValidator } from "@tanstack/zod-adapter";import { agentVaultCreateIntentSearchParams } from "@app/hooks/useAgentVaultCreateIntent";+import { agentVaultSkillSheetSearchParams } from "@app/hooks/useAgentVaultSheetState";import { AgentVaultAccessBundleDetailPage } from "./AgentVaultAccessBundleDetailPage";@@ -9,7 +10,12 @@ export const Route = createFileRoute("/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles/$accessBundleId")({component: AgentVaultAccessBundleDetailPage,- validateSearch: zodValidator(agentVaultCreateIntentSearchParams),+ validateSearch: zodValidator(+ agentVaultSkillSheetSearchParams.merge(agentVaultCreateIntentSearchParams)+ ),+ search: {+ middlewares: [stripSearchParams({ skillId: undefined })]+ },beforeLoad: ({ context, params }) => {return {breadcrumbs: [diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsxindex b7ee0f21d0..1536753a13 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/AgentVaultSessionsPage.tsx@@ -137,7 +137,7 @@ export const AgentVaultSessionsPage = () => {const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);const [mintedSession, setMintedSession] = useState<TAgentVaultMintedSession | null>(null);const [isSampleOpen, setIsSampleOpen] = useState(false);- const { sessionId: openSessionId, openSheet } = useAgentVaultSheetState();+ const { id: openSessionId, openSheet } = useAgentVaultSheetState();const { data, isPending } = useListAgentVaultSessions({scope: isAdmin ? scope : AgentVaultSessionScope.Mine,diff --git a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsxindex 03e4f8cc8a..87ef953a30 100644--- a/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx+++ b/frontend/src/pages/agent-vault/AgentVaultSessionsPage/components/SessionCreatedDialog.tsx@@ -22,65 +22,74 @@ type Props = {onOpenChange: (isOpen: boolean) => void;};-const runCommand = (token: string) =>+const runCommand = (token: string, siteUrl: string) =>`infisical agent-vault run \\--session-token ${token} \\--proxy <proxy-host>:17323 \\+ --domain ${siteUrl} \\-- <agent-command>`;-export const SessionCreatedDialog = ({ session, onOpenChange }: Props) => (- <Dialog open={Boolean(session)} onOpenChange={onOpenChange}>- <DialogContent className="max-w-2xl" onInteractOutside={(event) => event.preventDefault()}>- <DialogHeader>- <DialogTitle>Session Created</DialogTitle>- <DialogDescription>- Run this where your agent runs. The agent's traffic goes through the proxy, which- attaches the credentials this session carries.- </DialogDescription>- </DialogHeader>+export const SessionCreatedDialog = ({ session, onOpenChange }: Props) => {+ const { protocol, hostname, port } = window.location;+ const siteUrl = `${protocol}//${hostname}${port && port !== "80" ? `:${port}` : ""}`;- <div className="flex flex-col gap-4">- <Alert variant="warning">- <TriangleAlertIcon />- <AlertDescription>- This command is shown once. Copy it now, since the session token cannot be retrieved- later.- </AlertDescription>- </Alert>+ return (+ <Dialog open={Boolean(session)} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-2xl" onInteractOutside={(event) => event.preventDefault()}>+ <DialogHeader>+ <DialogTitle>Session Created</DialogTitle>+ <DialogDescription>+ Run this where your agent runs. The agent's traffic goes through the proxy, which+ attaches the credentials this session carries.+ </DialogDescription>+ </DialogHeader>- <div className="flex flex-col gap-2">- <CodeBlock label="Run an agent with it" value={runCommand(session?.token ?? "")} />- <p className="text-xs text-accent">- Replace <span className="font-mono"><proxy-host></span> with the host your proxy- runs on and <span className="font-mono"><agent-command></span> with the agent to- run, such as <span className="font-mono">claude</span>.- </p>- </div>+ <div className="flex flex-col gap-4">+ <Alert variant="warning">+ <TriangleAlertIcon />+ <AlertDescription>+ This command is shown once. Copy it now, since the session token cannot be retrieved+ later.+ </AlertDescription>+ </Alert>- <div className="flex flex-col gap-1.5">- <span className="text-xs text-accent">Expires</span>- <span className="text-sm">{formatSessionExpiry(session?.expiresAt ?? null)}</span>- </div>+ <div className="flex flex-col gap-2">+ <CodeBlock+ label="Run an agent with it"+ value={runCommand(session?.token ?? "", siteUrl)}+ />+ <p className="text-xs text-accent">+ Replace <span className="font-mono"><proxy-host></span> with the host your proxy+ runs on and <span className="font-mono"><agent-command></span> with the agent to+ run, such as <span className="font-mono">claude</span>.+ </p>+ </div>- <p className="mt-2 text-xs text-accent">- Learn how to{" "}- <a- href={AgentVaultDocsUrls.sessions}- target="_blank"- rel="noopener noreferrer"- className="underline underline-offset-2 hover:opacity-80"- >- create a session using the CLI or a machine identity- </a>- .- </p>- </div>+ <div className="flex flex-col gap-1.5">+ <span className="text-xs text-accent">Expires</span>+ <span className="text-sm">{formatSessionExpiry(session?.expiresAt ?? null)}</span>+ </div>- <DialogFooter>- <Button variant="av" onClick={() => onOpenChange(false)}>- Done- </Button>- </DialogFooter>- </DialogContent>- </Dialog>-);+ <p className="mt-2 text-xs text-accent">+ Learn how to{" "}+ <a+ href={AgentVaultDocsUrls.sessions}+ target="_blank"+ rel="noopener noreferrer"+ className="underline underline-offset-2 hover:opacity-80"+ >+ create a session using the CLI or a machine identity+ </a>+ .+ </p>+ </div>++ <DialogFooter>+ <Button variant="av" onClick={() => onOpenChange(false)}>+ Done+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSkillsPage/AgentVaultSkillsPage.tsx b/frontend/src/pages/agent-vault/AgentVaultSkillsPage/AgentVaultSkillsPage.tsxnew file mode 100644index 0000000000..059fd7949b--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSkillsPage/AgentVaultSkillsPage.tsx@@ -0,0 +1,28 @@+import { BookOpenTextIcon } from "lucide-react";++import { PageTitle } from "@app/components/PageTitle";+import { AccessRestrictedDialog, PageHeader } from "@app/components/v3";+import { useProjectPermission } from "@app/context";+import { ProjectType } from "@app/hooks/api/projects/types";+import { ProjectMembershipRole } from "@app/hooks/api/roles/types";++import { SkillsCard } from "./components/SkillsCard";++export const AgentVaultSkillsPage = () => {+ const { hasProjectRole } = useProjectPermission();+ const isAdmin = hasProjectRole(ProjectMembershipRole.Admin);++ return (+ <div className="mx-auto mb-6 flex w-full max-w-8xl flex-col">+ <PageTitle title="Skills" />++ <PageHeader+ scope={ProjectType.AgentVault}+ icon={BookOpenTextIcon}+ title="Skills"+ description="Keep the instructions agents follow and deliver them through access bundles."+ />+ {isAdmin ? <SkillsCard /> : <AccessRestrictedDialog />}+ </div>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSkillsPage/components/SkillsCard.tsx b/frontend/src/pages/agent-vault/AgentVaultSkillsPage/components/SkillsCard.tsxnew file mode 100644index 0000000000..bf008da633--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSkillsPage/components/SkillsCard.tsx@@ -0,0 +1,326 @@+import { useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { format } from "date-fns";+import {+ DownloadIcon,+ MoreHorizontalIcon,+ PencilIcon,+ PlusIcon,+ SearchIcon,+ TrashIcon+} from "lucide-react";++import { CreateSkillSheet } from "@app/components/agent-vault/skills/CreateSkillSheet";+import { DeleteSkillDialog } from "@app/components/agent-vault/skills/DeleteSkillDialog";+import { downloadSkillVersion } from "@app/components/agent-vault/skills/downloadSkillVersion";+import { SkillBundleBadges } from "@app/components/agent-vault/skills/SkillBundleBadges";+import { SkillDescription } from "@app/components/agent-vault/skills/SkillDescription";+import { SkillSheet } from "@app/components/agent-vault/skills/SkillSheet";+import { createNotification } from "@app/components/notifications";+import {+ Button,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ DocumentationLinkBadge,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ IconButton,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ Pagination,+ RowLink,+ Skeleton,+ Table,+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";+import {+ ProjectPermissionAgentVaultSkillActions,+ ProjectPermissionSub,+ useOrganization,+ useProjectPermission+} from "@app/context";+import {+ getUserTablePreference,+ PreferenceKey,+ setUserTablePreference+} from "@app/helpers/userTablePreferences";+import { useDebounce, useResetPageHelper } from "@app/hooks";+import {+ agentVaultKeys,+ fetchAgentVaultSkillVersion,+ useListAgentVaultSkills+} from "@app/hooks/api/agentVault";+import { TAgentVaultSkill } from "@app/hooks/api/agentVault/types";+import { useAgentVaultSheetState } from "@app/hooks/useAgentVaultSheetState";++import { AgentVaultDocsUrls } from "../../agent-vault-docs-urls";++export const SkillsCard = () => {+ const { openSheet } = useAgentVaultSheetState("skillId");+ const { currentOrg } = useOrganization();+ const queryClient = useQueryClient();+ const { permission } = useProjectPermission();+ const canCreate = permission.can(+ ProjectPermissionAgentVaultSkillActions.Create,+ ProjectPermissionSub.AgentVaultSkills+ );+ const canEdit = permission.can(+ ProjectPermissionAgentVaultSkillActions.Edit,+ ProjectPermissionSub.AgentVaultSkills+ );+ const canDelete = permission.can(+ ProjectPermissionAgentVaultSkillActions.Delete,+ ProjectPermissionSub.AgentVaultSkills+ );++ const [search, setSearch] = useState("");+ const [debouncedSearch] = useDebounce(search);+ const [page, setPage] = useState(1);+ const [perPage, setPerPage] = useState(() =>+ getUserTablePreference("agentVaultSkillsTable", PreferenceKey.PerPage, 20)+ );+ const [isCreateOpen, setIsCreateOpen] = useState(false);+ const [skillToDelete, setSkillToDelete] = useState<TAgentVaultSkill | null>(null);++ const searchTerm = debouncedSearch.trim();++ // The page goes back to 1 in the same render the debounced search lands in, as on the variables page.+ const [pagedSearchTerm, setPagedSearchTerm] = useState(searchTerm);+ if (pagedSearchTerm !== searchTerm) {+ setPagedSearchTerm(searchTerm);+ setPage(1);+ }+ const { data, isPending } = useListAgentVaultSkills({+ search: searchTerm || undefined,+ limit: perPage,+ offset: (page - 1) * perPage+ });+ const displayed = data?.skills ?? [];+ const totalCount = data?.totalCount ?? 0;+ useResetPageHelper({ totalCount, offset: (page - 1) * perPage, setPage });+ const hasSkills = totalCount > 0 || Boolean(searchTerm);++ const openSkill = (skill: Pick<TAgentVaultSkill, "id">) => openSheet(skill.id);++ const downloadSkill = async (skill: TAgentVaultSkill) => {+ try {+ const version = await queryClient.fetchQuery({+ queryKey: agentVaultKeys.skillVersion(currentOrg.id, skill.id, skill.latestVersion),+ queryFn: () => fetchAgentVaultSkillVersion(skill.id, skill.latestVersion),+ staleTime: Infinity+ });+ downloadSkillVersion(skill.name, version);+ } catch {+ createNotification({ text: `Couldn't download "${skill.name}". Try again.`, type: "error" });+ }+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle>+ Skills+ <DocumentationLinkBadge href={AgentVaultDocsUrls.skills} />+ </CardTitle>+ <CardDescription>+ A skill is a folder of instructions agents load when a task calls for it, delivered+ through the access bundles you add it to.+ </CardDescription>+ {canCreate && (+ <CardAction>+ <Button variant="av" onClick={() => setIsCreateOpen(true)}>+ <PlusIcon />+ Create Skill+ </Button>+ </CardAction>+ )}+ </CardHeader>++ {hasSkills && (+ <CardContent>+ <InputGroup>+ <InputGroupAddon>+ <SearchIcon />+ </InputGroupAddon>+ <InputGroupInput+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ placeholder="Search skills..."+ />+ </InputGroup>+ </CardContent>+ )}++ {!isPending && displayed.length === 0 ? (+ <CardContent>+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>{hasSkills ? "No skills match your search" : "No skills yet"}</EmptyTitle>+ <EmptyDescription>+ {hasSkills+ ? "Try a different search term."+ : "Create or upload a skill, or push one with the Infisical CLI."}+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ </CardContent>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead isTruncatable className="w-1/4">+ Name+ </TableHead>+ <TableHead isTruncatable className="w-2/5">+ Description+ </TableHead>+ <TableHead className="w-1/4">Access Bundles</TableHead>+ <TableHead>Updated</TableHead>+ <TableHead variant="action" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {isPending &&+ Array.from({ length: 3 }).map((_, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableRow key={`skill-skeleton-${index}`}>+ {Array.from({ length: 4 }).map((__, cell) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableCell key={`skill-skeleton-${index}-${cell}`}>+ <Skeleton className="h-4 w-full" />+ </TableCell>+ ))}+ <TableCell variant="action" />+ </TableRow>+ ))}+ {!isPending &&+ displayed.map((skill) => (+ <TableRow key={skill.id} linked>+ <TableCell isTruncatable>+ <RowLink+ to="/organizations/$orgId/agent-vault/skills"+ params={{ orgId: currentOrg.id }}+ search={{ skillId: skill.id }}+ title={skill.name}+ >+ {skill.name}+ </RowLink>+ </TableCell>+ <TableCell isTruncatable>+ <SkillDescription description={skill.description} />+ </TableCell>+ <TableCell>+ <SkillBundleBadges accessBundles={skill.accessBundles} />+ </TableCell>+ <TableCell>+ <Tooltip>+ <TooltipTrigger asChild>+ <span className="text-sm">+ {format(new Date(skill.updatedAt), "MMM d, yyyy")}+ </span>+ </TooltipTrigger>+ <TooltipContent>+ {format(new Date(skill.updatedAt), "MMM d, yyyy h:mm a")}+ </TooltipContent>+ </Tooltip>+ </TableCell>+ <TableCell variant="action">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ variant="ghost"+ size="xs"+ aria-label="Open skill actions"+ onClick={(event) => event.stopPropagation()}+ >+ <MoreHorizontalIcon />+ </IconButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ sideOffset={2}+ align="end"+ onClick={(event) => event.stopPropagation()}+ >+ {canEdit && (+ <DropdownMenuItem onClick={() => openSkill(skill)}>+ <PencilIcon />+ Edit+ </DropdownMenuItem>+ )}+ <DropdownMenuItem onClick={() => downloadSkill(skill)}>+ <DownloadIcon />+ Download+ </DropdownMenuItem>+ {canDelete && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="danger"+ onClick={() => setSkillToDelete(skill)}+ >+ <TrashIcon />+ Delete+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ </TableCell>+ </TableRow>+ ))}+ </TableBody>+ </Table>+ )}++ {totalCount > 0 && (+ <CardContent className="-mt-5 pt-0">+ <Pagination+ count={totalCount}+ page={page}+ perPage={perPage}+ onChangePage={setPage}+ onChangePerPage={(newPerPage) => {+ setPerPage(newPerPage);+ setPage(1);+ setUserTablePreference("agentVaultSkillsTable", PreferenceKey.PerPage, newPerPage);+ }}+ />+ </CardContent>+ )}++ <CreateSkillSheet+ isOpen={isCreateOpen}+ onOpenChange={setIsCreateOpen}+ onCreated={(skill) => openSkill(skill)}+ />++ <SkillSheet />++ <DeleteSkillDialog+ skill={skillToDelete}+ onOpenChange={(isOpen) => {+ if (!isOpen) setSkillToDelete(null);+ }}+ />+ </Card>+ );+};diff --git a/frontend/src/pages/agent-vault/AgentVaultSkillsPage/route.tsx b/frontend/src/pages/agent-vault/AgentVaultSkillsPage/route.tsxnew file mode 100644index 0000000000..ba1b465903--- /dev/null+++ b/frontend/src/pages/agent-vault/AgentVaultSkillsPage/route.tsx@@ -0,0 +1,19 @@+import { createFileRoute, stripSearchParams } from "@tanstack/react-router";+import { zodValidator } from "@tanstack/zod-adapter";++import { agentVaultSkillSheetSearchParams } from "@app/hooks/useAgentVaultSheetState";++import { AgentVaultSkillsPage } from "./AgentVaultSkillsPage";++export const Route = createFileRoute(+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/skills"+)({+ component: AgentVaultSkillsPage,+ validateSearch: zodValidator(agentVaultSkillSheetSearchParams),+ search: {+ middlewares: [stripSearchParams({ skillId: undefined })]+ },+ beforeLoad: ({ context }) => {+ return { breadcrumbs: [...context.breadcrumbs, { label: "Skills" }] };+ }+});diff --git a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts b/frontend/src/pages/agent-vault/agent-vault-docs-urls.tsindex e25e18d86f..23b91a6fbb 100644--- a/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts+++ b/frontend/src/pages/agent-vault/agent-vault-docs-urls.ts@@ -7,6 +7,7 @@ export const AgentVaultDocsUrls = {services: `${AGENT_VAULT_DOCS_BASE_URL}/services`,memberProvidedValues: `${AGENT_VAULT_DOCS_BASE_URL}/http-apis#member-provided-values`,variables: `${AGENT_VAULT_DOCS_BASE_URL}/variables`,+ skills: `${AGENT_VAULT_DOCS_BASE_URL}/skills`,sessions: `${AGENT_VAULT_DOCS_BASE_URL}/sessions`,proxies: `${AGENT_VAULT_DOCS_BASE_URL}/proxies`,sessionLogs: `${AGENT_VAULT_DOCS_BASE_URL}/session-logs`diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsxindex f755bf7792..8e32758f90 100644--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx@@ -16,6 +16,7 @@ import {ProjectPermissionAgentVaultAccessBundleActions,ProjectPermissionAgentVaultProxyActions,ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionAgentVaultSkillActions,ProjectPermissionCertificateActions,ProjectPermissionCertificateAuthorityActions,ProjectPermissionCertificatePolicyActions,@@ -314,6 +315,13 @@ const AgentVaultProxyPolicyActionSchema = z.object({[ProjectPermissionAgentVaultProxyActions.Revoke]: z.boolean().optional()});+const AgentVaultSkillPolicyActionSchema = z.object({+ [ProjectPermissionAgentVaultSkillActions.Read]: z.boolean().optional(),+ [ProjectPermissionAgentVaultSkillActions.Create]: z.boolean().optional(),+ [ProjectPermissionAgentVaultSkillActions.Edit]: z.boolean().optional(),+ [ProjectPermissionAgentVaultSkillActions.Delete]: z.boolean().optional()+});+const ProjectFolderGrantPolicyActionSchema = z.object({[ProjectPermissionProjectFolderGrantActions.ReadGrant]: z.boolean().optional(),[ProjectPermissionProjectFolderGrantActions.CreateGrant]: z.boolean().optional(),@@ -859,6 +867,9 @@ export const projectRoleFormSchema = z.object({[ProjectPermissionSub.AgentVaultProxies]: AgentVaultProxyPolicyActionSchema.array().default([]),+ [ProjectPermissionSub.AgentVaultSkills]: AgentVaultSkillPolicyActionSchema.array().default(+ []+ ),[ProjectPermissionSub.ProjectFolderGrant]: ProjectFolderGrantPolicyActionSchema.extend({inverted: z.boolean().optional(),conditions: ConditionSchema@@ -2594,6 +2605,32 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {}]},+ [ProjectPermissionSub.AgentVaultSkills]: {+ title: "Skills",+ description: "Manage the skills access bundles deliver to agents",+ actions: [+ {+ label: "Read",+ value: ProjectPermissionAgentVaultSkillActions.Read,+ description: "View skills, their versions and files"+ },+ {+ label: "Create",+ value: ProjectPermissionAgentVaultSkillActions.Create,+ description: "Add skills"+ },+ {+ label: "Modify",+ value: ProjectPermissionAgentVaultSkillActions.Edit,+ description: "Publish and restore skill versions"+ },+ {+ label: "Remove",+ value: ProjectPermissionAgentVaultSkillActions.Delete,+ description: "Delete skills"+ }+ ]+ },[ProjectPermissionSub.ProxiedServices]: {title: "Proxied Services",description: "Manage proxied services and route agent traffic through them",@@ -3518,7 +3555,8 @@ const SecretScanningSubject = (enabled = false) => ({const AgentVaultPermissionSubjects = (enabled = false) => ({[ProjectPermissionSub.AgentVaultAccessBundles]: enabled,[ProjectPermissionSub.AgentVaultSessions]: enabled,- [ProjectPermissionSub.AgentVaultProxies]: enabled+ [ProjectPermissionSub.AgentVaultProxies]: enabled,+ [ProjectPermissionSub.AgentVaultSkills]: enabled});// scott: this structure ensures we don't forget to add project permissions to their relevant project typediff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.tsindex 8b3c1357ab..998abec4eb 100644--- a/frontend/src/routeTree.gen.ts+++ b/frontend/src/routeTree.gen.ts@@ -122,6 +122,7 @@ import { Route as certManagerInventoryPageRouteImport } from './pages/cert-managimport { Route as certManagerCertificateAuthoritiesPageRouteImport } from './pages/cert-manager/CertificateAuthoritiesPage/route'import { Route as certManagerAlertingPageRouteImport } from './pages/cert-manager/AlertingPage/route'import { Route as agentVaultAgentVaultVariablesPageRouteImport } from './pages/agent-vault/AgentVaultVariablesPage/route'+import { Route as agentVaultAgentVaultSkillsPageRouteImport } from './pages/agent-vault/AgentVaultSkillsPage/route'import { Route as agentVaultAgentVaultSettingsPageRouteImport } from './pages/agent-vault/AgentVaultSettingsPage/route'import { Route as agentVaultAgentVaultSessionsPageRouteImport } from './pages/agent-vault/AgentVaultSessionsPage/route'import { Route as agentVaultAgentVaultProxiesPageRouteImport } from './pages/agent-vault/AgentVaultProxiesPage/route'@@ -1474,6 +1475,13 @@ const agentVaultAgentVaultVariablesPageRouteRoute =getParentRoute: () => agentVaultLayoutRoute,} as any)+const agentVaultAgentVaultSkillsPageRouteRoute =+ agentVaultAgentVaultSkillsPageRouteImport.update({+ id: '/skills',+ path: '/skills',+ getParentRoute: () => agentVaultLayoutRoute,+ } as any)+const agentVaultAgentVaultSettingsPageRouteRoute =agentVaultAgentVaultSettingsPageRouteImport.update({id: '/settings',@@ -3408,6 +3416,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof agentVaultAgentVaultSettingsPageRouteImportparentRoute: typeof agentVaultLayoutImport}+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/skills': {+ id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/skills'+ path: '/skills'+ fullPath: '/organizations/$orgId/agent-vault/skills'+ preLoaderRoute: typeof agentVaultAgentVaultSkillsPageRouteImport+ parentRoute: typeof agentVaultLayoutImport+ }'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables': {id: '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables'path: '/variables'@@ -5420,6 +5435,7 @@ interface agentVaultLayoutRouteChildren {agentVaultAgentVaultProxiesPageRouteRoute: typeof agentVaultAgentVaultProxiesPageRouteRouteagentVaultAgentVaultSessionsPageRouteRoute: typeof agentVaultAgentVaultSessionsPageRouteRouteagentVaultAgentVaultSettingsPageRouteRoute: typeof agentVaultAgentVaultSettingsPageRouteRoute+ agentVaultAgentVaultSkillsPageRouteRoute: typeof agentVaultAgentVaultSkillsPageRouteRouteagentVaultAgentVaultVariablesPageRouteRoute: typeof agentVaultAgentVaultVariablesPageRouteRouteredirectsAgentVaultIndexRedirectRoute: typeof redirectsAgentVaultIndexRedirectRouteAuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRoute: typeof AuthenticateInjectOrgDetailsOrgLayoutOrganizationsOrgIdAgentVaultAgentVaultLayoutAccessBundlesRouteWithChildren@@ -5438,6 +5454,8 @@ const agentVaultLayoutRouteChildren: agentVaultLayoutRouteChildren = {agentVaultAgentVaultSessionsPageRouteRoute,agentVaultAgentVaultSettingsPageRouteRoute:agentVaultAgentVaultSettingsPageRouteRoute,+ agentVaultAgentVaultSkillsPageRouteRoute:+ agentVaultAgentVaultSkillsPageRouteRoute,agentVaultAgentVaultVariablesPageRouteRoute:agentVaultAgentVaultVariablesPageRouteRoute,redirectsAgentVaultIndexRedirectRoute: redirectsAgentVaultIndexRedirectRoute,@@ -6356,6 +6374,7 @@ export interface FileRoutesByFullPath {'/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute'/organizations/$orgId/agent-vault/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute+ '/organizations/$orgId/agent-vault/skills': typeof agentVaultAgentVaultSkillsPageRouteRoute'/organizations/$orgId/agent-vault/variables': typeof agentVaultAgentVaultVariablesPageRouteRoute'/organizations/$orgId/cert-manager/alerting': typeof certManagerAlertingPageRouteRoute'/organizations/$orgId/cert-manager/certificate-authorities': typeof certManagerCertificateAuthoritiesPageRouteRoute@@ -6647,6 +6666,7 @@ export interface FileRoutesByTo {'/organizations/$orgId/agent-vault/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/organizations/$orgId/agent-vault/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute'/organizations/$orgId/agent-vault/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute+ '/organizations/$orgId/agent-vault/skills': typeof agentVaultAgentVaultSkillsPageRouteRoute'/organizations/$orgId/agent-vault/variables': typeof agentVaultAgentVaultVariablesPageRouteRoute'/organizations/$orgId/cert-manager/alerting': typeof certManagerAlertingPageRouteRoute'/organizations/$orgId/cert-manager/certificate-authorities': typeof certManagerCertificateAuthoritiesPageRouteRoute@@ -6933,6 +6953,7 @@ export interface FileRoutesById {'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies': typeof agentVaultAgentVaultProxiesPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions': typeof agentVaultAgentVaultSessionsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings': typeof agentVaultAgentVaultSettingsPageRouteRoute+ '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/skills': typeof agentVaultAgentVaultSkillsPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables': typeof agentVaultAgentVaultVariablesPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/cert-manager/_cert-manager-layout/alerting': typeof certManagerAlertingPageRouteRoute'/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/cert-manager/_cert-manager-layout/certificate-authorities': typeof certManagerCertificateAuthoritiesPageRouteRoute@@ -7235,6 +7256,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/agent-vault/proxies'| '/organizations/$orgId/agent-vault/sessions'| '/organizations/$orgId/agent-vault/settings'+ | '/organizations/$orgId/agent-vault/skills'| '/organizations/$orgId/agent-vault/variables'| '/organizations/$orgId/cert-manager/alerting'| '/organizations/$orgId/cert-manager/certificate-authorities'@@ -7525,6 +7547,7 @@ export interface FileRouteTypes {| '/organizations/$orgId/agent-vault/proxies'| '/organizations/$orgId/agent-vault/sessions'| '/organizations/$orgId/agent-vault/settings'+ | '/organizations/$orgId/agent-vault/skills'| '/organizations/$orgId/agent-vault/variables'| '/organizations/$orgId/cert-manager/alerting'| '/organizations/$orgId/cert-manager/certificate-authorities'@@ -7809,6 +7832,7 @@ export interface FileRouteTypes {| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings'+ | '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/skills'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/cert-manager/_cert-manager-layout/alerting'| '/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/cert-manager/_cert-manager-layout/certificate-authorities'@@ -8542,6 +8566,7 @@ export const routeTree = rootRoute"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/proxies","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/sessions","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/settings",+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/skills","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/","/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/access-bundles",@@ -8649,6 +8674,10 @@ export const routeTree = rootRoute"filePath": "agent-vault/AgentVaultSettingsPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"},+ "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/skills": {+ "filePath": "agent-vault/AgentVaultSkillsPage/route.tsx",+ "parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"+ },"/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout/variables": {"filePath": "agent-vault/AgentVaultVariablesPage/route.tsx","parent": "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/agent-vault/_agent-vault-layout"diff --git a/frontend/src/routes.ts b/frontend/src/routes.tsindex aafa47e56e..58305e630e 100644--- a/frontend/src/routes.ts+++ b/frontend/src/routes.ts@@ -387,6 +387,7 @@ const agentVaultRoutes = route("/organizations/$orgId/agent-vault", [route("/$accessBundleId", "agent-vault/AgentVaultAccessBundleDetailPage/route.tsx")]),route("/variables", "agent-vault/AgentVaultVariablesPage/route.tsx"),+ route("/skills", "agent-vault/AgentVaultSkillsPage/route.tsx"),route("/proxies", "agent-vault/AgentVaultProxiesPage/route.tsx"),route("/settings", "agent-vault/AgentVaultSettingsPage/route.tsx"),route("/audit-logs", "project/AuditLogsPage/route-agent-vault.tsx"),diff --git a/nginx/default.conf b/nginx/default.confindex b4d61b570a..4125fd9921 100644--- a/nginx/default.conf+++ b/nginx/default.conf@@ -28,6 +28,27 @@ server {proxy_cookie_path / "/; HttpOnly; SameSite=strict";}+ # Skill uploads accept up to 1MB of files (~1.37MB base64 + JSON on the wire).+ # Scoped to creating (POST /skills) and updating (PATCH /skills/:skillId) a skill, not all of /api.+ location ~ ^/api/v1/agent-vault/skills(/[^/]+)?/?$ {+ client_max_body_size 2M;++ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;++ proxy_set_header Host $http_host;+ proxy_set_header X-NginX-Proxy true;++ # This header is populated only by the dedicated TLS-cert-auth location.+ proxy_set_header X-Identity-Tls-Cert-Auth-Client-Cert "";++ proxy_pass http://backend:4000;+ proxy_redirect off;++ # proxy_cookie_path / "/; secure; HttpOnly; SameSite=strict";+ proxy_cookie_path / "/; HttpOnly; SameSite=strict";+ }+# KMS encrypt/decrypt/sign/verify accept payloads up to 1MB (~1.37MB base64 + JSON on the wire).# Scoped here so the larger body limit applies only to these endpoints, not all of /api.location ~ ^/api/v1/kms/keys/[^/]+/(encrypt|decrypt|sign|verify)$ {diff --git a/nginx/default.dev.conf b/nginx/default.dev.confindex c9cdc51ae1..fadbccd959 100644--- a/nginx/default.dev.conf+++ b/nginx/default.dev.conf@@ -35,6 +35,26 @@ server {proxy_cookie_path / "/; SameSite=strict";}+ # Skill uploads accept up to 1MB of files (~1.37MB base64 + JSON on the wire).+ # Scoped to creating (POST /skills) and updating (PATCH /skills/:skillId) a skill, not all of /api.+ location ~ ^/api/v1/agent-vault/skills(/[^/]+)?/?$ {+ client_max_body_size 2M;++ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;++ proxy_set_header Host $http_host;+ proxy_set_header X-NginX-Proxy true;++ # This header is populated only by the dedicated TLS-cert-auth location.+ proxy_set_header X-Identity-Tls-Cert-Auth-Client-Cert "";++ proxy_pass http://api;+ proxy_redirect off;++ proxy_cookie_path / "/; SameSite=strict";+ }+# KMS encrypt/decrypt/sign/verify accept payloads up to 1MB (~1.37MB base64 + JSON on the wire).# Scoped here so the larger body limit applies only to these endpoints, not all of /api.location ~ ^/api/v1/kms/keys/[^/]+/(encrypt|decrypt|sign|verify)$ {