Skip to content

The open-source app everyone uses to manage agents at work

Pin imported GitHub skills and add update checks

Dotta7e43020a28a1
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index f87961f010..412bf68f19 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -68,13 +68,18 @@ export type {
CompanySkillSourceType,
CompanySkillTrustLevel,
CompanySkillCompatibility,
+ CompanySkillSourceBadge,
CompanySkillFileInventoryEntry,
CompanySkill,
CompanySkillListItem,
CompanySkillUsageAgent,
CompanySkillDetail,
+ CompanySkillUpdateStatus,
CompanySkillImportRequest,
CompanySkillImportResult,
+ CompanySkillCreateRequest,
+ CompanySkillFileDetail,
+ CompanySkillFileUpdateRequest,
AgentSkillSyncMode,
AgentSkillState,
AgentSkillEntry,
@@ -251,12 +256,17 @@ export {
companySkillSourceTypeSchema,
companySkillTrustLevelSchema,
companySkillCompatibilitySchema,
+ companySkillSourceBadgeSchema,
companySkillFileInventoryEntrySchema,
companySkillSchema,
companySkillListItemSchema,
companySkillUsageAgentSchema,
companySkillDetailSchema,
+ companySkillUpdateStatusSchema,
companySkillImportSchema,
+ companySkillCreateSchema,
+ companySkillFileDetailSchema,
+ companySkillFileUpdateSchema,
portabilityIncludeSchema,
portabilityEnvInputSchema,
portabilityCompanyManifestEntrySchema,
diff --git a/packages/shared/src/types/company-skill.ts b/packages/shared/src/types/company-skill.ts
index 152dc67e94..4476d1b23d 100644
--- a/packages/shared/src/types/company-skill.ts
+++ b/packages/shared/src/types/company-skill.ts
@@ -4,6 +4,8 @@ export type CompanySkillTrustLevel = "markdown_only" | "assets" | "scripts_execu
export type CompanySkillCompatibility = "compatible" | "unknown" | "invalid";
+export type CompanySkillSourceBadge = "paperclip" | "github" | "local" | "url" | "catalog";
+
export interface CompanySkillFileInventoryEntry {
path: string;
kind: "skill" | "markdown" | "reference" | "script" | "asset" | "other";
@@ -29,6 +31,10 @@ export interface CompanySkill {
export interface CompanySkillListItem extends CompanySkill {
attachedAgentCount: number;
+ editable: boolean;
+ editableReason: string | null;
+ sourceLabel: string | null;
+ sourceBadge: CompanySkillSourceBadge;
}
export interface CompanySkillUsageAgent {
@@ -43,6 +49,19 @@ export interface CompanySkillUsageAgent {
export interface CompanySkillDetail extends CompanySkill {
attachedAgentCount: number;
usedByAgents: CompanySkillUsageAgent[];
+ editable: boolean;
+ editableReason: string | null;
+ sourceLabel: string | null;
+ sourceBadge: CompanySkillSourceBadge;
+}
+
+export interface CompanySkillUpdateStatus {
+ supported: boolean;
+ reason: string | null;
+ trackingRef: string | null;
+ currentRef: string | null;
+ latestRef: string | null;
+ hasUpdate: boolean;
}
export interface CompanySkillImportRequest {
@@ -53,3 +72,25 @@ export interface CompanySkillImportResult {
imported: CompanySkill[];
warnings: string[];
}
+
+export interface CompanySkillCreateRequest {
+ name: string;
+ slug?: string | null;
+ description?: string | null;
+ markdown?: string | null;
+}
+
+export interface CompanySkillFileDetail {
+ skillId: string;
+ path: string;
+ kind: CompanySkillFileInventoryEntry["kind"];
+ content: string;
+ language: string | null;
+ markdown: boolean;
+ editable: boolean;
+}
+
+export interface CompanySkillFileUpdateRequest {
+ path: string;
+ content: string;
+}
diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts
index 84e9864fe4..283dade491 100644
--- a/packages/shared/src/types/index.ts
+++ b/packages/shared/src/types/index.ts
@@ -3,13 +3,18 @@ export type {
CompanySkillSourceType,
CompanySkillTrustLevel,
CompanySkillCompatibility,
+ CompanySkillSourceBadge,
CompanySkillFileInventoryEntry,
CompanySkill,
CompanySkillListItem,
CompanySkillUsageAgent,
CompanySkillDetail,
+ CompanySkillUpdateStatus,
CompanySkillImportRequest,
CompanySkillImportResult,
+ CompanySkillCreateRequest,
+ CompanySkillFileDetail,
+ CompanySkillFileUpdateRequest,
} from "./company-skill.js";
export type {
AgentSkillSyncMode,
diff --git a/packages/shared/src/validators/company-skill.ts b/packages/shared/src/validators/company-skill.ts
index 422d25a0e9..a298398244 100644
--- a/packages/shared/src/validators/company-skill.ts
+++ b/packages/shared/src/validators/company-skill.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
export const companySkillSourceTypeSchema = z.enum(["local_path", "github", "url", "catalog"]);
export const companySkillTrustLevelSchema = z.enum(["markdown_only", "assets", "scripts_executables"]);
export const companySkillCompatibilitySchema = z.enum(["compatible", "unknown", "invalid"]);
+export const companySkillSourceBadgeSchema = z.enum(["paperclip", "github", "local", "url", "catalog"]);
export const companySkillFileInventoryEntrySchema = z.object({
path: z.string().min(1),
@@ -29,6 +30,10 @@ export const companySkillSchema = z.object({
export const companySkillListItemSchema = companySkillSchema.extend({
attachedAgentCount: z.number().int().nonnegative(),
+ editable: z.boolean(),
+ editableReason: z.string().nullable(),
+ sourceLabel: z.string().nullable(),
+ sourceBadge: companySkillSourceBadgeSchema,
});
export const companySkillUsageAgentSchema = z.object({
@@ -43,10 +48,47 @@ export const companySkillUsageAgentSchema = z.object({
export const companySkillDetailSchema = companySkillSchema.extend({
attachedAgentCount: z.number().int().nonnegative(),
usedByAgents: z.array(companySkillUsageAgentSchema).default([]),
+ editable: z.boolean(),
+ editableReason: z.string().nullable(),
+ sourceLabel: z.string().nullable(),
+ sourceBadge: companySkillSourceBadgeSchema,
+});
+
+export const companySkillUpdateStatusSchema = z.object({
+ supported: z.boolean(),
+ reason: z.string().nullable(),
+ trackingRef: z.string().nullable(),
+ currentRef: z.string().nullable(),
+ latestRef: z.string().nullable(),
+ hasUpdate: z.boolean(),
});
export const companySkillImportSchema = z.object({
source: z.string().min(1),
});
+export const companySkillCreateSchema = z.object({
+ name: z.string().min(1),
+ slug: z.string().min(1).nullable().optional(),
+ description: z.string().nullable().optional(),
+ markdown: z.string().nullable().optional(),
+});
+
+export const companySkillFileDetailSchema = z.object({
+ skillId: z.string().uuid(),
+ path: z.string().min(1),
+ kind: z.enum(["skill", "markdown", "reference", "script", "asset", "other"]),
+ content: z.string(),
+ language: z.string().nullable(),
+ markdown: z.boolean(),
+ editable: z.boolean(),
+});
+
+export const companySkillFileUpdateSchema = z.object({
+ path: z.string().min(1),
+ content: z.string(),
+});
+
export type CompanySkillImport = z.infer<typeof companySkillImportSchema>;
+export type CompanySkillCreate = z.infer<typeof companySkillCreateSchema>;
+export type CompanySkillFileUpdate = z.infer<typeof companySkillFileUpdateSchema>;
diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts
index f65256bd84..ae7a874551 100644
--- a/packages/shared/src/validators/index.ts
+++ b/packages/shared/src/validators/index.ts
@@ -8,13 +8,20 @@ export {
companySkillSourceTypeSchema,
companySkillTrustLevelSchema,
companySkillCompatibilitySchema,
+ companySkillSourceBadgeSchema,
companySkillFileInventoryEntrySchema,
companySkillSchema,
companySkillListItemSchema,
companySkillUsageAgentSchema,
companySkillDetailSchema,
+ companySkillUpdateStatusSchema,
companySkillImportSchema,
+ companySkillCreateSchema,
+ companySkillFileDetailSchema,
+ companySkillFileUpdateSchema,
type CompanySkillImport,
+ type CompanySkillCreate,
+ type CompanySkillFileUpdate,
} from "./company-skill.js";
export {
agentSkillStateSchema,
diff --git a/server/src/__tests__/company-skills.test.ts b/server/src/__tests__/company-skills.test.ts
index eb744b9bec..d092abd9b5 100644
--- a/server/src/__tests__/company-skills.test.ts
+++ b/server/src/__tests__/company-skills.test.ts
@@ -9,7 +9,7 @@ describe("company skill import source parsing", () => {
expect(parsed.resolvedSource).toBe("https://github.com/vercel-labs/skills");
expect(parsed.requestedSkillSlug).toBe("find-skills");
- expect(parsed.warnings[0]).toContain("skills.sh command");
+ expect(parsed.warnings).toEqual([]);
});
it("parses owner/repo/skill shorthand as a GitHub repo plus requested skill", () => {
@@ -18,4 +18,13 @@ describe("company skill import source parsing", () => {
expect(parsed.resolvedSource).toBe("https://github.com/vercel-labs/skills");
expect(parsed.requestedSkillSlug).toBe("find-skills");
});
+
+ it("parses skills.sh commands whose requested skill differs from the folder name", () => {
+ const parsed = parseSkillImportSourceInput(
+ "npx skills add https://github.com/remotion-dev/skills --skill remotion-best-practices",
+ );
+
+ expect(parsed.resolvedSource).toBe("https://github.com/remotion-dev/skills");
+ expect(parsed.requestedSkillSlug).toBe("remotion-best-practices");
+ });
});
diff --git a/server/src/routes/company-skills.ts b/server/src/routes/company-skills.ts
index 5219a97a22..1fee1a0606 100644
--- a/server/src/routes/company-skills.ts
+++ b/server/src/routes/company-skills.ts
@@ -1,6 +1,10 @@
import { Router } from "express";
import type { Db } from "@paperclipai/db";
-import { companySkillImportSchema } from "@paperclipai/shared";
+import {
+ companySkillCreateSchema,
+ companySkillFileUpdateSchema,
+ companySkillImportSchema,
+} from "@paperclipai/shared";
import { validate } from "../middleware/validate.js";
import { companySkillService, logActivity } from "../services/index.js";
import { assertCompanyAccess, getActorInfo } from "./authz.js";
@@ -28,6 +32,93 @@ export function companySkillRoutes(db: Db) {
res.json(result);
});
+ router.get("/companies/:companyId/skills/:skillId/update-status", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.updateStatus(companyId, skillId);
+ if (!result) {
+ res.status(404).json({ error: "Skill not found" });
+ return;
+ }
+ res.json(result);
+ });
+
+ router.get("/companies/:companyId/skills/:skillId/files", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ const relativePath = String(req.query.path ?? "SKILL.md");
+ assertCompanyAccess(req, companyId);
+ const result = await svc.readFile(companyId, skillId, relativePath);
+ if (!result) {
+ res.status(404).json({ error: "Skill not found" });
+ return;
+ }
+ res.json(result);
+ });
+
+ router.post(
+ "/companies/:companyId/skills",
+ validate(companySkillCreateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.createLocalSkill(companyId, req.body);
+
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_created",
+ entityType: "company_skill",
+ entityId: result.id,
+ details: {
+ slug: result.slug,
+ name: result.name,
+ },
+ });
+
+ res.status(201).json(result);
+ },
+ );
+
+ router.patch(
+ "/companies/:companyId/skills/:skillId/files",
+ validate(companySkillFileUpdateSchema),
+ async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.updateFile(
+ companyId,
+ skillId,
+ String(req.body.path ?? ""),
+ String(req.body.content ?? ""),
+ );
+
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_file_updated",
+ entityType: "company_skill",
+ entityId: skillId,
+ details: {
+ path: result.path,
+ markdown: result.markdown,
+ },
+ });
+
+ res.json(result);
+ },
+ );
+
router.post(
"/companies/:companyId/skills/import",
validate(companySkillImportSchema),
@@ -59,5 +150,34 @@ export function companySkillRoutes(db: Db) {
},
);
+ router.post("/companies/:companyId/skills/:skillId/install-update", async (req, res) => {
+ const companyId = req.params.companyId as string;
+ const skillId = req.params.skillId as string;
+ assertCompanyAccess(req, companyId);
+ const result = await svc.installUpdate(companyId, skillId);
+ if (!result) {
+ res.status(404).json({ error: "Skill not found" });
+ return;
+ }
+
+ const actor = getActorInfo(req);
+ await logActivity(db, {
+ companyId,
+ actorType: actor.actorType,
+ actorId: actor.actorId,
+ agentId: actor.agentId,
+ runId: actor.runId,
+ action: "company.skill_update_installed",
+ entityType: "company_skill",
+ entityId: result.id,
+ details: {
+ slug: result.slug,
+ sourceRef: result.sourceRef,
+ },
+ });
+
+ res.json(result);
+ });
+
return router;
}
diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts
index d67ec738d6..ccc309338f 100644
--- a/server/src/services/company-skills.ts
+++ b/server/src/services/company-skills.ts
@@ -6,18 +6,23 @@ import type { Db } from "@paperclipai/db";
import { companySkills } from "@paperclipai/db";
import type {
CompanySkill,
+ CompanySkillCreateRequest,
CompanySkillCompatibility,
CompanySkillDetail,
+ CompanySkillFileDetail,
CompanySkillFileInventoryEntry,
CompanySkillImportResult,
CompanySkillListItem,
+ CompanySkillSourceBadge,
CompanySkillSourceType,
CompanySkillTrustLevel,
+ CompanySkillUpdateStatus,
CompanySkillUsageAgent,
} from "@paperclipai/shared";
import { normalizeAgentUrlKey } from "@paperclipai/shared";
import { readPaperclipSkillSyncPreference } from "@paperclipai/adapter-utils/server-utils";
import { findServerAdapter } from "../adapters/index.js";
+import { resolvePaperclipInstanceRoot } from "../home-paths.js";
import { notFound, unprocessable } from "../errors.js";
import { agentService } from "./agents.js";
import { secretService } from "./secrets.js";
@@ -44,6 +49,15 @@ type ParsedSkillImportSource = {
warnings: string[];
};
+type SkillSourceMeta = {
+ sourceKind?: string;
+ owner?: string;
+ repo?: string;
+ ref?: string;
+ trackingRef?: string;
+ repoSkillDir?: string;
+};
+
function asString(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
@@ -233,6 +247,24 @@ async function fetchJson<T>(url: string): Promise<T> {
return response.json() as Promise<T>;
}
+async function resolveGitHubDefaultBranch(owner: string, repo: string) {
+ const response = await fetchJson<{ default_branch?: string }>(
+ `https://api.github.com/repos/${owner}/${repo}`,
+ );
+ return asString(response.default_branch) ?? "main";
+}
+
+async function resolveGitHubCommitSha(owner: string, repo: string, ref: string) {
+ const response = await fetchJson<{ sha?: string }>(
+ `https://api.github.com/repos/${owner}/${repo}/commits/${encodeURIComponent(ref)}`,
+ );
+ const sha = asString(response.sha);
+ if (!sha) {
+ throw unprocessable(`Failed to resolve GitHub ref ${ref}`);
+ }
+ return sha;
+}
+
function parseGitHubSourceUrl(rawUrl: string) {
const url = new URL(rawUrl);
if (url.hostname !== "github.com") {
@@ -247,15 +279,33 @@ function parseGitHubSourceUrl(rawUrl: string) {
let ref = "main";
let basePath = "";
let filePath: string | null = null;
+ let explicitRef = false;
if (parts[2] === "tree") {
ref = parts[3] ?? "main";
basePath = parts.slice(4).join("/");
+ explicitRef = true;
} else if (parts[2] === "blob") {
ref = parts[3] ?? "main";
filePath = parts.slice(4).join("/");
basePath = filePath ? path.posix.dirname(filePath) : "";
+ explicitRef = true;
}
- return { owner, repo, ref, basePath, filePath };
+ return { owner, repo, ref, basePath, filePath, explicitRef };
+}
+
+async function resolveGitHubPinnedRef(parsed: ReturnType<typeof parseGitHubSourceUrl>) {
+ if (/^[0-9a-f]{40}$/i.test(parsed.ref.trim())) {
+ return {
+ pinnedRef: parsed.ref,
+ trackingRef: parsed.explicitRef ? parsed.ref : null,
+ };
+ }
+
+ const trackingRef = parsed.explicitRef
+ ? parsed.ref
+ : await resolveGitHubDefaultBranch(parsed.owner, parsed.repo);
+ const pinnedRef = await resolveGitHubCommitSha(parsed.owner, parsed.repo, trackingRef);
+ return { pinnedRef, trackingRef };
}
function resolveRawGitHubUrl(owner: string, repo: string, ref: string, filePath: string) {
@@ -298,7 +348,6 @@ export function parseSkillImportSourceInput(rawInput: string): ParsedSkillImport
requestedSkillSlug = normalizeSkillSlug(token.slice("--skill=".length));
}
}
- warnings.push("Parsed a skills.sh command. Paperclip imports the referenced skill package without executing shell input.");
}
}
@@ -346,6 +395,10 @@ function matchesRequestedSkill(relativeSkillPath: string, requestedSkillSlug: st
return normalizeSkillSlug(path.posix.basename(skillDir)) === requestedSkillSlug;
}
+function deriveImportedSkillSlug(frontmatter: Record<string, unknown>, fallback: string) {
+ return normalizeSkillSlug(asString(frontmatter.name)) ?? normalizeAgentUrlKey(fallback) ?? "skill";
+}
+
async function walkLocalFiles(root: string, current: string, out: string[]) {
const entries = await fs.readdir(current, { withFileTypes: true });
for (const entry of entries) {
@@ -370,7 +423,7 @@ async function readLocalSkillImports(sourcePath: string): Promise<ImportedSkill[
if (stat.isFile()) {
const markdown = await fs.readFile(resolvedPath, "utf8");
const parsed = parseFrontmatterMarkdown(markdown);
- const slug = normalizeAgentUrlKey(path.basename(path.dirname(resolvedPath))) ?? "skill";
+ const slug = deriveImportedSkillSlug(parsed.frontmatter, path.basename(path.dirname(resolvedPath)));
const inventory: CompanySkillFileInventoryEntry[] = [
{ path: "SKILL.md", kind: "skill" },
];
@@ -380,12 +433,12 @@ async function readLocalSkillImports(sourcePath: string): Promise<ImportedSkill[
description: asString(parsed.frontmatter.description),
markdown,
sourceType: "local_path",
- sourceLocator: resolvedPath,
+ sourceLocator: path.dirname(resolvedPath),
sourceRef: null,
trustLevel: deriveTrustLevel(inventory),
compatibility: "compatible",
fileInventory: inventory,
- metadata: null,
+ metadata: { sourceKind: "local_path" },
}];
}
@@ -402,7 +455,7 @@ async function readLocalSkillImports(sourcePath: string): Promise<ImportedSkill[
const skillDir = path.posix.dirname(skillPath);
const markdown = await fs.readFile(path.join(root, skillPath), "utf8");
const parsed = parseFrontmatterMarkdown(markdown);
- const slug = normalizeAgentUrlKey(path.posix.basename(skillDir)) ?? "skill";
+ const slug = deriveImportedSkillSlug(parsed.frontmatter, path.posix.basename(skillDir));
const inventory = allFiles
.filter((entry) => entry === skillPath || entry.startsWith(`${skillDir}/`))
.map((entry) => {
@@ -419,12 +472,12 @@ async function readLocalSkillImports(sourcePath: string): Promise<ImportedSkill[
description: asString(parsed.frontmatter.description),
markdown,
sourceType: "local_path",
- sourceLocator: resolvedPath,
+ sourceLocator: path.join(root, skillDir),
sourceRef: null,
trustLevel: deriveTrustLevel(inventory),
compatibility: "compatible",
fileInventory: inventory,
- metadata: null,
+ metadata: { sourceKind: "local_path" },
});
}
@@ -439,20 +492,11 @@ async function readUrlSkillImports(
const warnings: string[] = [];
if (url.includes("github.com/")) {
const parsed = parseGitHubSourceUrl(url);
- let ref = parsed.ref;
- if (!/^[0-9a-f]{40}$/i.test(ref.trim())) {
- warnings.push("GitHub skill source is not pinned to a commit SHA; imports may drift if the ref changes.");
- }
+ const { pinnedRef, trackingRef } = await resolveGitHubPinnedRef(parsed);
+ let ref = pinnedRef;
const tree = await fetchJson<{ tree?: Array<{ path: string; type: string }> }>(
`https://api.github.com/repos/${parsed.owner}/${parsed.repo}/git/trees/${ref}?recursive=1`,
- ).catch(async () => {
- if (ref === "main") {
- ref = "master";
- warnings.push("GitHub ref main not found; falling back to master.");
- return fetchJson<{ tree?: Array<{ path: string; type: string }> }>(
- `https://api.github.com/repos/${parsed.owner}/${parsed.repo}/git/trees/${ref}?recursive=1`,
- );
- }
+ ).catch(() => {
throw unprocessable(`Failed to read GitHub tree for ${url}`);
});
const allPaths = (tree.tree ?? [])
@@ -468,13 +512,11 @@ async function readUrlSkillImports(
? relativePaths.filter((entry) => entry === path.posix.relative(parsed.basePath || ".", parsed.filePath!))
: relativePaths;
const skillPaths = filteredPaths.filter(
- (entry) => path.posix.basename(entry).toLowerCase() === "skill.md" && matchesRequestedSkill(entry, requestedSkillSlug),
+ (entry) => path.posix.basename(entry).toLowerCase() === "skill.md",
);
if (skillPaths.length === 0) {
throw unprocessable(
- requestedSkillSlug
- ? `Skill ${requestedSkillSlug} was not found in the provided GitHub source.`
- : "No SKILL.md files were found in the provided GitHub source.",
+ "No SKILL.md files were found in the provided GitHub source.",
);
}
const skills: ImportedSkill[] = [];
@@ -483,7 +525,10 @@ async function readUrlSkillImports(
const markdown = await fetchText(resolveRawGitHubUrl(parsed.owner, parsed.repo, ref, repoSkillPath));
const parsedMarkdown = parseFrontmatterMarkdown(markdown);
const skillDir = path.posix.dirname(relativeSkillPath);
- const slug = normalizeAgentUrlKey(path.posix.basename(skillDir)) ?? "skill";
+ const slug = deriveImportedSkillSlug(parsedMarkdown.frontmatter, path.posix.basename(skillDir));
+ if (requestedSkillSlug && !matchesRequestedSkill(relativeSkillPath, requestedSkillSlug) && slug !== requestedSkillSlug) {
+ continue;
+ }
const inventory = filteredPaths
.filter((entry) => entry === relativeSkillPath || entry.startsWith(`${skillDir}/`))
.map((entry) => ({
@@ -502,9 +547,23 @@ async function readUrlSkillImports(
trustLevel: deriveTrustLevel(inventory),
compatibility: "compatible",
fileInventory: inventory,
- metadata: null,
+ metadata: {
+ sourceKind: "github",
+ owner: parsed.owner,
+ repo: parsed.repo,
+ ref: ref,
+ trackingRef,
+ repoSkillDir: basePrefix ? `${basePrefix}${skillDir}` : skillDir,
+ },
});
}
+ if (skills.length === 0) {
+ throw unprocessable(
+ requestedSkillSlug
+ ? `Skill ${requestedSkillSlug} was not found in the provided GitHub source.`
+ : "No SKILL.md files were found in the provided GitHub source.",
+ );
+ }
return { skills, warnings };
}
@@ -513,7 +572,7 @@ async function readUrlSkillImports(
const parsedMarkdown = parseFrontmatterMarkdown(markdown);
const urlObj = new URL(url);
const fileName = path.posix.basename(urlObj.pathname);
- const slug = normalizeAgentUrlKey(fileName.replace(/\.md$/i, "")) ?? "skill";
+ const slug = deriveImportedSkillSlug(parsedMarkdown.frontmatter, fileName.replace(/\.md$/i, ""));
const inventory: CompanySkillFileInventoryEntry[] = [{ path: "SKILL.md", kind: "skill" }];
return {
skills: [{
@@ -527,7 +586,9 @@ async function readUrlSkillImports(
trustLevel: deriveTrustLevel(inventory),
compatibility: "compatible",
fileInventory: inventory,
- metadata: null,
+ metadata: {
+ sourceKind: "url",
+ },
}],
warnings,
};
@@ -567,6 +628,131 @@ function serializeFileInventory(
}));
}
+function getSkillMeta(skill: CompanySkill): SkillSourceMeta {
+ return isPlainRecord(skill.metadata) ? skill.metadata as SkillSourceMeta : {};
+}
+
+function normalizeSkillDirectory(skill: CompanySkill) {
+ if (skill.sourceType !== "local_path" || !skill.sourceLocator) return null;
+ const resolved = path.resolve(skill.sourceLocator);
+ if (path.basename(resolved).toLowerCase() === "skill.md") {
+ return path.dirname(resolved);
+ }
+ return resolved;
+}
+
+function resolveManagedSkillsRoot(companyId: string) {
+ return path.resolve(resolvePaperclipInstanceRoot(), "skills", companyId);
+}
+
+function resolveLocalSkillFilePath(skill: CompanySkill, relativePath: string) {
+ const normalized = normalizePortablePath(relativePath);
+ const skillDir = normalizeSkillDirectory(skill);
+ if (skillDir) {
+ return path.resolve(skillDir, normalized);
+ }
+
+ if (!skill.sourceLocator) return null;
+ const fallbackRoot = path.resolve(skill.sourceLocator);
+ const directPath = path.resolve(fallbackRoot, normalized);
+ return directPath;
+}
+
+function inferLanguageFromPath(filePath: string) {
+ const fileName = path.posix.basename(filePath).toLowerCase();
+ if (fileName === "skill.md" || fileName.endsWith(".md")) return "markdown";
+ if (fileName.endsWith(".ts")) return "typescript";
+ if (fileName.endsWith(".tsx")) return "tsx";
+ if (fileName.endsWith(".js")) return "javascript";
+ if (fileName.endsWith(".jsx")) return "jsx";
+ if (fileName.endsWith(".json")) return "json";
+ if (fileName.endsWith(".yml") || fileName.endsWith(".yaml")) return "yaml";
+ if (fileName.endsWith(".sh")) return "bash";
+ if (fileName.endsWith(".py")) return "python";
+ if (fileName.endsWith(".html")) return "html";
+ if (fileName.endsWith(".css")) return "css";
+ return null;
+}
+
+function isMarkdownPath(filePath: string) {
+ const fileName = path.posix.basename(filePath).toLowerCase();
+ return fileName === "skill.md" || fileName.endsWith(".md");
+}
+
+function deriveSkillSourceInfo(skill: CompanySkill): {
+ editable: boolean;
+ editableReason: string | null;
+ sourceLabel: string | null;
+ sourceBadge: CompanySkillSourceBadge;
+} {
+ const metadata = getSkillMeta(skill);
+ const localSkillDir = normalizeSkillDirectory(skill);
+ if (metadata.sourceKind === "paperclip_bundled") {
+ return {
+ editable: false,
+ editableReason: "Bundled Paperclip skills are read-only.",
+ sourceLabel: "Paperclip bundled",
+ sourceBadge: "paperclip",
+ };
+ }
+
+ if (skill.sourceType === "github") {
+ const owner = asString(metadata.owner) ?? null;
+ const repo = asString(metadata.repo) ?? null;
+ return {
+ editable: false,
+ editableReason: "Remote GitHub skills are read-only. Fork or import locally to edit them.",
+ sourceLabel: owner && repo ? `${owner}/${repo}` : skill.sourceLocator,
+ sourceBadge: "github",
+ };
+ }
+
+ if (skill.sourceType === "url") {
+ return {
+ editable: false,
+ editableReason: "URL-based skills are read-only. Save them locally to edit them.",
+ sourceLabel: skill.sourceLocator,
+ sourceBadge: "url",
+ };
+ }
+
+ if (skill.sourceType === "local_path") {
+ const managedRoot = resolveManagedSkillsRoot(skill.companyId);
+ if (localSkillDir && localSkillDir.startsWith(managedRoot)) {
+ return {
+ editable: true,
+ editableReason: null,
+ sourceLabel: "Paperclip workspace",
+ sourceBadge: "paperclip",
+ };
+ }
+
+ return {
+ editable: true,
+ editableReason: null,
+ sourceLabel: skill.sourceLocator,
+ sourceBadge: "local",
+ };
+ }
+
+ return {
+ editable: false,
+ editableReason: "This skill source is read-only.",
+ sourceLabel: skill.sourceLocator,
+ sourceBadge: "catalog",
+ };
+}
+
+function enrichSkill(skill: CompanySkill, attachedAgentCount: number, usedByAgents: CompanySkillUsageAgent[] = []) {
+ const source = deriveSkillSourceInfo(skill);
+ return {
+ ...skill,
+ attachedAgentCount,
+ usedByAgents,
+ ...source,
+ };
+}
+
export function companySkillService(db: Db) {
const agents = agentService(db);
const secretsSvc = secretService(db);
@@ -575,7 +761,15 @@ export function companySkillService(db: Db) {
for (const skillsRoot of resolveBundledSkillsRoot()) {
const stats = await fs.stat(skillsRoot).catch(() => null);
if (!stats?.isDirectory()) continue;
- const bundledSkills = await readLocalSkillImports(skillsRoot).catch(() => [] as ImportedSkill[]);
+ const bundledSkills = await readLocalSkillImports(skillsRoot)
+ .then((skills) => skills.map((skill) => ({
+ ...skill,
+ metadata: {
+ ...(skill.metadata ?? {}),
+ sourceKind: "paperclip_bundled",
+ },
+ })))
+ .catch(() => [] as ImportedSkill[]);
if (bundledSkills.length === 0) continue;
return upsertImportedSkills(companyId, bundledSkills);
}
@@ -596,10 +790,7 @@ export function companySkillService(db: Db) {
const preference = readPaperclipSkillSyncPreference(agent.adapterConfig as Record<string, unknown>);
return preference.desiredSkills.includes(skill.slug);
}).length;
- return {
- ...skill,
- attachedAgentCount,
- };
+ return enrichSkill(skill, attachedAgentCount);
});
}
@@ -671,13 +862,205 @@ export function companySkillService(db: Db) {
const skill = await getById(id);
if (!skill || skill.companyId !== companyId) return null;
const usedByAgents = await usage(companyId, skill.slug);
+ return enrichSkill(skill, usedByAgents.length, usedByAgents);
+ }
+
+ async function updateStatus(companyId: string, skillId: string): Promise<CompanySkillUpdateStatus | null> {
+ await ensureBundledSkills(companyId);
+ const skill = await getById(skillId);
+ if (!skill || skill.companyId !== companyId) return null;
+
+ if (skill.sourceType !== "github") {
+ return {
+ supported: false,
+ reason: "Only GitHub-managed skills support update checks.",
+ trackingRef: null,
+ currentRef: skill.sourceRef ?? null,
+ latestRef: null,
+ hasUpdate: false,
+ };
+ }
+
+ const metadata = getSkillMeta(skill);
+ const owner = asString(metadata.owner);
+ const repo = asString(metadata.repo);
+ const trackingRef = asString(metadata.trackingRef) ?? asString(metadata.ref);
+ if (!owner || !repo || !trackingRef) {
+ return {
+ supported: false,
+ reason: "This GitHub skill does not have enough metadata to track updates.",
+ trackingRef: trackingRef ?? null,
+ currentRef: skill.sourceRef ?? null,
+ latestRef: null,
+ hasUpdate: false,
+ };
+ }
+
+ const latestRef = await resolveGitHubCommitSha(owner, repo, trackingRef);
+ return {
+ supported: true,
+ reason: null,
+ trackingRef,
+ currentRef: skill.sourceRef ?? null,
+ latestRef,
+ hasUpdate: latestRef !== (skill.sourceRef ?? null),
+ };
+ }
+
+ async function readFile(companyId: string, skillId: string, relativePath: string): Promise<CompanySkillFileDetail | null> {
+ await ensureBundledSkills(companyId);
+ const skill = await getById(skillId);
+ if (!skill || skill.companyId !== companyId) return null;
+
+ const normalizedPath = normalizePortablePath(relativePath || "SKILL.md");
+ const fileEntry = skill.fileInventory.find((entry) => entry.path === normalizedPath);
+ if (!fileEntry) {
+ throw notFound("Skill file not found");
+ }
+
+ const source = deriveSkillSourceInfo(skill);
+ let content = "";
+
+ if (skill.sourceType === "local_path") {
+ const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
+ if (!absolutePath) throw notFound("Skill file not found");
+ content = await fs.readFile(absolutePath, "utf8");
+ } else if (skill.sourceType === "github") {
+ const metadata = getSkillMeta(skill);
+ const owner = asString(metadata.owner);
+ const repo = asString(metadata.repo);
+ const ref = skill.sourceRef ?? asString(metadata.ref) ?? "main";
+ const repoSkillDir = normalizePortablePath(asString(metadata.repoSkillDir) ?? skill.slug);
+ if (!owner || !repo) {
+ throw unprocessable("Skill source metadata is incomplete.");
+ }
+ const repoPath = normalizePortablePath(path.posix.join(repoSkillDir, normalizedPath));
+ content = await fetchText(resolveRawGitHubUrl(owner, repo, ref, repoPath));
+ } else if (skill.sourceType === "url") {
+ if (normalizedPath !== "SKILL.md") {
+ throw notFound("This skill source only exposes SKILL.md");
+ }
+ content = skill.markdown;
+ } else {
+ throw unprocessable("Unsupported skill source.");
+ }
+
return {
- ...skill,
- attachedAgentCount: usedByAgents.length,
- usedByAgents,
+ skillId: skill.id,
+ path: normalizedPath,
+ kind: fileEntry.kind,
+ content,
+ language: inferLanguageFromPath(normalizedPath),
+ markdown: isMarkdownPath(normalizedPath),
+ editable: source.editable,
};
}
+ async function createLocalSkill(companyId: string, input: CompanySkillCreateRequest): Promise<CompanySkill> {
+ const slug = normalizeSkillSlug(input.slug ?? input.name) ?? "skill";
+ const managedRoot = resolveManagedSkillsRoot(companyId);
+ const skillDir = path.resolve(managedRoot, slug);
+ const skillFilePath = path.resolve(skillDir, "SKILL.md");
+
+ await fs.mkdir(skillDir, { recursive: true });
+
+ const markdown = (input.markdown?.trim().length
+ ? input.markdown
+ : [
+ "---",
+ `name: ${input.name}`,
+ ...(input.description?.trim() ? [`description: ${input.description.trim()}`] : []),
+ "---",
+ "",
+ `# ${input.name}`,
+ "",
+ input.description?.trim() ? input.description.trim() : "Describe what this skill does.",
+ "",
+ ].join("\n"));
+
+ await fs.writeFile(skillFilePath, markdown, "utf8");
+
+ const parsed = parseFrontmatterMarkdown(markdown);
+ const imported = await upsertImportedSkills(companyId, [{
+ slug,
+ name: asString(parsed.frontmatter.name) ?? input.name,
+ description: asString(parsed.frontmatter.description) ?? input.description?.trim() ?? null,
+ markdown,
+ sourceType: "local_path",
+ sourceLocator: skillDir,
+ sourceRef: null,
+ trustLevel: "markdown_only",
+ compatibility: "compatible",
+ fileInventory: [{ path: "SKILL.md", kind: "skill" }],
+ metadata: { sourceKind: "managed_local" },
+ }]);
+
+ return imported[0]!;
+ }
+
+ async function updateFile(companyId: string, skillId: string, relativePath: string, content: string): Promise<CompanySkillFileDetail> {
+ await ensureBundledSkills(companyId);
+ const skill = await getById(skillId);
+ if (!skill || skill.companyId !== companyId) throw notFound("Skill not found");
+
+ const source = deriveSkillSourceInfo(skill);
+ if (!source.editable || skill.sourceType !== "local_path") {
+ throw unprocessable(source.editableReason ?? "This skill cannot be edited.");
+ }
+
+ const normalizedPath = normalizePortablePath(relativePath);
+ const absolutePath = resolveLocalSkillFilePath(skill, normalizedPath);
+ if (!absolutePath) throw notFound("Skill file not found");
+
+ await fs.mkdir(path.dirname(absolutePath), { recursive: true });
+ await fs.writeFile(absolutePath, content, "utf8");
+
+ if (normalizedPath === "SKILL.md") {
+ const parsed = parseFrontmatterMarkdown(content);
+ await db
+ .update(companySkills)
+ .set({
+ name: asString(parsed.frontmatter.name) ?? skill.name,
+ description: asString(parsed.frontmatter.description) ?? skill.description,
+ markdown: content,
+ updatedAt: new Date(),
+ })
+ .where(eq(companySkills.id, skill.id));
+ } else {
+ await db
+ .update(companySkills)
+ .set({ updatedAt: new Date() })
+ .where(eq(companySkills.id, skill.id));
+ }
+
+ const detail = await readFile(companyId, skillId, normalizedPath);
+ if (!detail) throw notFound("Skill file not found");
+ return detail;
+ }
+
+ async function installUpdate(companyId: string, skillId: string): Promise<CompanySkill | null> {
+ await ensureBundledSkills(companyId);
+ const skill = await getById(skillId);
+ if (!skill || skill.companyId !== companyId) return null;
+
+ const status = await updateStatus(companyId, skillId);
+ if (!status?.supported) {
+ throw unprocessable(status?.reason ?? "This skill does not support updates.");
+ }
+ if (!skill.sourceLocator) {
+ throw unprocessable("Skill source locator is missing.");
+ }
+
+ const result = await readUrlSkillImports(skill.sourceLocator, skill.slug);
+ const matching = result.skills.find((entry) => entry.slug === skill.slug) ?? result.skills[0] ?? null;
+ if (!matching) {
+ throw unprocessable(`Skill ${skill.slug} could not be re-imported from its source.`);
+ }
+
+ const imported = await upsertImportedSkills(companyId, [matching]);
+ return imported[0] ?? null;
+ }
+
async function upsertImportedSkills(companyId: string, imported: ImportedSkill[]): Promise<CompanySkill[]> {
const out: CompanySkill[] = [];
for (const skill of imported) {
@@ -749,6 +1132,11 @@ export function companySkillService(db: Db) {
getById,
getBySlug,
detail,
+ updateStatus,
+ readFile,
+ updateFile,
+ createLocalSkill,
importFromSource,
+ installUpdate,
};
}
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index be6e467de2..005b300154 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -112,8 +112,7 @@ function boardRoutes() {
<Route path="onboarding" element={<OnboardingRoutePage />} />
<Route path="companies" element={<Companies />} />
<Route path="company/settings" element={<CompanySettings />} />
- <Route path="skills" element={<CompanySkills />} />
- <Route path="skills/:skillId" element={<CompanySkills />} />
+ <Route path="skills/*" element={<CompanySkills />} />
<Route path="settings" element={<LegacySettingsRedirect />} />
<Route path="settings/*" element={<LegacySettingsRedirect />} />
<Route path="org" element={<OrgChart />} />
@@ -305,8 +304,7 @@ export function App() {
<Route path="companies" element={<UnprefixedBoardRedirect />} />
<Route path="issues" element={<UnprefixedBoardRedirect />} />
<Route path="issues/:issueId" element={<UnprefixedBoardRedirect />} />
- <Route path="skills" element={<UnprefixedBoardRedirect />} />
- <Route path="skills/:skillId" element={<UnprefixedBoardRedirect />} />
+ <Route path="skills/*" element={<UnprefixedBoardRedirect />} />
<Route path="settings" element={<LegacySettingsRedirect />} />
<Route path="settings/*" element={<LegacySettingsRedirect />} />
<Route path="agents" element={<UnprefixedBoardRedirect />} />
diff --git a/ui/src/api/companySkills.ts b/ui/src/api/companySkills.ts
index f29896a1c4..417dbe8fd3 100644
--- a/ui/src/api/companySkills.ts
+++ b/ui/src/api/companySkills.ts
@@ -1,7 +1,11 @@
import type {
+ CompanySkill,
+ CompanySkillCreateRequest,
CompanySkillDetail,
+ CompanySkillFileDetail,
CompanySkillImportResult,
CompanySkillListItem,
+ CompanySkillUpdateStatus,
} from "@paperclipai/shared";
import { api } from "./client";
@@ -12,9 +16,32 @@ export const companySkillsApi = {
api.get<CompanySkillDetail>(
`/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}`,
),
+ updateStatus: (companyId: string, skillId: string) =>
+ api.get<CompanySkillUpdateStatus>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/update-status`,
+ ),
+ file: (companyId: string, skillId: string, relativePath: string) =>
+ api.get<CompanySkillFileDetail>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/files?path=${encodeURIComponent(relativePath)}`,
+ ),
+ updateFile: (companyId: string, skillId: string, path: string, content: string) =>
+ api.patch<CompanySkillFileDetail>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/files`,
+ { path, content },
+ ),
+ create: (companyId: string, payload: CompanySkillCreateRequest) =>
+ api.post<CompanySkill>(
+ `/companies/${encodeURIComponent(companyId)}/skills`,
+ payload,
+ ),
importFromSource: (companyId: string, source: string) =>
api.post<CompanySkillImportResult>(
`/companies/${encodeURIComponent(companyId)}/skills/import`,
{ source },
),
+ installUpdate: (companyId: string, skillId: string) =>
+ api.post<CompanySkill>(
+ `/companies/${encodeURIComponent(companyId)}/skills/${encodeURIComponent(skillId)}/install-update`,
+ {},
+ ),
};
diff --git a/ui/src/hooks/useCompanyPageMemory.test.ts b/ui/src/hooks/useCompanyPageMemory.test.ts
index a64c60b81f..4f66901521 100644
--- a/ui/src/hooks/useCompanyPageMemory.test.ts
+++ b/ui/src/hooks/useCompanyPageMemory.test.ts
@@ -39,6 +39,16 @@ describe("getRememberedPathOwnerCompanyId", () => {
}),
).toBe("pap");
});
+
+ it("treats unprefixed skills routes as board routes instead of company prefixes", () => {
+ expect(
+ getRememberedPathOwnerCompanyId({
+ companies,
+ pathname: "/skills/skill-123/files/SKILL.md",
+ fallbackCompanyId: "pap",
+ }),
+ ).toBe("pap");
+ });
});
describe("sanitizeRememberedPathForCompany", () => {
@@ -68,4 +78,13 @@ describe("sanitizeRememberedPathForCompany", () => {
}),
).toBe("/dashboard");
});
+
+ it("keeps remembered skills paths intact for the target company", () => {
+ expect(
+ sanitizeRememberedPathForCompany({
+ path: "/skills/skill-123/files/SKILL.md",
+ companyPrefix: "PAP",
+ }),
+ ).toBe("/skills/skill-123/files/SKILL.md");
+ });
});
diff --git a/ui/src/lib/company-routes.ts b/ui/src/lib/company-routes.ts
index 736e38970a..512a4e61ae 100644
--- a/ui/src/lib/company-routes.ts
+++ b/ui/src/lib/company-routes.ts
@@ -2,6 +2,7 @@ const BOARD_ROUTE_ROOTS = new Set([
"dashboard",
"companies",
"company",
+ "skills",
"org",
"agents",
"projects",
diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts
index dda0e6942c..5f94250d14 100644
--- a/ui/src/lib/queryKeys.ts
+++ b/ui/src/lib/queryKeys.ts
@@ -7,6 +7,10 @@ export const queryKeys = {
companySkills: {
list: (companyId: string) => ["company-skills", companyId] as const,
detail: (companyId: string, skillId: string) => ["company-skills", companyId, skillId] as const,
+ updateStatus: (companyId: string, skillId: string) =>
+ ["company-skills", companyId, skillId, "update-status"] as const,
+ file: (companyId: string, skillId: string, relativePath: string) =>
+ ["company-skills", companyId, skillId, "file", relativePath] as const,
},
agents: {
list: (companyId: string) => ["agents", companyId] as const,
diff --git a/ui/src/pages/CompanySkills.tsx b/ui/src/pages/CompanySkills.tsx
index 24030c4cc8..6843f39093 100644
--- a/ui/src/pages/CompanySkills.tsx
+++ b/ui/src/pages/CompanySkills.tsx
@@ -1,10 +1,14 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useMemo, useState, type SVGProps } from "react";
import { Link, useNavigate, useParams } from "@/lib/router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type {
+ CompanySkillCreateRequest,
CompanySkillDetail,
+ CompanySkillFileDetail,
+ CompanySkillFileInventoryEntry,
CompanySkillListItem,
- CompanySkillTrustLevel,
+ CompanySkillSourceBadge,
+ CompanySkillUpdateStatus,
} from "@paperclipai/shared";
import { companySkillsApi } from "../api/companySkills";
import { useCompany } from "../context/CompanyContext";
@@ -13,22 +17,62 @@ import { useToast } from "../context/ToastContext";
import { queryKeys } from "../lib/queryKeys";
import { EmptyState } from "../components/EmptyState";
import { MarkdownBody } from "../components/MarkdownBody";
+import { MarkdownEditor } from "../components/MarkdownEditor";
import { PageSkeleton } from "../components/PageSkeleton";
-import { EntityRow } from "../components/EntityRow";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { cn } from "../lib/utils";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
import {
- ArrowUpRight,
- BookOpen,
Boxes,
- FolderInput,
+ ChevronDown,
+ ChevronRight,
+ Code2,
+ Eye,
+ FileCode2,
+ FileText,
+ Folder,
+ FolderOpen,
+ Github,
+ Link2,
+ ExternalLink,
+ Paperclip,
+ Pencil,
+ Plus,
RefreshCw,
- ShieldAlert,
- ShieldCheck,
- TerminalSquare,
+ Save,
+ Search,
} from "lucide-react";
+type SkillTreeNode = {
+ name: string;
+ path: string | null;
+ kind: "dir" | "file";
+ fileKind?: CompanySkillFileInventoryEntry["kind"];
+ children: SkillTreeNode[];
+};
+
+const SKILL_TREE_BASE_INDENT = 16;
+const SKILL_TREE_STEP_INDENT = 24;
+const SKILL_TREE_ROW_HEIGHT_CLASS = "min-h-9";
+
+function VercelMark(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
+ <path d="M12 4 21 19H3z" />
+ </svg>
+ );
+}
+
function stripFrontmatter(markdown: string) {
const normalized = markdown.replace(/\r\n/g, "\n");
if (!normalized.startsWith("---\n")) return normalized.trim();
@@ -37,280 +81,807 @@ function stripFrontmatter(markdown: string) {
return normalized.slice(closing + 5).trim();
}
-function trustTone(trustLevel: CompanySkillTrustLevel) {
- switch (trustLevel) {
- case "markdown_only":
- return "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300";
- case "assets":
- return "bg-amber-500/10 text-amber-700 dark:text-amber-300";
- case "scripts_executables":
- return "bg-red-500/10 text-red-700 dark:text-red-300";
- default:
- return "bg-muted text-muted-foreground";
+function buildTree(entries: CompanySkillFileInventoryEntry[]) {
+ const root: SkillTreeNode = { name: "", path: null, kind: "dir", children: [] };
+
+ for (const entry of entries) {
+ const segments = entry.path.split("/").filter(Boolean);
+ let current = root;
+ let currentPath = "";
+ for (const [index, segment] of segments.entries()) {
+ currentPath = currentPath ? `${currentPath}/${segment}` : segment;
+ const isLeaf = index === segments.length - 1;
+ let next = current.children.find((child) => child.name === segment);
+ if (!next) {
+ next = {
+ name: segment,
+ path: isLeaf ? entry.path : currentPath,
+ kind: isLeaf ? "file" : "dir",
+ fileKind: isLeaf ? entry.kind : undefined,
+ children: [],
+ };
+ current.children.push(next);
+ }
+ current = next;
+ }
}
+
+ function sortNode(node: SkillTreeNode) {
+ node.children.sort((left, right) => {
+ if (left.kind !== right.kind) return left.kind === "dir" ? -1 : 1;
+ if (left.name === "SKILL.md") return -1;
+ if (right.name === "SKILL.md") return 1;
+ return left.name.localeCompare(right.name);
+ });
+ node.children.forEach(sortNode);
+ }
+
+ sortNode(root);
+ return root.children;
}
-function trustLabel(trustLevel: CompanySkillTrustLevel) {
- switch (trustLevel) {
- case "markdown_only":
- return "Markdown only";
- case "assets":
- return "Assets";
- case "scripts_executables":
- return "Scripts";
+function sourceMeta(sourceBadge: CompanySkillSourceBadge, sourceLabel: string | null) {
+ const normalizedLabel = sourceLabel?.toLowerCase() ?? "";
+ const isSkillsShManaged =
+ normalizedLabel.includes("skills.sh") || normalizedLabel.includes("vercel-labs/skills");
+
+ switch (sourceBadge) {
+ case "github":
+ return isSkillsShManaged
+ ? { icon: VercelMark, label: sourceLabel ?? "skills.sh", managedLabel: "skills.sh managed" }
+ : { icon: Github, label: sourceLabel ?? "GitHub", managedLabel: "GitHub managed" };
+ case "url":
+ return { icon: Link2, label: sourceLabel ?? "URL", managedLabel: "URL managed" };
+ case "local":
+ return { icon: Folder, label: sourceLabel ?? "Folder", managedLabel: "Folder managed" };
+ case "paperclip":
+ return { icon: Paperclip, label: sourceLabel ?? "Paperclip", managedLabel: "Paperclip managed" };
default:
- return trustLevel;
+ return { icon: Boxes, label: sourceLabel ?? "Catalog", managedLabel: "Catalog managed" };
}
}
-function compatibilityLabel(detail: CompanySkillDetail | CompanySkillListItem) {
- switch (detail.compatibility) {
- case "compatible":
- return "Compatible";
- case "unknown":
- return "Unknown";
- case "invalid":
- return "Invalid";
- default:
- return detail.compatibility;
+function shortRef(ref: string | null | undefined) {
+ if (!ref) return null;
+ return ref.slice(0, 7);
+}
+
+function fileIcon(kind: CompanySkillFileInventoryEntry["kind"]) {
+ if (kind === "script" || kind === "reference") return FileCode2;
+ return FileText;
+}
+
+function encodeSkillFilePath(filePath: string) {
+ return filePath.split("/").map((segment) => encodeURIComponent(segment)).join("/");
+}
+
+function decodeSkillFilePath(filePath: string | undefined) {
+ if (!filePath) return "SKILL.md";
+ return filePath
+ .split("/")
+ .filter(Boolean)
+ .map((segment) => {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+ })
+ .join("/");
+}
+
+function parseSkillRoute(routePath: string | undefined) {
+ const segments = (routePath ?? "").split("/").filter(Boolean);
+ if (segments.length === 0) {
+ return { skillId: null, filePath: "SKILL.md" };
+ }
+
+ const [rawSkillId, rawMode, ...rest] = segments;
+ const skillId = rawSkillId ? decodeURIComponent(rawSkillId) : null;
+ if (!skillId) {
+ return { skillId: null, filePath: "SKILL.md" };
+ }
+
+ if (rawMode === "files") {
+ return {
+ skillId,
+ filePath: decodeSkillFilePath(rest.join("/")),
+ };
}
+
+ return { skillId, filePath: "SKILL.md" };
+}
+
+function skillRoute(skillId: string, filePath?: string | null) {
+ return filePath ? `/skills/${skillId}/files/${encodeSkillFilePath(filePath)}` : `/skills/${skillId}`;
}
-function SkillListItem({
- skill,
- selected,
+function parentDirectoryPaths(filePath: string) {
+ const segments = filePath.split("/").filter(Boolean);
+ const parents: string[] = [];
+ for (let index = 0; index < segments.length - 1; index += 1) {
+ parents.push(segments.slice(0, index + 1).join("/"));
+ }
+ return parents;
+}
+
+function NewSkillForm({
+ onCreate,
+ isPending,
+ onCancel,
}: {
- skill: CompanySkillListItem;
- selected: boolean;
+ onCreate: (payload: CompanySkillCreateRequest) => void;
+ isPending: boolean;
+ onCancel: () => void;
}) {
+ const [name, setName] = useState("");
+ const [slug, setSlug] = useState("");
+ const [description, setDescription] = useState("");
+
return (
- <Link
- to={`/skills/${skill.id}`}
- className={cn(
- "block rounded-xl border p-3 no-underline transition-colors",
- selected
- ? "border-primary bg-primary/5"
- : "border-border/70 bg-card hover:border-border hover:bg-accent/20",
- )}
- >
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="flex items-center gap-2">
- <span className="font-medium text-sm text-foreground">{skill.name}</span>
- <span className="rounded-full border border-border/70 px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">
- {skill.slug}
- </span>
- </div>
- {skill.description && (
- <p className="mt-1 line-clamp-2 text-xs text-muted-foreground">
- {skill.description}
- </p>
- )}
+ <div className="border-b border-border px-4 py-4">
+ <div className="space-y-3">
+ <Input
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ placeholder="Skill name"
+ className="h-9 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"
+ />
+ <Input
+ value={slug}
+ onChange={(event) => setSlug(event.target.value)}
+ placeholder="optional-shortname"
+ className="h-9 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"
+ />
+ <Textarea
+ value={description}
+ onChange={(event) => setDescription(event.target.value)}
+ placeholder="Short description"
+ className="min-h-20 rounded-none border-0 border-b border-border px-0 shadow-none focus-visible:ring-0"
+ />
+ <div className="flex items-center justify-end gap-2">
+ <Button variant="ghost" size="sm" onClick={onCancel} disabled={isPending}>
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ onClick={() => onCreate({ name, slug: slug || null, description: description || null })}
+ disabled={isPending || name.trim().length === 0}
+ >
+ {isPending ? "Creating..." : "Create skill"}
+ </Button>
</div>
- <span className={cn("shrink-0 rounded-full px-2 py-1 text-[10px] font-medium", trustTone(skill.trustLevel))}>
- {trustLabel(skill.trustLevel)}
- </span>
</div>
- <div className="mt-3 flex items-center justify-between gap-3 text-[11px] text-muted-foreground">
- <span>{skill.attachedAgentCount} agent{skill.attachedAgentCount === 1 ? "" : "s"}</span>
- <span>{skill.fileInventory.length} file{skill.fileInventory.length === 1 ? "" : "s"}</span>
+ </div>
+ );
+}
+
+function SkillTree({
+ nodes,
+ skillId,
+ selectedPath,
+ expandedDirs,
+ onToggleDir,
+ onSelectPath,
+ depth = 0,
+}: {
+ nodes: SkillTreeNode[];
+ skillId: string;
+ selectedPath: string;
+ expandedDirs: Set<string>;
+ onToggleDir: (path: string) => void;
+ onSelectPath: (path: string) => void;
+ depth?: number;
+}) {
+ return (
+ <div>
+ {nodes.map((node) => {
+ const expanded = node.kind === "dir" && node.path ? expandedDirs.has(node.path) : false;
+ if (node.kind === "dir") {
+ return (
+ <div key={node.path ?? node.name}>
+ <div
+ className={cn(
+ "group grid w-full grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",
+ SKILL_TREE_ROW_HEIGHT_CLASS,
+ )}
+ >
+ <button
+ type="button"
+ className="flex min-w-0 items-center gap-2 py-1 text-left"
+ style={{ paddingLeft: `${SKILL_TREE_BASE_INDENT + depth * SKILL_TREE_STEP_INDENT}px` }}
+ onClick={() => node.path && onToggleDir(node.path)}
+ >
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">
+ {expanded ? <FolderOpen className="h-3.5 w-3.5" /> : <Folder className="h-3.5 w-3.5" />}
+ </span>
+ <span className="truncate">{node.name}</span>
+ </button>
+ <button
+ type="button"
+ className="flex h-9 w-9 items-center justify-center self-center rounded-sm text-muted-foreground opacity-70 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100"
+ onClick={() => node.path && onToggleDir(node.path)}
+ >
+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ {expanded && (
+ <SkillTree
+ nodes={node.children}
+ skillId={skillId}
+ selectedPath={selectedPath}
+ expandedDirs={expandedDirs}
+ onToggleDir={onToggleDir}
+ onSelectPath={onSelectPath}
+ depth={depth + 1}
+ />
+ )}
+ </div>
+ );
+ }
+
+ const FileIcon = fileIcon(node.fileKind ?? "other");
+ return (
+ <Link
+ key={node.path ?? node.name}
+ className={cn(
+ "flex w-full items-center gap-2 pr-3 text-left text-sm text-muted-foreground hover:bg-accent/30 hover:text-foreground",
+ SKILL_TREE_ROW_HEIGHT_CLASS,
+ node.path === selectedPath && "text-foreground",
+ )}
+ style={{ paddingInlineStart: `${SKILL_TREE_BASE_INDENT + depth * SKILL_TREE_STEP_INDENT}px` }}
+ to={skillRoute(skillId, node.path)}
+ onClick={() => node.path && onSelectPath(node.path)}
+ >
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">
+ <FileIcon className="h-3.5 w-3.5" />
+ </span>
+ <span className="truncate">{node.name}</span>
+ </Link>
+ );
+ })}
+ </div>
+ );
+}
+
+function SkillList({
+ skills,
+ selectedSkillId,
+ skillFilter,
+ expandedSkillId,
+ expandedDirs,
+ selectedPaths,
+ onToggleSkill,
+ onToggleDir,
+ onSelectSkill,
+ onSelectPath,
+}: {
+ skills: CompanySkillListItem[];
+ selectedSkillId: string | null;
+ skillFilter: string;
+ expandedSkillId: string | null;
+ expandedDirs: Record<string, Set<string>>;
+ selectedPaths: Record<string, string>;
+ onToggleSkill: (skillId: string) => void;
+ onToggleDir: (skillId: string, path: string) => void;
+ onSelectSkill: (skillId: string) => void;
+ onSelectPath: (skillId: string, path: string) => void;
+}) {
+ const filteredSkills = skills.filter((skill) => {
+ const haystack = `${skill.name} ${skill.slug} ${skill.sourceLabel ?? ""}`.toLowerCase();
+ return haystack.includes(skillFilter.toLowerCase());
+ });
+
+ if (filteredSkills.length === 0) {
+ return (
+ <div className="px-4 py-6 text-sm text-muted-foreground">
+ No skills match this filter.
</div>
- </Link>
+ );
+ }
+
+ return (
+ <div>
+ {filteredSkills.map((skill) => {
+ const expanded = expandedSkillId === skill.id;
+ const tree = buildTree(skill.fileInventory);
+ const source = sourceMeta(skill.sourceBadge, skill.sourceLabel);
+ const SourceIcon = source.icon;
+
+ return (
+ <div key={skill.id} className="border-b border-border">
+ <div
+ className={cn(
+ "group grid grid-cols-[minmax(0,1fr)_2.25rem] items-center gap-x-1 px-3 py-1.5 hover:bg-accent/30",
+ skill.id === selectedSkillId && "text-foreground",
+ )}
+ >
+ <Link
+ to={skillRoute(skill.id)}
+ className="flex min-w-0 items-center self-stretch pr-2 text-left no-underline"
+ onClick={() => onSelectSkill(skill.id)}
+ >
+ <span className="flex min-w-0 items-center gap-2 self-center">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground opacity-75 transition-opacity group-hover:opacity-100">
+ <SourceIcon className="h-3.5 w-3.5" />
+ <span className="sr-only">{source.managedLabel}</span>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="top">{source.managedLabel}</TooltipContent>
+ </Tooltip>
+ <span className="block min-w-0 overflow-hidden text-[13px] font-medium leading-5 [display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:3]">
+ {skill.name}
+ </span>
+ </span>
+ </Link>
+ <button
+ type="button"
+ className="flex h-9 w-9 shrink-0 items-center justify-center self-center rounded-sm text-muted-foreground opacity-80 transition-[background-color,color,opacity] hover:bg-accent hover:text-foreground group-hover:opacity-100"
+ onClick={() => onToggleSkill(skill.id)}
+ aria-label={expanded ? `Collapse ${skill.name}` : `Expand ${skill.name}`}
+ >
+ {expanded ? <ChevronDown className="h-3.5 w-3.5" /> : <ChevronRight className="h-3.5 w-3.5" />}
+ </button>
+ </div>
+ <div
+ aria-hidden={!expanded}
+ className={cn(
+ "grid overflow-hidden transition-[grid-template-rows,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)]",
+ expanded ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
+ )}
+ >
+ <div className="min-h-0 overflow-hidden">
+ <SkillTree
+ nodes={tree}
+ skillId={skill.id}
+ selectedPath={selectedPaths[skill.id] ?? "SKILL.md"}
+ expandedDirs={expandedDirs[skill.id] ?? new Set<string>()}
+ onToggleDir={(path) => onToggleDir(skill.id, path)}
+ onSelectPath={(path) => onSelectPath(skill.id, path)}
+ depth={1}
+ />
+ </div>
+ </div>
+ </div>
+ );
+ })}
+ </div>
);
}
-function SkillDetailPanel({
+function SkillPane({
+ loading,
detail,
- isLoading,
+ file,
+ fileLoading,
+ updateStatus,
+ updateStatusLoading,
+ viewMode,
+ editMode,
+ draft,
+ setViewMode,
+ setEditMode,
+ setDraft,
+ onCheckUpdates,
+ checkUpdatesPending,
+ onInstallUpdate,
+ installUpdatePending,
+ onSave,
+ savePending,
}: {
+ loading: boolean;
detail: CompanySkillDetail | null | undefined;
- isLoading: boolean;
+ file: CompanySkillFileDetail | null | undefined;
+ fileLoading: boolean;
+ updateStatus: CompanySkillUpdateStatus | null | undefined;
+ updateStatusLoading: boolean;
+ viewMode: "preview" | "code";
+ editMode: boolean;
+ draft: string;
+ setViewMode: (mode: "preview" | "code") => void;
+ setEditMode: (value: boolean) => void;
+ setDraft: (value: string) => void;
+ onCheckUpdates: () => void;
+ checkUpdatesPending: boolean;
+ onInstallUpdate: () => void;
+ installUpdatePending: boolean;
+ onSave: () => void;
+ savePending: boolean;
}) {
- if (isLoading) {
- return <PageSkeleton variant="detail" />;
- }
-
if (!detail) {
+ if (loading) {
+ return <PageSkeleton variant="detail" />;
+ }
return (
- <div className="rounded-2xl border border-dashed border-border bg-card/40 p-8">
- <div className="max-w-md space-y-3">
- <div className="inline-flex h-11 w-11 items-center justify-center rounded-2xl bg-accent text-accent-foreground">
- <BookOpen className="h-5 w-5" />
- </div>
- <div>
- <h2 className="text-lg font-semibold">Select a skill</h2>
- <p className="mt-1 text-sm text-muted-foreground">
- Review its markdown, inspect files, and see which agents have it attached.
- </p>
- </div>
- </div>
- </div>
+ <EmptyState
+ icon={Boxes}
+ message="Select a skill to inspect its files."
+ />
);
}
- const markdownBody = stripFrontmatter(detail.markdown);
+ const source = sourceMeta(detail.sourceBadge, detail.sourceLabel);
+ const SourceIcon = source.icon;
+ const usedBy = detail.usedByAgents;
+ const body = file?.markdown ? stripFrontmatter(file.content) : file?.content ?? "";
+ const currentPin = shortRef(detail.sourceRef);
+ const latestPin = shortRef(updateStatus?.latestRef);
return (
- <div className="space-y-5">
- <section className="overflow-hidden rounded-2xl border border-border bg-card">
- <div className="border-b border-border bg-card px-5 py-4">
- <div className="flex flex-wrap items-start justify-between gap-3">
- <div className="min-w-0">
+ <div className="min-w-0">
+ <div className="border-b border-border px-5 py-4">
+ <div className="flex flex-wrap items-start justify-between gap-4">
+ <div className="min-w-0">
+ <h1 className="truncate text-2xl font-semibold">{detail.name}</h1>
+ {detail.description && (
+ <p className="mt-2 max-w-3xl text-sm text-muted-foreground">{detail.description}</p>
+ )}
+ </div>
+ {detail.editable ? (
+ <button
+ className="inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground"
+ onClick={() => setEditMode(!editMode)}
+ >
+ <Pencil className="h-3.5 w-3.5" />
+ {editMode ? "Stop editing" : "Edit"}
+ </button>
+ ) : (
+ <div className="text-sm text-muted-foreground">{detail.editableReason}</div>
+ )}
+ </div>
+
+ <div className="mt-4 space-y-3 border-t border-border pt-4 text-sm">
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2">
+ <div className="flex items-center gap-2">
+ <span className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">Source</span>
+ <span className="flex items-center gap-2">
+ <SourceIcon className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="truncate">{source.label}</span>
+ </span>
+ </div>
+ {detail.sourceType === "github" && (
<div className="flex flex-wrap items-center gap-2">
- <h2 className="text-xl font-semibold">{detail.name}</h2>
- <span className="rounded-full border border-border/70 px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">
- {detail.slug}
- </span>
- <span className={cn("rounded-full px-2 py-0.5 text-[10px] font-medium", trustTone(detail.trustLevel))}>
- {trustLabel(detail.trustLevel)}
- </span>
+ <span className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">Pin</span>
+ <span className="font-mono text-xs">{currentPin ?? "untracked"}</span>
+ {updateStatus?.trackingRef && (
+ <span className="text-xs text-muted-foreground">tracking {updateStatus.trackingRef}</span>
+ )}
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={onCheckUpdates}
+ disabled={checkUpdatesPending || updateStatusLoading}
+ >
+ <RefreshCw className={cn("mr-1.5 h-3.5 w-3.5", (checkUpdatesPending || updateStatusLoading) && "animate-spin")} />
+ Check for updates
+ </Button>
+ {updateStatus?.supported && updateStatus.hasUpdate && (
+ <Button
+ size="sm"
+ onClick={onInstallUpdate}
+ disabled={installUpdatePending}
+ >
+ <RefreshCw className={cn("mr-1.5 h-3.5 w-3.5", installUpdatePending && "animate-spin")} />
+ Install update{latestPin ? ` ${latestPin}` : ""}
+ </Button>
+ )}
+ {updateStatus?.supported && !updateStatus.hasUpdate && !updateStatusLoading && (
+ <span className="text-xs text-muted-foreground">Up to date</span>
+ )}
+ {!updateStatus?.supported && updateStatus?.reason && (
+ <span className="text-xs text-muted-foreground">{updateStatus.reason}</span>
+ )}
</div>
- {detail.description && (
- <p className="mt-2 max-w-2xl text-sm text-muted-foreground">{detail.description}</p>
- )}
- </div>
- <div className="grid shrink-0 gap-1 text-right text-[11px] text-muted-foreground">
- <span>{compatibilityLabel(detail)}</span>
- <span>{detail.attachedAgentCount} attached agent{detail.attachedAgentCount === 1 ? "" : "s"}</span>
+ )}
+ <div className="flex items-center gap-2">
+ <span className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">Mode</span>
+ <span>{detail.editable ? "Editable" : "Read only"}</span>
</div>
</div>
+ <div className="flex flex-wrap items-start gap-x-3 gap-y-1">
+ <span className="text-[11px] uppercase tracking-[0.18em] text-muted-foreground">Used by</span>
+ {usedBy.length === 0 ? (
+ <span className="text-muted-foreground">No agents attached</span>
+ ) : (
+ <div className="flex flex-wrap gap-x-3 gap-y-1">
+ {usedBy.map((agent) => (
+ <Link
+ key={agent.id}
+ to={`/agents/${agent.urlKey}/skills`}
+ className="text-foreground no-underline hover:underline"
+ >
+ {agent.name}
+ </Link>
+ ))}
+ </div>
+ )}
+ </div>
</div>
+ </div>
- <div className="grid gap-5 px-5 py-5 lg:grid-cols-[minmax(0,1fr)_18rem]">
+ <div className="border-b border-border px-5 py-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-0">
- <div className="mb-3 flex items-center justify-between gap-3">
- <h3 className="text-sm font-medium">SKILL.md</h3>
- {detail.sourceLocator?.startsWith("http") ? (
- <a
- href={detail.sourceLocator}
- target="_blank"
- rel="noreferrer"
- className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground"
- >
- Open source
- <ArrowUpRight className="h-3.5 w-3.5" />
- </a>
- ) : detail.sourceLocator ? (
- <span className="truncate text-xs font-mono text-muted-foreground">
- {detail.sourceLocator}
- </span>
- ) : null}
- </div>
- <div className="rounded-xl border border-border/70 bg-background px-4 py-4">
- <MarkdownBody>{markdownBody}</MarkdownBody>
- </div>
+ <div className="truncate font-mono text-sm">{file?.path ?? "SKILL.md"}</div>
</div>
-
- <div className="space-y-4">
- <section className="rounded-xl border border-border/70 bg-background px-4 py-4">
- <h3 className="text-sm font-medium">Inventory</h3>
- <div className="mt-3 space-y-2">
- {detail.fileInventory.map((entry) => (
- <div key={`${entry.kind}:${entry.path}`} className="flex items-center justify-between gap-3 text-xs">
- <span className="truncate font-mono text-muted-foreground">{entry.path}</span>
- <span className="rounded-full border border-border/70 px-2 py-0.5 uppercase tracking-wide text-[10px] text-muted-foreground">
- {entry.kind}
- </span>
- </div>
- ))}
+ <div className="flex items-center gap-2">
+ {file?.markdown && !editMode && (
+ <div className="flex items-center border border-border">
+ <button
+ className={cn("px-3 py-1.5 text-sm", viewMode === "preview" && "text-foreground", viewMode !== "preview" && "text-muted-foreground")}
+ onClick={() => setViewMode("preview")}
+ >
+ <span className="flex items-center gap-1.5">
+ <Eye className="h-3.5 w-3.5" />
+ View
+ </span>
+ </button>
+ <button
+ className={cn("border-l border-border px-3 py-1.5 text-sm", viewMode === "code" && "text-foreground", viewMode !== "code" && "text-muted-foreground")}
+ onClick={() => setViewMode("code")}
+ >
+ <span className="flex items-center gap-1.5">
+ <Code2 className="h-3.5 w-3.5" />
+ Code
+ </span>
+ </button>
</div>
- </section>
-
- <section className="rounded-xl border border-border/70 bg-background px-4 py-4">
- <h3 className="text-sm font-medium">Used By Agents</h3>
- {detail.usedByAgents.length === 0 ? (
- <p className="mt-3 text-sm text-muted-foreground">No agents are currently attached to this skill.</p>
- ) : (
- <div className="mt-3 space-y-2">
- {detail.usedByAgents.map((agent) => (
- <EntityRow
- key={agent.id}
- title={agent.name}
- subtitle={agent.adapterType}
- to={`/agents/${agent.urlKey}/skills`}
- trailing={agent.actualState ? (
- <span className="rounded-full border border-border/70 px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted-foreground">
- {agent.actualState}
- </span>
- ) : undefined}
- />
- ))}
- </div>
- )}
- </section>
+ )}
+ {editMode && file?.editable && (
+ <>
+ <Button variant="ghost" size="sm" onClick={() => setEditMode(false)} disabled={savePending}>
+ Cancel
+ </Button>
+ <Button size="sm" onClick={onSave} disabled={savePending}>
+ <Save className="mr-1.5 h-3.5 w-3.5" />
+ {savePending ? "Saving..." : "Save"}
+ </Button>
+ </>
+ )}
</div>
</div>
- </section>
+ </div>
+
+ <div className="min-h-[560px] px-5 py-5">
+ {fileLoading ? (
+ <PageSkeleton variant="detail" />
+ ) : !file ? (
+ <div className="text-sm text-muted-foreground">Select a file to inspect.</div>
+ ) : editMode && file.editable ? (
+ file.markdown ? (
+ <MarkdownEditor
+ value={draft}
+ onChange={setDraft}
+ bordered={false}
+ className="min-h-[520px]"
+ />
+ ) : (
+ <Textarea
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ className="min-h-[520px] rounded-none border-0 bg-transparent px-0 py-0 font-mono text-sm shadow-none focus-visible:ring-0"
+ />
+ )
+ ) : file.markdown && viewMode === "preview" ? (
+ <MarkdownBody>{body}</MarkdownBody>
+ ) : (
+ <pre className="overflow-x-auto whitespace-pre-wrap break-words border-0 bg-transparent p-0 font-mono text-sm text-foreground">
+ <code>{file.content}</code>
+ </pre>
+ )}
+ </div>
</div>
);
}
export function CompanySkills() {
- const { skillId } = useParams<{ skillId?: string }>();
+ const { "*": routePath } = useParams<{ "*": string }>();
const navigate = useNavigate();
const queryClient = useQueryClient();
const { selectedCompanyId } = useCompany();
const { setBreadcrumbs } = useBreadcrumbs();
const { pushToast } = useToast();
+ const [skillFilter, setSkillFilter] = useState("");
const [source, setSource] = useState("");
+ const [createOpen, setCreateOpen] = useState(false);
+ const [emptySourceHelpOpen, setEmptySourceHelpOpen] = useState(false);
+ const [expandedSkillId, setExpandedSkillId] = useState<string | null>(null);
+ const [expandedDirs, setExpandedDirs] = useState<Record<string, Set<string>>>({});
+ const [viewMode, setViewMode] = useState<"preview" | "code">("preview");
+ const [editMode, setEditMode] = useState(false);
+ const [draft, setDraft] = useState("");
+ const [displayedDetail, setDisplayedDetail] = useState<CompanySkillDetail | null>(null);
+ const [displayedFile, setDisplayedFile] = useState<CompanySkillFileDetail | null>(null);
+ const parsedRoute = useMemo(() => parseSkillRoute(routePath), [routePath]);
+ const routeSkillId = parsedRoute.skillId;
+ const selectedPath = parsedRoute.filePath;
useEffect(() => {
setBreadcrumbs([
{ label: "Skills", href: "/skills" },
- ...(skillId ? [{ label: "Detail" }] : []),
+ ...(routeSkillId ? [{ label: "Detail" }] : []),
]);
- }, [setBreadcrumbs, skillId]);
+ }, [routeSkillId, setBreadcrumbs]);
- const {
- data: skills,
- isLoading,
- error,
- } = useQuery({
+ const skillsQuery = useQuery({
queryKey: queryKeys.companySkills.list(selectedCompanyId ?? ""),
queryFn: () => companySkillsApi.list(selectedCompanyId!),
enabled: Boolean(selectedCompanyId),
});
const selectedSkillId = useMemo(() => {
- if (!skillId) return skills?.[0]?.id ?? null;
- return skillId;
- }, [skillId, skills]);
-
- const {
- data: detail,
- isLoading: detailLoading,
- } = useQuery({
+ if (!routeSkillId) return skillsQuery.data?.[0]?.id ?? null;
+ return routeSkillId;
+ }, [routeSkillId, skillsQuery.data]);
+
+ useEffect(() => {
+ if (routeSkillId || !selectedSkillId) return;
+ navigate(skillRoute(selectedSkillId), { replace: true });
+ }, [navigate, routeSkillId, selectedSkillId]);
+
+ const detailQuery = useQuery({
queryKey: queryKeys.companySkills.detail(selectedCompanyId ?? "", selectedSkillId ?? ""),
queryFn: () => companySkillsApi.detail(selectedCompanyId!, selectedSkillId!),
enabled: Boolean(selectedCompanyId && selectedSkillId),
});
+ const fileQuery = useQuery({
+ queryKey: queryKeys.companySkills.file(selectedCompanyId ?? "", selectedSkillId ?? "", selectedPath),
+ queryFn: () => companySkillsApi.file(selectedCompanyId!, selectedSkillId!, selectedPath),
+ enabled: Boolean(selectedCompanyId && selectedSkillId && selectedPath),
+ });
+
+ const updateStatusQuery = useQuery({
+ queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId ?? "", selectedSkillId ?? ""),
+ queryFn: () => companySkillsApi.updateStatus(selectedCompanyId!, selectedSkillId!),
+ enabled: Boolean(
+ selectedCompanyId
+ && selectedSkillId
+ && (detailQuery.data?.sourceType === "github" || displayedDetail?.sourceType === "github"),
+ ),
+ staleTime: 60_000,
+ });
+
+ useEffect(() => {
+ setExpandedSkillId(selectedSkillId);
+ }, [selectedSkillId]);
+
+ useEffect(() => {
+ if (!selectedSkillId || selectedPath === "SKILL.md") return;
+ const parents = parentDirectoryPaths(selectedPath);
+ if (parents.length === 0) return;
+ setExpandedDirs((current) => {
+ const next = new Set(current[selectedSkillId] ?? []);
+ let changed = false;
+ for (const parent of parents) {
+ if (!next.has(parent)) {
+ next.add(parent);
+ changed = true;
+ }
+ }
+ return changed ? { ...current, [selectedSkillId]: next } : current;
+ });
+ }, [selectedPath, selectedSkillId]);
+
+ useEffect(() => {
+ setEditMode(false);
+ }, [selectedSkillId, selectedPath]);
+
+ useEffect(() => {
+ if (detailQuery.data) {
+ setDisplayedDetail(detailQuery.data);
+ }
+ }, [detailQuery.data]);
+
+ useEffect(() => {
+ if (fileQuery.data) {
+ setDisplayedFile(fileQuery.data);
+ setDraft(fileQuery.data.content);
+ }
+ }, [fileQuery.data]);
+
+ useEffect(() => {
+ if (selectedSkillId) return;
+ setDisplayedDetail(null);
+ setDisplayedFile(null);
+ }, [selectedSkillId]);
+
+ const activeDetail = detailQuery.data ?? displayedDetail;
+ const activeFile = fileQuery.data ?? displayedFile;
+
const importSkill = useMutation({
mutationFn: (importSource: string) => companySkillsApi.importFromSource(selectedCompanyId!, importSource),
onSuccess: async (result) => {
await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) });
- if (result.imported[0]) {
- navigate(`/skills/${result.imported[0].id}`);
- }
+ if (result.imported[0]) navigate(skillRoute(result.imported[0].id));
pushToast({
tone: "success",
title: "Skills imported",
- body: `${result.imported.length} skill${result.imported.length === 1 ? "" : "s"} added to the company library.`,
+ body: `${result.imported.length} skill${result.imported.length === 1 ? "" : "s"} added.`,
});
if (result.warnings[0]) {
- pushToast({
- tone: "warn",
- title: "Import warnings",
- body: result.warnings[0],
- });
+ pushToast({ tone: "warn", title: "Import warnings", body: result.warnings[0] });
}
setSource("");
},
- onError: (importError) => {
+ onError: (error) => {
pushToast({
tone: "error",
title: "Skill import failed",
- body: importError instanceof Error ? importError.message : "Failed to import skill source.",
+ body: error instanceof Error ? error.message : "Failed to import skill source.",
+ });
+ },
+ });
+
+ const createSkill = useMutation({
+ mutationFn: (payload: CompanySkillCreateRequest) => companySkillsApi.create(selectedCompanyId!, payload),
+ onSuccess: async (skill) => {
+ await queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) });
+ navigate(skillRoute(skill.id));
+ setCreateOpen(false);
+ pushToast({
+ tone: "success",
+ title: "Skill created",
+ body: `${skill.name} is now editable in the Paperclip workspace.`,
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Skill creation failed",
+ body: error instanceof Error ? error.message : "Failed to create skill.",
+ });
+ },
+ });
+
+ const saveFile = useMutation({
+ mutationFn: () => companySkillsApi.updateFile(selectedCompanyId!, selectedSkillId!, selectedPath, draft),
+ onSuccess: async (result) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, selectedSkillId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.file(selectedCompanyId!, selectedSkillId!, selectedPath) }),
+ ]);
+ setDraft(result.content);
+ setEditMode(false);
+ pushToast({
+ tone: "success",
+ title: "Skill saved",
+ body: result.path,
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Save failed",
+ body: error instanceof Error ? error.message : "Failed to save skill file.",
+ });
+ },
+ });
+
+ const installUpdate = useMutation({
+ mutationFn: () => companySkillsApi.installUpdate(selectedCompanyId!, selectedSkillId!),
+ onSuccess: async (skill) => {
+ await Promise.all([
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.detail(selectedCompanyId!, selectedSkillId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.updateStatus(selectedCompanyId!, selectedSkillId!) }),
+ queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.file(selectedCompanyId!, selectedSkillId!, selectedPath) }),
+ ]);
+ navigate(skillRoute(skill.id, selectedPath));
+ pushToast({
+ tone: "success",
+ title: "Skill updated",
+ body: skill.sourceRef ? `Pinned to ${shortRef(skill.sourceRef)}` : skill.name,
+ });
+ },
+ onError: (error) => {
+ pushToast({
+ tone: "error",
+ title: "Update failed",
+ body: error instanceof Error ? error.message : "Failed to install skill update.",
});
},
});
@@ -319,120 +890,174 @@ export function CompanySkills() {
return <EmptyState icon={Boxes} message="Select a company to manage skills." />;
}
+ function handleAddSkillSource() {
+ const trimmedSource = source.trim();
+ if (trimmedSource.length === 0) {
+ setEmptySourceHelpOpen(true);
+ return;
+ }
+ importSkill.mutate(trimmedSource);
+ }
+
return (
- <div className="space-y-5">
- <section className="overflow-hidden rounded-2xl border border-border bg-card">
- <div className="border-b border-border bg-card px-5 py-5">
- <div className="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
- <div className="max-w-2xl">
- <div className="mb-2 inline-flex items-center gap-2 rounded-full border border-border/70 bg-background/70 px-3 py-1 text-[11px] uppercase tracking-[0.18em] text-muted-foreground">
- <Boxes className="h-3.5 w-3.5" />
- Company skill library
- </div>
- <h1 className="text-2xl font-semibold tracking-tight">Manage reusable skills once, attach them anywhere.</h1>
- <p className="mt-2 text-sm text-muted-foreground">
- Import `SKILL.md` packages from local paths, GitHub repos, or direct URLs. Agents attach by skill shortname, while adapters decide how those skills are installed or mounted.
- </p>
- </div>
- <div className="grid gap-2 text-xs text-muted-foreground sm:grid-cols-3">
- <div className="rounded-xl border border-border/70 bg-background/70 px-3 py-3">
- <div className="flex items-center gap-2 font-medium text-foreground">
- <ShieldCheck className="h-3.5 w-3.5 text-emerald-600 dark:text-emerald-400" />
- Markdown-first
- </div>
- <p className="mt-1">`skills.sh` compatible packages stay readable and repo-native.</p>
- </div>
- <div className="rounded-xl border border-border/70 bg-background/70 px-3 py-3">
- <div className="flex items-center gap-2 font-medium text-foreground">
- <FolderInput className="h-3.5 w-3.5 text-blue-600 dark:text-blue-400" />
- GitHub aware
- </div>
- <p className="mt-1">Import a repo, a subtree, or a single skill file without a registry.</p>
+ <>
+ <Dialog open={emptySourceHelpOpen} onOpenChange={setEmptySourceHelpOpen}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Add a skill source</DialogTitle>
+ <DialogDescription>
+ Paste a local path, GitHub URL, or `skills.sh` command into the field first.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-3 text-sm">
+ <a
+ href="https://skills.sh"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Browse skills.sh</span>
+ <span className="mt-1 block text-muted-foreground">
+ Find install commands and paste one here.
+ </span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
+ <a
+ href="https://github.com/search?q=SKILL.md&type=code"
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-start justify-between rounded-md border border-border px-3 py-3 text-foreground no-underline transition-colors hover:bg-accent/40"
+ >
+ <span>
+ <span className="block font-medium">Search GitHub</span>
+ <span className="mt-1 block text-muted-foreground">
+ Look for repositories with `SKILL.md`, then paste the repo URL here.
+ </span>
+ </span>
+ <ExternalLink className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ </a>
+ </div>
+ <DialogFooter showCloseButton />
+ </DialogContent>
+ </Dialog>
+
+ <div className="grid min-h-[calc(100vh-12rem)] gap-0 xl:grid-cols-[19rem_minmax(0,1fr)]">
+ <aside className="border-r border-border">
+ <div className="border-b border-border px-4 py-3">
+ <div className="flex items-center justify-between gap-2">
+ <div>
+ <h1 className="text-base font-semibold">Skills</h1>
+ <p className="text-xs text-muted-foreground">
+ {skillsQuery.data?.length ?? 0} available
+ </p>
</div>
- <div className="rounded-xl border border-border/70 bg-background/70 px-3 py-3">
- <div className="flex items-center gap-2 font-medium text-foreground">
- <ShieldAlert className="h-3.5 w-3.5 text-amber-600 dark:text-amber-400" />
- Trust surfaced
- </div>
- <p className="mt-1">Scripts and executable bundles stay visible instead of being hidden in setup.</p>
+ <div className="flex items-center gap-1">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId) })}
+ disabled={skillsQuery.isLoading}
+ >
+ <RefreshCw className="h-4 w-4" />
+ </Button>
+ <Button variant="ghost" size="icon-sm" onClick={() => setCreateOpen((value) => !value)}>
+ <Plus className="h-4 w-4" />
+ </Button>
</div>
</div>
- </div>
- </div>
- <div className="border-t border-border px-5 py-4">
- <div className="flex flex-col gap-3 lg:flex-row lg:items-center">
- <div className="flex-1">
- <Input
+ <div className="mt-3 flex items-center gap-2 border-b border-border pb-2">
+ <Search className="h-4 w-4 text-muted-foreground" />
+ <input
+ value={skillFilter}
+ onChange={(event) => setSkillFilter(event.target.value)}
+ placeholder="Filter skills"
+ className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
+ />
+ </div>
+
+ <div className="mt-3 flex items-center gap-2 border-b border-border pb-2">
+ <input
value={source}
onChange={(event) => setSource(event.target.value)}
- placeholder="Path, GitHub URL, npx skills add ..., or owner/repo/skill"
- className="h-10"
+ placeholder="Paste path, GitHub URL, or skills.sh command"
+ className="w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground"
/>
- </div>
- <div className="flex items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => queryClient.invalidateQueries({ queryKey: queryKeys.companySkills.list(selectedCompanyId) })}
- disabled={isLoading}
- >
- <RefreshCw className="mr-1.5 h-3.5 w-3.5" />
- Refresh
- </Button>
<Button
size="sm"
- onClick={() => importSkill.mutate(source.trim())}
- disabled={importSkill.isPending || source.trim().length === 0}
+ variant="ghost"
+ onClick={handleAddSkillSource}
+ disabled={importSkill.isPending}
>
- {importSkill.isPending ? "Importing..." : "Import skill"}
+ {importSkill.isPending ? <RefreshCw className="h-4 w-4 animate-spin" /> : "Add"}
</Button>
</div>
</div>
- </div>
- </section>
-
- {error && <p className="text-sm text-destructive">{error.message}</p>}
-
- {!isLoading && (skills?.length ?? 0) === 0 ? (
- <EmptyState
- icon={TerminalSquare}
- message="No company skills yet."
- action="Import your first skill"
- onAction={() => {
- const trimmed = source.trim();
- if (trimmed) importSkill.mutate(trimmed);
- }}
- />
- ) : (
- <div className="grid gap-5 xl:grid-cols-[22rem_minmax(0,1fr)]">
- <section className="space-y-3">
- <div className="flex items-center justify-between">
- <div>
- <h2 className="text-sm font-medium">Library</h2>
- <p className="text-xs text-muted-foreground">
- {skills?.length ?? 0} tracked skill{(skills?.length ?? 0) === 1 ? "" : "s"}
- </p>
- </div>
- </div>
- {isLoading ? (
- <PageSkeleton variant="list" />
- ) : (
- <div className="space-y-2">
- {(skills ?? []).map((skill) => (
- <SkillListItem
- key={skill.id}
- skill={skill}
- selected={skill.id === selectedSkillId}
- />
- ))}
- </div>
- )}
- </section>
- <SkillDetailPanel detail={detail} isLoading={detailLoading} />
+ {createOpen && (
+ <NewSkillForm
+ onCreate={(payload) => createSkill.mutate(payload)}
+ isPending={createSkill.isPending}
+ onCancel={() => setCreateOpen(false)}
+ />
+ )}
+
+ {skillsQuery.isLoading ? (
+ <PageSkeleton variant="list" />
+ ) : skillsQuery.error ? (
+ <div className="px-4 py-6 text-sm text-destructive">{skillsQuery.error.message}</div>
+ ) : (
+ <SkillList
+ skills={skillsQuery.data ?? []}
+ selectedSkillId={selectedSkillId}
+ skillFilter={skillFilter}
+ expandedSkillId={expandedSkillId}
+ expandedDirs={expandedDirs}
+ selectedPaths={selectedSkillId ? { [selectedSkillId]: selectedPath } : {}}
+ onToggleSkill={(currentSkillId) =>
+ setExpandedSkillId((current) => current === currentSkillId ? null : currentSkillId)
+ }
+ onToggleDir={(currentSkillId, path) => {
+ setExpandedDirs((current) => {
+ const next = new Set(current[currentSkillId] ?? []);
+ if (next.has(path)) next.delete(path);
+ else next.add(path);
+ return { ...current, [currentSkillId]: next };
+ });
+ }}
+ onSelectSkill={(currentSkillId) => setExpandedSkillId(currentSkillId)}
+ onSelectPath={() => {}}
+ />
+ )}
+ </aside>
+
+ <div className="min-w-0 pl-6">
+ <SkillPane
+ loading={skillsQuery.isLoading || detailQuery.isLoading}
+ detail={activeDetail}
+ file={activeFile}
+ fileLoading={fileQuery.isLoading && !activeFile}
+ updateStatus={updateStatusQuery.data}
+ updateStatusLoading={updateStatusQuery.isLoading}
+ viewMode={viewMode}
+ editMode={editMode}
+ draft={draft}
+ setViewMode={setViewMode}
+ setEditMode={setEditMode}
+ setDraft={setDraft}
+ onCheckUpdates={() => {
+ void updateStatusQuery.refetch();
+ }}
+ checkUpdatesPending={updateStatusQuery.isFetching}
+ onInstallUpdate={() => installUpdate.mutate()}
+ installUpdatePending={installUpdate.isPending}
+ onSave={() => saveFile.mutate()}
+ savePending={saveFile.isPending}
+ />
</div>
- )}
- </div>
+ </div>
+ </>
);
}