mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-18 09:45:23 +00:00
fix(skills): preserve legacy Skills Hub capabilities (#51977)
This commit is contained in:
parent
e46fa61681
commit
adcaa4d374
40 changed files with 3288 additions and 739 deletions
|
|
@ -59731,7 +59731,7 @@
|
|||
},
|
||||
"file": {
|
||||
"contentMediaType": "application/octet-stream",
|
||||
"description": "Replacement Agent Skills ZIP with the same declared skill name",
|
||||
"description": "Replacement ZIP retaining the registered and declared skill names",
|
||||
"title": "File",
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -59744,6 +59744,7 @@
|
|||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Explicit SemVer, or omit/send empty for automatic versioning on approval",
|
||||
"title": "Version"
|
||||
}
|
||||
},
|
||||
|
|
@ -59770,7 +59771,7 @@
|
|||
},
|
||||
"file": {
|
||||
"contentMediaType": "application/octet-stream",
|
||||
"description": "Replacement Agent Skills ZIP with the same declared skill name",
|
||||
"description": "Replacement ZIP retaining the registered and declared skill names",
|
||||
"title": "File",
|
||||
"type": "string"
|
||||
},
|
||||
|
|
@ -59800,6 +59801,22 @@
|
|||
"title": "File",
|
||||
"type": "string"
|
||||
},
|
||||
"metadata": {
|
||||
"anyOf": [
|
||||
{
|
||||
"contentMediaType": "application/json",
|
||||
"contentSchema": {
|
||||
"$ref": "#/components/schemas/SkillHubUpload"
|
||||
},
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional JSON registry metadata",
|
||||
"title": "Metadata"
|
||||
},
|
||||
"version": {
|
||||
"anyOf": [
|
||||
{
|
||||
|
|
@ -59832,7 +59849,19 @@
|
|||
"type": "object"
|
||||
},
|
||||
"ImportSkillRequest": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"metadata": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/SkillHubUpload"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional registry name and metadata overrides"
|
||||
},
|
||||
"path": {
|
||||
"anyOf": [
|
||||
{
|
||||
|
|
@ -59887,6 +59916,33 @@
|
|||
"title": "ImportSkillRequest",
|
||||
"type": "object"
|
||||
},
|
||||
"PluginAuthor": {
|
||||
"description": "Plugin author information.",
|
||||
"properties": {
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Author email",
|
||||
"title": "Email"
|
||||
},
|
||||
"name": {
|
||||
"description": "Author name",
|
||||
"title": "Name",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name"
|
||||
],
|
||||
"title": "PluginAuthor",
|
||||
"type": "object"
|
||||
},
|
||||
"PluginDownloadEvent": {
|
||||
"properties": {
|
||||
"authenticated": {
|
||||
|
|
@ -60102,86 +60158,6 @@
|
|||
"title": "SkillHubList",
|
||||
"type": "object"
|
||||
},
|
||||
"SkillHubMetadata": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"description": {
|
||||
"anyOf": [
|
||||
{
|
||||
"maxLength": 1024,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Description"
|
||||
},
|
||||
"domain": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Domain"
|
||||
},
|
||||
"expected_updated_at": {
|
||||
"anyOf": [
|
||||
{
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Published updated_at read by the editor. A stale value returns 409",
|
||||
"title": "Expected Updated At"
|
||||
},
|
||||
"keywords": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Keywords"
|
||||
},
|
||||
"namespace": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Namespace"
|
||||
},
|
||||
"version": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Explicit higher SemVer, or omit/null for an automatic patch bump",
|
||||
"title": "Version"
|
||||
}
|
||||
},
|
||||
"title": "SkillHubMetadata",
|
||||
"type": "object"
|
||||
},
|
||||
"SkillHubPendingSkill": {
|
||||
"properties": {
|
||||
"action": {
|
||||
|
|
@ -60223,6 +60199,27 @@
|
|||
}
|
||||
]
|
||||
},
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PluginAuthor"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"category": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Category"
|
||||
},
|
||||
"description": {
|
||||
"anyOf": [
|
||||
{
|
||||
|
|
@ -60245,6 +60242,17 @@
|
|||
],
|
||||
"title": "Domain"
|
||||
},
|
||||
"homepage": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Homepage"
|
||||
},
|
||||
"keywords": {
|
||||
"anyOf": [
|
||||
{
|
||||
|
|
@ -60308,6 +60316,123 @@
|
|||
"title": "SkillHubPublication",
|
||||
"type": "object"
|
||||
},
|
||||
"SkillHubRegistration": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PluginAuthor"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"category": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Category"
|
||||
},
|
||||
"description": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Description"
|
||||
},
|
||||
"domain": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Domain"
|
||||
},
|
||||
"homepage": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Homepage"
|
||||
},
|
||||
"keywords": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Keywords"
|
||||
},
|
||||
"name": {
|
||||
"description": "Registry skill name",
|
||||
"pattern": "^[a-z0-9-]+$",
|
||||
"title": "Name",
|
||||
"type": "string"
|
||||
},
|
||||
"namespace": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Namespace"
|
||||
},
|
||||
"source": {
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Repository or HTTPS archive source reference",
|
||||
"title": "Source",
|
||||
"type": "object"
|
||||
},
|
||||
"version": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"default": "1.0.0",
|
||||
"description": "Semantic version, defaults to 1.0.0 on creation",
|
||||
"title": "Version"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"source"
|
||||
],
|
||||
"title": "SkillHubRegistration",
|
||||
"type": "object"
|
||||
},
|
||||
"SkillHubRejection": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
|
|
@ -60431,6 +60556,27 @@
|
|||
],
|
||||
"title": "Approved By"
|
||||
},
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PluginAuthor"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"category": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Category"
|
||||
},
|
||||
"content_url": {
|
||||
"anyOf": [
|
||||
{
|
||||
|
|
@ -60510,6 +60656,17 @@
|
|||
],
|
||||
"title": "Download Url"
|
||||
},
|
||||
"homepage": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Homepage"
|
||||
},
|
||||
"id": {
|
||||
"title": "Id",
|
||||
"type": "string"
|
||||
|
|
@ -60766,16 +60923,39 @@
|
|||
"SkillHubSubmissionEdit": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"description": {
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PluginAuthor"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear"
|
||||
},
|
||||
"category": {
|
||||
"anyOf": [
|
||||
{
|
||||
"maxLength": 1024,
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Category"
|
||||
},
|
||||
"description": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear the registry description",
|
||||
"title": "Description"
|
||||
},
|
||||
"domain": {
|
||||
|
|
@ -60787,6 +60967,7 @@
|
|||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Domain"
|
||||
},
|
||||
"expected_revision": {
|
||||
|
|
@ -60808,6 +60989,18 @@
|
|||
"description": "Published updated_at read by the editor. A stale value returns 409",
|
||||
"title": "Expected Updated At"
|
||||
},
|
||||
"homepage": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Homepage"
|
||||
},
|
||||
"keywords": {
|
||||
"anyOf": [
|
||||
{
|
||||
|
|
@ -60820,6 +61013,7 @@
|
|||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null or an empty list to clear",
|
||||
"title": "Keywords"
|
||||
},
|
||||
"namespace": {
|
||||
|
|
@ -60831,6 +61025,7 @@
|
|||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Namespace"
|
||||
},
|
||||
"version": {
|
||||
|
|
@ -60842,7 +61037,7 @@
|
|||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Explicit higher SemVer, or omit/null for an automatic patch bump",
|
||||
"description": "Explicit SemVer, or omit/null for automatic versioning on approval",
|
||||
"title": "Version"
|
||||
}
|
||||
},
|
||||
|
|
@ -60894,6 +61089,247 @@
|
|||
"title": "SkillHubSubmissionRevision",
|
||||
"type": "object"
|
||||
},
|
||||
"SkillHubUpdate": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PluginAuthor"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear"
|
||||
},
|
||||
"category": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Category"
|
||||
},
|
||||
"description": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear the registry description",
|
||||
"title": "Description"
|
||||
},
|
||||
"domain": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Domain"
|
||||
},
|
||||
"expected_updated_at": {
|
||||
"anyOf": [
|
||||
{
|
||||
"format": "date-time",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Published updated_at read by the editor. A stale value returns 409",
|
||||
"title": "Expected Updated At"
|
||||
},
|
||||
"homepage": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Homepage"
|
||||
},
|
||||
"keywords": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null or an empty list to clear",
|
||||
"title": "Keywords"
|
||||
},
|
||||
"namespace": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Omit to preserve, null to clear",
|
||||
"title": "Namespace"
|
||||
},
|
||||
"source": {
|
||||
"anyOf": [
|
||||
{
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Explicit replacement source reference. Omit/null to preserve the stored source and archive",
|
||||
"title": "Source"
|
||||
},
|
||||
"version": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Explicit higher SemVer, or omit/null for an automatic patch bump",
|
||||
"title": "Version"
|
||||
}
|
||||
},
|
||||
"title": "SkillHubUpdate",
|
||||
"type": "object"
|
||||
},
|
||||
"SkillHubUpload": {
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/PluginAuthor"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"category": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Category"
|
||||
},
|
||||
"description": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Description"
|
||||
},
|
||||
"domain": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Domain"
|
||||
},
|
||||
"homepage": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Homepage"
|
||||
},
|
||||
"keywords": {
|
||||
"anyOf": [
|
||||
{
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Keywords"
|
||||
},
|
||||
"name": {
|
||||
"description": "Registry skill name",
|
||||
"pattern": "^[a-z0-9-]+$",
|
||||
"title": "Name",
|
||||
"type": "string"
|
||||
},
|
||||
"namespace": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"title": "Namespace"
|
||||
},
|
||||
"version": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"default": "1.0.0",
|
||||
"description": "Semantic version, defaults to 1.0.0 on creation",
|
||||
"title": "Version"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name"
|
||||
],
|
||||
"title": "SkillHubUpload",
|
||||
"type": "object"
|
||||
},
|
||||
"SkillHubVersion": {
|
||||
"properties": {
|
||||
"content_kind": {
|
||||
|
|
@ -61393,6 +61829,16 @@
|
|||
"title": "Sort Order",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "query",
|
||||
"name": "enabled_only",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"default": false,
|
||||
"title": "Enabled Only",
|
||||
"type": "boolean"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
|
|
@ -61430,13 +61876,21 @@
|
|||
},
|
||||
"/skill-hub/skills/import": {
|
||||
"post": {
|
||||
"description": "Import a public skills.sh or GitHub skill as a portable snapshot.",
|
||||
"description": "Register a source reference, or import a public skills.sh/GitHub URL as a portable snapshot.",
|
||||
"operationId": "import_skill_skill_hub_skills_import_post",
|
||||
"requestBody": {
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ImportSkillRequest"
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/SkillHubRegistration"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/ImportSkillRequest"
|
||||
}
|
||||
],
|
||||
"title": "Body"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -61625,7 +62079,7 @@
|
|||
]
|
||||
},
|
||||
"put": {
|
||||
"description": "Replace registry metadata, preserving files. Members submit an immutable proposal for admin review.",
|
||||
"description": "Update supplied registry fields. Omitted metadata is retained, null clears it, and version defaults to a bump.",
|
||||
"operationId": "replace_skill_metadata_skill_hub_skills__name__put",
|
||||
"parameters": [
|
||||
{
|
||||
|
|
@ -61642,7 +62096,7 @@
|
|||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/SkillHubMetadata"
|
||||
"$ref": "#/components/schemas/SkillHubUpdate"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
|
@ -61920,7 +62374,7 @@
|
|||
},
|
||||
"/skill-hub/skills/{name}/upload": {
|
||||
"put": {
|
||||
"description": "Replace skill files, retaining registry fields. Members propose an update against the original editor timestamp.",
|
||||
"description": "Replace files and refresh their inherited description, retaining registry overrides and other metadata.",
|
||||
"operationId": "replace_skill_archive_skill_hub_skills__name__upload_put",
|
||||
"parameters": [
|
||||
{
|
||||
|
|
@ -62114,7 +62568,7 @@
|
|||
},
|
||||
"/skill-hub/skills/{name}/versions/{version_id}/archive": {
|
||||
"get": {
|
||||
"description": "Download a retained publication as a portable ZIP with SKILL.md at its root.",
|
||||
"description": "Download a retained skill ZIP, preserving legacy packages without portable frontmatter.",
|
||||
"operationId": "download_skill_version_skill_hub_skills__name__versions__version_id__archive_get",
|
||||
"parameters": [
|
||||
{
|
||||
|
|
@ -62450,7 +62904,7 @@
|
|||
]
|
||||
},
|
||||
"put": {
|
||||
"description": "Replace a pending proposal's metadata, preserving files. Only its original submitting user may edit.",
|
||||
"description": "Update supplied proposal metadata. Omit/null version uses automatic versioning on approval.",
|
||||
"operationId": "edit_submission_skill_hub_submissions__submission_id__put",
|
||||
"parameters": [
|
||||
{
|
||||
|
|
@ -62573,7 +63027,7 @@
|
|||
},
|
||||
"/skill-hub/submissions/{submission_id}/archive": {
|
||||
"get": {
|
||||
"description": "Download an owned proposal as a private portable ZIP. Legacy nonportable archives return 404.",
|
||||
"description": "Download an owned proposal as a private ZIP, preserving legacy packages without portable frontmatter.",
|
||||
"operationId": "download_submission_skill_hub_submissions__submission_id__archive_get",
|
||||
"parameters": [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ from typing import Annotated, Final, Protocol, TypedDict, get_args
|
|||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from pydantic import Json, TypeAdapter
|
||||
from pydantic import Json, TypeAdapter, ValidationError
|
||||
from typing_extensions import ReadOnly, assert_never
|
||||
|
||||
from litellm._logging import verbose_proxy_logger
|
||||
|
|
@ -66,6 +66,7 @@ from litellm.types.proxy.auth.special_headers import SpecialHeaders
|
|||
from litellm.types.proxy.claude_code_endpoints import (
|
||||
InstallationPreference,
|
||||
ListPluginsResponse,
|
||||
PluginAuthor,
|
||||
PluginListItem,
|
||||
PluginResponse,
|
||||
PluginSpec,
|
||||
|
|
@ -109,6 +110,15 @@ MANIFEST_FIELDS: Final = TypeAdapter(dict[str, object])
|
|||
_SELF_INSTALLING_PREFERENCES: Final[frozenset[InstallationPreference]] = frozenset({"auto_install", "required"})
|
||||
|
||||
|
||||
def read_plugin_author(value: object) -> PluginAuthor | None:
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return PluginAuthor.model_validate({"name": value} if isinstance(value, str) else value)
|
||||
except ValidationError:
|
||||
return None
|
||||
|
||||
|
||||
def get_installation_preference(manifest: Mapping[str, object]) -> InstallationPreference | None:
|
||||
value: Final = manifest.get("installation_preference")
|
||||
if value is None or value in _INSTALLATION_PREFERENCES:
|
||||
|
|
@ -216,13 +226,13 @@ async def upload_plugin(
|
|||
"sha256": digest,
|
||||
}
|
||||
spec: Final = RegisterPluginRequest.model_validate({**metadata.model_dump(), "source": source})
|
||||
_validate_installation_preference(spec)
|
||||
validate_plugin_installation_preference(spec)
|
||||
published: Final = await uploads.publish(
|
||||
PluginPublication(
|
||||
name=spec.name,
|
||||
version=spec.version,
|
||||
description=spec.description,
|
||||
manifest=_build_plugin_manifest(spec.name, spec),
|
||||
manifest=build_plugin_manifest(spec.name, spec),
|
||||
content=archive,
|
||||
created_by=user_api_key_dict.user_id,
|
||||
)
|
||||
|
|
@ -445,7 +455,7 @@ _VALID_GIT_SUBDIR_PATH_RE: Final = re.compile(r"^[a-zA-Z0-9][a-zA-Z0-9._-]*(/[a-
|
|||
_VALID_SHA256_RE: Final = re.compile(r"^[0-9a-fA-F]{64}$")
|
||||
|
||||
|
||||
def _validate_plugin_source(source: Mapping[str, str]) -> None:
|
||||
def validate_plugin_source(source: Mapping[str, str]) -> None:
|
||||
"""Validate plugin source format, raising HTTPException on invalid input."""
|
||||
source_type: Final = source.get("source")
|
||||
if source_type == "github":
|
||||
|
|
@ -501,7 +511,7 @@ def _validate_plugin_source(source: Mapping[str, str]) -> None:
|
|||
)
|
||||
|
||||
|
||||
def _validate_installation_preference(spec: PluginSpec) -> None:
|
||||
def validate_plugin_installation_preference(spec: PluginSpec) -> None:
|
||||
if spec.installation_preference is None:
|
||||
return
|
||||
if spec.source.get("source") != "archive":
|
||||
|
|
@ -522,7 +532,7 @@ def _validate_installation_preference(spec: PluginSpec) -> None:
|
|||
)
|
||||
|
||||
|
||||
def _build_plugin_manifest(name: str, spec: PluginSpec) -> Mapping[str, object]:
|
||||
def build_plugin_manifest(name: str, spec: PluginSpec) -> Mapping[str, object]:
|
||||
"""Build the stored manifest dict shared by plugin create and update."""
|
||||
dumped: Final[Mapping[str, object]] = MappingProxyType(spec.model_dump(exclude_none=True))
|
||||
return {"name": name, **{key: value for key, value in dumped.items() if value and key != "name"}}
|
||||
|
|
@ -617,10 +627,10 @@ async def register_plugin(
|
|||
detail={"error": "Plugin name must be kebab-case (lowercase letters, numbers, hyphens)"},
|
||||
)
|
||||
|
||||
_validate_plugin_source(request.source)
|
||||
_validate_installation_preference(request)
|
||||
validate_plugin_source(request.source)
|
||||
validate_plugin_installation_preference(request)
|
||||
|
||||
manifest: Final[Mapping[str, object]] = _build_plugin_manifest(request.name, request)
|
||||
manifest: Final[Mapping[str, object]] = build_plugin_manifest(request.name, request)
|
||||
|
||||
plugin: Final = await uploads.publish(
|
||||
PluginPublication(
|
||||
|
|
@ -719,7 +729,7 @@ async def list_visible_plugins(enabled_only: bool, user_api_key_dict: UserAPIKey
|
|||
description=p.description,
|
||||
source=manifest.get("source", {}),
|
||||
has_agent_skill_metadata=has_agent_skill_metadata(MANIFEST_FIELDS.validate_python(manifest)),
|
||||
author=manifest.get("author"),
|
||||
author=read_plugin_author(manifest.get("author")),
|
||||
homepage=manifest.get("homepage"),
|
||||
keywords=manifest.get("keywords"),
|
||||
category=manifest.get("category"),
|
||||
|
|
@ -887,11 +897,11 @@ async def update_plugin(
|
|||
|
||||
current_manifest: Final = MANIFEST_FIELDS.validate_json(existing.manifest_json or "{}")
|
||||
if request.source != current_manifest.get("source"):
|
||||
_validate_plugin_source(request.source)
|
||||
_validate_installation_preference(request)
|
||||
validate_plugin_source(request.source)
|
||||
validate_plugin_installation_preference(request)
|
||||
|
||||
manifest: Final[Mapping[str, object]] = {
|
||||
**_build_plugin_manifest(plugin_name, request),
|
||||
**build_plugin_manifest(plugin_name, request),
|
||||
**(
|
||||
{"agent_skill": current_manifest["agent_skill"]}
|
||||
if "agent_skill" in current_manifest and request.source == current_manifest.get("source")
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ from urllib.parse import quote
|
|||
|
||||
import httpx
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, Response, UploadFile
|
||||
from pydantic import Json
|
||||
|
||||
import litellm
|
||||
from litellm.llms.custom_httpx.http_handler import (
|
||||
|
|
@ -27,20 +28,25 @@ from litellm.models.plugin_upload import (
|
|||
PublishedPlugin,
|
||||
has_agent_skill_metadata,
|
||||
)
|
||||
from litellm.models.skill_submission import SkillSubmission, SkillSubmissionStore
|
||||
from litellm.models.skill_submission import SkillProposal, SkillSubmission, SkillSubmissionStore
|
||||
from litellm.proxy._types import UserAPIKeyAuth
|
||||
from litellm.proxy.anthropic_endpoints.claude_code_endpoints.claude_code_marketplace import (
|
||||
MANIFEST_FIELDS,
|
||||
build_plugin_manifest,
|
||||
delete_plugin,
|
||||
disable_plugin,
|
||||
enable_plugin,
|
||||
get_installation_preference,
|
||||
get_plugin_downloads,
|
||||
header_key_caller,
|
||||
list_visible_plugins,
|
||||
plugin_archive_source_matches,
|
||||
plugin_archive_url,
|
||||
plugin_downloader,
|
||||
read_plugin_author,
|
||||
require_download_recorded,
|
||||
validate_plugin_installation_preference,
|
||||
validate_plugin_source,
|
||||
)
|
||||
from litellm.proxy.anthropic_endpoints.claude_code_endpoints.claude_code_skill_access import resolve_skill_visibility
|
||||
from litellm.proxy.anthropic_endpoints.claude_code_endpoints.skill_upload_archive import build_uploaded_skill_archive
|
||||
|
|
@ -54,6 +60,7 @@ from litellm.proxy.deps.repositories import PluginUploadRepositoryDep, SkillSubm
|
|||
from litellm.proxy.discovery_endpoints.agent_skills_archive import (
|
||||
SkillArchive,
|
||||
build_agent_skill_archive,
|
||||
read_skill_archive_members,
|
||||
)
|
||||
from litellm.proxy.discovery_endpoints.skill_hub_mutations import (
|
||||
SkillMutationError,
|
||||
|
|
@ -70,25 +77,32 @@ from litellm.proxy.discovery_endpoints.skill_import import (
|
|||
select_imported_skill,
|
||||
)
|
||||
from litellm.repositories.plugin_publication import read_plugin_publisher, read_plugin_review
|
||||
from litellm.types.proxy.claude_code_endpoints import PluginListItem
|
||||
from litellm.types.proxy.claude_code_endpoints import (
|
||||
PluginListItem,
|
||||
PluginSpec,
|
||||
RegisterPluginRequest,
|
||||
)
|
||||
from litellm.types.proxy.discovery_endpoints.agent_skills_endpoints import AgentSkillsIndexEntry
|
||||
from litellm.types.proxy.skill_hub import (
|
||||
ImportSkillRequest,
|
||||
SkillHubAgentSkill,
|
||||
SkillHubList,
|
||||
SkillHubMetadata,
|
||||
SkillHubMutationResponse,
|
||||
SkillHubPendingSkill,
|
||||
SkillHubProposal,
|
||||
SkillHubPublication,
|
||||
SkillHubRegistration,
|
||||
SkillHubRestore,
|
||||
SkillHubSkill,
|
||||
SkillHubUpdate,
|
||||
SkillHubUpload,
|
||||
SkillHubVersion,
|
||||
SkillHubVersions,
|
||||
SkillSortField,
|
||||
)
|
||||
|
||||
router: Final = APIRouter(prefix="/skill-hub/skills", tags=["Skills Hub"])
|
||||
_EDITABLE_METADATA: Final = frozenset(SkillHubMetadata.model_fields)
|
||||
router.add_api_route(
|
||||
"/{plugin_name}/downloads", get_plugin_downloads, methods=["GET"], response_model=PluginDownloadsResponse
|
||||
)
|
||||
|
|
@ -111,6 +125,10 @@ def _download_url(request: Request, name: str) -> str:
|
|||
return _url(request, f"skill-hub/skills/{quote(name, safe='')}/archive")
|
||||
|
||||
|
||||
def _portable_source(request: Request, name: str) -> Mapping[str, str]:
|
||||
return {"source": "archive", "url": _download_url(request, name)}
|
||||
|
||||
|
||||
def _skill_response(request: Request, plugin: PluginListItem, download_count: int | None = None) -> SkillHubSkill:
|
||||
local_archive: Final = plugin_archive_source_matches(
|
||||
request,
|
||||
|
|
@ -119,6 +137,7 @@ def _skill_response(request: Request, plugin: PluginListItem, download_count: in
|
|||
plugin.source.get("sha256", ""),
|
||||
has_agent_skill_metadata=plugin.has_agent_skill_metadata,
|
||||
)
|
||||
portable: Final = local_archive and plugin.has_agent_skill_metadata
|
||||
return SkillHubSkill(
|
||||
id=plugin.id,
|
||||
name=plugin.name,
|
||||
|
|
@ -127,6 +146,9 @@ def _skill_response(request: Request, plugin: PluginListItem, download_count: in
|
|||
domain=plugin.domain,
|
||||
namespace=plugin.namespace,
|
||||
keywords=None if plugin.keywords is None else tuple(plugin.keywords),
|
||||
author=plugin.author,
|
||||
category=plugin.category,
|
||||
homepage=plugin.homepage,
|
||||
updated_at=None if plugin.updated_at is None else datetime.fromisoformat(plugin.updated_at),
|
||||
created_at=None if plugin.created_at is None else datetime.fromisoformat(plugin.created_at),
|
||||
created_by=plugin.created_by,
|
||||
|
|
@ -134,9 +156,11 @@ def _skill_response(request: Request, plugin: PluginListItem, download_count: in
|
|||
published_by=plugin.published_by,
|
||||
security_scan_passed=plugin.security_scan_passed,
|
||||
visibility="public" if plugin.enabled else "private",
|
||||
source={"source": "archive", "url": _download_url(request, plugin.name)} if local_archive else plugin.source,
|
||||
download_url=_download_url(request, plugin.name) if local_archive else None,
|
||||
content_url=_url(request, f"skill-hub/skills/{quote(plugin.name, safe='')}/content") if local_archive else None,
|
||||
source=_portable_source(request, plugin.name) if portable else plugin.source,
|
||||
download_url=(
|
||||
_download_url(request, plugin.name) if portable else plugin.source.get("url") if local_archive else None
|
||||
),
|
||||
content_url=_url(request, f"skill-hub/skills/{quote(plugin.name, safe='')}/content") if portable else None,
|
||||
download_count=download_count,
|
||||
)
|
||||
|
||||
|
|
@ -153,9 +177,10 @@ async def list_skills(
|
|||
security_scan_passed: bool | None = None,
|
||||
sort_by: SkillSortField = "name",
|
||||
sort_order: Literal["asc", "desc"] = "asc",
|
||||
enabled_only: bool = False,
|
||||
) -> SkillHubList:
|
||||
"""Browse the caller's public and granted private skills."""
|
||||
catalog: Final = await list_visible_plugins(enabled_only=False, user_api_key_dict=caller)
|
||||
catalog: Final = await list_visible_plugins(enabled_only=enabled_only, user_api_key_dict=caller)
|
||||
needle: Final = query.strip().casefold()
|
||||
selected_tag: Final = tag.strip().casefold()
|
||||
matched: Final = tuple(
|
||||
|
|
@ -255,6 +280,9 @@ def skill_metadata_response(request: Request, metadata: PluginArchiveMetadata) -
|
|||
"domain": manifest.get("domain"),
|
||||
"namespace": manifest.get("namespace"),
|
||||
"keywords": manifest.get("keywords"),
|
||||
"author": read_plugin_author(manifest.get("author")),
|
||||
"category": manifest.get("category"),
|
||||
"homepage": manifest.get("homepage"),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
|
@ -275,12 +303,12 @@ def _require_admin(caller: UserAPIKeyAuth) -> None:
|
|||
async def replace_skill_metadata(
|
||||
request: Request,
|
||||
name: str,
|
||||
body: SkillHubMetadata,
|
||||
body: SkillHubUpdate,
|
||||
uploads: PluginUploadRepositoryDep,
|
||||
submissions: SkillSubmissionRepositoryDep,
|
||||
caller: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
|
||||
) -> SkillHubMutationResponse:
|
||||
"""Replace registry metadata, preserving files. Members submit an immutable proposal for admin review."""
|
||||
"""Update supplied registry fields. Omitted metadata is retained, null clears it, and version defaults to a bump."""
|
||||
existing: Final = await write_target(name, True, uploads, caller, body.expected_updated_at)
|
||||
if isinstance(existing, SkillMutationError):
|
||||
raise HTTPException(existing.status, existing.message)
|
||||
|
|
@ -289,17 +317,47 @@ async def replace_skill_metadata(
|
|||
publication: Final = PluginPublication(
|
||||
name=name,
|
||||
version=body.version,
|
||||
description=body.description,
|
||||
manifest={
|
||||
**{key: value for key, value in existing.manifest.items() if key not in _EDITABLE_METADATA},
|
||||
**body.model_dump(exclude_none=True),
|
||||
"name": name,
|
||||
},
|
||||
description=body.description if "description" in body.model_fields_set else existing.description,
|
||||
manifest=updated_skill_manifest(request, name, existing.manifest, body),
|
||||
created_by=caller.user_id,
|
||||
)
|
||||
return await _mutate(request, publication, existing, _require_store(uploads), submissions, caller)
|
||||
|
||||
|
||||
def updated_skill_manifest(
|
||||
request: Request, name: str, manifest: Mapping[str, object], body: SkillHubMetadata
|
||||
) -> Mapping[str, object]:
|
||||
replaced: Final = body.model_fields_set | {"version"}
|
||||
source: Final = body.source if isinstance(body, SkillHubUpdate) else None
|
||||
original: Final = PluginSpec.model_validate({"source": manifest.get("source", {})}).source
|
||||
displayed: Final = (
|
||||
source == _portable_source(request, name)
|
||||
and has_agent_skill_metadata(manifest)
|
||||
and plugin_archive_source_matches(
|
||||
request, name, original, original.get("sha256", ""), has_agent_skill_metadata=True
|
||||
)
|
||||
)
|
||||
changed: Final = source is not None and source != original and not displayed
|
||||
if changed and source is not None:
|
||||
validate_plugin_source(source)
|
||||
updated: Final = {
|
||||
**{
|
||||
key: value
|
||||
for key, value in manifest.items()
|
||||
if key not in replaced and not (changed and key == "agent_skill")
|
||||
},
|
||||
**body.model_dump(exclude={"source", "expected_revision"}, exclude_none=True, exclude_unset=True),
|
||||
"name": name,
|
||||
"source": source if changed else original,
|
||||
}
|
||||
validate_plugin_installation_preference(
|
||||
PluginSpec.model_validate(
|
||||
{"source": updated["source"], "installation_preference": get_installation_preference(updated)}
|
||||
)
|
||||
)
|
||||
return updated
|
||||
|
||||
|
||||
@router.post("/{name}/publish", response_model=SkillHubSkill)
|
||||
async def publish_skill(
|
||||
request: Request,
|
||||
|
|
@ -344,6 +402,7 @@ async def upload_skill(
|
|||
caller: Annotated[UserAPIKeyAuth, Depends(archive_writer)],
|
||||
file: Annotated[UploadFile, File(description="Agent Skills ZIP with SKILL.md and optional supporting files")],
|
||||
version: Annotated[str | None, Form()] = None,
|
||||
metadata: Annotated[Json[SkillHubUpload] | None, Form(description="Optional JSON registry metadata")] = None,
|
||||
) -> SkillHubMutationResponse:
|
||||
"""Publish a portable skill while retaining Claude marketplace compatibility."""
|
||||
store: Final = _require_store(uploads)
|
||||
|
|
@ -352,8 +411,72 @@ async def upload_skill(
|
|||
raise HTTPException(413, "Skill ZIP must be 10 MiB or smaller")
|
||||
archive: Final = await asyncio.to_thread(build_agent_skill_archive, content)
|
||||
if archive is None:
|
||||
if metadata is not None:
|
||||
return await _publish_legacy_upload(request, store, submissions, caller, content, metadata, version)
|
||||
raise HTTPException(422, "Upload a valid Agent Skill with name and description in SKILL.md")
|
||||
return await _publish(request, store, submissions, caller, archive, version, None)
|
||||
return await _publish(request, store, submissions, caller, archive, version, None, metadata)
|
||||
|
||||
|
||||
def _creation_version(version: str | None, metadata: SkillHubUpload | None) -> str | None:
|
||||
if metadata is None or "version" not in metadata.model_fields_set:
|
||||
return version
|
||||
if version is not None and metadata.version is not None and version != metadata.version:
|
||||
raise HTTPException(400, "Send matching versions or specify version in only one place")
|
||||
return version if version is not None else metadata.version
|
||||
|
||||
|
||||
async def _publish_legacy_upload(
|
||||
request: Request,
|
||||
store: PluginUploadStore,
|
||||
submissions: SkillSubmissionStore | None,
|
||||
caller: UserAPIKeyAuth,
|
||||
content: bytes,
|
||||
metadata: SkillHubUpload,
|
||||
version: str | None,
|
||||
) -> SkillHubMutationResponse:
|
||||
existing: Final = await write_target(metadata.name, False, store, caller)
|
||||
if isinstance(existing, SkillMutationError):
|
||||
raise HTTPException(existing.status, existing.message)
|
||||
publication: Final = await _prepare_legacy_upload(request, content, metadata, version, caller.user_id)
|
||||
return await _mutate(request, publication, existing, store, submissions, caller)
|
||||
|
||||
|
||||
async def _prepare_legacy_upload(
|
||||
request: Request,
|
||||
content: bytes,
|
||||
metadata: SkillHubUpload,
|
||||
version: str | None,
|
||||
created_by: str | None,
|
||||
) -> PluginPublication:
|
||||
archive: Final = await asyncio.to_thread(build_uploaded_skill_archive, content, metadata.name)
|
||||
if (
|
||||
archive is None
|
||||
or await asyncio.to_thread(
|
||||
read_skill_archive_members, archive, for_upload=True, skill_path=f"skills/{metadata.name}"
|
||||
)
|
||||
is None
|
||||
):
|
||||
raise HTTPException(422, "Upload a valid ZIP with SKILL.md and safe supporting files")
|
||||
digest: Final = hashlib.sha256(archive).hexdigest()
|
||||
spec: Final = RegisterPluginRequest.model_validate(
|
||||
{
|
||||
**metadata.model_dump(),
|
||||
"version": _creation_version(version, metadata),
|
||||
"source": {
|
||||
"source": "archive",
|
||||
"url": plugin_archive_url(request, metadata.name, digest),
|
||||
"sha256": digest,
|
||||
},
|
||||
}
|
||||
)
|
||||
return PluginPublication(
|
||||
name=spec.name,
|
||||
version=spec.version,
|
||||
description=spec.description,
|
||||
manifest=build_plugin_manifest(spec.name, spec),
|
||||
content=archive,
|
||||
created_by=created_by,
|
||||
)
|
||||
|
||||
|
||||
def import_http_client() -> httpx.AsyncClient:
|
||||
|
|
@ -363,13 +486,21 @@ def import_http_client() -> httpx.AsyncClient:
|
|||
@router.post("/import", response_model=SkillHubMutationResponse)
|
||||
async def import_skill(
|
||||
request: Request,
|
||||
body: ImportSkillRequest,
|
||||
body: SkillHubRegistration | ImportSkillRequest,
|
||||
uploads: PluginUploadRepositoryDep,
|
||||
submissions: SkillSubmissionRepositoryDep,
|
||||
caller: Annotated[UserAPIKeyAuth, Depends(archive_writer)],
|
||||
client: Annotated[httpx.AsyncClient, Depends(import_http_client)],
|
||||
) -> SkillHubMutationResponse:
|
||||
"""Import a public skills.sh or GitHub skill as a portable snapshot."""
|
||||
"""Register a source reference, or import a public skills.sh/GitHub URL as a portable snapshot."""
|
||||
if isinstance(body, SkillHubRegistration):
|
||||
return await _register_reference(
|
||||
request,
|
||||
_require_store(uploads),
|
||||
submissions,
|
||||
caller,
|
||||
RegisterPluginRequest.model_validate(body.model_dump()),
|
||||
)
|
||||
store: Final = _require_store(uploads)
|
||||
source: Final = parse_skill_source(body.url, skill=body.skill, ref=body.ref, path=body.path)
|
||||
if isinstance(source, SkillImportError):
|
||||
|
|
@ -380,7 +511,28 @@ async def import_skill(
|
|||
archive: Final = await asyncio.to_thread(select_imported_skill, content, source)
|
||||
if isinstance(archive, SkillImportError):
|
||||
raise HTTPException(archive.status, archive.message)
|
||||
return await _publish(request, store, submissions, caller, archive, body.version, body.url)
|
||||
return await _publish(request, store, submissions, caller, archive, body.version, body.url, body.metadata)
|
||||
|
||||
|
||||
async def _register_reference(
|
||||
request: Request,
|
||||
store: PluginUploadStore,
|
||||
submissions: SkillSubmissionStore | None,
|
||||
caller: UserAPIKeyAuth,
|
||||
body: RegisterPluginRequest,
|
||||
) -> SkillHubMutationResponse:
|
||||
validate_plugin_source(body.source)
|
||||
existing: Final = await write_target(body.name, False, store, caller)
|
||||
if isinstance(existing, SkillMutationError):
|
||||
raise HTTPException(existing.status, existing.message)
|
||||
publication: Final = PluginPublication(
|
||||
name=body.name,
|
||||
version=body.version,
|
||||
description=body.description,
|
||||
manifest=build_plugin_manifest(body.name, body),
|
||||
created_by=caller.user_id,
|
||||
)
|
||||
return await _mutate(request, publication, existing, store, submissions, caller)
|
||||
|
||||
|
||||
async def _publish(
|
||||
|
|
@ -391,11 +543,16 @@ async def _publish(
|
|||
archive: SkillArchive,
|
||||
version: str | None,
|
||||
origin: str | None,
|
||||
metadata: SkillHubUpload | None = None,
|
||||
) -> SkillHubMutationResponse:
|
||||
existing: Final = await write_target(archive.declared_name or "", False, store, caller)
|
||||
existing: Final = await write_target(
|
||||
metadata.name if metadata else archive.declared_name or "", False, store, caller
|
||||
)
|
||||
if isinstance(existing, SkillMutationError):
|
||||
raise HTTPException(existing.status, existing.message)
|
||||
publication: Final = await prepare_skill_publication(request, archive, version, origin, caller.user_id)
|
||||
publication: Final = await prepare_skill_publication(
|
||||
request, archive, _creation_version(version, metadata), origin, caller.user_id, metadata
|
||||
)
|
||||
return await _mutate(request, publication, existing, store, submissions, caller)
|
||||
|
||||
|
||||
|
|
@ -423,6 +580,7 @@ def skill_proposal_response(request: Request, submission: SkillSubmission) -> Sk
|
|||
"name": proposal.name,
|
||||
"description": proposal.description,
|
||||
"version": proposal.version,
|
||||
"author": read_plugin_author(proposal.manifest.get("author")),
|
||||
**(
|
||||
{
|
||||
"source": {
|
||||
|
|
@ -444,11 +602,11 @@ async def replace_skill_archive(
|
|||
uploads: PluginUploadRepositoryDep,
|
||||
submissions: SkillSubmissionRepositoryDep,
|
||||
caller: Annotated[UserAPIKeyAuth, Depends(archive_writer)],
|
||||
file: Annotated[UploadFile, File(description="Replacement Agent Skills ZIP with the same declared skill name")],
|
||||
file: Annotated[UploadFile, File(description="Replacement ZIP retaining the registered and declared skill names")],
|
||||
version: Annotated[str | None, Form()] = None,
|
||||
expected_updated_at: Annotated[datetime | None, Form()] = None,
|
||||
) -> SkillHubMutationResponse:
|
||||
"""Replace skill files, retaining registry fields. Members propose an update against the original editor timestamp."""
|
||||
"""Replace files and refresh their inherited description, retaining registry overrides and other metadata."""
|
||||
existing: Final = await write_target(name, True, uploads, caller, expected_updated_at)
|
||||
if isinstance(existing, SkillMutationError):
|
||||
raise HTTPException(existing.status, existing.message)
|
||||
|
|
@ -457,14 +615,50 @@ async def replace_skill_archive(
|
|||
content: Final = await file.read(MAX_IMPORT_BYTES + 1)
|
||||
if len(content) > MAX_IMPORT_BYTES:
|
||||
raise HTTPException(413, "Skill ZIP must be 10 MiB or smaller")
|
||||
archive: Final = await asyncio.to_thread(build_agent_skill_archive, content)
|
||||
if archive is None or archive.declared_name != name:
|
||||
raise HTTPException(422, "Replacement SKILL.md must declare the existing skill name and a description")
|
||||
prepared: Final = await prepare_skill_publication(request, archive, version, None, caller.user_id)
|
||||
publication: Final = replace(prepared, manifest={**existing.manifest, **prepared.manifest})
|
||||
publication: Final = await prepare_skill_replacement(request, content, existing, version, caller.user_id)
|
||||
return await _mutate(request, publication, existing, _require_store(uploads), submissions, caller)
|
||||
|
||||
|
||||
async def prepare_skill_replacement(
|
||||
request: Request,
|
||||
content: bytes,
|
||||
existing: PluginSnapshot | SkillProposal,
|
||||
version: str | None,
|
||||
created_by: str | None,
|
||||
) -> PluginPublication:
|
||||
archive: Final = await asyncio.to_thread(build_agent_skill_archive, content)
|
||||
declared: Final = (
|
||||
SkillHubAgentSkill.model_validate(existing.manifest["agent_skill"])
|
||||
if has_agent_skill_metadata(existing.manifest)
|
||||
else None
|
||||
)
|
||||
if declared is not None and (archive is None or archive.declared_name != declared.name):
|
||||
raise HTTPException(422, "Replacement SKILL.md must declare the existing skill name and a description")
|
||||
metadata: Final = SkillHubUpload.model_validate(
|
||||
{
|
||||
"name": existing.name,
|
||||
"version": version,
|
||||
**(
|
||||
{"description": existing.description}
|
||||
if declared is None or existing.description != declared.description
|
||||
else {}
|
||||
),
|
||||
}
|
||||
)
|
||||
prepared: Final = (
|
||||
await _prepare_legacy_upload(request, content, metadata, version, created_by)
|
||||
if archive is None
|
||||
else await prepare_skill_publication(request, archive, version, None, created_by, metadata)
|
||||
)
|
||||
return replace(
|
||||
prepared,
|
||||
manifest={
|
||||
**{key: value for key, value in existing.manifest.items() if key != "description"},
|
||||
**prepared.manifest,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def skill_publication_response(
|
||||
request: Request, publication: PluginPublication, published: PublishedPlugin
|
||||
) -> SkillHubSkill:
|
||||
|
|
@ -488,6 +682,9 @@ def skill_publication_response(
|
|||
"domain": publication.manifest.get("domain"),
|
||||
"namespace": publication.manifest.get("namespace"),
|
||||
"keywords": publication.manifest.get("keywords"),
|
||||
"author": read_plugin_author(publication.manifest.get("author")),
|
||||
"category": publication.manifest.get("category"),
|
||||
"homepage": publication.manifest.get("homepage"),
|
||||
}
|
||||
),
|
||||
)
|
||||
|
|
@ -499,8 +696,9 @@ async def prepare_skill_publication(
|
|||
version: str | None,
|
||||
origin: str | None,
|
||||
created_by: str | None,
|
||||
metadata: SkillHubUpload | None = None,
|
||||
) -> PluginPublication:
|
||||
name: Final = archive.declared_name
|
||||
name: Final = metadata.name if metadata is not None else archive.declared_name
|
||||
if name is None:
|
||||
raise HTTPException(422, "SKILL.md must declare a skill name")
|
||||
plugin: Final = await asyncio.to_thread(build_uploaded_skill_archive, archive.content, name)
|
||||
|
|
@ -515,13 +713,24 @@ async def prepare_skill_publication(
|
|||
"url": plugin_archive_url(request, name, digest),
|
||||
"sha256": digest,
|
||||
}
|
||||
manifest: Final = {
|
||||
"name": name,
|
||||
"description": archive.declared_description,
|
||||
"version": version,
|
||||
"source": source,
|
||||
"agent_skill": {
|
||||
description: Final = (
|
||||
metadata.description
|
||||
if metadata is not None and "description" in metadata.model_fields_set
|
||||
else archive.declared_description
|
||||
)
|
||||
spec: Final = RegisterPluginRequest.model_validate(
|
||||
{
|
||||
**(metadata.model_dump() if metadata else {}),
|
||||
"name": name,
|
||||
"description": description,
|
||||
"version": version,
|
||||
"source": source,
|
||||
}
|
||||
)
|
||||
manifest: Final = {
|
||||
**build_plugin_manifest(name, spec),
|
||||
"agent_skill": {
|
||||
"name": archive.declared_name,
|
||||
"description": archive.declared_description,
|
||||
"digest": archive.digest,
|
||||
"origin": origin,
|
||||
|
|
@ -530,7 +739,7 @@ async def prepare_skill_publication(
|
|||
return PluginPublication(
|
||||
name=name,
|
||||
version=version,
|
||||
description=archive.declared_description,
|
||||
description=description,
|
||||
manifest=manifest,
|
||||
content=plugin,
|
||||
created_by=created_by,
|
||||
|
|
@ -608,37 +817,41 @@ async def download_skill_version(
|
|||
uploads: PluginUploadRepositoryDep,
|
||||
caller: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
|
||||
) -> Response:
|
||||
"""Download a retained publication as a portable ZIP with SKILL.md at its root."""
|
||||
"""Download a retained skill ZIP, preserving legacy packages without portable frontmatter."""
|
||||
store: Final = _require_store(uploads)
|
||||
metadata: Final = await _version_metadata(name, store, caller)
|
||||
version: Final = await store.version(metadata, version_id)
|
||||
if version is None:
|
||||
raise HTTPException(404, "Skill version not found")
|
||||
content: Final = await store.version_content(metadata, version_id)
|
||||
archive: Final = (
|
||||
await asyncio.to_thread(build_agent_skill_archive, content, plugin_name=name) if content is not None else None
|
||||
)
|
||||
if archive is None:
|
||||
raise HTTPException(404, "This version has no retained Agent Skills archive")
|
||||
if content is None:
|
||||
raise HTTPException(404, "This version has no retained skill archive")
|
||||
payload: Final = await skill_archive_payload(content, name)
|
||||
digest: Final = hashlib.sha256(payload).hexdigest()
|
||||
require_download_recorded(
|
||||
await store.record_download(
|
||||
replace(metadata, version=version.version),
|
||||
archive.digest.removeprefix("sha256:"),
|
||||
digest,
|
||||
plugin_downloader(caller),
|
||||
)
|
||||
)
|
||||
return Response(
|
||||
archive.content,
|
||||
payload,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{name}.zip"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"ETag": f'"{archive.digest}"',
|
||||
"ETag": f'"sha256:{digest}"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def skill_archive_payload(content: bytes, name: str) -> bytes:
|
||||
archive: Final = await asyncio.to_thread(build_agent_skill_archive, content, plugin_name=name)
|
||||
return archive.content if archive is not None else content
|
||||
|
||||
|
||||
@router.post("/{name}/versions/{version_id}/restore", response_model=SkillHubSkill)
|
||||
async def restore_skill_version(
|
||||
request: Request,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
import asyncio
|
||||
from dataclasses import replace
|
||||
import hashlib
|
||||
from typing import Annotated, Final
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, Response, UploadFile
|
||||
|
|
@ -17,12 +16,13 @@ from litellm.proxy._types import UserAPIKeyAuth
|
|||
from litellm.proxy.anthropic_endpoints.claude_code_endpoints.claude_code_skill_access import resolve_skill_visibility
|
||||
from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
|
||||
from litellm.proxy.deps.repositories import PluginUploadRepositoryDep, SkillSubmissionRepositoryDep
|
||||
from litellm.proxy.discovery_endpoints.agent_skills_archive import build_agent_skill_archive
|
||||
from litellm.proxy.discovery_endpoints.skill_hub_endpoints import (
|
||||
prepare_skill_publication,
|
||||
prepare_skill_replacement,
|
||||
skill_archive_payload,
|
||||
skill_metadata_response,
|
||||
skill_proposal_response,
|
||||
skill_publication_response,
|
||||
updated_skill_manifest,
|
||||
)
|
||||
from litellm.proxy.discovery_endpoints.skill_hub_mutations import (
|
||||
SkillMutationError,
|
||||
|
|
@ -36,7 +36,6 @@ from litellm.proxy.discovery_endpoints.skill_hub_mutations import (
|
|||
from litellm.proxy.discovery_endpoints.skill_import import MAX_IMPORT_BYTES
|
||||
from litellm.repositories.plugin_publication import resolve_plugin_version
|
||||
from litellm.types.proxy.skill_hub import (
|
||||
SkillHubMetadata,
|
||||
SkillHubRejection,
|
||||
SkillHubReviewResponse,
|
||||
SkillHubSubmission,
|
||||
|
|
@ -134,28 +133,24 @@ async def download_submission(
|
|||
submissions: SkillSubmissionRepositoryDep,
|
||||
caller: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
|
||||
) -> Response:
|
||||
"""Download an owned proposal as a private portable ZIP. Legacy nonportable archives return 404."""
|
||||
"""Download an owned proposal as a private ZIP, preserving legacy packages without portable frontmatter."""
|
||||
owner: Final = _owner(caller)
|
||||
store: Final = _store(submissions)
|
||||
submission: Final = await store.get(submission_id, owner)
|
||||
if submission is None:
|
||||
raise HTTPException(404, "Skill submission not found")
|
||||
content: Final = await store.get_archive(submission_id, owner)
|
||||
archive: Final = (
|
||||
await asyncio.to_thread(build_agent_skill_archive, content, plugin_name=submission.plugin_name)
|
||||
if content is not None
|
||||
else None
|
||||
)
|
||||
if archive is None:
|
||||
raise HTTPException(404, "This submission has no portable Agent Skills archive")
|
||||
if content is None:
|
||||
raise HTTPException(404, "This submission has no stored archive")
|
||||
payload: Final = await skill_archive_payload(content, submission.plugin_name)
|
||||
return Response(
|
||||
archive.content,
|
||||
payload,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{submission.plugin_name}.zip"',
|
||||
"Cache-Control": "private, no-store",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"ETag": f'"{archive.digest}"',
|
||||
"ETag": f'"sha256:{hashlib.sha256(payload).hexdigest()}"',
|
||||
},
|
||||
)
|
||||
|
||||
|
|
@ -284,7 +279,7 @@ async def edit_submission(
|
|||
uploads: PluginUploadRepositoryDep,
|
||||
caller: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
|
||||
) -> SkillHubSubmission:
|
||||
"""Replace a pending proposal's metadata, preserving files. Only its original submitting user may edit."""
|
||||
"""Update supplied proposal metadata. Omit/null version uses automatic versioning on approval."""
|
||||
owner: Final = _editor(caller)
|
||||
store: Final = _store(submissions)
|
||||
submission: Final = await _editable(
|
||||
|
|
@ -293,15 +288,8 @@ async def edit_submission(
|
|||
publication: Final = PluginPublication(
|
||||
name=submission.plugin_name,
|
||||
version=body.version,
|
||||
description=body.description,
|
||||
manifest={
|
||||
**{
|
||||
key: value
|
||||
for key, value in submission.proposal.manifest.items()
|
||||
if key not in SkillHubMetadata.model_fields
|
||||
},
|
||||
**body.model_dump(exclude={"expected_revision"}, exclude_none=True),
|
||||
},
|
||||
description=body.description if "description" in body.model_fields_set else submission.proposal.description,
|
||||
manifest=updated_skill_manifest(request, submission.plugin_name, submission.proposal.manifest, body),
|
||||
created_by=owner,
|
||||
)
|
||||
result: Final = await store.edit(submission_id, owner, body.expected_revision, publication)
|
||||
|
|
@ -315,9 +303,12 @@ async def edit_submission_archive(
|
|||
submissions: SkillSubmissionRepositoryDep,
|
||||
uploads: PluginUploadRepositoryDep,
|
||||
caller: Annotated[UserAPIKeyAuth, Depends(archive_writer)],
|
||||
file: Annotated[UploadFile, File(description="Replacement Agent Skills ZIP with the same declared skill name")],
|
||||
file: Annotated[UploadFile, File(description="Replacement ZIP retaining the registered and declared skill names")],
|
||||
expected_revision: Annotated[int, Form(ge=0)],
|
||||
version: Annotated[str | None, Form()] = None,
|
||||
version: Annotated[
|
||||
str | None,
|
||||
Form(description="Explicit SemVer, or omit/send empty for automatic versioning on approval"),
|
||||
] = None,
|
||||
) -> SkillHubSubmission:
|
||||
"""Replace a pending proposal's files using the upload limits. Only its original submitting user may edit."""
|
||||
owner: Final = _editor(caller)
|
||||
|
|
@ -326,11 +317,7 @@ async def edit_submission_archive(
|
|||
content: Final = await file.read(MAX_IMPORT_BYTES + 1)
|
||||
if len(content) > MAX_IMPORT_BYTES:
|
||||
raise HTTPException(413, "Skill ZIP must be 10 MiB or smaller")
|
||||
archive: Final = await asyncio.to_thread(build_agent_skill_archive, content)
|
||||
if archive is None or archive.declared_name != submission.plugin_name:
|
||||
raise HTTPException(422, "Replacement SKILL.md must declare the existing skill name and a description")
|
||||
prepared: Final = await prepare_skill_publication(request, archive, version, None, owner)
|
||||
publication: Final = replace(prepared, manifest={**submission.proposal.manifest, **prepared.manifest})
|
||||
publication: Final = await prepare_skill_replacement(request, content, submission.proposal, version, owner)
|
||||
result: Final = await store.edit(submission_id, owner, expected_revision, publication)
|
||||
return _response(request, _changed(result), caller)
|
||||
|
||||
|
|
|
|||
|
|
@ -60,9 +60,12 @@ def parse_skill_source(
|
|||
return GitHubSkillSource(parts[0], parts[1], ref, parts[2], path)
|
||||
if len(parts) == 2:
|
||||
return GitHubSkillSource(parts[0], parts[1].removesuffix(".git"), ref, skill, path)
|
||||
if len(parts) < 5 or parts[2] != "tree" or path is not None or ref != "HEAD":
|
||||
return SkillImportError(400, "Use a repository URL with ref and path, or a GitHub tree URL")
|
||||
return GitHubSkillSource(parts[0], parts[1], parts[3], skill, "/".join(parts[4:]))
|
||||
if len(parts) < 5 or parts[2] not in ("tree", "blob") or path is not None or ref != "HEAD":
|
||||
return SkillImportError(400, "Use a repository URL with ref and path, or a GitHub tree or SKILL.md blob URL")
|
||||
if parts[2] == "blob" and parts[-1] != "SKILL.md":
|
||||
return SkillImportError(400, "GitHub blob URLs must identify a SKILL.md file")
|
||||
directory: Final = parts[4:-1] if parts[2] == "blob" else parts[4:]
|
||||
return GitHubSkillSource(parts[0], parts[1], parts[3], skill, "/".join(directory))
|
||||
|
||||
|
||||
async def fetch_skill_source(source: GitHubSkillSource, client: httpx.AsyncClient) -> bytes | SkillImportError:
|
||||
|
|
|
|||
|
|
@ -26,7 +26,7 @@ The endpoint must be reachable from the gateway. A customer's laptop works while
|
|||
|
||||
Open Skills, Submissions, and Review as a proxy admin. Click **Scan for threats**, inspect the report, then independently approve or reject the proposal. Scanning is optional and never changes approval permissions or blocks publication. The report shows findings, locations, remediation, risk score, scanner version and whether semantic analysis actually ran. Incomplete reports do not establish safety
|
||||
|
||||
Uploaded ZIPs are sent privately to the scanner with their exact stored bytes. Metadata-only edits reuse the matching stored archive. If that archive is missing or changed, submit a new ZIP before scanning. The displayed SHA-256 identifies that archive, and the scan examines its files rather than proposed catalog metadata. Remote URL reports describe the source at scan time and do not freeze its contents. GitHub branch/tag refs and explicit-ref subdirectories are supported. Other ref/subdirectory combinations require a ZIP so the adapter does not silently scan the wrong revision
|
||||
Uploaded ZIPs are sent privately to the scanner with their exact stored bytes. Metadata-only edits reuse the matching stored archive. If that archive is missing or changed, submit a new ZIP before scanning. The displayed SHA-256 identifies that archive, and the scan examines its files rather than proposed catalog metadata. Remote URL reports describe the source at scan time and do not freeze its contents. GitHub branch/tag refs and explicit-ref subdirectories are supported. Commit-pinned sources and other ref/subdirectory combinations require a ZIP so the adapter does not silently scan the wrong revision
|
||||
|
||||
The latest scan result is retained with the submission. Running scans have a deadline. If a gateway restarts or the scanner becomes unavailable, the attempt expires and an admin can retry. Retries replace the latest report. Approving or rejecting during a scan does not cancel it or change the decision
|
||||
|
||||
|
|
|
|||
|
|
@ -37,6 +37,8 @@ def authenticate(credentials: Annotated[HTTPAuthorizationCredentials, Depends(HT
|
|||
|
||||
|
||||
def source_target(source: dict[str, str]) -> str:
|
||||
if source.get("sha"):
|
||||
raise HTTPException(400, "Upload a ZIP to scan this source's exact commit")
|
||||
target: Final = (
|
||||
"https://github.com/" + source.get("repo", "") if source.get("source") == "github" else source.get("url", "")
|
||||
)
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ from pydantic import ConfigDict, Field
|
|||
|
||||
from litellm.models.skill_submission import SubmissionOperation, SubmissionStatus
|
||||
from litellm.types.llms.base import LiteLLMBaseModel
|
||||
from litellm.types.proxy.claude_code_endpoints import PluginAuthor
|
||||
|
||||
SkillSortField: TypeAlias = Literal[
|
||||
"name",
|
||||
|
|
@ -39,6 +40,9 @@ class SkillHubSkill(LiteLLMBaseModel):
|
|||
domain: str | None = None
|
||||
namespace: str | None = None
|
||||
keywords: tuple[str, ...] | None = None
|
||||
author: PluginAuthor | None = None
|
||||
category: str | None = None
|
||||
homepage: str | None = None
|
||||
download_count: int | None = Field(None, description="Gateway ZIP downloads, including repeat downloads")
|
||||
|
||||
|
||||
|
|
@ -51,27 +55,56 @@ class SkillHubList(LiteLLMBaseModel):
|
|||
next_offset: int | None
|
||||
|
||||
|
||||
class SkillHubUpload(LiteLLMBaseModel):
|
||||
model_config = ConfigDict(frozen=True, extra="forbid")
|
||||
|
||||
name: str = Field(..., pattern=r"^[a-z0-9-]+$", description="Registry skill name")
|
||||
version: str | None = Field("1.0.0", description="Semantic version, defaults to 1.0.0 on creation")
|
||||
description: str | None = None
|
||||
author: PluginAuthor | None = None
|
||||
homepage: str | None = None
|
||||
keywords: tuple[str, ...] | None = None
|
||||
category: str | None = None
|
||||
domain: str | None = None
|
||||
namespace: str | None = None
|
||||
|
||||
|
||||
class SkillHubRegistration(SkillHubUpload):
|
||||
source: Mapping[str, str] = Field(description="Repository or HTTPS archive source reference")
|
||||
|
||||
|
||||
class ImportSkillRequest(LiteLLMBaseModel):
|
||||
model_config = ConfigDict(frozen=True)
|
||||
model_config = ConfigDict(frozen=True, extra="forbid")
|
||||
|
||||
url: str = Field(description="Public skills.sh skill URL or GitHub repository URL")
|
||||
skill: str | None = Field(None, description="Skill name to select when a repository contains several skills")
|
||||
ref: str = Field("HEAD", description="Git commit, tag or branch to import")
|
||||
path: str | None = Field(None, description="Repository-relative skill directory")
|
||||
version: str | None = Field(None, description="Semantic version, or omit/null to start at 1.0.0")
|
||||
metadata: SkillHubUpload | None = Field(None, description="Optional registry name and metadata overrides")
|
||||
|
||||
|
||||
class SkillHubMetadata(LiteLLMBaseModel):
|
||||
model_config = ConfigDict(frozen=True, extra="forbid")
|
||||
|
||||
description: str | None = Field(None, max_length=1024)
|
||||
description: str | None = Field(None, description="Omit to preserve, null to clear the registry description")
|
||||
version: str | None = Field(None, description="Explicit higher SemVer, or omit/null for an automatic patch bump")
|
||||
expected_updated_at: datetime | None = Field(
|
||||
None, description="Published updated_at read by the editor. A stale value returns 409", exclude=True
|
||||
)
|
||||
domain: str | None = None
|
||||
namespace: str | None = None
|
||||
keywords: tuple[str, ...] | None = None
|
||||
domain: str | None = Field(None, description="Omit to preserve, null to clear")
|
||||
namespace: str | None = Field(None, description="Omit to preserve, null to clear")
|
||||
keywords: tuple[str, ...] | None = Field(None, description="Omit to preserve, null or an empty list to clear")
|
||||
author: PluginAuthor | None = Field(None, description="Omit to preserve, null to clear")
|
||||
category: str | None = Field(None, description="Omit to preserve, null to clear")
|
||||
homepage: str | None = Field(None, description="Omit to preserve, null to clear")
|
||||
|
||||
|
||||
class SkillHubUpdate(SkillHubMetadata):
|
||||
source: Mapping[str, str] | None = Field(
|
||||
None,
|
||||
description="Explicit replacement source reference. Omit/null to preserve the stored source and archive",
|
||||
)
|
||||
|
||||
|
||||
class SkillHubPublication(LiteLLMBaseModel):
|
||||
|
|
@ -124,6 +157,9 @@ class SkillHubProposal(LiteLLMBaseModel):
|
|||
domain: str | None = None
|
||||
namespace: str | None = None
|
||||
keywords: tuple[str, ...] | None = None
|
||||
author: PluginAuthor | None = None
|
||||
category: str | None = None
|
||||
homepage: str | None = None
|
||||
source: Mapping[str, str]
|
||||
agent_skill: SkillHubAgentSkill | None = None
|
||||
|
||||
|
|
@ -183,6 +219,7 @@ class SkillHubSubmissionRevision(LiteLLMBaseModel):
|
|||
|
||||
class SkillHubSubmissionEdit(SkillHubMetadata):
|
||||
expected_revision: int = Field(ge=0, description="Revision read from the submission detail")
|
||||
version: str | None = Field(None, description="Explicit SemVer, or omit/null for automatic versioning on approval")
|
||||
|
||||
|
||||
class SkillHubReviewResponse(LiteLLMBaseModel):
|
||||
|
|
|
|||
|
|
@ -1,11 +1,18 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { renderHook, waitFor } from "@testing-library/react";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { keepPreviousData, QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import React, { ReactNode } from "react";
|
||||
import { useInfiniteUsers, useUserEmailLookup, useUserLookup } from "./useUsers";
|
||||
import {
|
||||
useInfiniteUsers,
|
||||
useUserEmailLookup,
|
||||
useUserLookup,
|
||||
useUserIdentityLookup,
|
||||
userIdentityLabel,
|
||||
} from "./useUsers";
|
||||
import { userGetInfoV2, userListCall } from "@/components/networking";
|
||||
import type { UserInfoV2Response, UserListResponse } from "@/components/networking";
|
||||
import { ApiError } from "@/lib/http/client";
|
||||
import type { CurrentUser } from "../currentUser/useCurrentUser";
|
||||
|
||||
vi.mock("@/components/networking", () => ({
|
||||
userGetInfoV2: vi.fn(),
|
||||
|
|
@ -27,6 +34,11 @@ vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
|
|||
default: () => mockUseAuthorized(),
|
||||
}));
|
||||
|
||||
const mockUseCurrentUser = vi.fn<(accessToken: string | null) => { data?: CurrentUser; isPlaceholderData?: boolean }>();
|
||||
vi.mock("../currentUser/useCurrentUser", () => ({
|
||||
useCurrentUser: (accessToken: string | null) => mockUseCurrentUser(accessToken),
|
||||
}));
|
||||
|
||||
const DEFAULT_AUTH = {
|
||||
accessToken: "test-access-token",
|
||||
userId: "test-user-id",
|
||||
|
|
@ -48,6 +60,12 @@ const buildUserListResponse = (page: number, totalPages: number, userCount = 2):
|
|||
user_email: `user-${page}-${i}@example.com`,
|
||||
user_alias: null,
|
||||
user_role: "Internal User",
|
||||
allowed_cache_controls: [],
|
||||
model_max_budget: {},
|
||||
model_spend: {},
|
||||
models: [],
|
||||
policies: [],
|
||||
teams: [],
|
||||
spend: 0,
|
||||
max_budget: null,
|
||||
key_count: 0,
|
||||
|
|
@ -448,3 +466,128 @@ describe("useUserEmailLookup", () => {
|
|||
expect(userListCall).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("useUserIdentityLookup", () => {
|
||||
let queryClient: QueryClient;
|
||||
const adminScope = { accessToken: "admin-token", userRole: "Admin" };
|
||||
const admin: CurrentUser = { user_id: "admin-id", user_email: "admin@example.com", user_role: "proxy_admin" };
|
||||
const member: CurrentUser = { user_id: "member-id", user_email: "member@example.com", user_role: "internal_user" };
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
React.createElement(QueryClientProvider, { client: queryClient }, children);
|
||||
const lookup = (
|
||||
ids: Parameters<typeof useUserIdentityLookup>[0],
|
||||
scope: Parameters<typeof useUserIdentityLookup>[1] = adminScope,
|
||||
) => renderHook(() => useUserIdentityLookup(ids, scope), { wrapper });
|
||||
|
||||
beforeEach(() => {
|
||||
queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, placeholderData: keepPreviousData } } });
|
||||
vi.clearAllMocks();
|
||||
mockUseCurrentUser.mockReturnValue({ data: admin });
|
||||
vi.mocked(userGetInfoV2).mockRejectedValue(new ApiError("Not Found", 404, {}));
|
||||
vi.mocked(userListCall).mockRejectedValue(new ApiError("Forbidden", 403, {}));
|
||||
});
|
||||
|
||||
afterEach(() => queryClient.clear());
|
||||
|
||||
it.each([
|
||||
[" alice@example.com ", "Alice", "alice@example.com"],
|
||||
[null, " Alice ", "Alice"],
|
||||
[" ", " ", "id"],
|
||||
])("labels by email, alias, then id", (user_email, user_alias, expected) => {
|
||||
expect(userIdentityLabel("id", { id: { user_email, user_alias } })).toBe(expected);
|
||||
});
|
||||
|
||||
it("matches singleton by exact id, never email", async () => {
|
||||
vi.mocked(userGetInfoV2).mockResolvedValue(buildUserInfoV2Response("different-id"));
|
||||
const { result } = lookup(["alice@example.com"]);
|
||||
await waitFor(() => expect(queryClient.isFetching()).toBe(0));
|
||||
expect(result.current).toEqual({});
|
||||
expect(userGetInfoV2).toHaveBeenCalledExactlyOnceWith("admin-token", "alice@example.com");
|
||||
});
|
||||
|
||||
it.each([undefined, 403, 404])("resolves exact ids across batches, retaining successes after %s", async (status) => {
|
||||
const ids = Array.from({ length: 201 }, (_, index) => `user-${String(index).padStart(3, "0")}`);
|
||||
const template = buildUserListResponse(1, 1, 1);
|
||||
vi.mocked(userListCall).mockImplementation(async (_token, batch) => ({
|
||||
...template,
|
||||
users: [...(batch ?? []), "unrequested-id"].map((user_id) => ({ ...template.users[0], user_id })),
|
||||
}));
|
||||
if (status) vi.mocked(userListCall).mockRejectedValueOnce(new ApiError("Unavailable", status, {}));
|
||||
vi.mocked(userGetInfoV2).mockResolvedValue(buildUserInfoV2Response(ids[200]));
|
||||
const { result } = lookup([...ids, ids[0]]);
|
||||
await waitFor(() => expect(queryClient.isFetching()).toBe(0));
|
||||
expect(Object.keys(result.current)).toEqual(status ? ids.slice(100) : ids);
|
||||
expect(userIdentityLabel(ids[0], result.current)).toBe(status ? ids[0] : template.users[0].user_email);
|
||||
expect(userListCall).toHaveBeenCalledTimes(2);
|
||||
expect(userListCall).toHaveBeenNthCalledWith(1, "admin-token", ids.slice(0, 100), 1, 100);
|
||||
expect(userListCall).toHaveBeenNthCalledWith(2, "admin-token", ids.slice(100, 200), 1, 100);
|
||||
expect(userGetInfoV2).toHaveBeenCalledExactlyOnceWith("admin-token", ids[200]);
|
||||
});
|
||||
|
||||
it.each([200, 403])("enriches only self, keeping authenticated email after status %s", async (status) => {
|
||||
mockUseCurrentUser.mockReturnValue({ data: member });
|
||||
if (status === 200) vi.mocked(userGetInfoV2).mockResolvedValue(buildUserInfoV2Response("member-id"));
|
||||
const { result } = lookup(["member-id", "other-id"], { accessToken: "member-token" });
|
||||
expect(userIdentityLabel("member-id", result.current)).toBe(member.user_email);
|
||||
await waitFor(() => expect(queryClient.isFetching()).toBe(0));
|
||||
expect(result.current).toEqual({
|
||||
"member-id": { user_email: member.user_email, user_alias: status === 200 ? "Alice" : null },
|
||||
});
|
||||
expect(userGetInfoV2).toHaveBeenCalledExactlyOnceWith("member-token", "member-id");
|
||||
expect(userListCall).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ...adminScope, userRole: "Internal User", ids: ["other-id"] },
|
||||
{ accessToken: "member-token", userRole: undefined, ids: ["member@example.com", "other-id"] },
|
||||
{ ...adminScope, ids: [null, undefined, ""] },
|
||||
{ ...adminScope, accessToken: null, ids: ["admin-id", "other-id"] },
|
||||
])("does not query outside scope $accessToken / $userRole / $ids", ({ ids, ...scope }) => {
|
||||
if (scope.accessToken === "member-token") mockUseCurrentUser.mockReturnValue({ data: member });
|
||||
const { result } = lookup(ids, scope);
|
||||
expect(result.current).toEqual({});
|
||||
expect(mockUseCurrentUser).toHaveBeenCalledWith(scope.accessToken);
|
||||
expect(mockUseAuthorized).not.toHaveBeenCalled();
|
||||
expect(userListCall).not.toHaveBeenCalled();
|
||||
expect(userGetInfoV2).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["supplied-role", "server-role", "read-only", "ids", "account", "logout"])(
|
||||
"clears privileged data immediately after a %s transition, including placeholders",
|
||||
async (change) => {
|
||||
const id = change === "account" ? "admin-id" : "other-id";
|
||||
vi.mocked(userGetInfoV2).mockResolvedValue(buildUserInfoV2Response(id));
|
||||
const initialProps: Parameters<typeof useUserIdentityLookup>[1] & { ids: string[] } = {
|
||||
...adminScope,
|
||||
userRole: change === "account" ? undefined : adminScope.userRole,
|
||||
isViewOnly: false,
|
||||
ids: [id],
|
||||
};
|
||||
const { result, rerender } = renderHook(({ ids, ...scope }) => useUserIdentityLookup(ids, scope), {
|
||||
wrapper,
|
||||
initialProps,
|
||||
});
|
||||
await waitFor(() => expect(queryClient.isFetching()).toBe(0));
|
||||
expect(userIdentityLabel(id, result.current)).toBe(change === "account" ? admin.user_email : "alice@example.com");
|
||||
vi.mocked(userGetInfoV2).mockRejectedValue(new ApiError("Forbidden", 403, {}));
|
||||
if (change === "server-role")
|
||||
mockUseCurrentUser.mockReturnValue({ data: { ...admin, user_role: "internal_user" } });
|
||||
if (change === "account") mockUseCurrentUser.mockReturnValue({ data: admin, isPlaceholderData: true });
|
||||
const nextToken = change === "account" ? "member-token" : initialProps.accessToken;
|
||||
const nextProps = {
|
||||
accessToken: change === "logout" ? null : nextToken,
|
||||
userRole: change === "supplied-role" ? "Internal User" : initialProps.userRole,
|
||||
isViewOnly: change === "read-only",
|
||||
ids: change === "ids" ? ["new-id"] : initialProps.ids,
|
||||
};
|
||||
rerender(nextProps);
|
||||
expect(result.current).toEqual({});
|
||||
await waitFor(() => expect(queryClient.isFetching()).toBe(0));
|
||||
mockUseCurrentUser.mockReturnValue({ data: member });
|
||||
rerender(nextProps);
|
||||
expect(result.current).toEqual({});
|
||||
expect(userListCall).not.toHaveBeenCalled();
|
||||
if (change === "logout") expect(userGetInfoV2).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { createQueryKeys } from "../common/queryKeysFactory";
|
|||
import { canListUsers } from "@/utils/roles";
|
||||
import useAuthorized from "@/app/(dashboard)/hooks/useAuthorized";
|
||||
import { ApiError } from "@/lib/http/client";
|
||||
import { useCurrentUser } from "../currentUser/useCurrentUser";
|
||||
|
||||
const infiniteUsersKeys = createQueryKeys("infiniteUsers");
|
||||
const userLookupKeys = createQueryKeys("userLookup");
|
||||
|
|
@ -42,6 +43,73 @@ export const useInfiniteUsers = (pageSize: number = DEFAULT_PAGE_SIZE, searchEma
|
|||
|
||||
const USER_LIST_MAX_PAGE_SIZE = 100;
|
||||
|
||||
export type UserIdentityLookup = Readonly<
|
||||
Record<string, Readonly<Pick<UserInfoV2Response, "user_email" | "user_alias">>>
|
||||
>;
|
||||
|
||||
export const userIdentityLabel = (id: string | null | undefined, identities: UserIdentityLookup): string => {
|
||||
if (!id) return "";
|
||||
return identities[id]?.user_email?.trim() || identities[id]?.user_alias?.trim() || id;
|
||||
};
|
||||
|
||||
export const useUserIdentityLookup = (
|
||||
userIds: readonly (string | null | undefined)[],
|
||||
scope: { accessToken: string | null; userRole?: string; isViewOnly?: boolean },
|
||||
): UserIdentityLookup => {
|
||||
const { accessToken, userRole, isViewOnly = false } = scope;
|
||||
const currentUser = useCurrentUser(accessToken);
|
||||
const me = currentUser.isPlaceholderData ? undefined : currentUser.data;
|
||||
const effectiveRole = userRole ?? me?.user_role ?? "";
|
||||
const canLookupOthers = canListUsers(effectiveRole);
|
||||
const ids = Array.from(new Set(userIds.filter((id): id is string => typeof id === "string" && id !== ""))).sort();
|
||||
const lookupIds = canLookupOthers ? ids : ids.filter((id) => id === me?.user_id);
|
||||
const { data, isPlaceholderData } = useQuery<UserIdentityLookup>({
|
||||
queryKey: [
|
||||
"userIdentityLookup",
|
||||
{ accessToken, effectiveRole, isViewOnly, currentUserRole: me?.user_role, currentUserId: me?.user_id, ids },
|
||||
],
|
||||
queryFn: async () => {
|
||||
if (!accessToken) return {};
|
||||
const batches = Array.from({ length: Math.ceil(lookupIds.length / USER_LIST_MAX_PAGE_SIZE) }, (_, index) =>
|
||||
lookupIds.slice(index * USER_LIST_MAX_PAGE_SIZE, (index + 1) * USER_LIST_MAX_PAGE_SIZE),
|
||||
);
|
||||
const users = await Promise.all(
|
||||
batches.map(async (batch) => {
|
||||
try {
|
||||
if (batch.length === 1) {
|
||||
const user = await userGetInfoV2(accessToken, batch[0]);
|
||||
return user.user_id === batch[0] ? [user] : [];
|
||||
}
|
||||
const response = await userListCall(accessToken, batch, 1, batch.length);
|
||||
return response.users.filter((user) => batch.includes(user.user_id));
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && (error.status === 403 || error.status === 404)) return [];
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
);
|
||||
return Object.fromEntries(
|
||||
users
|
||||
.flat()
|
||||
.map((user) => [user.user_id, { user_email: user.user_email ?? null, user_alias: user.user_alias ?? null }]),
|
||||
);
|
||||
},
|
||||
enabled: Boolean(accessToken) && lookupIds.length > 0,
|
||||
});
|
||||
|
||||
if (!accessToken) return {};
|
||||
const identities = isPlaceholderData ? {} : data ?? {};
|
||||
if (!me || !ids.includes(me.user_id)) return identities;
|
||||
const self = identities[me.user_id] ?? { user_email: null, user_alias: null };
|
||||
return {
|
||||
...identities,
|
||||
[me.user_id]: {
|
||||
...self,
|
||||
user_email: me.user_email?.trim() || self.user_email,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const useUserEmailLookup = (userIds: readonly string[]) => {
|
||||
const { accessToken, userRole } = useAuthorized();
|
||||
const distinctIds = Array.from(new Set(userIds.filter((id) => id !== ""))).sort();
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ const published: SkillHubSkill = {
|
|||
content_url: "/skill-hub/skills/shared-skill/content",
|
||||
updated_at: "2026-10-20T00:00:00Z",
|
||||
download_count: 0,
|
||||
security_scan_passed: false,
|
||||
};
|
||||
|
||||
const pending: SkillSubmission = {
|
||||
|
|
@ -61,6 +62,20 @@ const pending: SkillSubmission = {
|
|||
rejection_reason: null,
|
||||
};
|
||||
|
||||
const creator = { user_id: "creator-uuid", user_email: "creator@example.test", user_alias: "Creator" };
|
||||
const authoredMetadata = {
|
||||
author: { name: "Original Maintainer", email: "maintainer@example.test" },
|
||||
category: "Review",
|
||||
homepage: "https://example.test/skill",
|
||||
};
|
||||
|
||||
const ownedSubmission: SkillSubmission = {
|
||||
...pending,
|
||||
can_edit: true,
|
||||
revision: 3,
|
||||
proposal: { ...pending.proposal, version: "3.0.0" },
|
||||
};
|
||||
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
const queryDefaults = testQueryClient.getDefaultOptions();
|
||||
let catalog: SkillHubSkill[];
|
||||
|
|
@ -70,6 +85,7 @@ let pageRequests: { limit: number; offset: number }[];
|
|||
let writes: { path: string; method: string; body: RequestInit["body"] }[];
|
||||
let reviewFailure: string | null;
|
||||
let directPublication: boolean;
|
||||
let identities: { user_id: string; user_email: string; user_alias: string }[];
|
||||
|
||||
const respondToWrite = (path: string, body: RequestInit["body"]) => {
|
||||
if (reviewFailure && path.startsWith("/skill-hub/submissions/"))
|
||||
|
|
@ -91,12 +107,13 @@ const respondToWrite = (path: string, body: RequestInit["body"]) => {
|
|||
};
|
||||
return Response.json(result);
|
||||
}
|
||||
if (path === `/skill-hub/submissions/${pending.id}`) {
|
||||
if (path === `/skill-hub/submissions/${pending.id}` || path === `/skill-hub/submissions/${pending.id}/upload`) {
|
||||
const metadata = typeof body === "string" ? JSON.parse(body) : {};
|
||||
const version = body instanceof FormData ? body.get("version") : null;
|
||||
submissions = submissions.map((item) => ({
|
||||
...item,
|
||||
revision: (item.revision ?? 0) + 1,
|
||||
proposal: { ...item.proposal, ...metadata },
|
||||
proposal: { ...item.proposal, ...metadata, ...(typeof version === "string" ? { version: version || null } : {}) },
|
||||
}));
|
||||
return Response.json(submissions[0]);
|
||||
}
|
||||
|
|
@ -105,7 +122,7 @@ const respondToWrite = (path: string, body: RequestInit["body"]) => {
|
|||
return Response.json(submissions[0]);
|
||||
}
|
||||
if (directPublication) {
|
||||
catalog = [{ ...published, version: "3.0.0", description: "Admin-published instructions" }];
|
||||
catalog = [{ ...catalog[0], version: "3.0.0", description: "Admin-published instructions" }];
|
||||
return Response.json(catalog[0]);
|
||||
}
|
||||
submissions = [pending];
|
||||
|
|
@ -173,6 +190,27 @@ function scanResponse(method: string) {
|
|||
});
|
||||
}
|
||||
|
||||
const respondToIdentity = (url: URL, headers: Headers): Response | undefined => {
|
||||
const path = url.pathname;
|
||||
if (path === "/management/v1/users/me") {
|
||||
const member = headers.get("Authorization") === "Bearer member-token";
|
||||
return Response.json({
|
||||
user_id: member ? "member@example.org" : "admin",
|
||||
user_email: member ? "member@example.org" : null,
|
||||
user_role: member ? "internal_user" : "proxy_admin",
|
||||
});
|
||||
}
|
||||
if (path === "/user/list") {
|
||||
const ids = url.searchParams.get("user_ids")?.split(",") ?? [];
|
||||
return Response.json({ users: identities.filter((user) => ids.includes(user.user_id)) });
|
||||
}
|
||||
if (path === "/v2/user/info") {
|
||||
const user = identities.find((user) => user.user_id === url.searchParams.get("user_id"));
|
||||
return user ? Response.json(user) : Response.json({ detail: "Not found" }, { status: 404 });
|
||||
}
|
||||
if (path === "/.well-known/litellm-ui-config") return Response.json({ claude_code_marketplace_auth_required: true });
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
scanFailure = false;
|
||||
scanRequested = false;
|
||||
|
|
@ -185,16 +223,19 @@ beforeEach(() => {
|
|||
writes = [];
|
||||
reviewFailure = null;
|
||||
directPublication = false;
|
||||
fetchMock.mockReset().mockImplementation(async (input, options) => {
|
||||
identities = [];
|
||||
fetchMock.mockReset().mockImplementation(async (input, options = {}) => {
|
||||
const request = input instanceof Request ? input : null;
|
||||
const url = new URL(request?.url ?? String(input), "http://localhost");
|
||||
const path = url.pathname;
|
||||
const method = request?.method ?? options?.method ?? "GET";
|
||||
const { method = "GET", headers } = request ?? options;
|
||||
const identityResponse = respondToIdentity(url, new Headers(headers));
|
||||
if (identityResponse) return identityResponse;
|
||||
if (path === `/skill-hub/submissions/${pending.id}/scan`) {
|
||||
return scanResponse(method);
|
||||
}
|
||||
if (method !== "GET") {
|
||||
const body = request ? await request.text() : options?.body;
|
||||
const body = request ? await request.text() : options.body;
|
||||
writes.push({ path, method, body });
|
||||
return respondToWrite(path, body);
|
||||
}
|
||||
|
|
@ -233,8 +274,6 @@ beforeEach(() => {
|
|||
if (path.endsWith("/archive")) return new Response("zip-bytes", { headers: { "Content-Type": "application/zip" } });
|
||||
if (path === `/skill-hub/submissions/${pending.id}`)
|
||||
return Response.json({ submission: submissions[0], current_skill: catalog[0] });
|
||||
if (path === "/.well-known/litellm-ui-config")
|
||||
return Response.json({ claude_code_marketplace_auth_required: true });
|
||||
return Response.json({ detail: "Unexpected request" }, { status: 404 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
|
@ -262,7 +301,7 @@ it("refreshes published counts after a retained download", async () => {
|
|||
URL.createObjectURL = vi.fn(() => "blob:skill-download");
|
||||
renderWithProviders(<ClaudeCodePluginsPanel accessToken="admin-token" userRole="Admin" />);
|
||||
expect(await screen.findByRole("cell", { name: "0" }, { timeout: 5000 })).toBeInTheDocument();
|
||||
expect(fetchMock).toHaveBeenCalledOnce();
|
||||
expect(catalogRequests).toHaveLength(1);
|
||||
fireEvent.click(screen.getByText(published.name));
|
||||
await screen.findByRole("button", { name: "Edit Skill" });
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Version history" }));
|
||||
|
|
@ -306,7 +345,7 @@ it("paginates the neutral catalog and refreshes detail for a recreated skill", a
|
|||
await waitFor(() => expect(screen.getByRole("button", { name: "Previous" })).toBeDisabled());
|
||||
});
|
||||
|
||||
it.each(["descriptor", "archive"])("requires a portable %s for a submitted ZIP preview", async (missing) => {
|
||||
it.each(["descriptor", "archive"])("previews stored ZIPs with missing %s", async (missing) => {
|
||||
submissions = [
|
||||
{
|
||||
...pending,
|
||||
|
|
@ -317,7 +356,8 @@ it.each(["descriptor", "archive"])("requires a portable %s for a submitted ZIP p
|
|||
renderSubmissions();
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Review" }));
|
||||
expect(await screen.findByText("Currently published")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Download submitted ZIP" })).not.toBeInTheDocument();
|
||||
if (missing === "descriptor") expect(screen.getByRole("button", { name: "Download submitted ZIP" })).toBeEnabled();
|
||||
else expect(screen.queryByRole("button", { name: "Download submitted ZIP" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Approve and publish" })).toBeEnabled();
|
||||
});
|
||||
|
||||
|
|
@ -415,10 +455,21 @@ it("allows a member submission, explains approval and refreshes their pending li
|
|||
expect(screen.getByRole("tab", { name: "Published skills" })).toHaveAttribute("aria-selected", "true"),
|
||||
);
|
||||
fireEvent.click(screen.getByRole("button", { name: "+ Register your skill" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Import URL" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Add from URL" }));
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Source URL" }), {
|
||||
target: { value: "https://github.com/example/new-skill" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Store a copy in LiteLLM" }));
|
||||
fireEvent.change(screen.getByLabelText("Registry name (optional)"), { target: { value: "review-alias" } });
|
||||
fireEvent.click(screen.getByText("Advanced metadata (optional)"));
|
||||
for (const [label, value] of [
|
||||
["Author Name (Optional)", authoredMetadata.author.name],
|
||||
["Author Email (Optional)", authoredMetadata.author.email],
|
||||
["Category (Optional)", authoredMetadata.category],
|
||||
["Homepage (Optional)", authoredMetadata.homepage],
|
||||
]) {
|
||||
fireEvent.change(screen.getByLabelText(label), { target: { value } });
|
||||
}
|
||||
fireEvent.click(screen.getByRole("button", { name: "Submit for approval" }));
|
||||
await waitFor(() =>
|
||||
expect(toast.success).toHaveBeenCalledWith("Submitted for admin approval. The published skill is unchanged"),
|
||||
|
|
@ -429,6 +480,7 @@ it("allows a member submission, explains approval and refreshes their pending li
|
|||
path: "/skill-hub/skills/import",
|
||||
method: "POST",
|
||||
});
|
||||
expect(JSON.parse(String(writes[0].body)).metadata).toEqual({ name: "review-alias", ...authoredMetadata });
|
||||
fireEvent.click(screen.getByRole("tab", { name: "My submissions" }));
|
||||
expect(await screen.findByText("Pending review")).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("button", { name: "View details" }));
|
||||
|
|
@ -453,7 +505,7 @@ it("retries failed detail loading before enabling edits", async () => {
|
|||
expect(await screen.findByRole("button", { name: "Edit Skill" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("edits the loaded detail with automatic version intent and preserves the approved skill while review is pending", async () => {
|
||||
it("replaces an existing source without publishing the member's proposal", async () => {
|
||||
const loaded = { ...published, updated_at: "2026-10-21T12:00:00Z" };
|
||||
const fetchStub = fetchMock.getMockImplementation()!;
|
||||
fetchMock.mockImplementation((input, options) =>
|
||||
|
|
@ -469,21 +521,24 @@ it("edits the loaded detail with automatic version intent and preserves the appr
|
|||
const form = screen.getByRole("dialog");
|
||||
expect(within(form).getByLabelText("Version override (optional)")).toHaveValue("");
|
||||
expect(within(form).getByLabelText("Namespace (optional)")).toHaveValue(published.namespace);
|
||||
fireEvent.click(within(form).getByRole("radio", { name: "Replace source" }));
|
||||
const source = { source: "url", url: "https://gitlab.com/example/skills" };
|
||||
fireEvent.change(within(form).getByLabelText("Source URL"), { target: { value: source.url } });
|
||||
fireEvent.change(within(form).getByLabelText("Description (Optional)"), {
|
||||
target: { value: "Proposed instructions" },
|
||||
});
|
||||
fireEvent.change(within(form).getByLabelText("Namespace (optional)"), { target: { value: "" } });
|
||||
fireEvent.click(within(form).getByRole("button", { name: "Submit for approval" }));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
|
||||
expect(writes[0]).toMatchObject({ path: "/skill-hub/skills/shared-skill", method: "PUT" });
|
||||
const expectedMetadata = {
|
||||
version: null,
|
||||
expected_updated_at: loaded.updated_at,
|
||||
domain: published.domain,
|
||||
namespace: published.namespace,
|
||||
keywords: published.keywords,
|
||||
description: "Proposed instructions",
|
||||
namespace: null,
|
||||
source,
|
||||
};
|
||||
expect(JSON.parse(String(writes[0].body))).toMatchObject(expectedMetadata);
|
||||
expect(JSON.parse(String(writes[0].body))).toEqual(expectedMetadata);
|
||||
expect(await screen.findByText("Recorded release")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Proposed instructions")).not.toBeInTheDocument();
|
||||
});
|
||||
|
|
@ -509,7 +564,11 @@ it.each(["metadata", "upload"])(
|
|||
"keeps direct admin %s publication and wires an explicit version override",
|
||||
async (sourceType) => {
|
||||
directPublication = true;
|
||||
identities = [creator];
|
||||
catalog = [{ ...published, ...authoredMetadata, created_by: creator.user_id }];
|
||||
renderWithProviders(<ClaudeCodePluginsPanel accessToken="admin-token" userRole="Admin" />);
|
||||
expect(await screen.findByText(creator.user_email)).toBeInTheDocument();
|
||||
expect(screen.getByTitle(creator.user_id)).toHaveTextContent(creator.user_email);
|
||||
const form = await openEdit();
|
||||
fireEvent.change(within(form).getByLabelText("Version override (optional)"), { target: { value: "3.0.0" } });
|
||||
fireEvent.change(within(form).getByLabelText("Description (Optional)"), {
|
||||
|
|
@ -526,6 +585,8 @@ it.each(["metadata", "upload"])(
|
|||
expect(await screen.findByText("Admin-published instructions")).toBeInTheDocument();
|
||||
expect(toast.success).toHaveBeenCalledWith("Skill updated successfully");
|
||||
expect(screen.queryByText("Submitted for admin approval")).not.toBeInTheDocument();
|
||||
expect(screen.getByText(authoredMetadata.author.name)).toBeInTheDocument();
|
||||
expect(screen.getByRole("row", { name: `Created by ${creator.user_email}` })).toBeInTheDocument();
|
||||
const body = writes[0].body;
|
||||
if (body instanceof FormData) {
|
||||
expect(body.get("version")).toBe("3.0.0");
|
||||
|
|
@ -537,6 +598,8 @@ it.each(["metadata", "upload"])(
|
|||
);
|
||||
|
||||
it("lets an admin inspect full proposed values, download the private ZIP, approve and see refreshed published details", async () => {
|
||||
identities = [creator];
|
||||
submissions = [{ ...pending, submitted_by: creator.user_id, proposal: { ...pending.proposal, ...authoredMetadata } }];
|
||||
const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
|
||||
vi.stubGlobal(
|
||||
"URL",
|
||||
|
|
@ -544,9 +607,14 @@ it("lets an admin inspect full proposed values, download the private ZIP, approv
|
|||
);
|
||||
setGlobalLitellmHeaderName("X-LiteLLM-Key");
|
||||
renderSubmissions();
|
||||
await screen.findByText(`Submitted by ${creator.user_email}`, { exact: false });
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Review" }));
|
||||
expect(await screen.findByText("Currently published")).toBeInTheDocument();
|
||||
const dialog = within(screen.getByRole("dialog"));
|
||||
expect(await dialog.findByText(`Submitted by ${creator.user_email}`)).toBeInTheDocument();
|
||||
expect(dialog.getByText(authoredMetadata.author.name, { exact: false })).toHaveTextContent(
|
||||
authoredMetadata.author.email,
|
||||
);
|
||||
expect(dialog.getByText("Approved instructions")).toBeInTheDocument();
|
||||
expect(dialog.getByText("Proposed instructions")).toBeInTheDocument();
|
||||
expect(dialog.getByText("Next patch version on approval")).toBeInTheDocument();
|
||||
|
|
@ -596,20 +664,33 @@ it("saves an admin rejection reason for the author and keeps the published metad
|
|||
expect(await screen.findByRole("cell", { name: "Approved instructions" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("refreshes detail after a review conflict and removes actions when another reviewer has already acted", async () => {
|
||||
renderSubmissions();
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Review" }));
|
||||
await screen.findByRole("button", { name: "Approve and publish" });
|
||||
reviewFailure = "Submission has already been reviewed";
|
||||
submissions = [{ ...pending, status: "rejected", rejection_reason: "Already reviewed elsewhere" }];
|
||||
fireEvent.click(screen.getByRole("button", { name: "Approve and publish" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(reviewFailure);
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Approve and publish" })).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole("button", { name: "Reject" })).not.toBeInTheDocument();
|
||||
expect(
|
||||
within(screen.getByRole("dialog")).getByText("Rejection reason: Already reviewed elsewhere"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
it.each(["approved", "rejected"] as const)(
|
||||
"refreshes detail after another reviewer has %s the submission",
|
||||
async (status) => {
|
||||
identities = [creator];
|
||||
renderSubmissions();
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Review" }));
|
||||
await screen.findByRole("button", { name: "Approve and publish" });
|
||||
reviewFailure = "Submission has already been reviewed";
|
||||
submissions = [
|
||||
{
|
||||
...pending,
|
||||
status,
|
||||
rejection_reason: status === "rejected" ? "Already reviewed elsewhere" : null,
|
||||
reviewed_by: creator.user_id,
|
||||
reviewed_at: pending.created_at,
|
||||
},
|
||||
];
|
||||
fireEvent.click(screen.getByRole("button", { name: "Approve and publish" }));
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(reviewFailure);
|
||||
await waitFor(() => expect(screen.queryByRole("button", { name: "Approve and publish" })).not.toBeInTheDocument());
|
||||
expect(screen.queryByRole("button", { name: "Reject" })).not.toBeInTheDocument();
|
||||
const dialog = within(screen.getByRole("dialog"));
|
||||
await dialog.findByText(`${status === "approved" ? "Approved" : "Rejected"} by ${creator.user_email}`, {
|
||||
exact: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an effective Admin viewer read-only while allowing full submission inspection", async () => {
|
||||
renderWithProviders(<ClaudeCodePluginsPanel accessToken="viewer-token" userRole="Admin" isViewOnly />);
|
||||
|
|
@ -807,8 +888,8 @@ it("applies tag and scan filters across the catalog and resets pagination when s
|
|||
expect(catalogRequests.at(-1)?.searchParams.get("security_scan_passed")).toBe("true");
|
||||
});
|
||||
|
||||
it("lets an owner edit the viewed proposal and withdraw it with its current revision", async () => {
|
||||
submissions = [{ ...pending, can_edit: true, revision: 3, proposal: { ...pending.proposal, version: "3.0.0" } }];
|
||||
it.each([false, true])("edits and withdraws the owner's proposal with version reset %s", async (resetVersion) => {
|
||||
submissions = [ownedSubmission];
|
||||
renderWithProviders(<ClaudeCodePluginsPanel accessToken="member-token" userRole="Internal User" />, {
|
||||
searchParams: "tab=submissions",
|
||||
});
|
||||
|
|
@ -823,12 +904,15 @@ it("lets an owner edit the viewed proposal and withdraw it with its current revi
|
|||
fireEvent.change(await screen.findByLabelText("Description (Optional)"), {
|
||||
target: { value: "Owner revised instructions" },
|
||||
});
|
||||
if (resetVersion) fireEvent.change(screen.getByLabelText("Version override (optional)"), { target: { value: "" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save submission" }));
|
||||
expect(await screen.findByRole("cell", { name: "Owner revised instructions" })).toBeInTheDocument();
|
||||
expect(JSON.parse(String(writes[0].body))).toMatchObject({
|
||||
const expectedMetadata = {
|
||||
expected_revision: 3,
|
||||
description: "Owner revised instructions",
|
||||
});
|
||||
version: resetVersion ? null : "3.0.0",
|
||||
};
|
||||
expect(JSON.parse(String(writes[0].body))).toEqual(expectedMetadata);
|
||||
expect(catalog).toEqual([published]);
|
||||
fireEvent.click(screen.getByRole("button", { name: "Withdraw submission" }));
|
||||
expect(writes).toHaveLength(1);
|
||||
|
|
@ -843,6 +927,39 @@ it("lets an owner edit the viewed proposal and withdraw it with its current revi
|
|||
expect(screen.queryByRole("button", { name: "Withdraw submission" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ action: "untouched", input: null, expectedVersion: "3.0.0" },
|
||||
{ action: "cleared", input: "", expectedVersion: null },
|
||||
{ action: "overridden", input: " 4.0.0 ", expectedVersion: "4.0.0" },
|
||||
])("saves a pending ZIP with its version $action", async ({ input, expectedVersion }) => {
|
||||
submissions = [ownedSubmission];
|
||||
renderWithProviders(<ClaudeCodePluginsPanel accessToken="member-token" userRole="Internal User" />, {
|
||||
searchParams: "tab=submissions",
|
||||
});
|
||||
fireEvent.click(await screen.findByRole("button", { name: "View details" }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Edit submission" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Upload ZIP" }));
|
||||
expect(screen.getByLabelText("Version override (optional)")).toHaveValue("3.0.0");
|
||||
const file = new File(["replacement"], "skill.zip", { type: "application/zip" });
|
||||
fireEvent.change(screen.getByLabelText("Skill ZIP file"), { target: { files: [file] } });
|
||||
if (input !== null) {
|
||||
fireEvent.change(screen.getByLabelText("Version override (optional)"), { target: { value: input } });
|
||||
}
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save submission" }));
|
||||
expect(
|
||||
await screen.findByRole("cell", { name: expectedVersion ?? "Next patch version on approval" }),
|
||||
).toBeInTheDocument();
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0]).toMatchObject({ path: `/skill-hub/submissions/${pending.id}/upload`, method: "PUT" });
|
||||
expect(Object.fromEntries(writes[0].body as FormData)).toEqual({
|
||||
file,
|
||||
expected_revision: "3",
|
||||
version: expectedVersion ?? "",
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "Edit submission" }));
|
||||
expect(screen.getByLabelText("Version override (optional)")).toHaveValue(expectedVersion ?? "");
|
||||
});
|
||||
|
||||
it("keeps admin review separate from ownership and sends the displayed revision", async () => {
|
||||
submissions = [{ ...pending, revision: 7, can_edit: false }];
|
||||
renderSubmissions();
|
||||
|
|
@ -884,6 +1001,7 @@ it.each(["metadata", "upload"])(
|
|||
expect(screen.getByLabelText("Description (Optional)")).toHaveValue("Latest edit");
|
||||
fireEvent.click(screen.getByRole("button", { name: "Save submission" }));
|
||||
await waitFor(() => expect(writes).toHaveLength(2));
|
||||
expect(JSON.parse(String(writes[1].body))).toMatchObject({ expected_revision: 1, description: "Latest edit" });
|
||||
expect(JSON.parse(String(writes[1].body))).toEqual({ expected_revision: 1, version: null });
|
||||
expect(await screen.findByRole("cell", { name: "Latest edit" })).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import { toast } from "@/lib/toast";
|
|||
import { isPendingSkill, type SkillHubSkill, type SkillMutationResponse } from "@/components/claude_code_plugins/types";
|
||||
import { useUrlTab } from "@/hooks/useUrlTab";
|
||||
import SkillSubmissions from "./SkillSubmissions";
|
||||
import { useUserIdentityLookup } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
|
||||
interface ClaudeCodePluginsPanelProps {
|
||||
accessToken: string | null;
|
||||
|
|
@ -48,6 +49,8 @@ function skillPermissions(accessToken: string | null, userRole: string, isViewOn
|
|||
}
|
||||
|
||||
interface CatalogSkillDetailProps {
|
||||
userRole: string;
|
||||
isViewOnly: boolean;
|
||||
skill: SkillHubSkill;
|
||||
accessToken: string | null;
|
||||
queryScope: QueryKey;
|
||||
|
|
@ -58,6 +61,8 @@ interface CatalogSkillDetailProps {
|
|||
}
|
||||
|
||||
function CatalogSkillDetail({
|
||||
userRole,
|
||||
isViewOnly,
|
||||
skill,
|
||||
accessToken,
|
||||
queryScope,
|
||||
|
|
@ -74,6 +79,12 @@ function CatalogSkillDetail({
|
|||
queryFn: () => getSkillHubSkill(accessToken!, skill.name),
|
||||
enabled: Boolean(accessToken),
|
||||
});
|
||||
const displayedSkill = detail.data ?? skill;
|
||||
const users = useUserIdentityLookup([displayedSkill.created_by, displayedSkill.approved_by], {
|
||||
accessToken,
|
||||
userRole,
|
||||
isViewOnly,
|
||||
});
|
||||
return (
|
||||
<>
|
||||
{detail.isError && (
|
||||
|
|
@ -85,7 +96,8 @@ function CatalogSkillDetail({
|
|||
</div>
|
||||
)}
|
||||
<SkillDetail
|
||||
skill={skillHubDetail(detail.data ?? skill)}
|
||||
skill={skillHubDetail(displayedSkill)}
|
||||
users={users}
|
||||
onBack={onBack}
|
||||
accessToken={accessToken}
|
||||
isAdmin={isAdmin}
|
||||
|
|
@ -132,6 +144,10 @@ const SkillsPanelContent: React.FC<ClaudeCodePluginsPanelProps> = ({
|
|||
enabled: Boolean(accessToken),
|
||||
});
|
||||
const pluginsList = plugins.data?.skills ?? [];
|
||||
const users = useUserIdentityLookup(
|
||||
pluginsList.flatMap((skill) => [skill.created_by, skill.approved_by]),
|
||||
{ accessToken, userRole, isViewOnly: readOnly },
|
||||
);
|
||||
const selectedSkill = pluginsList.find((plugin) => plugin.id === selectedSkillId);
|
||||
const refreshSkills = async () => {
|
||||
await Promise.all([
|
||||
|
|
@ -172,6 +188,8 @@ const SkillsPanelContent: React.FC<ClaudeCodePluginsPanelProps> = ({
|
|||
<div className="w-full mx-auto flex-auto overflow-y-auto m-8 p-2">
|
||||
{selectedSkill ? (
|
||||
<CatalogSkillDetail
|
||||
userRole={userRole}
|
||||
isViewOnly={readOnly}
|
||||
skill={selectedSkill}
|
||||
isAdmin={isAdmin}
|
||||
accessToken={accessToken}
|
||||
|
|
@ -212,6 +230,7 @@ const SkillsPanelContent: React.FC<ClaudeCodePluginsPanelProps> = ({
|
|||
</div>
|
||||
)}
|
||||
<PluginTable
|
||||
users={users}
|
||||
pluginsList={pluginsList}
|
||||
isLoading={plugins.isLoading}
|
||||
filtered={filters.active}
|
||||
|
|
@ -242,6 +261,8 @@ const SkillsPanelContent: React.FC<ClaudeCodePluginsPanelProps> = ({
|
|||
<TabsContent value="submissions">
|
||||
{accessToken && (
|
||||
<SkillSubmissions
|
||||
userRole={userRole}
|
||||
isViewOnly={readOnly}
|
||||
accessToken={accessToken}
|
||||
queryScope={queryScope}
|
||||
canReview={isAdmin}
|
||||
|
|
|
|||
|
|
@ -9,8 +9,10 @@ import { DataTable } from "@/components/shared/DataTable";
|
|||
import { SkillHubSkill } from "@/components/claude_code_plugins/types";
|
||||
|
||||
import { getPluginTableColumns } from "./PluginTableColumns";
|
||||
import type { UserIdentityLookup } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
|
||||
interface PluginTableProps {
|
||||
users?: UserIdentityLookup;
|
||||
pluginsList: SkillHubSkill[];
|
||||
sorting: SortingState;
|
||||
onSortingChange: OnChangeFn<SortingState>;
|
||||
|
|
@ -39,6 +41,7 @@ function EmptyState({ filtered }: { filtered: boolean }) {
|
|||
}
|
||||
|
||||
const PluginTable: React.FC<PluginTableProps> = ({
|
||||
users,
|
||||
pluginsList,
|
||||
sorting,
|
||||
onSortingChange,
|
||||
|
|
@ -50,10 +53,10 @@ const PluginTable: React.FC<PluginTableProps> = ({
|
|||
}) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const columns = useMemo(
|
||||
() => getPluginTableColumns({ isAdmin, onPluginClick, onDeleteClick }),
|
||||
[isAdmin, onPluginClick, onDeleteClick],
|
||||
);
|
||||
const columns = useMemo(() => {
|
||||
const dependencies = { isAdmin, onPluginClick, onDeleteClick, users };
|
||||
return getPluginTableColumns(dependencies);
|
||||
}, [isAdmin, onPluginClick, onDeleteClick, users]);
|
||||
|
||||
return (
|
||||
<DataTable
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { getSkillMetadataColumns } from "@/components/claude_code_plugins/SkillMetadataColumns";
|
||||
import type { UserIdentityLookup } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { Copy, MoreHorizontal, Trash2 } from "lucide-react";
|
||||
|
|
@ -65,12 +66,14 @@ function PluginRowActions({ plugin, isAdmin, onDeleteClick }: PluginRowActionsPr
|
|||
}
|
||||
|
||||
interface PluginTableColumnsDeps {
|
||||
users?: UserIdentityLookup;
|
||||
isAdmin: boolean;
|
||||
onPluginClick: (pluginId: string) => void;
|
||||
onDeleteClick: (pluginName: string, displayName: string) => void;
|
||||
}
|
||||
|
||||
export const getPluginTableColumns = ({
|
||||
users,
|
||||
isAdmin,
|
||||
onPluginClick,
|
||||
onDeleteClick,
|
||||
|
|
@ -145,7 +148,7 @@ export const getPluginTableColumns = ({
|
|||
/>
|
||||
),
|
||||
},
|
||||
...getSkillMetadataColumns<SkillHubSkill>(),
|
||||
...getSkillMetadataColumns<SkillHubSkill>(users),
|
||||
{
|
||||
id: "actions",
|
||||
meta: { className: "text-right", headerClassName: "text-right" },
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import { useUrlTableState, type UrlTableStateOptions } from "@/components/shared
|
|||
import SkillScanPanel from "./SkillScanPanel";
|
||||
import { toast } from "@/lib/toast";
|
||||
import AddPluginForm from "./add_plugin_form";
|
||||
import { useUserIdentityLookup, userIdentityLabel } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancel,
|
||||
|
|
@ -28,7 +29,18 @@ import {
|
|||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
|
||||
const METADATA_FIELDS = ["name", "version", "description", "source", "keywords", "domain", "namespace"] as const;
|
||||
const METADATA_FIELDS = [
|
||||
"name",
|
||||
"version",
|
||||
"description",
|
||||
"source",
|
||||
"author",
|
||||
"category",
|
||||
"homepage",
|
||||
"keywords",
|
||||
"domain",
|
||||
"namespace",
|
||||
] as const;
|
||||
|
||||
const displayValue = (value: unknown): string => {
|
||||
if (value === null || value === undefined || value === "") return "";
|
||||
|
|
@ -60,15 +72,23 @@ function SubmissionStatus({ status }: { status: SkillSubmission["status"] }) {
|
|||
);
|
||||
}
|
||||
|
||||
function SubmissionSummary({ submission }: { submission: SkillSubmission }) {
|
||||
function SubmissionSummary({
|
||||
submission,
|
||||
scope,
|
||||
}: {
|
||||
submission: SkillSubmission;
|
||||
scope: Pick<SubmissionReviewProps, "accessToken" | "userRole" | "isViewOnly">;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const users = useUserIdentityLookup([submission.submitted_by, submission.reviewed_by], scope);
|
||||
const reviewed = submission.status === "approved" || submission.status === "rejected";
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-wrap items-center gap-3 text-sm">
|
||||
<SubmissionStatus status={submission.status} />
|
||||
<span>{t(`skills.submissions.operation.${submission.operation}`)}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{t("skills.submissions.submittedBy", { name: submission.submitted_by })}
|
||||
<span className="text-muted-foreground" title={submission.submitted_by}>
|
||||
{t("skills.submissions.submittedBy", { name: userIdentityLabel(submission.submitted_by, users) })}
|
||||
</span>
|
||||
</div>
|
||||
{submission.status === "pending_review" && (
|
||||
|
|
@ -79,10 +99,10 @@ function SubmissionSummary({ submission }: { submission: SkillSubmission }) {
|
|||
{t("skills.submissions.rejectionReason", { reason: submission.rejection_reason })}
|
||||
</p>
|
||||
)}
|
||||
{submission.reviewed_at && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("skills.submissions.reviewedBy", {
|
||||
name: submission.reviewed_by,
|
||||
{submission.reviewed_at && reviewed && (
|
||||
<p className="text-sm text-muted-foreground" title={submission.reviewed_by ?? undefined}>
|
||||
{t(submission.status === "approved" ? "skills.submissions.approvedBy" : "skills.submissions.rejectedBy", {
|
||||
name: userIdentityLabel(submission.reviewed_by, users),
|
||||
date: new Date(submission.reviewed_at).toLocaleString(),
|
||||
})}
|
||||
</p>
|
||||
|
|
@ -145,7 +165,7 @@ function SubmissionComparison({
|
|||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{submission.has_archive && submission.proposal.agent_skill && (
|
||||
{submission.has_archive && (
|
||||
<Button variant="outline" onClick={onDownload} disabled={downloading}>
|
||||
{t(downloading ? "skills.submissions.downloading" : "skills.submissions.download")}
|
||||
</Button>
|
||||
|
|
@ -155,6 +175,8 @@ function SubmissionComparison({
|
|||
}
|
||||
|
||||
interface SubmissionReviewProps {
|
||||
userRole: string;
|
||||
isViewOnly: boolean;
|
||||
id: string;
|
||||
accessToken: string;
|
||||
queryScope: QueryKey;
|
||||
|
|
@ -165,6 +187,8 @@ interface SubmissionReviewProps {
|
|||
}
|
||||
|
||||
function SubmissionReview({
|
||||
userRole,
|
||||
isViewOnly,
|
||||
id,
|
||||
accessToken,
|
||||
queryScope,
|
||||
|
|
@ -257,7 +281,7 @@ function SubmissionReview({
|
|||
)}
|
||||
{submission && (
|
||||
<>
|
||||
<SubmissionSummary submission={submission} />
|
||||
<SubmissionSummary submission={submission} scope={{ accessToken, userRole, isViewOnly }} />
|
||||
<SubmissionComparison
|
||||
submission={submission}
|
||||
current={current}
|
||||
|
|
@ -349,6 +373,8 @@ function SubmissionReview({
|
|||
}
|
||||
|
||||
interface SkillSubmissionsProps {
|
||||
userRole: string;
|
||||
isViewOnly: boolean;
|
||||
accessToken: string;
|
||||
queryScope: QueryKey;
|
||||
canReview: boolean;
|
||||
|
|
@ -358,6 +384,8 @@ interface SkillSubmissionsProps {
|
|||
}
|
||||
|
||||
export default function SkillSubmissions({
|
||||
userRole,
|
||||
isViewOnly,
|
||||
accessToken,
|
||||
queryScope,
|
||||
canReview,
|
||||
|
|
@ -373,6 +401,10 @@ export default function SkillSubmissions({
|
|||
queryKey: [...queryScope, "submissions", pageIndex, pageSize],
|
||||
queryFn: () => listSkillSubmissions(accessToken, { limit: pageSize, offset: pageIndex * pageSize }),
|
||||
});
|
||||
const users = useUserIdentityLookup(
|
||||
submissions.data?.submissions.flatMap((submission) => [submission.submitted_by, submission.reviewed_by]) ?? [],
|
||||
{ accessToken, userRole, isViewOnly },
|
||||
);
|
||||
const isEmpty = submissions.isSuccess && submissions.data.submissions.length === 0;
|
||||
const changePage = (page: number) => {
|
||||
setSelectedId(null);
|
||||
|
|
@ -409,8 +441,8 @@ export default function SkillSubmissions({
|
|||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{submission.proposal.description}</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t("skills.submissions.submittedBy", { name: submission.submitted_by })} ·{" "}
|
||||
<p className="text-xs text-muted-foreground" title={submission.submitted_by}>
|
||||
{t("skills.submissions.submittedBy", { name: userIdentityLabel(submission.submitted_by, users) })} ·{" "}
|
||||
{new Date(submission.created_at).toLocaleString()}
|
||||
</p>
|
||||
{submission.rejection_reason && (
|
||||
|
|
@ -448,6 +480,8 @@ export default function SkillSubmissions({
|
|||
</div>
|
||||
{selectedId && (
|
||||
<SubmissionReview
|
||||
userRole={userRole}
|
||||
isViewOnly={isViewOnly}
|
||||
key={selectedId}
|
||||
id={selectedId}
|
||||
accessToken={accessToken}
|
||||
|
|
|
|||
|
|
@ -16,48 +16,136 @@ const chooseFile = (selected = file) =>
|
|||
fireEvent.change(screen.getByLabelText("Skill ZIP file"), { target: { files: [selected] } });
|
||||
const change = (label: string, value: string) => fireEvent.change(screen.getByLabelText(label), { target: { value } });
|
||||
const submit = () => fireEvent.click(screen.getByRole("button", { name: "Register skill" }));
|
||||
const openImport = () => {
|
||||
const openImport = (url = "https://github.com/example/skills") => {
|
||||
renderWithProviders(<AddPluginForm {...props} />);
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Import URL" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Add from URL" }));
|
||||
change("Source URL", url);
|
||||
if (!url.startsWith("https://skills.sh/")) {
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Store a copy in LiteLLM" }));
|
||||
}
|
||||
};
|
||||
|
||||
describe("AddPluginForm", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("starts with a portable ZIP and offers host-agnostic imports without guessing metadata", () => {
|
||||
it("offers ZIP or URL, with managed copies available for supported URL hosts", () => {
|
||||
renderWithProviders(<AddPluginForm {...props} />);
|
||||
expect(screen.getByRole("radio", { name: "Upload ZIP" })).toBeChecked();
|
||||
expect(screen.getByText(/frontmatter supplies the skill name and description/)).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Import URL" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Add from URL" }));
|
||||
expect(screen.getByLabelText("Source URL")).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("Path (optional)")).toBeEnabled();
|
||||
expect(screen.queryByLabelText("Skill Name")).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("radio", { name: "Use the external source" })).toBeChecked();
|
||||
expect(screen.getByRole("radio", { name: "Store a copy in LiteLLM" })).toHaveAttribute("aria-disabled", "true");
|
||||
change("Source URL", " HTTPS://www.GitHub.com/example/skills ");
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Store a copy in LiteLLM" }));
|
||||
expect(screen.getByLabelText("Registry name (optional)")).toHaveValue("");
|
||||
expect(screen.getByRole("radio", { name: "Add from URL" })).toBeChecked();
|
||||
change("Skill selector (optional)", "previous-draft");
|
||||
change("Source URL", " www.Skills.sh/example/skills/review ");
|
||||
expect(screen.getByLabelText("Skill selector (optional)")).toBeDisabled();
|
||||
expect(screen.getByLabelText("Skill selector (optional)")).toHaveValue("review");
|
||||
expect(screen.getByRole("radio", { name: "Use the external source" })).toHaveAttribute("aria-disabled", "true");
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Upload ZIP" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Add from URL" }));
|
||||
expect(screen.getByRole("radio", { name: "Store a copy in LiteLLM" })).toBeChecked();
|
||||
change("Source URL", "GitHub.com/example/skills");
|
||||
expect(screen.getByLabelText("Skill selector (optional)")).toBeEnabled();
|
||||
expect(screen.getByLabelText("Skill selector (optional)")).toHaveValue("previous-draft");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://github.com/anthropics/claude-code",
|
||||
"https://github.com/anthropics/claude-code/tree/main/plugins/my-skill",
|
||||
"https://gitlab.com/group/repo",
|
||||
"https://skills-bucket.s3.us-east-1.amazonaws.com/plugins/s3-skill-1.0.0.zip",
|
||||
])("submits the original source URL %s", async (url) => {
|
||||
it.each(["https://github.com/anthropics/claude-code", "https://skills.sh/example/skills/review"])(
|
||||
"submits the canonical source URL %s",
|
||||
async (url) => {
|
||||
openImport();
|
||||
change(
|
||||
"Source URL",
|
||||
` ${url.replace("https://", "HTTPS://www.").replace(".com", ".COM").replace(".sh", ".SH")} `,
|
||||
);
|
||||
submit();
|
||||
await waitFor(() => expect(importSkill).toHaveBeenCalledWith("sk-test", { url }));
|
||||
expect(props.onSuccess).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["tree/release/v2/skills/review", "blob/release/v2/skills/review/SKILL.md"])(
|
||||
"imports one canonical selection from %s after changing sources",
|
||||
async (location) => {
|
||||
openImport();
|
||||
change("Skill selector (optional)", "review");
|
||||
change("Git ref", "release/v2");
|
||||
const url = "https://github.com/example/other-skills";
|
||||
change("Source URL", `${url}/tree/release/v2`);
|
||||
expect(screen.getByLabelText("Path (optional)")).toBeEnabled();
|
||||
change("Path (optional)", "previous-draft");
|
||||
change("Version (Optional)", "3.0.0");
|
||||
change("Source URL", `${url}/${location}`);
|
||||
expect(screen.getByLabelText("Path (optional)")).toBeDisabled();
|
||||
expect(screen.getByLabelText("Path (optional)")).toHaveValue("skills/review");
|
||||
expect(screen.getByLabelText("Skill selector (optional)")).toHaveAccessibleDescription(/both must match/);
|
||||
submit();
|
||||
const expected = { url, skill: "review", ref: "release/v2", path: "skills/review", version: "3.0.0" };
|
||||
await waitFor(() => expect(importSkill).toHaveBeenCalledWith("sk-test", expected));
|
||||
},
|
||||
);
|
||||
|
||||
it("switches unsupported import hosts to references and preserves source drafts", async () => {
|
||||
openImport();
|
||||
change("Source URL", url);
|
||||
change("Registry name (optional)", "review");
|
||||
const repository = "https://gitlab.com/team/repo";
|
||||
const archive = "https://artifacts.example.test/skill.zip";
|
||||
change("Source URL", repository);
|
||||
expect(screen.getByRole("radio", { name: "Use the external source" })).toBeChecked();
|
||||
expect(screen.getByRole("radio", { name: "Store a copy in LiteLLM" })).toHaveAttribute("aria-disabled", "true");
|
||||
expect(screen.queryByLabelText("Skill selector (optional)")).not.toBeInTheDocument();
|
||||
change("Path (optional)", "plugins/review");
|
||||
change("Source URL", archive);
|
||||
expect(screen.getByLabelText("Path (optional)")).toBeDisabled();
|
||||
expect(screen.getByLabelText("Path (optional)")).toHaveValue("");
|
||||
expect(screen.queryByLabelText("Git ref")).not.toBeInTheDocument();
|
||||
change("Source URL", repository);
|
||||
expect(screen.getByLabelText("Path (optional)")).toBeEnabled();
|
||||
expect(screen.getByLabelText("Path (optional)")).toHaveValue("plugins/review");
|
||||
change("Git ref", "release/v2");
|
||||
change("Source URL", archive);
|
||||
submit();
|
||||
await waitFor(() => expect(importSkill).toHaveBeenCalledWith("sk-test", { url }));
|
||||
expect(props.onSuccess).toHaveBeenCalledOnce();
|
||||
await waitFor(() =>
|
||||
expect(importSkill).toHaveBeenCalledWith("sk-test", {
|
||||
name: "review",
|
||||
source: { source: "archive", url: archive },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps explicit selector, ref and path choices when a source URL changes", async () => {
|
||||
openImport();
|
||||
change("Source URL", "https://gitlab.com/group/repo");
|
||||
change("Skill selector (optional)", "review");
|
||||
change("Git ref (optional)", "release/v2");
|
||||
change("Path (optional)", "skills/review");
|
||||
change("Version (Optional)", "3.0.0");
|
||||
const url = "https://github.com/example/skills/tree/release/v2";
|
||||
change("Source URL", url);
|
||||
it("shows the GitLab browser directory and sends its clone URL, full ref and path", async () => {
|
||||
renderWithProviders(<AddPluginForm {...props} />);
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Add from URL" }));
|
||||
change("Registry name", "review");
|
||||
change("Source URL", "https://gitlab.com/team/repo");
|
||||
change("Path (optional)", "previous-draft");
|
||||
change("Source URL", "https://gitlab.com/team/subgroup/repo/-/blob/release/v2/plugins/review/SKILL.md");
|
||||
expect(screen.getByLabelText("Git ref")).not.toHaveAttribute("placeholder");
|
||||
expect(screen.getByLabelText("Git ref")).toHaveAccessibleDescription(/Enter the full Git ref from this URL/);
|
||||
expect(screen.getByLabelText("Path (optional)")).toBeDisabled();
|
||||
expect(screen.getByLabelText("Path (optional)")).toHaveValue("");
|
||||
expect(screen.queryByText(/^Detected:/)).not.toBeInTheDocument();
|
||||
submit();
|
||||
const expected = { url, skill: "review", ref: "release/v2", path: "skills/review", version: "3.0.0" };
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Enter the full Git ref from this URL");
|
||||
expect(importSkill).not.toHaveBeenCalled();
|
||||
change("Git ref", "release/v2");
|
||||
expect(screen.getByLabelText("Path (optional)")).toBeDisabled();
|
||||
expect(screen.getByLabelText("Path (optional)")).toHaveValue("plugins/review");
|
||||
expect(screen.getByText(/^Detected:/)).toHaveTextContent("plugins/review (release/v2)");
|
||||
submit();
|
||||
const expected = {
|
||||
name: "review",
|
||||
source: {
|
||||
source: "git-subdir",
|
||||
url: "https://gitlab.com/team/subgroup/repo",
|
||||
ref: "release/v2",
|
||||
path: "plugins/review",
|
||||
},
|
||||
};
|
||||
await waitFor(() => expect(importSkill).toHaveBeenCalledWith("sk-test", expected));
|
||||
});
|
||||
|
||||
|
|
@ -88,7 +176,7 @@ describe("AddPluginForm", () => {
|
|||
expect(props.onSuccess).not.toHaveBeenCalled();
|
||||
submit();
|
||||
await waitFor(() => expect(props.onSuccess).toHaveBeenCalledOnce());
|
||||
expect(uploadSkill).toHaveBeenLastCalledWith("sk-test", file, "2.0.0", undefined);
|
||||
expect(uploadSkill).toHaveBeenLastCalledWith("sk-test", file, "2.0.0", { skill: undefined, metadata: undefined });
|
||||
expect(importSkill).not.toHaveBeenCalled();
|
||||
expect(props.onClose).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
|
@ -107,15 +195,18 @@ describe("AddPluginForm", () => {
|
|||
it("clears a file on mode change, allows reselection and restores source validation", async () => {
|
||||
renderWithProviders(<AddPluginForm {...props} />);
|
||||
chooseFile();
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Import URL" }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Add from URL" }));
|
||||
change("Registry name", "review");
|
||||
submit();
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Please enter a repository or zip archive URL");
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Please enter a valid repository or zip archive URL");
|
||||
fireEvent.click(screen.getByRole("radio", { name: "Upload ZIP" }));
|
||||
submit();
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent("Please choose a .zip file");
|
||||
chooseFile();
|
||||
submit();
|
||||
await waitFor(() => expect(uploadSkill).toHaveBeenCalledWith("sk-test", file, "", undefined));
|
||||
await waitFor(() =>
|
||||
expect(uploadSkill).toHaveBeenCalledWith("sk-test", file, "", { skill: undefined, metadata: { name: "review" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks an invalid version and cancels without publishing", async () => {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { useState } from "react";
|
||||
import type { UseFormReturn } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
import i18n from "@/i18n/i18n";
|
||||
import { toast } from "@/lib/toast";
|
||||
import { ApiError } from "@/lib/http/client";
|
||||
import {
|
||||
|
|
@ -19,17 +18,43 @@ import { Input } from "@/components/ui/input";
|
|||
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { useZodForm } from "@/lib/forms/useZodForm";
|
||||
import { isValidSemanticVersion } from "@/components/claude_code_plugins/helpers";
|
||||
import {
|
||||
availableSkillUrlModes,
|
||||
parseSkillImportSource,
|
||||
parseSkillSource,
|
||||
requiresBrowserRefConfirmation,
|
||||
} from "@/components/claude_code_plugins/helpers";
|
||||
import {
|
||||
isPendingSkill,
|
||||
type SkillHubSkill,
|
||||
type SkillMutationResponse,
|
||||
type SkillSubmission,
|
||||
} from "@/components/claude_code_plugins/types";
|
||||
import { buildSkillImport, buildSkillMetadata, skillFormValues } from "@/components/claude_code_plugins/skillForm";
|
||||
import {
|
||||
buildSkillImport,
|
||||
buildSkillMetadata,
|
||||
buildSkillRegistration,
|
||||
buildSkillUpdate,
|
||||
buildSkillUploadMetadata,
|
||||
skillFormSchema,
|
||||
skillFormValues,
|
||||
type SkillFormValues,
|
||||
} from "@/components/claude_code_plugins/skillForm";
|
||||
|
||||
const EDIT_SKILL_SOURCES = ["metadata", "upload"] as const;
|
||||
const NEW_SKILL_SOURCES = ["upload", "import"] as const;
|
||||
const EDIT_SKILL_SOURCES = ["metadata", "upload", "replace"] as const;
|
||||
const SUBMISSION_SOURCES = ["metadata", "upload"] as const;
|
||||
const NEW_SKILL_SOURCES = ["upload", "register"] as const;
|
||||
const URL_SKILL_SOURCES = ["register", "import"] as const;
|
||||
|
||||
const ADVANCED_FIELDS = [
|
||||
"authorName",
|
||||
"authorEmail",
|
||||
"category",
|
||||
"domain",
|
||||
"namespace",
|
||||
"keywords",
|
||||
"homepage",
|
||||
] as const;
|
||||
|
||||
interface AddPluginFormProps {
|
||||
visible: boolean;
|
||||
|
|
@ -41,43 +66,6 @@ interface AddPluginFormProps {
|
|||
requiresApproval?: boolean;
|
||||
}
|
||||
|
||||
const skillShape = {
|
||||
mode: z.enum(["upload", "import", "metadata"]),
|
||||
archiveFile: z
|
||||
.file()
|
||||
.refine((file) => file.name.toLowerCase().endsWith(".zip"), {
|
||||
error: () => i18n.t("skills.addForm.errors.zipRequired"),
|
||||
})
|
||||
.max(10 * 1024 * 1024, { error: () => i18n.t("skills.addForm.errors.zipTooLarge") })
|
||||
.nullable(),
|
||||
url: z.string(),
|
||||
skill: z.string(),
|
||||
ref: z.string(),
|
||||
path: z.string(),
|
||||
domain: z.string(),
|
||||
namespace: z.string(),
|
||||
description: z.string(),
|
||||
keywords: z.string(),
|
||||
version: z.string().refine((value) => !value.trim() || isValidSemanticVersion(value.trim()), {
|
||||
error: () => i18n.t("skills.addForm.toasts.invalidVersion"),
|
||||
}),
|
||||
};
|
||||
const skillSchema = z.object(skillShape).superRefine((values, context) => {
|
||||
if (values.mode === "upload" && !values.archiveFile) {
|
||||
context.addIssue({ code: "custom", path: ["archiveFile"], message: i18n.t("skills.addForm.errors.zipRequired") });
|
||||
}
|
||||
if (values.mode === "import" && !values.url.trim()) {
|
||||
context.addIssue({ code: "custom", path: ["url"], message: i18n.t("skills.addForm.errors.urlRequired") });
|
||||
}
|
||||
if (values.mode === "metadata" && values.description.length > 1024) {
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["description"],
|
||||
message: i18n.t("skills.addForm.errors.descriptionTooLong"),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function formLabels(editing: boolean, submission: boolean, requiresApproval: boolean) {
|
||||
if (submission) return { title: "skills.submissions.edit", submit: "skills.submissions.save" } as const;
|
||||
const directSubmit = editing ? "skills.addForm.save" : "skills.addForm.submit";
|
||||
|
|
@ -87,6 +75,221 @@ function formLabels(editing: boolean, submission: boolean, requiresApproval: boo
|
|||
} as const;
|
||||
}
|
||||
|
||||
interface SkillFormFieldsProps {
|
||||
form: UseFormReturn<SkillFormValues>;
|
||||
skill?: SkillHubSkill;
|
||||
}
|
||||
|
||||
interface SkillSourceSelectorsProps {
|
||||
form: UseFormReturn<SkillFormValues>;
|
||||
mode: "register" | "import" | "replace";
|
||||
}
|
||||
|
||||
function SkillSourceSelectors({ form, mode }: SkillSourceSelectorsProps) {
|
||||
const { t } = useTranslation();
|
||||
const sourceUrl = form.watch("url");
|
||||
const sourcePath = form.watch("path");
|
||||
const sourceRef = form.watch("ref");
|
||||
const source =
|
||||
mode === "import"
|
||||
? parseSkillImportSource(sourceUrl, sourcePath, sourceRef)
|
||||
: { preview: parseSkillSource(sourceUrl, sourcePath, sourceRef), skillFromUrl: undefined };
|
||||
const sourcePreview = source?.preview;
|
||||
const needsRef = requiresBrowserRefConfirmation(sourcePreview, sourceRef);
|
||||
const displayPreview = needsRef ? null : sourcePreview;
|
||||
const isArchive = sourcePreview?.parsed.source === "archive";
|
||||
const archivePathLock = isArchive ? "archive" : undefined;
|
||||
const pathLock = sourcePreview?.pathFromUrl ? "gitSubdir" : archivePathLock;
|
||||
const referenceFields = isArchive ? (["path"] as const) : (["ref", "path"] as const);
|
||||
const sourceFields = mode === "import" ? (["skill", "ref", "path"] as const) : referenceFields;
|
||||
const lockedValues: Partial<Record<keyof SkillFormValues, string>> = {
|
||||
...(pathLock ? { path: displayPreview?.parsed.path ?? "" } : {}),
|
||||
...(source?.skillFromUrl ? { skill: source.skillFromUrl } : {}),
|
||||
};
|
||||
const sourceDescriptions: Partial<Record<keyof SkillFormValues, string>> = {
|
||||
skill: t(source?.skillFromUrl ? "skills.addForm.hints.skillFromUrl" : "skills.addForm.hints.skill"),
|
||||
path: t(pathLock ? `skills.addForm.subPathLock.${pathLock}` : "skills.addForm.hints.subPath"),
|
||||
ref: t(needsRef ? "skills.addForm.errors.browserRefRequired" : "skills.addForm.hints.ref"),
|
||||
};
|
||||
return (
|
||||
<>
|
||||
{sourceFields.map((name) => (
|
||||
<FormField
|
||||
key={name}
|
||||
control={form.control}
|
||||
name={name}
|
||||
label={t(`skills.addForm.neutralLabels.${name}`)}
|
||||
description={sourceDescriptions[name]}
|
||||
>
|
||||
{(field) => (
|
||||
<Input
|
||||
{...field}
|
||||
disabled={lockedValues[name] !== undefined}
|
||||
value={lockedValues[name] ?? field.value}
|
||||
placeholder={name === "ref" ? displayPreview?.parsed.ref ?? displayPreview?.parsed.sha : undefined}
|
||||
/>
|
||||
)}
|
||||
</FormField>
|
||||
))}
|
||||
<p className="text-sm text-muted-foreground">{t(`skills.addForm.${mode}Hint`)}</p>
|
||||
{displayPreview && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t("skills.addForm.detected", { source: displayPreview.label })}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SkillSourceFields({
|
||||
form,
|
||||
skill,
|
||||
changeMode,
|
||||
}: SkillFormFieldsProps & { changeMode: (value: string) => void }) {
|
||||
const { t } = useTranslation();
|
||||
const mode = form.watch("mode");
|
||||
const sourceUrl = form.watch("url");
|
||||
const urlModes = availableSkillUrlModes(sourceUrl);
|
||||
const changeSourceMode = (url: string) => {
|
||||
if (skill) return;
|
||||
const available = availableSkillUrlModes(url);
|
||||
if (available.length === 1 && available[0] !== mode) changeMode(available[0]);
|
||||
};
|
||||
if (mode === "metadata") return null;
|
||||
if (mode === "upload") {
|
||||
return (
|
||||
<FormField
|
||||
key="archiveFile"
|
||||
control={form.control}
|
||||
name="archiveFile"
|
||||
label={t("skills.addForm.labels.archive")}
|
||||
description={t(skill ? "skills.addForm.replacementHint" : "skills.addForm.uploadHint")}
|
||||
>
|
||||
{({ value, onChange, ...field }) => (
|
||||
<Input
|
||||
{...field}
|
||||
type="file"
|
||||
accept=".zip,application/zip"
|
||||
onChange={(event) => onChange(event.target.files?.[0] ?? null)}
|
||||
/>
|
||||
)}
|
||||
</FormField>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<FormField key="url" control={form.control} name="url" label={t("skills.addForm.neutralLabels.url")}>
|
||||
{(field) => (
|
||||
<Input
|
||||
{...field}
|
||||
onChange={(event) => {
|
||||
field.onChange(event);
|
||||
changeSourceMode(event.target.value);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</FormField>
|
||||
{!skill && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="mode"
|
||||
label={t("skills.addForm.urlStorage")}
|
||||
description={t("skills.addForm.urlStorageHint")}
|
||||
>
|
||||
{({ value }) => (
|
||||
<RadioGroup
|
||||
value={value}
|
||||
onValueChange={changeMode}
|
||||
aria-label={t("skills.addForm.urlStorage")}
|
||||
className="gap-3"
|
||||
>
|
||||
{URL_SKILL_SOURCES.map((option) => (
|
||||
<label key={option} className="flex items-center gap-2 text-sm has-[[aria-disabled=true]]:opacity-50">
|
||||
<RadioGroupItem value={option} disabled={!urlModes.some((mode) => mode === option)} />
|
||||
{t(`skills.addForm.urlModes.${option}`)}
|
||||
</label>
|
||||
))}
|
||||
</RadioGroup>
|
||||
)}
|
||||
</FormField>
|
||||
)}
|
||||
<SkillSourceSelectors form={form} mode={mode} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SkillMetadataFields({ form, skill }: SkillFormFieldsProps) {
|
||||
const { t } = useTranslation();
|
||||
const mode = form.watch("mode");
|
||||
const sourceUrl = form.watch("url");
|
||||
const sourcePath = form.watch("path");
|
||||
const sourceRef = form.watch("ref");
|
||||
if (skill && mode === "upload") return null;
|
||||
const referenceMode = mode === "register" || mode === "replace";
|
||||
const sourcePreview = referenceMode ? parseSkillSource(sourceUrl, sourcePath, sourceRef) : null;
|
||||
const hasAdvancedErrors =
|
||||
ADVANCED_FIELDS.some((field) => form.formState.errors[field]) || Boolean(form.formState.errors.sha256);
|
||||
return (
|
||||
<>
|
||||
{!skill && (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
label={t(mode === "register" ? "skills.addForm.registryName" : "skills.addForm.optionalRegistryName")}
|
||||
description={t("skills.addForm.registryNameHint")}
|
||||
>
|
||||
{(field) => <Input {...field} />}
|
||||
</FormField>
|
||||
)}
|
||||
<FormField control={form.control} name="description" label={t("skills.addForm.labels.description")}>
|
||||
{(field) => <Textarea {...field} />}
|
||||
</FormField>
|
||||
<details open={hasAdvancedErrors || undefined} className="space-y-4">
|
||||
<summary className="cursor-pointer text-sm font-medium">{t("skills.addForm.advancedMetadata")}</summary>
|
||||
<p className="text-sm text-muted-foreground">{t("skills.addForm.authorOverrideHint")}</p>
|
||||
<FieldGroup>
|
||||
{ADVANCED_FIELDS.map((name) => (
|
||||
<FormField
|
||||
key={name}
|
||||
control={form.control}
|
||||
name={name}
|
||||
label={t(
|
||||
name === "domain" || name === "namespace" || name === "keywords"
|
||||
? `skills.addForm.neutralLabels.${name}`
|
||||
: `skills.addForm.labels.${name}`,
|
||||
)}
|
||||
>
|
||||
{(field) => <Input {...field} />}
|
||||
</FormField>
|
||||
))}
|
||||
{sourcePreview?.parsed.source === "archive" && (
|
||||
<FormField control={form.control} name="sha256" label={t("skills.addForm.labels.sha256")}>
|
||||
{(field) => <Input {...field} />}
|
||||
</FormField>
|
||||
)}
|
||||
</FieldGroup>
|
||||
</details>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SkillVersionField({ form, skill, submission }: SkillFormFieldsProps & Pick<AddPluginFormProps, "submission">) {
|
||||
const { t } = useTranslation();
|
||||
const version = submission ? submission.publishedVersion : skill?.version;
|
||||
return (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="version"
|
||||
label={t(skill ? "skills.addForm.versionOverride" : "skills.addForm.labels.version")}
|
||||
description={
|
||||
skill ? t("skills.addForm.versionContext", { version: version ?? t("skills.submissions.notSet") }) : undefined
|
||||
}
|
||||
>
|
||||
{(field) => <Input {...field} placeholder={skill ? t("skills.addForm.automaticVersion") : "1.0.0"} />}
|
||||
</FormField>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AddPluginForm({
|
||||
visible,
|
||||
onClose,
|
||||
|
|
@ -97,17 +300,16 @@ export default function AddPluginForm({
|
|||
requiresApproval = false,
|
||||
}: AddPluginFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const form = useZodForm(skillSchema, {
|
||||
const form = useZodForm(skillFormSchema(skill), {
|
||||
defaultValues: {
|
||||
...skillFormValues(skill),
|
||||
...(submission ? { version: submission.value.proposal.version ?? "" } : {}),
|
||||
},
|
||||
});
|
||||
const mode = form.watch("mode");
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
const conflictedSubmission = error instanceof ApiError && error.status === 409 ? submission : undefined;
|
||||
const isSubmitting = form.formState.isSubmitting;
|
||||
const submit = async (values: z.infer<typeof skillSchema>) => {
|
||||
const submit = async (values: SkillFormValues) => {
|
||||
if (!accessToken) return;
|
||||
setError(null);
|
||||
try {
|
||||
|
|
@ -127,12 +329,22 @@ export default function AddPluginForm({
|
|||
}
|
||||
const write = () => {
|
||||
if (values.mode === "upload" && values.archiveFile) {
|
||||
return uploadSkillHubSkill(accessToken, values.archiveFile, values.version, skill);
|
||||
return uploadSkillHubSkill(accessToken, values.archiveFile, values.version, {
|
||||
skill,
|
||||
metadata: skill ? undefined : buildSkillUploadMetadata(values),
|
||||
});
|
||||
}
|
||||
if (skill) return updateSkillHubSkill(accessToken, skill.name, buildSkillMetadata(values, skill));
|
||||
return importSkillHubSkill(accessToken, buildSkillImport(values));
|
||||
if (skill) return updateSkillHubSkill(accessToken, skill.name, buildSkillUpdate(values, skill));
|
||||
if (values.mode === "register") {
|
||||
const registration = buildSkillRegistration(values);
|
||||
if (!registration) return;
|
||||
return importSkillHubSkill(accessToken, registration);
|
||||
}
|
||||
const imported = buildSkillImport(values);
|
||||
if (imported) return importSkillHubSkill(accessToken, imported);
|
||||
};
|
||||
const response = await write();
|
||||
if (!response) return;
|
||||
const publishedMessage = skill ? "skills.addForm.toasts.updated" : "skills.addForm.toasts.registered";
|
||||
toast.success(t(isPendingSkill(response) ? "skills.addForm.toasts.submitted" : publishedMessage));
|
||||
onSuccess?.(response);
|
||||
|
|
@ -142,15 +354,16 @@ export default function AddPluginForm({
|
|||
}
|
||||
};
|
||||
const changeMode = (value: string) => {
|
||||
if (value !== "upload" && value !== "import" && value !== "metadata") return;
|
||||
form.setValue("mode", value);
|
||||
const nextMode = [...EDIT_SKILL_SOURCES, ...URL_SKILL_SOURCES].find((option) => option === value);
|
||||
if (!nextMode) return;
|
||||
form.setValue("mode", nextMode === "register" ? availableSkillUrlModes(form.getValues("url"))[0] : nextMode);
|
||||
form.setValue("archiveFile", null);
|
||||
form.clearErrors();
|
||||
setError(null);
|
||||
};
|
||||
const labels = formLabels(Boolean(skill), Boolean(submission), requiresApproval);
|
||||
const fields =
|
||||
mode === "import" ? (["url", "skill", "ref", "path"] as const) : (["domain", "namespace", "keywords"] as const);
|
||||
const editSources = submission ? SUBMISSION_SOURCES : EDIT_SKILL_SOURCES;
|
||||
const sources = skill ? editSources : NEW_SKILL_SOURCES;
|
||||
return (
|
||||
<Dialog open={visible} onOpenChange={(open) => !open && !isSubmitting && onClose()}>
|
||||
<DialogContent className="max-h-[90dvh] overflow-y-auto sm:max-w-xl">
|
||||
|
|
@ -163,8 +376,13 @@ export default function AddPluginForm({
|
|||
<fieldset disabled={isSubmitting} className="space-y-6">
|
||||
<FormField control={form.control} name="mode" label={t("skills.addForm.labels.source")}>
|
||||
{({ value }) => (
|
||||
<RadioGroup value={value} onValueChange={changeMode} className="flex gap-5">
|
||||
{(skill ? EDIT_SKILL_SOURCES : NEW_SKILL_SOURCES).map((option) => (
|
||||
<RadioGroup
|
||||
value={value === "import" ? "register" : value}
|
||||
onValueChange={changeMode}
|
||||
aria-label={t("skills.addForm.labels.source")}
|
||||
className="flex flex-wrap gap-5"
|
||||
>
|
||||
{sources.map((option) => (
|
||||
<label key={option} className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem value={option} />
|
||||
{t(`skills.addForm.modes.${option}`)}
|
||||
|
|
@ -174,59 +392,9 @@ export default function AddPluginForm({
|
|||
)}
|
||||
</FormField>
|
||||
<FieldGroup>
|
||||
{mode === "upload" ? (
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="archiveFile"
|
||||
label={t("skills.addForm.labels.archive")}
|
||||
description={t(skill ? "skills.addForm.replacementHint" : "skills.addForm.uploadHint")}
|
||||
>
|
||||
{({ value, onChange, ...field }) => (
|
||||
<Input
|
||||
{...field}
|
||||
type="file"
|
||||
accept=".zip,application/zip"
|
||||
onChange={(event) => onChange(event.target.files?.[0] ?? null)}
|
||||
/>
|
||||
)}
|
||||
</FormField>
|
||||
) : (
|
||||
<>
|
||||
{mode === "metadata" && (
|
||||
<FormField control={form.control} name="description" label={t("skills.addForm.labels.description")}>
|
||||
{(field) => <Textarea {...field} maxLength={1024} />}
|
||||
</FormField>
|
||||
)}
|
||||
{fields.map((name) => (
|
||||
<FormField
|
||||
key={name}
|
||||
control={form.control}
|
||||
name={name}
|
||||
label={t(`skills.addForm.neutralLabels.${name}`)}
|
||||
>
|
||||
{(field) => <Input {...field} />}
|
||||
</FormField>
|
||||
))}
|
||||
{mode === "import" && (
|
||||
<p className="text-sm text-muted-foreground">{t("skills.addForm.importHint")}</p>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="version"
|
||||
label={t(skill ? "skills.addForm.versionOverride" : "skills.addForm.labels.version")}
|
||||
description={
|
||||
skill
|
||||
? t("skills.addForm.versionContext", {
|
||||
version:
|
||||
(submission ? submission.publishedVersion : skill.version) ?? t("skills.submissions.notSet"),
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{(field) => <Input {...field} placeholder={skill ? t("skills.addForm.automaticVersion") : "1.0.0"} />}
|
||||
</FormField>
|
||||
<SkillSourceFields form={form} skill={skill} changeMode={changeMode} />
|
||||
<SkillMetadataFields form={form} skill={skill} />
|
||||
<SkillVersionField form={form} skill={skill} submission={submission} />
|
||||
</FieldGroup>
|
||||
</fieldset>
|
||||
{error && (
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { screen, waitFor } from "@testing-library/react";
|
||||
import { screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderWithProviders } from "@/../tests/test-utils";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderWithProviders, testQueryClient } from "@/../tests/test-utils";
|
||||
import type { Plugin } from "@/components/claude_code_plugins/types";
|
||||
import SkillHubDashboard from "./SkillHubDashboard";
|
||||
|
||||
|
|
@ -18,6 +18,50 @@ const skills: Plugin[] = [
|
|||
},
|
||||
];
|
||||
|
||||
beforeEach(() => testQueryClient.clear());
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("shows creator email in the authenticated hub and keeps directory data off the public view", async () => {
|
||||
const creator = { user_id: "creator-uuid", user_email: "creator@example.test", user_alias: "Creator Name" };
|
||||
const fetchMock = vi.fn<typeof fetch>(async (input) => {
|
||||
const url = new URL(input instanceof Request ? input.url : String(input), "http://localhost");
|
||||
if (url.pathname === "/management/v1/users/me")
|
||||
return Response.json({ user_id: "admin", user_email: null, user_role: "proxy_admin" });
|
||||
if (url.pathname === "/v2/user/info") return Response.json(creator);
|
||||
return Response.json({ detail: "Unexpected request" }, { status: 404 });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
const catalog = [{ ...skills[0], created_by: creator.user_id }];
|
||||
const { rerender } = renderWithProviders(
|
||||
<SkillHubDashboard skills={catalog} isLoading={false} accessToken="admin-token" />,
|
||||
);
|
||||
expect(await screen.findByRole("cell", { name: creator.user_email })).toBeInTheDocument();
|
||||
fetchMock.mockClear();
|
||||
rerender(<SkillHubDashboard skills={catalog} isLoading={false} accessToken="admin-token" publicPage />);
|
||||
expect(screen.getByRole("cell", { name: creator.user_id })).toBeInTheDocument();
|
||||
expect(screen.queryByText(creator.user_email)).not.toBeInTheDocument();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("links a pinned GitLab source and renders SSH sources as text", () => {
|
||||
const sha = "a".repeat(40);
|
||||
const catalog: Plugin[] = [
|
||||
{
|
||||
...skills[0],
|
||||
source: { source: "git-subdir", url: "https://gitlab.com/team/nested/repo.git", sha, path: "plugins/example" },
|
||||
},
|
||||
{ ...skills[1], source: { source: "url", url: "git@git.example.test:team/repo.git" } },
|
||||
];
|
||||
renderWithProviders(<SkillHubDashboard skills={catalog} isLoading={false} />);
|
||||
expect(within(screen.getByRole("row", { name: /alpha/ })).getByRole("link")).toHaveAttribute(
|
||||
"href",
|
||||
`https://gitlab.com/team/nested/repo/-/tree/${sha}/plugins/example`,
|
||||
);
|
||||
const sshRow = screen.getByRole("row", { name: /beta/ });
|
||||
expect(sshRow).toHaveTextContent("git@git.example.test:team/repo.git");
|
||||
expect(within(sshRow).queryByRole("link")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe("Skills Hub sorting", () => {
|
||||
it.each(["Category", "Domain", "Status", "Downloads"])("sorts by %s through the table header", async (header) => {
|
||||
const user = userEvent.setup();
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ import {
|
|||
SKILL_SORT_FIELDS,
|
||||
} from "@/components/claude_code_plugins/skillCatalog";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { useUserIdentityLookup } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
|
||||
const ALL_DOMAINS = "__all_domains__";
|
||||
const DASHBOARD_SORT_FIELDS = [...SKILL_SORT_FIELDS, "category", "domain", "enabled"];
|
||||
|
|
@ -59,6 +60,10 @@ const SkillHubDashboard: React.FC<SkillHubDashboardProps> = ({
|
|||
const filters = useSkillFilters(DASHBOARD_SORT_FIELDS);
|
||||
const [domainFilter, setDomainFilter] = useState<string | undefined>(undefined);
|
||||
const [selectedSkill, setSelectedSkill] = useState<Plugin | null>(null);
|
||||
const users = useUserIdentityLookup(
|
||||
skills.flatMap((skill) => [skill.created_by, skill.approved_by]),
|
||||
{ accessToken: publicPage ? null : accessToken ?? null },
|
||||
);
|
||||
|
||||
// Derived stats
|
||||
const totalSkills = skills.length;
|
||||
|
|
@ -79,7 +84,7 @@ const SkillHubDashboard: React.FC<SkillHubDashboardProps> = ({
|
|||
);
|
||||
}, [skills, filters.search, filters.tag, filters.scan, domainFilter]);
|
||||
|
||||
const columns = useMemo(() => getSkillHubTableColumns({ onSkillClick: setSelectedSkill }), []);
|
||||
const columns = useMemo(() => getSkillHubTableColumns({ onSkillClick: setSelectedSkill, users }), [users]);
|
||||
|
||||
const domainItems = useMemo(
|
||||
() => [
|
||||
|
|
@ -95,6 +100,7 @@ const SkillHubDashboard: React.FC<SkillHubDashboardProps> = ({
|
|||
return (
|
||||
<SkillDetail
|
||||
skill={legacySkillDetail(selectedSkill)}
|
||||
users={users}
|
||||
onBack={() => setSelectedSkill(null)}
|
||||
isAdmin={isAdmin}
|
||||
accessToken={accessToken}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
"use client";
|
||||
|
||||
import { getSkillMetadataColumns } from "@/components/claude_code_plugins/SkillMetadataColumns";
|
||||
import { getSourceDisplayText, getSourceLink } from "@/components/claude_code_plugins/helpers";
|
||||
import type { UserIdentityLookup } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
|
||||
import { ColumnDef } from "@tanstack/react-table";
|
||||
import { Copy, ExternalLink, Info, MoreHorizontal } from "lucide-react";
|
||||
|
|
@ -21,21 +23,6 @@ import { copyToClipboard } from "@/utils/dataUtils";
|
|||
import { Plugin } from "@/components/claude_code_plugins/types";
|
||||
import i18n from "@/i18n/i18n";
|
||||
|
||||
function getSkillSourceLink(skill: Plugin): { url: string; label: string } | null {
|
||||
const src = skill.source;
|
||||
if (src?.source === "github" && src.repo) {
|
||||
return { url: `https://github.com/${src.repo}`, label: src.repo };
|
||||
}
|
||||
if (src?.source === "git-subdir" && src.url) {
|
||||
const url = src.path ? `${src.url}/tree/main/${src.path}` : src.url;
|
||||
return { url, label: url.replace("https://github.com/", "") };
|
||||
}
|
||||
if ((src?.source === "url" || src?.source === "archive") && src.url) {
|
||||
return { url: src.url, label: src.url.replace(/^https?:\/\//, "") };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface SkillHubRowActionsProps {
|
||||
skill: Plugin;
|
||||
onSkillClick: (skill: Plugin) => void;
|
||||
|
|
@ -70,10 +57,11 @@ function SkillHubRowActions({ skill, onSkillClick }: SkillHubRowActionsProps) {
|
|||
}
|
||||
|
||||
interface SkillHubTableColumnsDeps {
|
||||
users?: UserIdentityLookup;
|
||||
onSkillClick: (skill: Plugin) => void;
|
||||
}
|
||||
|
||||
export const getSkillHubTableColumns = ({ onSkillClick }: SkillHubTableColumnsDeps): ColumnDef<Plugin>[] => [
|
||||
export const getSkillHubTableColumns = ({ onSkillClick, users }: SkillHubTableColumnsDeps): ColumnDef<Plugin>[] => [
|
||||
{
|
||||
id: "name",
|
||||
accessorKey: "name",
|
||||
|
|
@ -131,17 +119,23 @@ export const getSkillHubTableColumns = ({ onSkillClick }: SkillHubTableColumnsDe
|
|||
size: 200,
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => {
|
||||
const link = getSkillSourceLink(row.original);
|
||||
if (!link) return <span className="text-xs text-muted-foreground">-</span>;
|
||||
const link = getSourceLink(row.original.source);
|
||||
const label = getSourceDisplayText(row.original.source);
|
||||
if (!link)
|
||||
return (
|
||||
<span className="block max-w-60 truncate text-xs text-muted-foreground" title={label}>
|
||||
{label}
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<a
|
||||
href={link.url}
|
||||
href={link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex max-w-60 items-center gap-1 text-xs text-primary hover:underline"
|
||||
title={link.label}
|
||||
title={label}
|
||||
>
|
||||
<span className="truncate">{link.label}</span>
|
||||
<span className="truncate">{label}</span>
|
||||
<ExternalLink className="size-3 shrink-0" />
|
||||
</a>
|
||||
);
|
||||
|
|
@ -161,7 +155,7 @@ export const getSkillHubTableColumns = ({ onSkillClick }: SkillHubTableColumnsDe
|
|||
/>
|
||||
),
|
||||
},
|
||||
...getSkillMetadataColumns<Plugin>(),
|
||||
...getSkillMetadataColumns<Plugin>(users),
|
||||
{
|
||||
id: "actions",
|
||||
meta: { className: "text-right", headerClassName: "text-right" },
|
||||
|
|
|
|||
|
|
@ -4,13 +4,16 @@ import { DateCell, StatusBadge } from "@/components/shared/table_cells";
|
|||
import { Badge } from "@/components/ui/badge";
|
||||
import i18n from "@/i18n/i18n";
|
||||
import type { SkillCatalogMetadata } from "./skillCatalog";
|
||||
import { userIdentityLabel, type UserIdentityLookup } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
|
||||
const IDENTITY_LABELS = {
|
||||
created_by: "skills.table.columns.createdBy",
|
||||
approved_by: "skills.table.columns.approvedBy",
|
||||
} as const;
|
||||
|
||||
export function getSkillMetadataColumns<T extends SkillCatalogMetadata>(): ColumnDef<T>[] {
|
||||
export function getSkillMetadataColumns<T extends SkillCatalogMetadata>(
|
||||
users: UserIdentityLookup = {},
|
||||
): ColumnDef<T>[] {
|
||||
return [
|
||||
{
|
||||
id: "download_count",
|
||||
|
|
@ -46,10 +49,15 @@ export function getSkillMetadataColumns<T extends SkillCatalogMetadata>(): Colum
|
|||
accessorKey: field,
|
||||
size: 190,
|
||||
enableSorting: true,
|
||||
header: ({ column }) => <DataTableSortHeader column={column} title={i18n.t(IDENTITY_LABELS[field])} />,
|
||||
header: ({ column }) => (
|
||||
<DataTableSortHeader
|
||||
column={column}
|
||||
title={<span title={i18n.t("skills.table.identitySortHelp")}>{i18n.t(IDENTITY_LABELS[field])}</span>}
|
||||
/>
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="block max-w-48 truncate text-xs" title={row.original[field] ?? undefined}>
|
||||
{row.original[field] || i18n.t("skills.table.notRecorded")}
|
||||
{userIdentityLabel(row.original[field], users) || i18n.t("skills.table.notRecorded")}
|
||||
</span>
|
||||
),
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -159,28 +159,51 @@ describe("getSourceDisplayText", () => {
|
|||
describe("getSourceLink", () => {
|
||||
it("returns github link for github source", () => {
|
||||
expect(getSourceLink({ source: "github", repo: "org/repo" })).toBe("https://github.com/org/repo");
|
||||
expect(getSourceLink({ source: "github", repo: "org/repo.git", ref: "v2.0" })).toBe(
|
||||
"https://github.com/org/repo/tree/v2.0",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns url for url source", () => {
|
||||
expect(getSourceLink({ source: "url", url: "https://example.com" })).toBe("https://example.com");
|
||||
it.each([
|
||||
"https://example.com",
|
||||
"https://git.internal.example/team/repo.git",
|
||||
"https://dev.azure.com/team/project/_git/repo",
|
||||
"https://github.com/org/repo/tree/release/plugins/example",
|
||||
"https://gitlab.com/team/repo/-/tree/release/plugins/example",
|
||||
])("returns url for an unknown forge or existing browser source %s", (url) => {
|
||||
const source = { source: "url", url, ref: "release", path: "plugins/example" };
|
||||
expect(getSourceLink(source)).toBe(url);
|
||||
});
|
||||
|
||||
it("returns the repo url for a github git-subdir source", () => {
|
||||
expect(getSourceLink({ source: "git-subdir", url: "https://github.com/org/repo", path: "plugins/x" })).toBe(
|
||||
expect(getSourceLink({ source: "git-subdir", url: "https://github.com/org/repo.git", path: "plugins/x" })).toBe(
|
||||
"https://github.com/org/repo",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns the repo url for a gitlab git-subdir source", () => {
|
||||
expect(getSourceLink({ source: "git-subdir", url: "https://gitlab.com/org/repo", path: "sub/dir" })).toBe(
|
||||
expect(getSourceLink({ source: "git-subdir", url: "https://gitlab.com/org/repo.git/", path: "sub/dir" })).toBe(
|
||||
"https://gitlab.com/org/repo",
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["github.com/org/repo", "tree"],
|
||||
["gitlab.com/team/nested/repo", "-/tree"],
|
||||
])("links branches and commits at %s", (repo, route) => {
|
||||
const root = `https://${repo}`;
|
||||
const sha = "abcde12345".repeat(4);
|
||||
const source = { source: "git-subdir", url: `${root}.git/`, path: "plugins/example" };
|
||||
expect(getSourceLink({ ...source, ref: "release/2" })).toBe(`${root}/${route}/release%2F2/plugins/example`);
|
||||
expect(getSourceLink({ ...source, ref: "release/2", sha })).toBe(`${root}/${route}/${sha}/plugins/example`);
|
||||
});
|
||||
|
||||
it("returns the archive url for an archive source", () => {
|
||||
expect(getSourceLink({ source: "archive", url: "https://bucket.s3.amazonaws.com/skill.zip" })).toBe(
|
||||
"https://bucket.s3.amazonaws.com/skill.zip",
|
||||
);
|
||||
const url = "https://gitlab.com/team/repo/-/archive/release/repo.zip?download=1";
|
||||
expect(getSourceLink({ source: "archive", url })).toBe(url);
|
||||
});
|
||||
|
||||
it("returns null when no repo or url", () => {
|
||||
|
|
@ -192,7 +215,7 @@ describe("getSourceLink", () => {
|
|||
"http://git.internal.example/org/repo",
|
||||
);
|
||||
expect(getSourceLink({ source: "git-subdir", url: "HTTPS://gitlab.com/org/repo", path: "sub/dir" })).toBe(
|
||||
"HTTPS://gitlab.com/org/repo",
|
||||
"https://gitlab.com/org/repo",
|
||||
);
|
||||
});
|
||||
|
||||
|
|
@ -320,6 +343,8 @@ describe("parseKeywords", () => {
|
|||
});
|
||||
|
||||
describe("parseSkillSource", () => {
|
||||
const githubRefSource = { source: "git-subdir", url: "https://github.com/org/repo", ref: "main" };
|
||||
|
||||
it("parses a plain github repo", () => {
|
||||
expect(parseSkillSource("github.com/org/repo")?.parsed).toEqual({ source: "github", repo: "org/repo" });
|
||||
});
|
||||
|
|
@ -333,16 +358,14 @@ describe("parseSkillSource", () => {
|
|||
|
||||
it("parses a github tree URL into a git-subdir", () => {
|
||||
expect(parseSkillSource("github.com/org/repo/tree/main/plugins/x")?.parsed).toEqual({
|
||||
source: "git-subdir",
|
||||
url: "https://github.com/org/repo",
|
||||
...githubRefSource,
|
||||
path: "plugins/x",
|
||||
});
|
||||
});
|
||||
|
||||
it("drops a trailing file segment from a github blob URL", () => {
|
||||
expect(parseSkillSource("github.com/org/repo/blob/main/x/SKILL.md")?.parsed).toEqual({
|
||||
source: "git-subdir",
|
||||
url: "https://github.com/org/repo",
|
||||
...githubRefSource,
|
||||
path: "x",
|
||||
});
|
||||
});
|
||||
|
|
@ -355,10 +378,10 @@ describe("parseSkillSource", () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("treats a gitlab repo as a raw url source", () => {
|
||||
expect(parseSkillSource("gitlab.com/org/repo")?.parsed).toEqual({
|
||||
it.each(["gitlab.com", "www.gitlab.com", "www.gitlab.com:8443"])("treats a %s repo as a raw url source", (host) => {
|
||||
expect(parseSkillSource(`${host}/org/repo`)?.parsed).toEqual({
|
||||
source: "url",
|
||||
url: "https://gitlab.com/org/repo",
|
||||
url: `https://${host}/org/repo`,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -377,18 +400,23 @@ describe("parseSkillSource", () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("combines a self-hosted host with an explicit subfolder", () => {
|
||||
expect(parseSkillSource("https://git.acme.com/team/repo", "sub/dir")?.parsed).toEqual({
|
||||
it.each([
|
||||
"https://git.acme.com/team/repo",
|
||||
"https://dev.azure.com/org/project/_git/repo",
|
||||
"https://git.example.test/team/repo/-/tree/main",
|
||||
"https://www.gitlab.com.example.test/team/repo/-/tree/main",
|
||||
])("combines a self-hosted host %s with an explicit subfolder", (url) => {
|
||||
expect(parseSkillSource(url, "sub/dir")?.parsed).toEqual({
|
||||
source: "git-subdir",
|
||||
url: "https://git.acme.com/team/repo",
|
||||
url,
|
||||
path: "sub/dir",
|
||||
});
|
||||
expect(parseSkillSource(url, "sub/dir", "release/v2")?.parsed).toMatchObject({ url, ref: "release/v2" });
|
||||
});
|
||||
|
||||
it("lets a github URL-encoded subdir win over an also-provided subfolder", () => {
|
||||
expect(parseSkillSource("github.com/org/repo/tree/main/plugins/x", "ignored/path")?.parsed).toEqual({
|
||||
source: "git-subdir",
|
||||
url: "https://github.com/org/repo",
|
||||
...githubRefSource,
|
||||
path: "plugins/x",
|
||||
});
|
||||
});
|
||||
|
|
@ -416,6 +444,7 @@ describe("parseSkillSource", () => {
|
|||
"ssh://git@ghe.example.com:2222/org/nested/repo.git",
|
||||
]) {
|
||||
expect(parseSkillSource(url)?.parsed).toEqual({ source: "url", url });
|
||||
expect(parseSkillSource(url, "plugins/x", "release/v2")?.parsed).toMatchObject({ url, ref: "release/v2" });
|
||||
}
|
||||
expect(parseSkillSource("git@ssh.dev.azure.com:v3/org/project/repo")?.suggestedName).toBe("repo");
|
||||
});
|
||||
|
|
@ -477,11 +506,11 @@ describe("parseSkillSource", () => {
|
|||
});
|
||||
});
|
||||
|
||||
it("keeps the query string of a zip URL so versioned or signed object links still resolve", () => {
|
||||
expect(parseSkillSource("https://bucket.s3.amazonaws.com/skill.ZIP?versionId=abc")?.parsed).toEqual({
|
||||
source: "archive",
|
||||
url: "https://bucket.s3.amazonaws.com/skill.ZIP?versionId=abc",
|
||||
});
|
||||
it.each([
|
||||
"https://bucket.s3.amazonaws.com/skill.ZIP?versionId=abc",
|
||||
"https://www.gitlab.com:8443/team/repo/-/archive/release/repo.zip?download=1",
|
||||
])("preserves the archive URL %s including its query string", (url) => {
|
||||
expect(parseSkillSource(url)?.parsed).toEqual({ source: "archive", url });
|
||||
});
|
||||
|
||||
it("ignores the subfolder for a zip URL since the archive is installed whole", () => {
|
||||
|
|
@ -514,10 +543,11 @@ describe("parseSkillSource", () => {
|
|||
expect(parseSkillSource("github.com/org/repo", "a//b")).toBeNull();
|
||||
});
|
||||
|
||||
it("treats a blob URL pointing at a root file as the plain repo", () => {
|
||||
expect(parseSkillSource("github.com/org/repo/blob/main/SKILL.md")?.parsed).toEqual({
|
||||
it.each(["main", "a".repeat(40)])("treats a root blob at %s as the plain repo", (target) => {
|
||||
expect(parseSkillSource(`github.com/org/repo/blob/${target}/SKILL.md`)?.parsed).toEqual({
|
||||
source: "github",
|
||||
repo: "org/repo",
|
||||
...(target === "main" ? { ref: target } : { sha: target }),
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -533,23 +563,65 @@ describe("parseSkillSource", () => {
|
|||
|
||||
it("routes uppercase and www github hosts through the github shorthand", () => {
|
||||
expect(parseSkillSource("GitHub.com/org/repo/tree/main/x")?.parsed).toEqual({
|
||||
source: "git-subdir",
|
||||
url: "https://github.com/org/repo",
|
||||
...githubRefSource,
|
||||
path: "x",
|
||||
});
|
||||
expect(parseSkillSource("www.github.com/org/repo")?.parsed).toEqual({ source: "github", repo: "org/repo" });
|
||||
});
|
||||
|
||||
it("keeps a dotted folder name as the subdir path", () => {
|
||||
it("keeps a dotted tree directory and removes a blob filename regardless of extension", () => {
|
||||
expect(parseSkillSource("github.com/org/repo/tree/main/my.md")?.parsed).toEqual({
|
||||
...githubRefSource,
|
||||
path: "my.md",
|
||||
});
|
||||
expect(parseSkillSource("github.com/org/repo/blob/main/my.skill")?.parsed).toEqual({
|
||||
source: "git-subdir",
|
||||
url: "https://github.com/org/repo",
|
||||
path: "my.skill",
|
||||
source: "github",
|
||||
repo: "org/repo",
|
||||
ref: "main",
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the repo for a tree URL with a branch but no folder", () => {
|
||||
expect(parseSkillSource("github.com/org/repo/tree/main")?.parsed).toEqual({ source: "github", repo: "org/repo" });
|
||||
it.each([
|
||||
["github.com/org/repo/tree/main", { source: "github", repo: "org/repo", ref: "main" }],
|
||||
["gitlab.com/team/repo/-/tree/release", { source: "url", url: "https://gitlab.com/team/repo", ref: "release" }],
|
||||
])("keeps the root repository and ref for %s", (url, source) => {
|
||||
expect(parseSkillSource(url)?.parsed).toEqual(source);
|
||||
const selected = { source: "git-subdir", ref: source.ref, path: "skills/review" };
|
||||
expect(parseSkillSource(url, selected.path)?.parsed).toMatchObject(selected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["gitlab.com", "tree/release/plugins/x", ""],
|
||||
["WWW.GITLAB.COM:8443", "blob/release/plugins/x/SKILL.md", ":8443"],
|
||||
["www.gitlab.com", "blob/release/plugins/x/example.zip", ""],
|
||||
])("normalizes GitLab browser host %s and path %s", (host, route, port) => {
|
||||
const expected = {
|
||||
source: "git-subdir",
|
||||
url: `https://gitlab.com${port}/team/subgroup/repo`,
|
||||
path: "plugins/x",
|
||||
ref: "release",
|
||||
};
|
||||
const source = parseSkillSource(`https://${host}/team/subgroup/repo/-/${route}`);
|
||||
expect(source?.parsed).toEqual(expected);
|
||||
expect(source?.label).toContain("release");
|
||||
});
|
||||
|
||||
it.each(["github.com/org/repo/tree", "gitlab.com/team/repo/-/tree"])(
|
||||
"preserves an encoded or explicitly selected slash-containing ref in %s",
|
||||
(prefix) => {
|
||||
const encoded = parseSkillSource(`https://${prefix}/release%2Fv2/plugins/x`);
|
||||
const explicit = parseSkillSource(`https://${prefix}/release/v2/plugins/x`, "", "release/v2");
|
||||
expect(encoded?.parsed).toEqual(explicit?.parsed);
|
||||
expect(explicit?.parsed).toMatchObject({ ref: "release/v2", path: "plugins/x" });
|
||||
expect(parseSkillSource(`https://${prefix}/release/v2/plugins/x`, "", "different")).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("normalizes commit pins for an explicit clone ref", () => {
|
||||
const sha = "abcdef1234".repeat(4);
|
||||
const fromInput = parseSkillSource("https://gitlab.com/team/repo", "plugins/x", sha.toUpperCase())?.parsed;
|
||||
expect(fromInput).toMatchObject({ sha });
|
||||
expect(fromInput).not.toHaveProperty("ref");
|
||||
});
|
||||
|
||||
it("kebab-cases the suggested name from a mixed-case repo", () => {
|
||||
|
|
|
|||
|
|
@ -3,12 +3,14 @@
|
|||
*/
|
||||
|
||||
import i18n from "@/i18n/i18n";
|
||||
import type { Plugin, PluginSource } from "./types";
|
||||
import type { Plugin, PluginSource, SkillImport } from "./types";
|
||||
|
||||
export interface SkillSourcePreview {
|
||||
parsed: PluginSource;
|
||||
label: string;
|
||||
suggestedName: string;
|
||||
pathFromUrl?: boolean;
|
||||
fileFromUrl?: string;
|
||||
}
|
||||
|
||||
export const SUBDIR_PATH_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9._-]*(\/[a-zA-Z0-9][a-zA-Z0-9._-]*)*$/;
|
||||
|
|
@ -21,8 +23,7 @@ export const isValidSubPath = (subPath: string): boolean => {
|
|||
};
|
||||
|
||||
const GITHUB_HOST = "github.com";
|
||||
|
||||
const SKILL_FILE_EXTENSION_REGEX = /\.(md|markdown|txt|json|ya?ml|toml)$/i;
|
||||
const withoutWww = (host: string): string => host.replace(/^www\./, "");
|
||||
|
||||
const ZIP_ARCHIVE_REGEX = /\.zip$/i;
|
||||
|
||||
|
|
@ -89,7 +90,57 @@ const toKebabCase = (value: string): string =>
|
|||
.replace(/-+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
|
||||
const parseGitHubSource = (url: URL, subPath?: string): SkillSourcePreview | null => {
|
||||
const withGitRef = (preview: SkillSourcePreview | null, ref?: string): SkillSourcePreview | null => {
|
||||
const target = ref?.trim();
|
||||
if (!preview || !target) return preview;
|
||||
return {
|
||||
...preview,
|
||||
parsed: {
|
||||
...preview.parsed,
|
||||
...(/^[a-fA-F0-9]{40}$/.test(target) ? { sha: target.toLowerCase() } : { ref: target }),
|
||||
},
|
||||
label: `${preview.label} (${target})`,
|
||||
};
|
||||
};
|
||||
|
||||
interface BrowserLocation {
|
||||
ref: string;
|
||||
path: string;
|
||||
pathFromUrl: boolean;
|
||||
fileFromUrl?: string;
|
||||
}
|
||||
|
||||
const browserLocation = (
|
||||
parts: string[],
|
||||
kind: "tree" | "blob",
|
||||
explicitRef?: string,
|
||||
subPath?: string,
|
||||
): BrowserLocation | null => {
|
||||
if (!parts.length) return null;
|
||||
try {
|
||||
const ref = explicitRef?.trim() || decodeURIComponent(parts[0]);
|
||||
const refLength = explicitRef?.trim()
|
||||
? parts.findIndex((_, index) => decodeURIComponent(parts.slice(0, index + 1).join("/")) === ref) + 1
|
||||
: 1;
|
||||
if (!refLength || (kind === "blob" && parts.length === refLength)) return null;
|
||||
const path = parts
|
||||
.slice(refLength, kind === "blob" ? -1 : undefined)
|
||||
.map(decodeURIComponent)
|
||||
.join("/");
|
||||
const fileFromUrl = kind === "blob" ? decodeURIComponent(parts[parts.length - 1]) : undefined;
|
||||
const pathFromUrl = Boolean(path || fileFromUrl);
|
||||
return { ref, path: pathFromUrl ? path : normalizeSubPath(subPath ?? ""), pathFromUrl, fileFromUrl };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const parseGitHubSource = (
|
||||
url: URL,
|
||||
subPath?: string,
|
||||
ref?: string,
|
||||
pathContract: "reference" | "portable" = "reference",
|
||||
): SkillSourcePreview | null => {
|
||||
const parts = pathSegments(url);
|
||||
if (parts.length < 2) {
|
||||
return null;
|
||||
|
|
@ -108,42 +159,29 @@ const parseGitHubSource = (url: URL, subPath?: string): SkillSourcePreview | nul
|
|||
suggestedName: toKebabCase(repoBase),
|
||||
};
|
||||
|
||||
const isTreeOrBlob = parts.length >= 4 && (parts[2] === "tree" || parts[2] === "blob");
|
||||
if (isTreeOrBlob) {
|
||||
const pathParts = parts.slice(4);
|
||||
const last = lastSegment(pathParts.join("/"));
|
||||
const effective = SKILL_FILE_EXTENSION_REGEX.test(last) ? pathParts.slice(0, -1) : pathParts;
|
||||
if (effective.length === 0) {
|
||||
return repoPreview;
|
||||
}
|
||||
const path = normalizeSubPath(effective.join("/"));
|
||||
if (!SUBDIR_PATH_REGEX.test(path)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
parsed: { source: "git-subdir", url: repoUrl, path },
|
||||
label: i18n.t("claudeCodePlugins.sources.githubSubdir", { repo: repoFull, path }),
|
||||
suggestedName: toKebabCase(lastSegment(path)),
|
||||
};
|
||||
}
|
||||
|
||||
if (parts.length !== 2) {
|
||||
const kind = parts[2];
|
||||
const location = kind === "tree" || kind === "blob" ? browserLocation(parts.slice(3), kind, ref, subPath) : undefined;
|
||||
if (location === null || (location === undefined && parts.length !== 2)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const normalized = normalizeSubPath(subPath ?? "");
|
||||
if (normalized !== "") {
|
||||
if (!SUBDIR_PATH_REGEX.test(normalized)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
parsed: { source: "git-subdir", url: repoUrl, path: normalized },
|
||||
label: i18n.t("claudeCodePlugins.sources.githubSubdir", { repo: repoFull, path: normalized }),
|
||||
suggestedName: toKebabCase(lastSegment(normalized)),
|
||||
};
|
||||
const path = location?.path ?? normalizeSubPath(subPath ?? "");
|
||||
if (pathContract === "reference" && path && !SUBDIR_PATH_REGEX.test(path)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return repoPreview;
|
||||
const preview: SkillSourcePreview = path
|
||||
? {
|
||||
parsed: { source: "git-subdir", url: repoUrl, path },
|
||||
label: i18n.t("claudeCodePlugins.sources.githubSubdir", { repo: repoFull, path }),
|
||||
suggestedName: toKebabCase(lastSegment(path)),
|
||||
}
|
||||
: repoPreview;
|
||||
return withGitRef(
|
||||
{
|
||||
...preview,
|
||||
...(location ? { pathFromUrl: location.pathFromUrl, fileFromUrl: location.fileFromUrl } : {}),
|
||||
},
|
||||
location?.ref ?? ref,
|
||||
);
|
||||
};
|
||||
|
||||
const buildGitSourcePreview = (
|
||||
|
|
@ -179,6 +217,21 @@ const parseRawGitSource = (url: URL, subPath?: string): SkillSourcePreview | nul
|
|||
return buildGitSourcePreview("Git", buildRepoUrl(url), repoName, subPath);
|
||||
};
|
||||
|
||||
const parseGitLabBrowserSource = (url: URL, subPath?: string, ref?: string): SkillSourcePreview | null => {
|
||||
const parts = pathSegments(url);
|
||||
const separator = parts.findIndex((part, index) => part === "-" && ["tree", "blob"].includes(parts[index + 1]));
|
||||
const kind = parts[separator + 1];
|
||||
if (separator < 2 || (kind !== "tree" && kind !== "blob")) return null;
|
||||
const location = browserLocation(parts.slice(separator + 2), kind, ref, subPath);
|
||||
if (!location) return null;
|
||||
const repoUrl = `${url.protocol}//${withoutWww(url.host)}/${parts.slice(0, separator).join("/")}`;
|
||||
const preview = buildGitSourcePreview("Git", repoUrl, parts[separator - 1].replace(/\.git$/, ""), location.path);
|
||||
const selected = preview
|
||||
? { ...preview, pathFromUrl: location.pathFromUrl, fileFromUrl: location.fileFromUrl }
|
||||
: null;
|
||||
return withGitRef(selected, location.ref);
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse an scp-style `git@host:org/repo` or `ssh://git@host/org/repo` clone URL, registering it
|
||||
* exactly as typed: git treats the `.git` suffix as optional, and forcing one on breaks hosts whose
|
||||
|
|
@ -210,6 +263,81 @@ const parseArchiveSource = (url: URL): SkillSourcePreview => ({
|
|||
suggestedName: toKebabCase(lastSegment(url.pathname).replace(ZIP_ARCHIVE_REGEX, "")),
|
||||
});
|
||||
|
||||
const parseSkillImportUrl = (rawUrl: string): URL | null => {
|
||||
const url = parseRepoUrl(rawUrl);
|
||||
if (!url) return null;
|
||||
const host = withoutWww(url.host);
|
||||
return [GITHUB_HOST, "skills.sh"].includes(host)
|
||||
? toUrl(`${url.protocol}//${host}${url.pathname}${url.search}${url.hash}`)
|
||||
: null;
|
||||
};
|
||||
|
||||
export const requiresBrowserRefConfirmation = (preview: SkillSourcePreview | null | undefined, ref: string): boolean =>
|
||||
Boolean(
|
||||
preview?.pathFromUrl &&
|
||||
preview.parsed.path &&
|
||||
!(ref.trim() || preview.parsed.sha || preview.parsed.ref?.includes("/")),
|
||||
);
|
||||
|
||||
export const availableSkillUrlModes = (rawUrl: string) => {
|
||||
const url = parseSkillImportUrl(rawUrl);
|
||||
if (url?.host === "skills.sh") return ["import"] as const;
|
||||
return url ? (["register", "import"] as const) : (["register"] as const);
|
||||
};
|
||||
|
||||
interface SkillImportSource {
|
||||
selection: Pick<SkillImport, "url" | "skill" | "ref" | "path">;
|
||||
preview: SkillSourcePreview | null;
|
||||
skillFromUrl?: string;
|
||||
}
|
||||
|
||||
const parseDirectorySkillSource = (url: URL, path?: string, ref?: string): SkillImportSource | null => {
|
||||
try {
|
||||
const parts = url.pathname
|
||||
.replace(/^\/+|\/+$/g, "")
|
||||
.split("/")
|
||||
.map(decodeURIComponent);
|
||||
if (parts.length !== 3 || parts.slice(0, 2).some((part) => !GITHUB_REPO_REGEX.test(part))) return null;
|
||||
const skillFromUrl = parts[2];
|
||||
if (!skillFromUrl) return null;
|
||||
return {
|
||||
selection: {
|
||||
url: url.href,
|
||||
...(ref?.trim() ? { ref: ref.trim() } : {}),
|
||||
...(path?.trim() ? { path: path.trim() } : {}),
|
||||
},
|
||||
preview: null,
|
||||
skillFromUrl,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
export const parseSkillImportSource = (
|
||||
rawUrl: string,
|
||||
path?: string,
|
||||
ref?: string,
|
||||
skill?: string,
|
||||
): SkillImportSource | null => {
|
||||
const url = parseSkillImportUrl(rawUrl);
|
||||
if (!url || url.search || url.hash) return null;
|
||||
if (url.host === "skills.sh") return parseDirectorySkillSource(url, path, ref);
|
||||
const preview = parseGitHubSource(url, path, ref, "portable");
|
||||
if (!preview || (preview.fileFromUrl && preview.fileFromUrl !== "SKILL.md")) return null;
|
||||
const source = preview.parsed;
|
||||
const revision = source.sha ?? source.ref;
|
||||
return {
|
||||
selection: {
|
||||
url: source.source === "github" ? `https://github.com/${source.repo}` : source.url ?? url.href,
|
||||
...(skill?.trim() ? { skill: skill.trim() } : {}),
|
||||
...(revision ? { ref: revision } : {}),
|
||||
...(source.path || preview.fileFromUrl ? { path: source.path ?? "" } : {}),
|
||||
},
|
||||
preview,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse any git-accessible repository URL or https zip archive URL into a registerable skill
|
||||
* source. A `.zip` path is an `archive` source (S3, Artifactory, any static host). GitHub URLs
|
||||
|
|
@ -217,22 +345,29 @@ const parseArchiveSource = (url: URL): SkillSourcePreview => ({
|
|||
* authenticates with the user's own key; every other host is treated as a raw repo URL,
|
||||
* with an optional subfolder turning it into git-subdir.
|
||||
*/
|
||||
export const parseSkillSource = (rawUrl: string, subPath?: string): SkillSourcePreview | null => {
|
||||
export const parseSkillSource = (rawUrl: string, subPath?: string, ref?: string): SkillSourcePreview | null => {
|
||||
const ssh = parseSshSource(rawUrl, subPath);
|
||||
if (ssh) {
|
||||
return ssh;
|
||||
return withGitRef(ssh, ref);
|
||||
}
|
||||
const url = parseRepoUrl(rawUrl);
|
||||
if (!url) {
|
||||
return null;
|
||||
}
|
||||
const host = withoutWww(url.hostname);
|
||||
if (host === GITHUB_HOST && ["tree", "blob"].includes(pathSegments(url)[2])) {
|
||||
return parseGitHubSource(url, subPath, ref);
|
||||
}
|
||||
if (host === "gitlab.com" && /\/-\/(?:tree|blob)(?:\/|$)/.test(url.pathname)) {
|
||||
return parseGitLabBrowserSource(url, subPath, ref);
|
||||
}
|
||||
if (ZIP_ARCHIVE_REGEX.test(url.pathname)) {
|
||||
return parseArchiveSource(url);
|
||||
}
|
||||
if (url.hostname.replace(/^www\./, "") === GITHUB_HOST) {
|
||||
return parseGitHubSource(url, subPath);
|
||||
if (host === GITHUB_HOST) {
|
||||
return parseGitHubSource(url, subPath, ref);
|
||||
}
|
||||
return parseRawGitSource(url, subPath);
|
||||
return withGitRef(parseRawGitSource(url, subPath), ref);
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -298,11 +433,22 @@ export const getSourceDisplayText = (source: Plugin["source"]): string => {
|
|||
* Get clickable link for plugin source. Ssh clone urls are not browsable, so they yield null.
|
||||
*/
|
||||
export const getSourceLink = (source: Plugin["source"]): string | null => {
|
||||
if (source.source === "github" && source.repo) {
|
||||
return `https://github.com/${source.repo}`;
|
||||
}
|
||||
const linksToUrl = source.source === "url" || source.source === "git-subdir" || source.source === "archive";
|
||||
return linksToUrl && source.url && BROWSABLE_URL_REGEX.test(source.url) ? source.url : null;
|
||||
if (!["github", "url", "git-subdir", "archive"].includes(source.source)) return null;
|
||||
const link = source.source === "github" ? source.repo && `https://github.com/${source.repo}` : source.url;
|
||||
if (!link || !BROWSABLE_URL_REGEX.test(link)) return null;
|
||||
if (source.source === "archive") return link;
|
||||
const url = toUrl(link);
|
||||
const host = url && withoutWww(url.hostname);
|
||||
if (!url || (host !== GITHUB_HOST && host !== "gitlab.com")) return link;
|
||||
const parts = pathSegments(url);
|
||||
const isRepository = host === GITHUB_HOST ? parts.length === 2 : parts.length >= 2 && !parts.includes("-");
|
||||
if (!isRepository) return link;
|
||||
const root = buildRepoUrl(url).replace(/\.git$/, "");
|
||||
const ref = source.sha || source.ref;
|
||||
if (!ref) return root;
|
||||
const path =
|
||||
source.source === "git-subdir" && source.path ? `/${source.path.split("/").map(encodeURIComponent).join("/")}` : "";
|
||||
return `${root}/${host === GITHUB_HOST ? "tree" : "-/tree"}/${encodeURIComponent(ref)}${path}`;
|
||||
};
|
||||
|
||||
export const getManagedSkillArchivePath = (
|
||||
|
|
|
|||
|
|
@ -1,6 +1,15 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
import { buildSkillImport, buildSkillMetadata, skillFormValues } from "./skillForm";
|
||||
import {
|
||||
buildSkillImport,
|
||||
buildSkillMetadata,
|
||||
buildSkillRegistration,
|
||||
buildSkillUpdate,
|
||||
buildSkillUploadMetadata,
|
||||
skillFormSchema,
|
||||
skillFormValues,
|
||||
} from "./skillForm";
|
||||
import type { SkillHubSkill } from "./types";
|
||||
import { availableSkillUrlModes } from "./helpers";
|
||||
|
||||
const skill: SkillHubSkill = {
|
||||
id: "skill-1",
|
||||
|
|
@ -12,34 +21,62 @@ const skill: SkillHubSkill = {
|
|||
domain: "Engineering",
|
||||
namespace: "workflows",
|
||||
visibility: "public",
|
||||
security_scan_passed: false,
|
||||
updated_at: "2026-10-20T00:00:00Z",
|
||||
};
|
||||
|
||||
const metadata = {
|
||||
name: "registry-alias",
|
||||
description: "Registry description.".repeat(80),
|
||||
domain: "Engineering",
|
||||
namespace: "tools",
|
||||
keywords: ["review", "quality"],
|
||||
author: { name: "Maintainer", email: "maintainer@example.test" },
|
||||
category: "Productivity",
|
||||
homepage: "https://example.test/skill",
|
||||
version: "3.1.0",
|
||||
};
|
||||
const authored = { ...skill, ...metadata };
|
||||
const archiveFile = new File(["legacy SKILL.md without frontmatter"], "legacy.zip");
|
||||
const values = {
|
||||
...skillFormValues(authored),
|
||||
mode: "register" as const,
|
||||
version: metadata.version,
|
||||
url: "https://gitlab.com/team/subgroup/repo/-/tree/release/v2/skills/review",
|
||||
ref: "release/v2",
|
||||
path: "previous-draft",
|
||||
skill: "unused-selector",
|
||||
archiveFile,
|
||||
sha256: "aBcD".repeat(16),
|
||||
};
|
||||
const automaticVersion = { version: null, expected_updated_at: skill.updated_at };
|
||||
|
||||
describe("skill form payloads", () => {
|
||||
it.each([["sales, finance", "review"], [" workflow ", "review", "review"], [], null])(
|
||||
"preserves unchanged keywords in a complete metadata replacement: %j",
|
||||
"leaves stored keywords untouched during another metadata edit: %j",
|
||||
(keywords) => {
|
||||
const published = { ...skill, keywords };
|
||||
const published = { ...skill, keywords, domain: " Engineering ", namespace: " workflows ", author: null };
|
||||
const values = skillFormValues(published);
|
||||
expect(values.version).toBe("");
|
||||
const expected = {
|
||||
description: "Updated instructions",
|
||||
keywords,
|
||||
domain: skill.domain,
|
||||
namespace: skill.namespace,
|
||||
description: metadata.description,
|
||||
version: null,
|
||||
expected_updated_at: skill.updated_at,
|
||||
};
|
||||
expect(buildSkillMetadata({ ...values, description: "Updated instructions" }, published)).toEqual(expected);
|
||||
expect(buildSkillMetadata({ ...values, description: metadata.description }, published)).toEqual(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it("parses intentional edits and clears blank metadata without changing the source", () => {
|
||||
it.each(["", " \t "])("clears blank metadata %j without changing the source", (blank) => {
|
||||
const values = {
|
||||
...skillFormValues(skill),
|
||||
domain: "",
|
||||
namespace: "",
|
||||
description: "",
|
||||
...skillFormValues(authored),
|
||||
domain: blank,
|
||||
namespace: blank,
|
||||
description: blank,
|
||||
authorName: blank,
|
||||
authorEmail: blank,
|
||||
category: blank,
|
||||
homepage: blank,
|
||||
keywords: "security, review",
|
||||
version: "3.0.0",
|
||||
};
|
||||
|
|
@ -47,16 +84,155 @@ describe("skill form payloads", () => {
|
|||
description: null,
|
||||
domain: null,
|
||||
namespace: null,
|
||||
author: null,
|
||||
category: null,
|
||||
homepage: null,
|
||||
keywords: ["security", "review"],
|
||||
version: "3.0.0",
|
||||
expected_updated_at: skill.updated_at,
|
||||
};
|
||||
expect(buildSkillMetadata(values, skill)).toEqual(expected);
|
||||
expect(buildSkillMetadata({ ...values, keywords: "" }, skill).keywords).toEqual([]);
|
||||
expect(buildSkillMetadata(skillFormSchema(authored).parse(values), authored)).toEqual(expected);
|
||||
expect(buildSkillMetadata({ ...values, keywords: blank }, authored).keywords).toEqual([]);
|
||||
expect(buildSkillMetadata({ ...skillFormValues(authored), authorEmail: blank }, authored)).toEqual({
|
||||
...automaticVersion,
|
||||
author: { name: metadata.author.name, email: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves source URL parsing to the API", () => {
|
||||
const values = { ...skillFormValues(), url: "https://github.com/example/skills/tree/release/v2/review" };
|
||||
expect(buildSkillImport(values)).toEqual({ url: values.url });
|
||||
it("keeps complete creation payloads, long descriptions and normalized replacement sources", () => {
|
||||
expect(buildSkillUploadMetadata(skillFormSchema().parse({ ...values, mode: "upload" }))).toEqual(metadata);
|
||||
const imported = { ...values, mode: "import" as const, url: "https://github.com/example/repo" };
|
||||
const { url, skill, ref, path, version } = imported;
|
||||
const expectedImport = { url, skill, ref, path, version, metadata };
|
||||
expect(buildSkillImport(skillFormSchema().parse(imported))).toEqual(expectedImport);
|
||||
const source = {
|
||||
source: "git-subdir",
|
||||
url: "https://gitlab.com/team/subgroup/repo",
|
||||
path: "skills/review",
|
||||
ref: values.ref,
|
||||
};
|
||||
expect(buildSkillRegistration(skillFormSchema().parse(values))).toEqual({ ...metadata, source });
|
||||
const intent = { ...automaticVersion, version: values.version };
|
||||
const replacement = skillFormSchema(authored).parse({ ...values, mode: "replace" });
|
||||
expect(buildSkillUpdate(replacement, authored)).toEqual({ ...intent, source });
|
||||
expect(buildSkillUpdate({ ...replacement, mode: "metadata" }, authored)).toEqual(intent);
|
||||
const browserUrl = `${imported.url}/tree/release/v2/skills/review`;
|
||||
for (const mode of ["replace", "import"] as const) {
|
||||
const unresolved = { ...replacement, mode, url: browserUrl, ref: "" };
|
||||
expect(skillFormSchema(authored).safeParse(unresolved).error?.issues).toContainEqual(
|
||||
expect.objectContaining({ path: ["ref"] }),
|
||||
);
|
||||
}
|
||||
for (const revision of ["release%2Fv2", "a".repeat(40)]) {
|
||||
const unambiguous = { ...values, ref: "", url: values.url.replace("release/v2", revision) };
|
||||
expect(skillFormSchema().safeParse(unambiguous).success).toBe(true);
|
||||
}
|
||||
for (const [ref, path] of [
|
||||
["release", "v2/skills/review"],
|
||||
["release/v2", "skills/review"],
|
||||
]) {
|
||||
const reference = skillFormSchema().parse({ ...values, ref });
|
||||
const snapshot = skillFormSchema().parse({ ...imported, url: browserUrl, ref });
|
||||
expect(buildSkillRegistration(reference)?.source).toMatchObject({ ref, path });
|
||||
expect(buildSkillImport(snapshot)).toMatchObject({ ref, path });
|
||||
}
|
||||
expect(
|
||||
skillFormValues({ ...authored, source: { source: "archive", url: "/skill-hub/skills/shared-skill/archive" } })
|
||||
.url,
|
||||
).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("skill form validation", () => {
|
||||
it.each([
|
||||
"https://github.com:8443",
|
||||
"https://www.github.com:8443",
|
||||
"https://www.skills.sh:8443",
|
||||
"https://user@github.com",
|
||||
"http://github.com",
|
||||
"https://gitlab.com",
|
||||
"https://git.example.test",
|
||||
])("offers only external references for %s", (origin) =>
|
||||
expect(availableSkillUrlModes(`${origin}/example/repo`)).toEqual(["register"]),
|
||||
);
|
||||
it.each(["github.com", "skills.sh"])("normalizes %s through validation and request serialization", (host) => {
|
||||
const url = `https://${host}/example/repo${host === "skills.sh" ? "/review" : ""}`;
|
||||
const expected = { url, ref: "main", path: "skills/review", ...(host === "github.com" ? { skill: "draft" } : {}) };
|
||||
for (const inputUrl of [
|
||||
url,
|
||||
` ${url.replace(host, host.toUpperCase())} `,
|
||||
url.replace("https://", ""),
|
||||
url.replace(host, `${host}:443`),
|
||||
url.replace(host, `www.${host}`),
|
||||
url.replace(host, `www.${host}:443`),
|
||||
]) {
|
||||
const draft = {
|
||||
...skillFormValues(),
|
||||
mode: "import",
|
||||
url: inputUrl,
|
||||
skill: "draft",
|
||||
ref: "main",
|
||||
path: "skills/review",
|
||||
};
|
||||
expect(availableSkillUrlModes(inputUrl)).toContain("import");
|
||||
expect(buildSkillImport(skillFormSchema().parse(draft))).toEqual(expected);
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["https://github.com/example/repo/tree/main/skills/review", "HEAD"],
|
||||
["https://github.com/example/repo/blob/main/README.md", "main"],
|
||||
["https://github.com/example/repo/tree/main/skills/review?ref=other", "main"],
|
||||
["HTTPS://GitHub.com/example/repo/tree/main/skills/review", "other"],
|
||||
["https://github.com:8443/example/repo", "main"],
|
||||
["https://www.github.com:8443/example/repo", "main"],
|
||||
["https://www.skills.sh:8443/example/repo/review", "main"],
|
||||
["https://user@github.com/example/repo", "main"],
|
||||
["http://github.com/example/repo", "main"],
|
||||
["https://github.com/example/repo#section", "main"],
|
||||
["https://skills.sh/example/repo", "main"],
|
||||
["https://skills.sh/example/repo/review?ref=other", "main"],
|
||||
["https://skills.sh/example/repo/%ZZ", "main"],
|
||||
["https://gitlab.com/example/repo", "main"],
|
||||
])("rejects conflicting or unsupported import selection %s", (url, ref) => {
|
||||
const input = { ...values, mode: "import" as const, url, ref };
|
||||
expect(skillFormSchema().safeParse(input).error?.issues).toContainEqual(expect.objectContaining({ path: ["url"] }));
|
||||
expect(buildSkillImport(input)).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", "skills/with spaces", "skills/with spaces"],
|
||||
["/tree/main", "", undefined],
|
||||
["/tree/main", "skills/review", "skills/review"],
|
||||
["/blob/main/SKILL.md", "previous-draft", ""],
|
||||
["/tree/main/skills/re%76iew", "previous-draft", "skills/review"],
|
||||
["/blob/main/skills/with%20spaces/SKILL.md", "previous-draft", "skills/with spaces"],
|
||||
])("preserves portable import directory rules for %s", (location, path, expected) => {
|
||||
const url = "https://github.com/example/repo";
|
||||
const draft = { ...values, mode: "import", url: url + location, ref: "main", path };
|
||||
const input = skillFormSchema().parse(draft);
|
||||
expect(buildSkillImport(input)).toMatchObject({ url, ref: "main" });
|
||||
expect(buildSkillImport(input)?.path).toBe(expected);
|
||||
});
|
||||
|
||||
it.each(["register", "replace"] as const)("validates and preserves an optional archive digest during %s", (mode) => {
|
||||
const published = mode === "replace" ? authored : undefined;
|
||||
const input = { ...values, mode, url: "https://artifacts.example.test/skill.zip" };
|
||||
const schema = skillFormSchema(published);
|
||||
expect(schema.safeParse({ ...input, url: "not a repository" }).success).toBe(false);
|
||||
expect(schema.safeParse({ ...input, sha256: "" }).success).toBe(true);
|
||||
expect(schema.safeParse({ ...input, sha256: "invalid" }).error?.issues).toContainEqual(
|
||||
expect.objectContaining({ path: ["sha256"] }),
|
||||
);
|
||||
const validated = schema.parse({ ...input, sha256: ` ${values.sha256} ` });
|
||||
const payload = published ? buildSkillUpdate(validated, published) : buildSkillRegistration(validated);
|
||||
expect(payload?.source).toEqual({ source: "archive", url: input.url, sha256: values.sha256 });
|
||||
});
|
||||
|
||||
it.each(["upload", "import", "register"] as const)("requires registry and author names for %s metadata", (mode) => {
|
||||
const input = { ...values, mode, url: "https://github.com/example/repo" };
|
||||
expect(skillFormSchema().safeParse({ ...input, name: "" }).success).toBe(false);
|
||||
expect(skillFormSchema().safeParse({ ...input, authorName: "" }).success).toBe(false);
|
||||
expect(skillFormSchema().safeParse(input).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,48 +1,241 @@
|
|||
import { parseKeywords } from "./helpers";
|
||||
import type { SkillHubSkill, SkillImport, SkillMetadata } from "./types";
|
||||
import { z } from "zod";
|
||||
import i18n from "@/i18n/i18n";
|
||||
import type en from "@/i18n/locales/en.json";
|
||||
import {
|
||||
isValidEmail,
|
||||
isValidSemanticVersion,
|
||||
isValidSha256,
|
||||
parseKeywords,
|
||||
parseSkillImportSource,
|
||||
parseSkillSource,
|
||||
requiresBrowserRefConfirmation,
|
||||
validatePluginName,
|
||||
} from "./helpers";
|
||||
import type {
|
||||
SkillHubSkill,
|
||||
SkillHubRegisterRequest,
|
||||
SkillImport,
|
||||
SkillMetadata,
|
||||
SkillUpdate,
|
||||
SkillUploadMetadata,
|
||||
} from "./types";
|
||||
|
||||
type FormMessages = (typeof en)["skills"]["addForm"];
|
||||
type FormErrorKey = `errors.${keyof FormMessages["errors"]}` | `toasts.${keyof FormMessages["toasts"]}`;
|
||||
|
||||
export interface SkillFormValues {
|
||||
mode: "upload" | "import" | "metadata";
|
||||
mode: "upload" | "import" | "register" | "metadata" | "replace";
|
||||
archiveFile: File | null;
|
||||
url: string;
|
||||
skill: string;
|
||||
ref: string;
|
||||
path: string;
|
||||
name: string;
|
||||
domain: string;
|
||||
namespace: string;
|
||||
description: string;
|
||||
keywords: string;
|
||||
version: string;
|
||||
authorName: string;
|
||||
authorEmail: string;
|
||||
category: string;
|
||||
homepage: string;
|
||||
sha256: string;
|
||||
}
|
||||
|
||||
export const skillFormValues = (skill?: SkillHubSkill): SkillFormValues => ({
|
||||
mode: skill ? "metadata" : "upload",
|
||||
const EMPTY_SKILL_FORM: SkillFormValues = {
|
||||
mode: "upload",
|
||||
archiveFile: null,
|
||||
url: "",
|
||||
skill: "",
|
||||
ref: "",
|
||||
path: "",
|
||||
domain: skill?.domain ?? "",
|
||||
namespace: skill?.namespace ?? "",
|
||||
description: skill?.description ?? "",
|
||||
keywords: skill?.keywords?.join(", ") ?? "",
|
||||
name: "",
|
||||
domain: "",
|
||||
namespace: "",
|
||||
description: "",
|
||||
keywords: "",
|
||||
version: "",
|
||||
authorName: "",
|
||||
authorEmail: "",
|
||||
category: "",
|
||||
homepage: "",
|
||||
sha256: "",
|
||||
};
|
||||
|
||||
export const skillFormValues = (skill?: SkillHubSkill): SkillFormValues => {
|
||||
if (!skill) return { ...EMPTY_SKILL_FORM };
|
||||
return {
|
||||
...EMPTY_SKILL_FORM,
|
||||
mode: "metadata",
|
||||
name: skill.name,
|
||||
domain: skill.domain ?? "",
|
||||
namespace: skill.namespace ?? "",
|
||||
description: skill.description ?? "",
|
||||
keywords: skill.keywords?.join(", ") ?? "",
|
||||
authorName: skill.author?.name ?? "",
|
||||
authorEmail: skill.author?.email ?? "",
|
||||
category: skill.category ?? "",
|
||||
homepage: skill.homepage ?? "",
|
||||
};
|
||||
};
|
||||
|
||||
export const buildSkillMetadata = (values: SkillFormValues, skill: SkillHubSkill): SkillMetadata => {
|
||||
const initial = skillFormValues(skill);
|
||||
return {
|
||||
version: values.version.trim() || null,
|
||||
expected_updated_at: skill.updated_at,
|
||||
...(values.description !== initial.description ? { description: values.description.trim() || null } : {}),
|
||||
...(values.domain !== initial.domain ? { domain: values.domain.trim() || null } : {}),
|
||||
...(values.namespace !== initial.namespace ? { namespace: values.namespace.trim() || null } : {}),
|
||||
...(values.keywords !== initial.keywords ? { keywords: parseKeywords(values.keywords) } : {}),
|
||||
...(values.authorName !== initial.authorName || values.authorEmail !== initial.authorEmail
|
||||
? {
|
||||
author: values.authorName.trim()
|
||||
? { name: values.authorName.trim(), email: values.authorEmail.trim() || null }
|
||||
: null,
|
||||
}
|
||||
: {}),
|
||||
...(values.category !== initial.category ? { category: values.category.trim() || null } : {}),
|
||||
...(values.homepage !== initial.homepage ? { homepage: values.homepage.trim() || null } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
export const buildSkillUploadMetadata = (values: SkillFormValues): SkillUploadMetadata | undefined => {
|
||||
if (!values.name.trim()) return undefined;
|
||||
return {
|
||||
name: values.name.trim(),
|
||||
...(values.version.trim() ? { version: values.version.trim() } : {}),
|
||||
...(values.description.trim() ? { description: values.description.trim() } : {}),
|
||||
...(values.domain.trim() ? { domain: values.domain.trim() } : {}),
|
||||
...(values.namespace.trim() ? { namespace: values.namespace.trim() } : {}),
|
||||
...(values.keywords.trim() ? { keywords: parseKeywords(values.keywords) } : {}),
|
||||
...(values.authorName.trim()
|
||||
? {
|
||||
author: {
|
||||
name: values.authorName.trim(),
|
||||
...(values.authorEmail.trim() ? { email: values.authorEmail.trim() } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(values.category.trim() ? { category: values.category.trim() } : {}),
|
||||
...(values.homepage.trim() ? { homepage: values.homepage.trim() } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
export const buildSkillImport = (values: SkillFormValues): SkillImport | null => {
|
||||
const source = parseSkillImportSource(values.url, values.path, values.ref, values.skill);
|
||||
if (!source) return null;
|
||||
const metadata = buildSkillUploadMetadata(values);
|
||||
return {
|
||||
...source.selection,
|
||||
...(values.version.trim() ? { version: values.version.trim() } : {}),
|
||||
...(metadata ? { metadata } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
export const buildSkillReference = (values: SkillFormValues): SkillHubRegisterRequest["source"] | null => {
|
||||
const preview = parseSkillSource(values.url, values.path, values.ref);
|
||||
if (!preview) return null;
|
||||
return {
|
||||
...preview.parsed,
|
||||
...(preview.parsed.source === "archive" && values.sha256.trim() ? { sha256: values.sha256.trim() } : {}),
|
||||
};
|
||||
};
|
||||
|
||||
export const buildSkillRegistration = (values: SkillFormValues): SkillHubRegisterRequest | null => {
|
||||
const source = buildSkillReference(values);
|
||||
const metadata = buildSkillUploadMetadata(values);
|
||||
return source && metadata ? { ...metadata, source } : null;
|
||||
};
|
||||
|
||||
export const buildSkillUpdate = (values: SkillFormValues, skill: SkillHubSkill): SkillUpdate => ({
|
||||
...buildSkillMetadata(values, skill),
|
||||
...(values.mode === "replace" ? { source: buildSkillReference(values) } : {}),
|
||||
});
|
||||
|
||||
export const buildSkillMetadata = (values: SkillFormValues, skill: SkillHubSkill): SkillMetadata => ({
|
||||
description: values.description.trim() || null,
|
||||
domain: values.domain.trim() || null,
|
||||
namespace: values.namespace.trim() || null,
|
||||
keywords:
|
||||
values.keywords === skillFormValues(skill).keywords ? skill.keywords ?? null : parseKeywords(values.keywords),
|
||||
version: values.version.trim() || null,
|
||||
expected_updated_at: skill.updated_at,
|
||||
});
|
||||
const CREATION_METADATA_FIELDS = [
|
||||
"description",
|
||||
"domain",
|
||||
"namespace",
|
||||
"keywords",
|
||||
"authorName",
|
||||
"authorEmail",
|
||||
"category",
|
||||
"homepage",
|
||||
] as const;
|
||||
|
||||
export const buildSkillImport = (values: SkillFormValues): SkillImport => ({
|
||||
url: values.url,
|
||||
...(values.skill.trim() ? { skill: values.skill.trim() } : {}),
|
||||
...(values.ref.trim() ? { ref: values.ref.trim() } : {}),
|
||||
...(values.path.trim() ? { path: values.path.trim() } : {}),
|
||||
...(values.version.trim() ? { version: values.version.trim() } : {}),
|
||||
});
|
||||
type SkillFormIssue = (path: keyof SkillFormValues, key: FormErrorKey) => void;
|
||||
|
||||
function validateSkillSource(values: SkillFormValues, issue: SkillFormIssue) {
|
||||
if (values.mode === "upload") {
|
||||
if (!values.archiveFile?.name.toLowerCase().endsWith(".zip")) issue("archiveFile", "errors.zipRequired");
|
||||
if (values.archiveFile && values.archiveFile.size > 10 * 1024 * 1024) issue("archiveFile", "errors.zipTooLarge");
|
||||
return;
|
||||
}
|
||||
if (values.mode !== "metadata") validateSkillUrl(values, issue);
|
||||
}
|
||||
|
||||
function validateSkillUrl(values: SkillFormValues, issue: SkillFormIssue) {
|
||||
if (values.mode === "import" && !values.url.trim()) return issue("url", "errors.urlRequired");
|
||||
const imported =
|
||||
values.mode === "import" ? parseSkillImportSource(values.url, values.path, values.ref, values.skill) : null;
|
||||
if (values.mode === "import" && !imported) return issue("url", "errors.importUrlInvalid");
|
||||
const preview = imported ? imported.preview : parseSkillSource(values.url, values.path, values.ref);
|
||||
if (!preview) {
|
||||
if (!imported) issue("url", "toasts.invalidUrl");
|
||||
return;
|
||||
}
|
||||
const source = preview.parsed;
|
||||
if (requiresBrowserRefConfirmation(preview, values.ref)) {
|
||||
issue("ref", "errors.browserRefRequired");
|
||||
}
|
||||
if (values.mode !== "import" && source.source === "archive" && !isValidSha256(values.sha256)) {
|
||||
issue("sha256", "errors.sha256Invalid");
|
||||
}
|
||||
}
|
||||
|
||||
function validateRegistryName(values: SkillFormValues, issue: SkillFormIssue) {
|
||||
const needsName = values.mode === "register" || CREATION_METADATA_FIELDS.some((field) => values[field].trim());
|
||||
if (needsName && !values.name.trim()) issue("name", "errors.metadataNameRequired");
|
||||
if (values.name.trim() && !validatePluginName(values.name.trim())) issue("name", "errors.nameInvalid");
|
||||
}
|
||||
|
||||
function validateSkillMetadata(values: SkillFormValues, skill: SkillHubSkill | undefined, issue: SkillFormIssue) {
|
||||
const initial = skillFormValues(skill);
|
||||
if (values.authorName === initial.authorName && values.authorEmail === initial.authorEmail) return;
|
||||
if (values.authorEmail.trim() && !values.authorName.trim()) issue("authorName", "errors.authorNameRequired");
|
||||
if (!isValidEmail(values.authorEmail.trim())) issue("authorEmail", "errors.emailInvalid");
|
||||
}
|
||||
|
||||
const skillFormShape = {
|
||||
mode: z.enum(["upload", "import", "register", "metadata", "replace"]),
|
||||
archiveFile: z.file().nullable(),
|
||||
url: z.string(),
|
||||
skill: z.string(),
|
||||
ref: z.string(),
|
||||
path: z.string(),
|
||||
name: z.string(),
|
||||
domain: z.string(),
|
||||
namespace: z.string(),
|
||||
description: z.string(),
|
||||
keywords: z.string(),
|
||||
version: z.string(),
|
||||
authorName: z.string(),
|
||||
authorEmail: z.string(),
|
||||
category: z.string(),
|
||||
homepage: z.string(),
|
||||
sha256: z.string(),
|
||||
};
|
||||
|
||||
export const skillFormSchema = (skill?: SkillHubSkill) =>
|
||||
z.object(skillFormShape).superRefine((values, context) => {
|
||||
const issue: SkillFormIssue = (path, key) =>
|
||||
context.addIssue({ code: "custom", path: [path], message: i18n.t(`skills.addForm.${key}`) });
|
||||
validateSkillSource(values, issue);
|
||||
if (values.version.trim() && !isValidSemanticVersion(values.version.trim()))
|
||||
issue("version", "toasts.invalidVersion");
|
||||
if (skill && values.mode === "upload") return;
|
||||
if (!skill) validateRegistryName(values, issue);
|
||||
validateSkillMetadata(values, skill, issue);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import shutil
|
|||
import signal
|
||||
import sys
|
||||
import tempfile
|
||||
import termios
|
||||
import time
|
||||
import zipfile
|
||||
from collections.abc import Mapping, Sequence
|
||||
|
|
@ -14,6 +15,10 @@ from pathlib import Path
|
|||
from typing import Final, TypeAlias, cast
|
||||
|
||||
Environment: TypeAlias = Mapping[str, str]
|
||||
SKILL_NAME: Final = "declared-fixture-skill"
|
||||
SKILL_CONTENT: Final = (
|
||||
f"---\nname: {SKILL_NAME}\ndescription: Fixture skill\nmetadata:\n internal: true\n---\nfixture skill\n"
|
||||
)
|
||||
|
||||
|
||||
def external_command(tool: str) -> None:
|
||||
|
|
@ -27,9 +32,13 @@ def external_command(tool: str) -> None:
|
|||
if os.environ["SKILL_FIXTURE_FAIL"] == "1":
|
||||
sys.exit(22)
|
||||
with zipfile.ZipFile(output, "w") as archive:
|
||||
archive.writestr("SKILL.md", "fixture skill")
|
||||
archive.writestr("SKILL.md", SKILL_CONTENT)
|
||||
return
|
||||
source: Final = Path(args[args.index("add") + 1])
|
||||
if "--skill" in args and args[args.index("--skill") + 1] != SKILL_NAME:
|
||||
sys.exit(1)
|
||||
if "--skill" not in args and os.environ.get("INSTALL_INTERNAL_SKILLS") not in ("1", "true"):
|
||||
sys.exit(1)
|
||||
if "--copy" in args:
|
||||
shutil.copytree(source, root / "installed")
|
||||
else:
|
||||
|
|
@ -76,6 +85,12 @@ def run(command: str, fail: bool) -> None:
|
|||
break
|
||||
output += chunk
|
||||
if not sent and b"LiteLLM API key: " in output:
|
||||
while (
|
||||
cast(int, termios.tcgetattr(terminal)[3]) & termios.ECHO
|
||||
): # cast-ok: lflag is an integer bitmask
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("Terminal echo remained enabled")
|
||||
time.sleep(0.001)
|
||||
os.write(terminal, f"{secret}\n".encode())
|
||||
sent = True
|
||||
finally:
|
||||
|
|
@ -89,15 +104,24 @@ def run(command: str, fail: bool) -> None:
|
|||
curl_args: Final = cast(Sequence[str], curl["args"]) # cast-ok: fixture records argv
|
||||
installed: Final = root / "installed" / "SKILL.md"
|
||||
temporary: Final = Path(curl_args[curl_args.index("--output") + 1]).parent
|
||||
sys.stdout.write(json.dumps({
|
||||
"status": os.waitstatus_to_exitcode(status),
|
||||
"header": curl["header"],
|
||||
"installArgs": npx["args"] if npx else None,
|
||||
"telemetry": cast(Environment, npx["env"]).get("DISABLE_TELEMETRY") if npx else None, # cast-ok: own env
|
||||
"secretLeaked": secret in json.dumps((output.decode(), curl_args, curl["env"], npx)),
|
||||
"retained": installed.read_text() if installed.exists() else None,
|
||||
"temporaryRemoved": not temporary.exists(),
|
||||
}))
|
||||
sys.stdout.write(
|
||||
json.dumps(
|
||||
{
|
||||
"status": os.waitstatus_to_exitcode(status),
|
||||
"header": curl["header"],
|
||||
"downloadInternalSkills": cast(Environment, curl["env"]).get(
|
||||
"INSTALL_INTERNAL_SKILLS"
|
||||
), # cast-ok: own env
|
||||
"installArgs": npx["args"] if npx else None,
|
||||
"telemetry": cast(Environment, npx["env"]).get("DISABLE_TELEMETRY")
|
||||
if npx
|
||||
else None, # cast-ok: own env
|
||||
"secretLeaked": secret in json.dumps((output.decode(), curl_args, curl["env"], npx)),
|
||||
"retained": installed.read_text() if installed.exists() else None,
|
||||
"temporaryRemoved": not temporary.exists(),
|
||||
}
|
||||
)
|
||||
)
|
||||
marker: Final = temporary / ".skill-install-fixture"
|
||||
if marker.exists() and marker.read_text() == str(root):
|
||||
shutil.rmtree(temporary)
|
||||
|
|
|
|||
|
|
@ -16,12 +16,18 @@ describe("skill install commands", () => {
|
|||
it("quotes the public index name without executing shell substitutions", () => {
|
||||
const name = "review' $(printf injected) `printf injected`";
|
||||
const command = buildSkillInstallCommand({ ...options, global: true, publicSkill: { name } });
|
||||
const result = spawnSync("bash", ["-c", `npx() { printf '%s\\n' "$DISABLE_TELEMETRY" "$@"; }; ${command}`], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const result = spawnSync(
|
||||
"bash",
|
||||
["-c", `npx() { printf '%s\\n' "$DISABLE_TELEMETRY" "$INSTALL_INTERNAL_SKILLS" "$@"; }; ${command}`],
|
||||
{
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, INSTALL_INTERNAL_SKILLS: "0" },
|
||||
},
|
||||
);
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stdout.trim().split("\n")).toEqual([
|
||||
"1",
|
||||
"0",
|
||||
"skills@1.7.6",
|
||||
"add",
|
||||
options.gatewayUrl,
|
||||
|
|
@ -33,8 +39,12 @@ describe("skill install commands", () => {
|
|||
]);
|
||||
});
|
||||
|
||||
it.each(["success", "fail"])("executes a private install with safe credentials and cleanup on %s", (outcome) => {
|
||||
const command = buildSkillInstallCommand({ ...options, agent: "claude-code", global: true })!;
|
||||
it.each([
|
||||
["success", false],
|
||||
["success", true],
|
||||
["fail", true],
|
||||
] as const)("installs the internal root with safe credentials and cleanup: %s, global=%s", (outcome, global) => {
|
||||
const command = buildSkillInstallCommand({ ...options, agent: "claude-code", global })!;
|
||||
const result = spawnSync(
|
||||
"python3",
|
||||
[fileURLToPath(new URL("./skillInstall.fixture.py", import.meta.url)), outcome],
|
||||
|
|
@ -48,16 +58,21 @@ describe("skill install commands", () => {
|
|||
const expected = {
|
||||
status: outcome === "success" ? 0 : 22,
|
||||
header: "X-LiteLLM-Key: Bearer private-fixture-key\n",
|
||||
downloadInternalSkills: null,
|
||||
secretLeaked: false,
|
||||
temporaryRemoved: true,
|
||||
retained: outcome === "success" ? "fixture skill" : null,
|
||||
retained:
|
||||
outcome === "success"
|
||||
? "---\nname: declared-fixture-skill\ndescription: Fixture skill\nmetadata:\n internal: true\n---\nfixture skill\n"
|
||||
: null,
|
||||
telemetry: outcome === "success" ? "1" : null,
|
||||
};
|
||||
const receipt = JSON.parse(result.stdout) as typeof expected & { installArgs: string[] | null };
|
||||
expect(receipt).toMatchObject(expected);
|
||||
expect(receipt.installArgs).toEqual(
|
||||
outcome === "success" ? expect.arrayContaining(["--skill", "review", "-a", "claude-code", "-g"]) : null,
|
||||
outcome === "success" ? expect.arrayContaining(["-a", "claude-code", "--copy", "--yes"]) : null,
|
||||
);
|
||||
expect(receipt.installArgs?.includes("-g") ?? false).toBe(outcome === "success" && global);
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
|
|
|||
|
|
@ -77,6 +77,6 @@ printf '%s: Bearer %s\\n' ${shellQuote(options.authHeaderName)} "$skill_key" |
|
|||
${shellQuote(archive.href)} --output "$skill_tmp/skill.zip"
|
||||
unset skill_key
|
||||
unzip -q "$skill_tmp/skill.zip" -d "$skill_tmp/skill"
|
||||
DISABLE_TELEMETRY=1 npx --yes ${skillsPackage} add "$skill_tmp/skill" --skill ${shellQuote(options.name)} -a ${options.agent} --copy --yes${scope}
|
||||
DISABLE_TELEMETRY=1 INSTALL_INTERNAL_SKILLS=1 npx --yes ${skillsPackage} add "$skill_tmp/skill" -a ${options.agent} --copy --yes${scope}
|
||||
LITELLM_SKILL`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { chooseSelectOption, renderWithProviders, testQueryClient } from "@/../t
|
|||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { getProxyBaseUrl, setGlobalLitellmHeaderName } from "@/components/networking";
|
||||
import SkillDetail, { skillHubDetail } from "./skill_detail";
|
||||
import type { Plugin, PluginDownloadEvent, PluginDownloadsResponse } from "./types";
|
||||
import type { Plugin, PluginDownloadEvent, PluginDownloadsResponse, SkillHubSkill } from "./types";
|
||||
|
||||
const digest = "a".repeat(64);
|
||||
const archivePath = `/claude-code/plugins/my-skill/archive/${digest}.zip`;
|
||||
|
|
@ -26,6 +26,19 @@ const renderSkill = (source = skill.source, isAdmin = false) =>
|
|||
renderWithProviders(
|
||||
<SkillDetail skill={{ ...skill, source }} onBack={vi.fn()} accessToken="dashboard-token" isAdmin={isAdmin} />,
|
||||
);
|
||||
const renderHub = (overrides: Partial<SkillHubSkill> = {}) => {
|
||||
const hubSkill: SkillHubSkill = {
|
||||
...skill,
|
||||
security_scan_passed: false,
|
||||
visibility: "private",
|
||||
download_url: "/skill-hub/skills/my-skill/archive",
|
||||
content_url: "/skill-hub/skills/my-skill/content",
|
||||
...overrides,
|
||||
};
|
||||
return renderWithProviders(
|
||||
<SkillDetail skill={skillHubDetail(hubSkill)} onBack={vi.fn()} accessToken="dashboard-token" isAdmin />,
|
||||
);
|
||||
};
|
||||
const downloadsUrl = `${getProxyBaseUrl()}/skill-hub/skills/my-skill/downloads?limit=25`;
|
||||
const event = {
|
||||
id: "9007199254740993",
|
||||
|
|
@ -75,11 +88,11 @@ it.each(["legacy", "portable"])(
|
|||
URL.createObjectURL = vi.fn(() => "blob:skill-download");
|
||||
setGlobalLitellmHeaderName("X-LiteLLM-Key");
|
||||
const expectedUrl = kind === "portable" ? `${getProxyBaseUrl()}/skill-hub/skills/my-skill/archive` : url;
|
||||
const detail =
|
||||
kind === "portable"
|
||||
? skillHubDetail({ ...skill, visibility: "private", download_url: "/skill-hub/skills/my-skill/archive" })
|
||||
: skill;
|
||||
renderWithProviders(<SkillDetail skill={detail} onBack={vi.fn()} accessToken="dashboard-token" />);
|
||||
renderHub(kind === "legacy" ? { download_url: url, content_url: null } : {});
|
||||
if (kind === "legacy") {
|
||||
expect(screen.getByRole("tab", { name: "How to Use" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Install / Share" })).not.toBeInTheDocument();
|
||||
}
|
||||
skillRequestMock.mockResolvedValueOnce(Response.json({ detail: "Archive not found" }, { status: 404 }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Download ZIP" }));
|
||||
expect(screen.getByRole("button", { name: "Downloading…" })).toBeDisabled();
|
||||
|
|
@ -105,16 +118,42 @@ it.each(["legacy", "portable"])(
|
|||
|
||||
it("keeps an external archive as a link while retaining stored download history", async () => {
|
||||
const externalUrl = `https://external.example.com${archivePath}`;
|
||||
renderSkill({ ...skill.source, url: externalUrl }, true);
|
||||
const reference = {
|
||||
source: { ...skill.source, url: externalUrl },
|
||||
download_url: null,
|
||||
content_url: null,
|
||||
author: { name: "Maintainer", email: "maintainer@example.test" },
|
||||
category: "Review",
|
||||
homepage: "https://example.test/skill",
|
||||
};
|
||||
renderHub(reference);
|
||||
for (const name of ["Maintainer", "maintainer@example.test", "Review", "https://example.test/skill"])
|
||||
expect(screen.getByRole("cell", { name })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Install / Share" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("link")).toHaveAttribute("href", externalUrl);
|
||||
expect(screen.getByRole("link")).toHaveAttribute("target", "_blank");
|
||||
expect(screen.queryByRole("button", { name: "Download ZIP" })).not.toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole("tab", { name: "How to Use" }));
|
||||
expect(screen.getByText("/plugin install my-skill@litellm")).toBeInTheDocument();
|
||||
skillRequestMock.mockResolvedValueOnce(Response.json(page([event])));
|
||||
fireEvent.click(screen.getByRole("tab", { name: "Downloads" }));
|
||||
expect(await screen.findByRole("cell", { name: event.user_email })).toBeInTheDocument();
|
||||
expect(screen.getByText(/External downloads are not tracked/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders the stored GitLab ref and subdirectory as the source link", () => {
|
||||
const source = {
|
||||
source: "git-subdir",
|
||||
url: "https://gitlab.com/team/nested/repo.git",
|
||||
ref: "release-2",
|
||||
path: "plugins/example",
|
||||
};
|
||||
renderSkill(source);
|
||||
const href = "https://gitlab.com/team/nested/repo/-/tree/release-2/plugins/example";
|
||||
expect(screen.getByRole("link")).toHaveAttribute("href", href);
|
||||
expect(screen.getByRole("link")).toHaveTextContent(href.replace("https://", ""));
|
||||
});
|
||||
|
||||
it("shows attribution and string cursors, retains rows on failure, and hides populated history on role loss", async () => {
|
||||
setGlobalLitellmHeaderName("X-LiteLLM-Key");
|
||||
const view = renderSkill(skill.source, true);
|
||||
|
|
@ -198,13 +237,7 @@ it("copies the selected private install without sharing a session key and report
|
|||
const writeText = vi.spyOn(navigator.clipboard, "writeText").mockReturnValueOnce(pendingCopy.promise);
|
||||
setGlobalLitellmHeaderName("X-LiteLLM-Key");
|
||||
skillRequestMock.mockResolvedValue(Response.json({ detail: "Not Found" }, { status: 404 }));
|
||||
renderWithProviders(
|
||||
<SkillDetail
|
||||
skill={skillHubDetail({ ...skill, visibility: "private", download_url: "/skill-hub/skills/my-skill/archive" })}
|
||||
onBack={vi.fn()}
|
||||
accessToken="dashboard-token"
|
||||
/>,
|
||||
);
|
||||
renderHub();
|
||||
expect(skillRequestMock).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Install / Share" }));
|
||||
await chooseSelectOption(user, screen.getByRole("combobox", { name: "Coding agent" }), "Claude Code");
|
||||
|
|
@ -239,13 +272,7 @@ it("offers the indexed public skill name and discards its availability when reop
|
|||
skills: [{ name: "my-skill-2", type: "archive", url: `${getProxyBaseUrl()}${portablePath}?digest=sha256:abc` }],
|
||||
}),
|
||||
);
|
||||
renderWithProviders(
|
||||
<SkillDetail
|
||||
skill={skillHubDetail({ ...skill, visibility: "public", download_url: portablePath })}
|
||||
onBack={vi.fn()}
|
||||
accessToken="dashboard-token"
|
||||
/>,
|
||||
);
|
||||
renderHub({ visibility: "public", download_url: portablePath });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Install / Share" }));
|
||||
fireEvent.click(await screen.findByRole("radio", { name: "Public command" }));
|
||||
focusManager.setFocused(false);
|
||||
|
|
|
|||
|
|
@ -12,6 +12,11 @@ vi.mock("@/app/(dashboard)/hooks/claudeCodeMarketplace/useClaudeCodeMarketplaceR
|
|||
useClaudeCodeMarketplaceRequiresKey: () => mockUseMarketplaceRequiresKey(),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/networking", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/components/networking")>()),
|
||||
getProxyBaseUrl: () => "https://gateway.example.test/proxy/",
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
mockUseMarketplaceRequiresKey.mockReturnValue(false);
|
||||
});
|
||||
|
|
@ -76,7 +81,11 @@ describe("SkillDetail marketplace setup", () => {
|
|||
|
||||
it("offers the add command and a keyless snippet when the marketplace is open", () => {
|
||||
renderSetupTab();
|
||||
expect(screen.getByText(/^\/plugin marketplace add .*\/claude-code\/marketplace\.json$/)).toBeInTheDocument();
|
||||
const command = "/plugin marketplace add https://gateway.example.test/proxy/claude-code/marketplace.json";
|
||||
expect(screen.getByText(command)).toBeInTheDocument();
|
||||
expect(screen.getByText(/"extraKnownMarketplaces"/)).toHaveTextContent(
|
||||
'"url": "https://gateway.example.test/proxy/claude-code/marketplace.json"',
|
||||
);
|
||||
expect(screen.queryByText(/Bearer/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/\/plugin marketplace remove/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
|
@ -86,6 +95,9 @@ describe("SkillDetail marketplace setup", () => {
|
|||
renderSetupTab();
|
||||
expect(screen.queryByText(/\/plugin marketplace add/)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(/"Authorization": "Bearer <your-litellm-key>"/)).toBeInTheDocument();
|
||||
expect(screen.getByText(/"extraKnownMarketplaces"/)).toHaveTextContent(
|
||||
'"url": "https://gateway.example.test/proxy/claude-code/marketplace.json"',
|
||||
);
|
||||
expect(screen.getByText("/plugin marketplace remove litellm")).toBeInTheDocument();
|
||||
expect(screen.getByText(/uninstalls the plugins you installed from it/)).toBeInTheDocument();
|
||||
});
|
||||
|
|
|
|||
|
|
@ -20,13 +20,14 @@ import {
|
|||
import type { Plugin, SkillHubSkill } from "./types";
|
||||
import SkillVersionHistory from "./SkillVersionHistory";
|
||||
import SkillInstallDialog from "./SkillInstallDialog";
|
||||
import { userIdentityLabel, type UserIdentityLookup } from "@/app/(dashboard)/hooks/users/useUsers";
|
||||
|
||||
type SkillDetailData = Pick<
|
||||
SkillHubSkill,
|
||||
"id" | "name" | "source" | "version" | "description" | "domain" | "namespace" | "keywords" | "updated_at"
|
||||
> &
|
||||
Pick<Plugin, "enabled"> &
|
||||
Partial<Pick<Plugin, "created_at" | "category" | "author">> & {
|
||||
Partial<Pick<Plugin, "created_at" | "created_by" | "approved_by" | "category" | "author" | "homepage">> & {
|
||||
portable?: boolean;
|
||||
downloadAvailable?: boolean;
|
||||
};
|
||||
|
|
@ -34,17 +35,9 @@ type SkillDetailData = Pick<
|
|||
export const legacySkillDetail = (skill: Plugin): SkillDetailData => skill;
|
||||
|
||||
export const skillHubDetail = (skill: SkillHubSkill): SkillDetailData => ({
|
||||
id: skill.id,
|
||||
name: skill.name,
|
||||
source: skill.source,
|
||||
version: skill.version,
|
||||
description: skill.description,
|
||||
domain: skill.domain,
|
||||
namespace: skill.namespace,
|
||||
keywords: skill.keywords,
|
||||
updated_at: skill.updated_at,
|
||||
...skill,
|
||||
enabled: skill.visibility === "public",
|
||||
portable: true,
|
||||
portable: Boolean(skill.content_url),
|
||||
downloadAvailable: Boolean(skill.download_url),
|
||||
});
|
||||
|
||||
|
|
@ -79,8 +72,7 @@ const SkillSource: React.FC<
|
|||
setDownloading(false);
|
||||
}
|
||||
};
|
||||
const link = getSourceLink(source);
|
||||
const href = link && source.source === "git-subdir" && source.path ? `${link}/tree/main/${source.path}` : link;
|
||||
const href = getSourceLink(source);
|
||||
if (!archivePath && !href && !source.url) return null;
|
||||
return (
|
||||
<div className="mb-6">
|
||||
|
|
@ -117,6 +109,7 @@ const SkillSource: React.FC<
|
|||
};
|
||||
|
||||
interface SkillDetailProps {
|
||||
users?: UserIdentityLookup;
|
||||
skill: SkillDetailData;
|
||||
onBack: () => void;
|
||||
isAdmin?: boolean;
|
||||
|
|
@ -127,6 +120,7 @@ interface SkillDetailProps {
|
|||
}
|
||||
|
||||
const SkillDetail: React.FC<SkillDetailProps> = ({
|
||||
users = {},
|
||||
skill,
|
||||
onBack,
|
||||
accessToken,
|
||||
|
|
@ -161,10 +155,11 @@ const SkillDetail: React.FC<SkillDetailProps> = ({
|
|||
|
||||
const installCommand = formatInstallCommand(skill);
|
||||
|
||||
const settingsSnippet = buildMarketplaceSettingsSnippet(
|
||||
typeof window !== "undefined" ? window.location.origin : "<proxy-url>",
|
||||
marketplaceRequiresKey,
|
||||
);
|
||||
const proxyBaseUrl = getProxyBaseUrl().replace(/\/+$/, "");
|
||||
const marketplaceCommand = `/plugin marketplace add ${proxyBaseUrl}/claude-code/marketplace.json`;
|
||||
const settingsSnippet = buildMarketplaceSettingsSnippet(proxyBaseUrl, marketplaceRequiresKey);
|
||||
const creator = skill.created_by ? users[skill.created_by] : undefined;
|
||||
const author = skill.author ?? (creator ? { name: creator.user_alias, email: creator.user_email } : undefined);
|
||||
|
||||
const detailRows = [
|
||||
...(skill.category
|
||||
|
|
@ -177,9 +172,17 @@ const SkillDetail: React.FC<SkillDetailProps> = ({
|
|||
...(skill.version
|
||||
? [{ property: t("claudeCodePlugins.skillDetail.properties.version"), value: skill.version }]
|
||||
: []),
|
||||
...(skill.author?.name
|
||||
? [{ property: t("claudeCodePlugins.skillDetail.properties.author"), value: skill.author.name }]
|
||||
...(author?.name ? [{ property: t("claudeCodePlugins.skillDetail.properties.author"), value: author.name }] : []),
|
||||
...(author?.email
|
||||
? [{ property: t("claudeCodePlugins.skillDetail.properties.authorEmail"), value: author.email }]
|
||||
: []),
|
||||
...(accessToken && skill.created_by
|
||||
? [{ property: t("skills.table.columns.createdBy"), value: userIdentityLabel(skill.created_by, users) }]
|
||||
: []),
|
||||
...(accessToken && skill.approved_by
|
||||
? [{ property: t("skills.table.columns.approvedBy"), value: userIdentityLabel(skill.approved_by, users) }]
|
||||
: []),
|
||||
...(skill.homepage ? [{ property: t("skills.submissions.fields.homepage"), value: skill.homepage }] : []),
|
||||
...(skill.created_at
|
||||
? [
|
||||
{
|
||||
|
|
@ -451,13 +454,7 @@ const SkillDetail: React.FC<SkillDetailProps> = ({
|
|||
{t("claudeCodePlugins.skillDetail.runInClaudeCode")}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
const origin = typeof window !== "undefined" ? window.location.origin : "";
|
||||
copyToClipboard(
|
||||
`/plugin marketplace add ${origin}/claude-code/marketplace.json`,
|
||||
"marketplace-cmd",
|
||||
);
|
||||
}}
|
||||
onClick={() => copyToClipboard(marketplaceCommand, "marketplace-cmd")}
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center gap-1 border-none bg-transparent p-0 text-xs",
|
||||
copiedKey === "marketplace-cmd" ? "text-success" : "text-info",
|
||||
|
|
@ -470,7 +467,7 @@ const SkillDetail: React.FC<SkillDetailProps> = ({
|
|||
</button>
|
||||
</div>
|
||||
<pre className="m-0 bg-card px-4 py-3.5 font-mono text-[13px] text-foreground">
|
||||
{`/plugin marketplace add ${typeof window !== "undefined" ? window.location.origin : "<proxy-url>"}/claude-code/marketplace.json`}
|
||||
{marketplaceCommand}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ export interface PluginSource {
|
|||
repo?: string; // Format: "org/repo" for GitHub
|
||||
url?: string; // Full URL for other sources
|
||||
path?: string; // Subdirectory path for git-subdir
|
||||
ref?: string;
|
||||
sha?: string;
|
||||
sha256?: string;
|
||||
}
|
||||
|
||||
|
|
@ -28,9 +30,17 @@ export type SkillRegisterRequest = Omit<components["schemas"]["RegisterPluginReq
|
|||
export type SkillListQuery = NonNullable<operations["list_skills_skill_hub_skills_get"]["parameters"]["query"]>;
|
||||
|
||||
export type SkillHubSkill = components["schemas"]["SkillHubSkill"];
|
||||
export type SkillMetadata = components["schemas"]["SkillHubMetadata"];
|
||||
export type SkillImport = Omit<components["schemas"]["ImportSkillRequest"], "ref"> &
|
||||
Partial<Pick<components["schemas"]["ImportSkillRequest"], "ref">>;
|
||||
export type SkillMetadata = Omit<components["schemas"]["SkillHubSubmissionEdit"], "expected_revision">;
|
||||
export type SkillUpdate = components["schemas"]["SkillHubUpdate"];
|
||||
type SkillCreationMetadata = NonNullable<components["schemas"]["ImportSkillRequest"]["metadata"]>;
|
||||
export type SkillUploadMetadata = Omit<SkillCreationMetadata, "version"> &
|
||||
Partial<Pick<SkillCreationMetadata, "version">>;
|
||||
export type SkillHubRegisterRequest = SkillUploadMetadata &
|
||||
Pick<components["schemas"]["SkillHubRegistration"], "source">;
|
||||
export type SkillImport = Omit<components["schemas"]["ImportSkillRequest"], "ref" | "metadata"> &
|
||||
Partial<Pick<components["schemas"]["ImportSkillRequest"], "ref">> & {
|
||||
metadata?: SkillUploadMetadata | null;
|
||||
};
|
||||
export type SkillMutationResponse = SkillHubSkill | components["schemas"]["SkillHubPendingSkill"];
|
||||
export type SkillSubmission = components["schemas"]["SkillHubSubmission"];
|
||||
|
||||
|
|
|
|||
|
|
@ -97,8 +97,11 @@ import { EmailEventSettingsResponse, EmailEventSettingsUpdateRequest } from "./e
|
|||
import type {
|
||||
ListPluginsResponse,
|
||||
SkillRegisterRequest,
|
||||
SkillHubRegisterRequest,
|
||||
SkillMutationResponse,
|
||||
SkillImport,
|
||||
SkillUpdate,
|
||||
SkillUploadMetadata,
|
||||
} from "./claude_code_plugins/types";
|
||||
import type { ModelBudgetUsage, ModelMaxBudget } from "./key_team_helpers/ModelMaxBudgetEditor";
|
||||
import type { StoredModelMaxBudget } from "./key_team_helpers/modelMaxBudgetPayload";
|
||||
|
|
@ -6917,24 +6920,22 @@ export const getSkillHubSkill = (accessToken: string, name: string) =>
|
|||
accessToken,
|
||||
});
|
||||
|
||||
export const importSkillHubSkill = (accessToken: string, body: SkillImport) =>
|
||||
export const importSkillHubSkill = (accessToken: string, body: SkillImport | SkillHubRegisterRequest) =>
|
||||
apiClient.post<SkillMutationResponse>("/skill-hub/skills/import", { accessToken, body });
|
||||
|
||||
export const updateSkillHubSkill = (
|
||||
accessToken: string,
|
||||
name: string,
|
||||
body: components["schemas"]["SkillHubMetadata"],
|
||||
) => apiClient.put<SkillMutationResponse>(`/skill-hub/skills/${encodeURIComponent(name)}`, { accessToken, body });
|
||||
export const updateSkillHubSkill = (accessToken: string, name: string, body: SkillUpdate) =>
|
||||
apiClient.put<SkillMutationResponse>(`/skill-hub/skills/${encodeURIComponent(name)}`, { accessToken, body });
|
||||
|
||||
export const uploadSkillHubSkill = (
|
||||
accessToken: string,
|
||||
file: File,
|
||||
version: string,
|
||||
skill?: components["schemas"]["SkillHubSkill"],
|
||||
{ skill, metadata }: { skill?: components["schemas"]["SkillHubSkill"]; metadata?: SkillUploadMetadata } = {},
|
||||
): Promise<SkillMutationResponse> => {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
if (version.trim()) body.append("version", version.trim());
|
||||
if (!skill && metadata) body.append("metadata", JSON.stringify(metadata));
|
||||
if (skill?.updated_at) body.append("expected_updated_at", skill.updated_at);
|
||||
return skill
|
||||
? apiClient.put(`/skill-hub/skills/${encodeURIComponent(skill.name)}/upload`, { accessToken, rawBody: body })
|
||||
|
|
@ -6975,12 +6976,12 @@ export const uploadSkillSubmission = (
|
|||
accessToken: string,
|
||||
submission: components["schemas"]["SkillHubSubmission"],
|
||||
file: File,
|
||||
version: string,
|
||||
version?: string,
|
||||
): Promise<components["schemas"]["SkillHubSubmission"]> => {
|
||||
const body = new FormData();
|
||||
body.append("file", file);
|
||||
body.append("expected_revision", String(submission.revision ?? 0));
|
||||
if (version.trim()) body.append("version", version.trim());
|
||||
if (version !== undefined) body.append("version", version.trim());
|
||||
return apiClient.put(`/skill-hub/submissions/${encodeURIComponent(submission.id)}/upload`, {
|
||||
accessToken,
|
||||
rawBody: body,
|
||||
|
|
|
|||
|
|
@ -615,15 +615,26 @@ describe("PublicAiHub", () => {
|
|||
it("opens the chosen skill with its source and install commands and updates the URL", async () => {
|
||||
const onUrlUpdate = vi.fn();
|
||||
const user = userEvent.setup();
|
||||
const source = {
|
||||
source: "git-subdir",
|
||||
url: "https://gitlab.com/team/nested/research-tools.git",
|
||||
ref: "release-2",
|
||||
path: "plugins/research",
|
||||
};
|
||||
apiGetMock.mockImplementation((path: string, options?: Query) =>
|
||||
path === SKILL_HUB_PATH ? Promise.resolve({ plugins: [{ ...SKILLS[0], source }] }) : respond(path, options),
|
||||
);
|
||||
renderWithProviders(<PublicAiHub accessToken={null} />, { searchParams: { tab: "skills" }, onUrlUpdate });
|
||||
await user.click(await screen.findByRole("link", { name: /research-assistant/ }));
|
||||
|
||||
const dialog = await screen.findByRole("dialog", { name: "Details" });
|
||||
expect(within(dialog).getByRole("heading", { name: "research-assistant", level: 2 })).toBeInTheDocument();
|
||||
expect(within(dialog).getByRole("button", { name: "github.com/example/research-tools" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://github.com/example/research-tools",
|
||||
);
|
||||
expect(
|
||||
within(dialog).getByRole("button", {
|
||||
name: "gitlab.com/team/nested/research-tools/-/tree/release-2/plugins/research",
|
||||
exact: true,
|
||||
}),
|
||||
).toHaveAttribute("href", "https://gitlab.com/team/nested/research-tools/-/tree/release-2/plugins/research");
|
||||
expect(within(dialog).getByText("knowledge")).toBeInTheDocument();
|
||||
expect(within(dialog).getByText("Research")).toBeInTheDocument();
|
||||
expect(
|
||||
|
|
|
|||
|
|
@ -14,8 +14,7 @@ import { marketplaceCommand, skillInstallCommand } from "./hubSnippets";
|
|||
import { InspectorHeader } from "./InspectorHeader";
|
||||
|
||||
function sourceValue(source: Plugin["source"]) {
|
||||
const link = getSourceLink(source);
|
||||
const href = link && source.source === "git-subdir" && source.path ? `${link}/tree/main/${source.path}` : link;
|
||||
const href = getSourceLink(source);
|
||||
if (!href) return getSourceDisplayText(source) || null;
|
||||
return (
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -1767,6 +1767,7 @@
|
|||
"securityScan": "Security scan"
|
||||
},
|
||||
"notRecorded": "Not recorded",
|
||||
"identitySortHelp": "Sort by user ID. Emails are display labels only.",
|
||||
"scanHelp": "Yes means this published version has a completed scan with no findings and a risk score of 0. No means it has not passed a recorded scan."
|
||||
},
|
||||
"addForm": {
|
||||
|
|
@ -1790,12 +1791,16 @@
|
|||
"keywords": "Tags (Optional)",
|
||||
"version": "Version (Optional)",
|
||||
"authorName": "Author Name (Optional)",
|
||||
"authorEmail": "Author Email (Optional)"
|
||||
"authorEmail": "Author Email (Optional)",
|
||||
"homepage": "Homepage (Optional)"
|
||||
},
|
||||
"hints": {
|
||||
"archive": "Choose a ZIP from your computer, up to 10 MiB. Include SKILL.md at the root or inside one skill folder, along with any supporting files. The skill will use the same visibility settings as skills added by URL.",
|
||||
"sourceUrl": "Link to a Git repository, a skill folder, or a ZIP archive containing SKILL.md and any supporting files. For private repositories, use an SSH clone URL with access configured in your agent.",
|
||||
"subPath": "Path within the repository where the skill lives (e.g., skills/my-skill). Leave empty if the skill is at the repo root.",
|
||||
"subPath": "Optional directory within the repository, such as skills/my-skill.",
|
||||
"skill": "Match the name inside SKILL.md. If you also select a path, both must match. Clear this field to select by path only.",
|
||||
"skillFromUrl": "This skills.sh URL supplies the skill name. Change the URL to select a different skill.",
|
||||
"ref": "For browser URLs, match the ref in the URL, including any slashes. For clone URLs, choose a branch, tag, or 40-character commit SHA.",
|
||||
"sha256": "Optional SHA-256 digest for verifying the ZIP archive’s integrity.",
|
||||
"name": "Unique identifier in kebab-case format (e.g., my-skill)",
|
||||
"domain": "Top-level grouping in the Skills Hub (e.g., Productivity)",
|
||||
|
|
@ -1829,12 +1834,15 @@
|
|||
"zipRequired": "Please choose a .zip file",
|
||||
"zipTooLarge": "The ZIP file must be 10 MiB or smaller",
|
||||
"urlRequired": "Please enter a repository or zip archive URL",
|
||||
"browserRefRequired": "Enter the full Git ref from this URL, including any slashes, to confirm where the repository path starts",
|
||||
"importUrlInvalid": "Use a public GitHub repository, tree or SKILL.md URL, or a skills.sh skill URL. Check the ref and remove query parameters and fragments.",
|
||||
"subPathInvalid": "Subfolder must be a relative path like skills/my-skill (letters, numbers, dots, hyphens, underscores)",
|
||||
"sha256Invalid": "SHA-256 must be a 64-character hex digest",
|
||||
"nameRequired": "Please enter skill name",
|
||||
"nameInvalid": "Name must be kebab-case (lowercase, numbers, hyphens only)",
|
||||
"emailInvalid": "Please enter a valid email",
|
||||
"descriptionTooLong": "Description must be 1024 characters or fewer"
|
||||
"metadataNameRequired": "Enter a registry name to register a source or set custom metadata",
|
||||
"authorNameRequired": "Enter an author name when providing an email"
|
||||
},
|
||||
"toasts": {
|
||||
"noToken": "No access token available",
|
||||
|
|
@ -1857,21 +1865,35 @@
|
|||
"versionOverrideHint": "Leave blank to assign the next patch version when this change is published",
|
||||
"modes": {
|
||||
"upload": "Upload ZIP",
|
||||
"import": "Import URL",
|
||||
"metadata": "Edit metadata"
|
||||
"metadata": "Edit metadata",
|
||||
"register": "Add from URL",
|
||||
"replace": "Replace source"
|
||||
},
|
||||
"neutralLabels": {
|
||||
"url": "Source URL",
|
||||
"skill": "Skill selector (optional)",
|
||||
"ref": "Git ref (optional)",
|
||||
"ref": "Git ref",
|
||||
"path": "Path (optional)",
|
||||
"domain": "Domain (optional)",
|
||||
"namespace": "Namespace (optional)",
|
||||
"keywords": "Tags (optional)"
|
||||
},
|
||||
"uploadHint": "Choose a ZIP up to 10 MiB containing SKILL.md. Its frontmatter supplies the skill name and description.",
|
||||
"replacementHint": "The replacement SKILL.md supplies the description. Domain, namespace, and keywords are preserved.",
|
||||
"importHint": "Enter the original source URL. Use a skill selector or path when the repository contains several skills. Leave the ref blank to use HEAD.",
|
||||
"uploadHint": "Choose a ZIP up to 10 MiB containing SKILL.md. Its frontmatter supplies the skill name and description. For a legacy ZIP without frontmatter, enter a registry name below.",
|
||||
"replacementHint": "The replacement SKILL.md updates its default description. Custom descriptions and other metadata are preserved.",
|
||||
"urlStorage": "URL storage",
|
||||
"urlModes": {
|
||||
"register": "Use the external source",
|
||||
"import": "Store a copy in LiteLLM"
|
||||
},
|
||||
"urlStorageHint": "Store public GitHub or skills.sh content in LiteLLM, or let clients install from an external repository or archive. skills.sh links require a stored copy.",
|
||||
"importHint": "Store a portable skill from public GitHub or skills.sh for downloads and installation across supported agents. Use a selector or path for repositories with several skills. Browser URLs supply their revision; repository URLs use HEAD unless you set a ref.",
|
||||
"registerHint": "Register a Git repository, subfolder, or HTTPS ZIP for clients to install. LiteLLM stores the reference without downloading its contents.",
|
||||
"replaceHint": "Replace the published source with this reference. This removes the current managed archive and portable descriptor when published. Previous versions remain available.",
|
||||
"registryName": "Registry name",
|
||||
"optionalRegistryName": "Registry name (optional)",
|
||||
"registryNameHint": "Use a unique kebab-case name. An explicit name is required for custom metadata and legacy ZIPs. It does not change the files.",
|
||||
"advancedMetadata": "Advanced metadata (optional)",
|
||||
"authorOverrideHint": "Leave author fields empty to use the submitter's profile. Fill them in to credit a different author. The submitter is recorded automatically from the authenticated account.",
|
||||
"saving": "Saving..."
|
||||
},
|
||||
"scanning": {
|
||||
|
|
@ -1917,7 +1939,8 @@
|
|||
"noCurrent": "No currently published skill is available for comparison",
|
||||
"pendingNotice": "Awaiting admin approval. The published skill remains unchanged",
|
||||
"submittedBy": "Submitted by {{name}}",
|
||||
"reviewedBy": "Reviewed by {{name}} on {{date}}",
|
||||
"approvedBy": "Approved by {{name}} on {{date}}",
|
||||
"rejectedBy": "Rejected by {{name}} on {{date}}",
|
||||
"rejectionReason": "Rejection reason: {{reason}}",
|
||||
"reasonLabel": "Rejection reason (optional)",
|
||||
"approve": "Approve and publish",
|
||||
|
|
@ -1949,7 +1972,6 @@
|
|||
"category": "Category",
|
||||
"domain": "Domain",
|
||||
"namespace": "Namespace",
|
||||
"installation_preference": "Installation preference",
|
||||
"agent_skill": "Portable skill descriptor"
|
||||
},
|
||||
"nextPatchVersion": "Next patch version on approval",
|
||||
|
|
@ -1973,7 +1995,7 @@
|
|||
"allScans": "All scan statuses",
|
||||
"scanned": "Security scan: Yes",
|
||||
"notScanned": "Security scan: No",
|
||||
"search": "Search skills, tags, or people…",
|
||||
"search": "Search skills, tags, or user IDs…",
|
||||
"clear": "Clear filters"
|
||||
}
|
||||
},
|
||||
|
|
@ -2045,6 +2067,7 @@
|
|||
"namespace": "Namespace",
|
||||
"version": "Version",
|
||||
"author": "Author",
|
||||
"authorEmail": "Author email",
|
||||
"added": "Added"
|
||||
},
|
||||
"overview": {
|
||||
|
|
|
|||
211
litellm/ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
211
litellm/ui/litellm-dashboard/src/lib/http/schema.d.ts
generated
vendored
|
|
@ -16324,7 +16324,7 @@ export interface paths {
|
|||
put?: never;
|
||||
/**
|
||||
* Import Skill
|
||||
* @description Import a public skills.sh or GitHub skill as a portable snapshot.
|
||||
* @description Register a source reference, or import a public skills.sh/GitHub URL as a portable snapshot.
|
||||
*/
|
||||
post: operations["import_skill_skill_hub_skills_import_post"];
|
||||
delete?: never;
|
||||
|
|
@ -16367,7 +16367,7 @@ export interface paths {
|
|||
get: operations["get_skill_skill_hub_skills__name__get"];
|
||||
/**
|
||||
* Replace Skill Metadata
|
||||
* @description Replace registry metadata, preserving files. Members submit an immutable proposal for admin review.
|
||||
* @description Update supplied registry fields. Omitted metadata is retained, null clears it, and version defaults to a bump.
|
||||
*/
|
||||
put: operations["replace_skill_metadata_skill_hub_skills__name__put"];
|
||||
post?: never;
|
||||
|
|
@ -16471,7 +16471,7 @@ export interface paths {
|
|||
get?: never;
|
||||
/**
|
||||
* Replace Skill Archive
|
||||
* @description Replace skill files, retaining registry fields. Members propose an update against the original editor timestamp.
|
||||
* @description Replace files and refresh their inherited description, retaining registry overrides and other metadata.
|
||||
*/
|
||||
put: operations["replace_skill_archive_skill_hub_skills__name__upload_put"];
|
||||
post?: never;
|
||||
|
|
@ -16530,7 +16530,7 @@ export interface paths {
|
|||
};
|
||||
/**
|
||||
* Download Skill Version
|
||||
* @description Download a retained publication as a portable ZIP with SKILL.md at its root.
|
||||
* @description Download a retained skill ZIP, preserving legacy packages without portable frontmatter.
|
||||
*/
|
||||
get: operations["download_skill_version_skill_hub_skills__name__versions__version_id__archive_get"];
|
||||
put?: never;
|
||||
|
|
@ -16618,7 +16618,7 @@ export interface paths {
|
|||
get: operations["get_submission_skill_hub_submissions__submission_id__get"];
|
||||
/**
|
||||
* Edit Submission
|
||||
* @description Replace a pending proposal's metadata, preserving files. Only its original submitting user may edit.
|
||||
* @description Update supplied proposal metadata. Omit/null version uses automatic versioning on approval.
|
||||
*/
|
||||
put: operations["edit_submission_skill_hub_submissions__submission_id__put"];
|
||||
post?: never;
|
||||
|
|
@ -16657,7 +16657,7 @@ export interface paths {
|
|||
};
|
||||
/**
|
||||
* Download Submission
|
||||
* @description Download an owned proposal as a private portable ZIP. Legacy nonportable archives return 404.
|
||||
* @description Download an owned proposal as a private ZIP, preserving legacy packages without portable frontmatter.
|
||||
*/
|
||||
get: operations["download_submission_skill_hub_submissions__submission_id__archive_get"];
|
||||
put?: never;
|
||||
|
|
@ -29433,10 +29433,13 @@ export interface components {
|
|||
expected_revision: number;
|
||||
/**
|
||||
* File
|
||||
* @description Replacement Agent Skills ZIP with the same declared skill name
|
||||
* @description Replacement ZIP retaining the registered and declared skill names
|
||||
*/
|
||||
file: string;
|
||||
/** Version */
|
||||
/**
|
||||
* Version
|
||||
* @description Explicit SemVer, or omit/send empty for automatic versioning on approval
|
||||
*/
|
||||
version?: string | null;
|
||||
};
|
||||
/** Body_image_edit_api_images_edits_post */
|
||||
|
|
@ -29483,7 +29486,7 @@ export interface components {
|
|||
expected_updated_at?: string | null;
|
||||
/**
|
||||
* File
|
||||
* @description Replacement Agent Skills ZIP with the same declared skill name
|
||||
* @description Replacement ZIP retaining the registered and declared skill names
|
||||
*/
|
||||
file: string;
|
||||
/** Version */
|
||||
|
|
@ -29601,6 +29604,11 @@ export interface components {
|
|||
* @description Agent Skills ZIP with SKILL.md and optional supporting files
|
||||
*/
|
||||
file: string;
|
||||
/**
|
||||
* Metadata
|
||||
* @description Optional JSON registry metadata
|
||||
*/
|
||||
metadata?: string | null;
|
||||
/** Version */
|
||||
version?: string | null;
|
||||
};
|
||||
|
|
@ -36068,6 +36076,8 @@ export interface components {
|
|||
};
|
||||
/** ImportSkillRequest */
|
||||
ImportSkillRequest: {
|
||||
/** @description Optional registry name and metadata overrides */
|
||||
metadata?: components["schemas"]["SkillHubUpload"] | null;
|
||||
/**
|
||||
* Path
|
||||
* @description Repository-relative skill directory
|
||||
|
|
@ -48929,27 +48939,6 @@ export interface components {
|
|||
*/
|
||||
tags: string[];
|
||||
};
|
||||
/** SkillHubMetadata */
|
||||
SkillHubMetadata: {
|
||||
/** Description */
|
||||
description?: string | null;
|
||||
/** Domain */
|
||||
domain?: string | null;
|
||||
/**
|
||||
* Expected Updated At
|
||||
* @description Published updated_at read by the editor. A stale value returns 409
|
||||
*/
|
||||
expected_updated_at?: string | null;
|
||||
/** Keywords */
|
||||
keywords?: string[] | null;
|
||||
/** Namespace */
|
||||
namespace?: string | null;
|
||||
/**
|
||||
* Version
|
||||
* @description Explicit higher SemVer, or omit/null for an automatic patch bump
|
||||
*/
|
||||
version?: string | null;
|
||||
};
|
||||
/** SkillHubPendingSkill */
|
||||
SkillHubPendingSkill: {
|
||||
/**
|
||||
|
|
@ -48971,10 +48960,15 @@ export interface components {
|
|||
/** SkillHubProposal */
|
||||
SkillHubProposal: {
|
||||
agent_skill?: components["schemas"]["SkillHubAgentSkill"] | null;
|
||||
author?: components["schemas"]["PluginAuthor"] | null;
|
||||
/** Category */
|
||||
category?: string | null;
|
||||
/** Description */
|
||||
description: string | null;
|
||||
/** Domain */
|
||||
domain?: string | null;
|
||||
/** Homepage */
|
||||
homepage?: string | null;
|
||||
/** Keywords */
|
||||
keywords?: string[] | null;
|
||||
/** Name */
|
||||
|
|
@ -48990,6 +48984,40 @@ export interface components {
|
|||
};
|
||||
/** SkillHubPublication */
|
||||
SkillHubPublication: Record<string, never>;
|
||||
/** SkillHubRegistration */
|
||||
SkillHubRegistration: {
|
||||
author?: components["schemas"]["PluginAuthor"] | null;
|
||||
/** Category */
|
||||
category?: string | null;
|
||||
/** Description */
|
||||
description?: string | null;
|
||||
/** Domain */
|
||||
domain?: string | null;
|
||||
/** Homepage */
|
||||
homepage?: string | null;
|
||||
/** Keywords */
|
||||
keywords?: string[] | null;
|
||||
/**
|
||||
* Name
|
||||
* @description Registry skill name
|
||||
*/
|
||||
name: string;
|
||||
/** Namespace */
|
||||
namespace?: string | null;
|
||||
/**
|
||||
* Source
|
||||
* @description Repository or HTTPS archive source reference
|
||||
*/
|
||||
source: {
|
||||
[key: string]: string;
|
||||
};
|
||||
/**
|
||||
* Version
|
||||
* @description Semantic version, defaults to 1.0.0 on creation
|
||||
* @default 1.0.0
|
||||
*/
|
||||
version: string | null;
|
||||
};
|
||||
/** SkillHubRejection */
|
||||
SkillHubRejection: {
|
||||
/** Expected Revision */
|
||||
|
|
@ -49035,6 +49063,9 @@ export interface components {
|
|||
SkillHubSkill: {
|
||||
/** Approved By */
|
||||
approved_by?: string | null;
|
||||
author?: components["schemas"]["PluginAuthor"] | null;
|
||||
/** Category */
|
||||
category?: string | null;
|
||||
/** Content Url */
|
||||
content_url?: string | null;
|
||||
/** Created At */
|
||||
|
|
@ -49052,6 +49083,8 @@ export interface components {
|
|||
download_count?: number | null;
|
||||
/** Download Url */
|
||||
download_url?: string | null;
|
||||
/** Homepage */
|
||||
homepage?: string | null;
|
||||
/** Id */
|
||||
id: string;
|
||||
/** Keywords */
|
||||
|
|
@ -49137,9 +49170,22 @@ export interface components {
|
|||
};
|
||||
/** SkillHubSubmissionEdit */
|
||||
SkillHubSubmissionEdit: {
|
||||
/** Description */
|
||||
/** @description Omit to preserve, null to clear */
|
||||
author?: components["schemas"]["PluginAuthor"] | null;
|
||||
/**
|
||||
* Category
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
category?: string | null;
|
||||
/**
|
||||
* Description
|
||||
* @description Omit to preserve, null to clear the registry description
|
||||
*/
|
||||
description?: string | null;
|
||||
/** Domain */
|
||||
/**
|
||||
* Domain
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
domain?: string | null;
|
||||
/**
|
||||
* Expected Revision
|
||||
|
|
@ -49151,13 +49197,24 @@ export interface components {
|
|||
* @description Published updated_at read by the editor. A stale value returns 409
|
||||
*/
|
||||
expected_updated_at?: string | null;
|
||||
/** Keywords */
|
||||
/**
|
||||
* Homepage
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
homepage?: string | null;
|
||||
/**
|
||||
* Keywords
|
||||
* @description Omit to preserve, null or an empty list to clear
|
||||
*/
|
||||
keywords?: string[] | null;
|
||||
/** Namespace */
|
||||
/**
|
||||
* Namespace
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
namespace?: string | null;
|
||||
/**
|
||||
* Version
|
||||
* @description Explicit higher SemVer, or omit/null for an automatic patch bump
|
||||
* @description Explicit SemVer, or omit/null for automatic versioning on approval
|
||||
*/
|
||||
version?: string | null;
|
||||
};
|
||||
|
|
@ -49178,6 +49235,85 @@ export interface components {
|
|||
*/
|
||||
expected_revision: number;
|
||||
};
|
||||
/** SkillHubUpdate */
|
||||
SkillHubUpdate: {
|
||||
/** @description Omit to preserve, null to clear */
|
||||
author?: components["schemas"]["PluginAuthor"] | null;
|
||||
/**
|
||||
* Category
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
category?: string | null;
|
||||
/**
|
||||
* Description
|
||||
* @description Omit to preserve, null to clear the registry description
|
||||
*/
|
||||
description?: string | null;
|
||||
/**
|
||||
* Domain
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
domain?: string | null;
|
||||
/**
|
||||
* Expected Updated At
|
||||
* @description Published updated_at read by the editor. A stale value returns 409
|
||||
*/
|
||||
expected_updated_at?: string | null;
|
||||
/**
|
||||
* Homepage
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
homepage?: string | null;
|
||||
/**
|
||||
* Keywords
|
||||
* @description Omit to preserve, null or an empty list to clear
|
||||
*/
|
||||
keywords?: string[] | null;
|
||||
/**
|
||||
* Namespace
|
||||
* @description Omit to preserve, null to clear
|
||||
*/
|
||||
namespace?: string | null;
|
||||
/**
|
||||
* Source
|
||||
* @description Explicit replacement source reference. Omit/null to preserve the stored source and archive
|
||||
*/
|
||||
source?: {
|
||||
[key: string]: string;
|
||||
} | null;
|
||||
/**
|
||||
* Version
|
||||
* @description Explicit higher SemVer, or omit/null for an automatic patch bump
|
||||
*/
|
||||
version?: string | null;
|
||||
};
|
||||
/** SkillHubUpload */
|
||||
SkillHubUpload: {
|
||||
author?: components["schemas"]["PluginAuthor"] | null;
|
||||
/** Category */
|
||||
category?: string | null;
|
||||
/** Description */
|
||||
description?: string | null;
|
||||
/** Domain */
|
||||
domain?: string | null;
|
||||
/** Homepage */
|
||||
homepage?: string | null;
|
||||
/** Keywords */
|
||||
keywords?: string[] | null;
|
||||
/**
|
||||
* Name
|
||||
* @description Registry skill name
|
||||
*/
|
||||
name: string;
|
||||
/** Namespace */
|
||||
namespace?: string | null;
|
||||
/**
|
||||
* Version
|
||||
* @description Semantic version, defaults to 1.0.0 on creation
|
||||
* @default 1.0.0
|
||||
*/
|
||||
version: string | null;
|
||||
};
|
||||
/** SkillHubVersion */
|
||||
SkillHubVersion: {
|
||||
/**
|
||||
|
|
@ -78176,6 +78312,7 @@ export interface operations {
|
|||
security_scan_passed?: boolean | null;
|
||||
sort_by?: "name" | "download_count" | "updated_at" | "created_at" | "created_by" | "published_by" | "approved_by" | "security_scan_passed";
|
||||
sort_order?: "asc" | "desc";
|
||||
enabled_only?: boolean;
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
|
|
@ -78212,7 +78349,7 @@ export interface operations {
|
|||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["ImportSkillRequest"];
|
||||
"application/json": components["schemas"]["SkillHubRegistration"] | components["schemas"]["ImportSkillRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
|
|
@ -78311,7 +78448,7 @@ export interface operations {
|
|||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["SkillHubMetadata"];
|
||||
"application/json": components["schemas"]["SkillHubUpdate"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
|
|
|
|||
|
|
@ -164,23 +164,47 @@ async def hub(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[HubClient]:
|
|||
|
||||
async def _upload(
|
||||
hub: HubClient, content: bytes, key: str | None = MASTER_KEY, version: str | None = "2.0.0",
|
||||
*, metadata: Mapping[str, object] | None = None,
|
||||
) -> httpx.Response:
|
||||
return await hub.client.post(
|
||||
f"{HUB}/upload",
|
||||
headers=_headers(key),
|
||||
data={"version": version} if version is not None else {},
|
||||
data={
|
||||
**({"version": version} if version is not None else {}),
|
||||
**({"metadata": json.dumps(metadata)} if metadata is not None else {}),
|
||||
},
|
||||
files={"file": ("notes.zip", content, "application/zip")},
|
||||
)
|
||||
|
||||
|
||||
def _stored_upload(hub: HubClient, enabled: bool = True) -> prisma_models.LiteLLM_ClaudeCodePluginTable:
|
||||
data: Final = hub.plugins.create.await_args.kwargs["data"]
|
||||
record: Final = prisma_models.LiteLLM_ClaudeCodePluginTable(
|
||||
id="hub-id", name=data["name"], version=data["version"], description=data["description"], anonymous_download_count=0,
|
||||
manifest_json=data["manifest_json"], enabled=enabled, updated_at=data["updated_at"],
|
||||
async def _replace_archive(
|
||||
hub: HubClient, path: str, files: Mapping[str, bytes], data: Mapping[str, str],
|
||||
key: str = MEMBER_KEY,
|
||||
) -> httpx.Response:
|
||||
return await hub.client.put(
|
||||
path + "/upload", headers=_headers(key), data=data,
|
||||
files={"file": ("replacement.zip", _zip(files), "application/zip")},
|
||||
)
|
||||
|
||||
|
||||
async def _edit_metadata(
|
||||
hub: HubClient, path: str, metadata: Mapping[str, object], key: str = MEMBER_KEY,
|
||||
) -> httpx.Response:
|
||||
return await hub.client.put(path, headers=_headers(key), json=metadata)
|
||||
|
||||
|
||||
def _stored_plugin(hub: HubClient, enabled: bool = True) -> prisma_models.LiteLLM_ClaudeCodePluginTable:
|
||||
record: Final = prisma_models.LiteLLM_ClaudeCodePluginTable.model_validate({
|
||||
"id": "hub-id", "anonymous_download_count": 0,
|
||||
**hub.plugins.create.await_args.kwargs["data"], "enabled": enabled,
|
||||
})
|
||||
hub.plugins.find_unique.return_value = record
|
||||
hub.plugins.find_many.return_value = [record]
|
||||
return record
|
||||
|
||||
|
||||
def _stored_upload(hub: HubClient, enabled: bool = True) -> prisma_models.LiteLLM_ClaudeCodePluginTable:
|
||||
record: Final = _stored_plugin(hub, enabled)
|
||||
hub.archives.find_first.return_value = prisma_models.LiteLLM_ClaudeCodePluginUpload(
|
||||
plugin_name=record.name, content=hub.archives.create.await_args.kwargs["data"]["content"],
|
||||
)
|
||||
|
|
@ -373,7 +397,14 @@ async def test_deleted_skill_is_not_served_when_download_cannot_be_recorded(hub:
|
|||
assert hub.downloads.create.await_count == (0 if key is None else 2)
|
||||
|
||||
|
||||
async def test_search_paginates_visible_matches(hub: HubClient) -> None:
|
||||
@pytest.mark.parametrize("key,enabled_only,names", (
|
||||
(PLAIN_KEY, False, ("other-notes", NAME)),
|
||||
(MASTER_KEY, True, ("other-notes", NAME)),
|
||||
(MASTER_KEY, False, ("other-notes", NAME, "private-notes")),
|
||||
))
|
||||
async def test_search_paginates_visible_matches(
|
||||
hub: HubClient, key: str, enabled_only: bool, names: tuple[str, ...],
|
||||
) -> None:
|
||||
assert (await _upload(hub, _zip(FILES))).status_code == 200
|
||||
record: Final = _stored_upload(hub)
|
||||
hub.plugins.find_many.return_value = [
|
||||
|
|
@ -381,14 +412,21 @@ async def test_search_paginates_visible_matches(hub: HubClient) -> None:
|
|||
record.model_copy(update={"name": "other-notes"}),
|
||||
record.model_copy(update={"name": "unmatched", "description": "Different topic"}),
|
||||
]
|
||||
for offset, name in enumerate(("other-notes", NAME)):
|
||||
|
||||
async def find_rows(where: Mapping[str, object]) -> list[prisma_models.LiteLLM_ClaudeCodePluginTable]:
|
||||
return [row for row in hub.plugins.find_many.return_value if where.get("enabled") is not True or row.enabled]
|
||||
|
||||
hub.plugins.find_many.side_effect = find_rows
|
||||
for offset, name in enumerate(names):
|
||||
response: Final = await hub.client.get(
|
||||
HUB, headers=_headers(PLAIN_KEY), params={"query": "SYNTHETIC", "limit": 1, "offset": offset},
|
||||
HUB, headers=_headers(key), params={
|
||||
"query": "SYNTHETIC", "limit": 1, "offset": offset, "enabled_only": str(enabled_only).lower(),
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert [item["name"] for item in response.json()["skills"]] == [name]
|
||||
assert response.json()["count"] == 2
|
||||
assert response.json()["next_offset"] == (1 if offset == 0 else None)
|
||||
assert response.json()["count"] == len(names)
|
||||
assert response.json()["next_offset"] == (offset + 1 if offset + 1 < len(names) else None)
|
||||
|
||||
|
||||
async def test_metadata_publication_and_deletion_preserve_files_and_grants(hub: HubClient) -> None:
|
||||
|
|
@ -397,16 +435,27 @@ async def test_metadata_publication_and_deletion_preserve_files_and_grants(hub:
|
|||
manifest: Final = json.loads(original.manifest_json)
|
||||
|
||||
for route, metadata in (
|
||||
(f"/claude-code/plugins/{NAME}", {"source": manifest["source"], "description": "Legacy edit"}),
|
||||
(f"{HUB}/{NAME}", {"description": "Neutral edit", "version": "3.0.0", "keywords": ["notes"]}),
|
||||
(f"{HUB}/{NAME}", {}),
|
||||
(f"/claude-code/plugins/{NAME}", {
|
||||
"source": manifest["source"], "description": "Legacy edit", "installation_preference": "required",
|
||||
}),
|
||||
(f"{HUB}/{NAME}", {"description": "Registry description " * 80, "version": "3.0.0", "keywords": ["notes"]}),
|
||||
(f"{HUB}/{NAME}", {"description": None}),
|
||||
):
|
||||
response: Final = await hub.client.put(route, headers=_headers(MASTER_KEY), json=metadata)
|
||||
assert response.status_code == 200, response.text
|
||||
assert json.loads(hub.plugins.find_unique.return_value.manifest_json)["agent_skill"] == manifest["agent_skill"]
|
||||
details: Final = await hub.client.get(f"{HUB}/{NAME}", headers=_headers(PLAIN_KEY))
|
||||
assert details.json()["description"] == metadata.get("description")
|
||||
assert "installation_preference" not in details.json()
|
||||
legacy: Final = await hub.client.get(f"/claude-code/plugins/{NAME}", headers=_headers(MASTER_KEY))
|
||||
assert legacy.json()["installation_preference"] == "required"
|
||||
assert legacy.json()["description"] == metadata.get("description")
|
||||
_assert_portable(await hub.client.get(details.json()["download_url"]))
|
||||
invalid: Final = await _edit_metadata(
|
||||
hub, f"{HUB}/{NAME}", {"source": {"source": "url", "url": "https://gitlab.com/example/skills"}}, MASTER_KEY,
|
||||
)
|
||||
assert invalid.status_code == 400, invalid.text
|
||||
assert json.loads(hub.plugins.find_unique.return_value.manifest_json)["source"] == manifest["source"]
|
||||
for action, public in (("unpublish", False), ("publish", True)):
|
||||
changed: Final = await hub.client.post(f"{HUB}/{NAME}/{action}", headers=_headers(MASTER_KEY))
|
||||
assert changed.status_code == 200
|
||||
|
|
@ -438,25 +487,51 @@ async def test_rejected_uploads_do_not_write(hub: HubClient, content: bytes, key
|
|||
hub.plugins.create.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_stored_content_survives_duplicate_upload_and_is_hidden_after_source_replacement(hub: HubClient) -> None:
|
||||
@pytest.mark.parametrize("route,key", (
|
||||
("/claude-code/plugins", MASTER_KEY), (HUB, MASTER_KEY), (HUB, MEMBER_KEY),
|
||||
))
|
||||
async def test_stored_content_survives_duplicate_upload_and_is_hidden_after_source_replacement(
|
||||
pending_hub: HubClient, route: str, key: str,
|
||||
) -> None:
|
||||
hub: Final = pending_hub
|
||||
assert (await _upload(hub, _zip(FILES))).status_code == 200
|
||||
original: Final = _stored_upload(hub)
|
||||
hub.plugins.create.side_effect = UniqueViolationError({"message": "duplicate", "error_code": "P2002"})
|
||||
response: Final = await _upload(hub, _zip({**FILES, "references/guide.md": b"replacement"}))
|
||||
assert response.status_code == 409
|
||||
assert response.status_code == 409, response.text
|
||||
legacy: Final = await _upload(hub, _zip({"SKILL.md": b"Legacy instructions.\n"}), metadata={"name": NAME})
|
||||
reference: Final = await hub.client.post(
|
||||
f"{HUB}/import", headers=_headers(MASTER_KEY),
|
||||
json={"name": NAME, "source": {"source": "github", "repo": "example/skills"}},
|
||||
)
|
||||
assert legacy.status_code == reference.status_code == 409
|
||||
assert hub.plugins.create.await_count == 1
|
||||
_assert_portable(await hub.client.get(f"{HUB}/{NAME}/archive"))
|
||||
hub.plugins.update.assert_not_awaited()
|
||||
hub.archives.find_first.reset_mock()
|
||||
manifest: Final = json.loads(original.manifest_json)
|
||||
external: Final = {
|
||||
external: Final = {"source": "url", "url": "https://gitlab.com/example/replacement"} if key == MEMBER_KEY else {
|
||||
**manifest["source"],
|
||||
"url": str(httpx.URL(manifest["source"]["url"]).copy_with(scheme="https", host="external.example")),
|
||||
}
|
||||
replaced: Final = await hub.client.put(
|
||||
f"/claude-code/plugins/{NAME}", headers=_headers(MASTER_KEY),
|
||||
json={"source": external, "agent_skill": manifest["agent_skill"]},
|
||||
f"{route}/{NAME}", headers=_headers(key),
|
||||
json={
|
||||
"source": external, "expected_updated_at": original.updated_at.isoformat(),
|
||||
**({"agent_skill": manifest["agent_skill"]} if route != HUB else {}),
|
||||
},
|
||||
)
|
||||
assert replaced.status_code == 200, replaced.text
|
||||
if key == MEMBER_KEY:
|
||||
path: Final = f"/skill-hub/submissions/{replaced.json()['submission_id']}"
|
||||
proposal: Final = (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json()["submission"]
|
||||
assert proposal["has_archive"] is False and proposal["proposal"]["agent_skill"] is None
|
||||
assert proposal["proposal"]["source"] == external
|
||||
_assert_portable(await hub.client.get(f"{HUB}/{NAME}/archive"))
|
||||
hub.archives.find_first.reset_mock()
|
||||
approved: Final = await hub.client.put(path + "/approve", headers=_headers(MASTER_KEY))
|
||||
assert approved.status_code == 200, approved.text
|
||||
hub.archives.delete_many.assert_awaited_once_with(where={"plugin_name": NAME})
|
||||
assert "agent_skill" not in json.loads(hub.plugins.find_unique.return_value.manifest_json)
|
||||
details: Final = await hub.client.get(f"{HUB}/{NAME}", headers=_headers(MASTER_KEY))
|
||||
assert details.json()["source"] == external and details.json()["download_url"] is None
|
||||
|
|
@ -537,10 +612,11 @@ async def test_neutral_metadata_publication_pairs_version_and_preserved_skill_sn
|
|||
return current
|
||||
|
||||
hub.plugins.update.side_effect = replace_row
|
||||
updated: Final = await hub.client.put(
|
||||
f"{HUB}/{NAME}", headers=_headers(MASTER_KEY),
|
||||
json={"description": "Registry description", "domain": "notes", "namespace": "team", "keywords": ["notes"]},
|
||||
)
|
||||
metadata: Final = {
|
||||
**REGISTRY_METADATA, "description": "Registry description",
|
||||
"domain": "notes", "namespace": "team", "keywords": ["notes"],
|
||||
}
|
||||
updated: Final = await _edit_metadata(hub, f"{HUB}/{NAME}", metadata, MASTER_KEY)
|
||||
assert updated.status_code == 200, updated.text
|
||||
assert updated.json()["version"] == "1.0.1"
|
||||
assert updated.json()["download_url"] == f"https://public.example{HUB}/{NAME}/archive"
|
||||
|
|
@ -553,14 +629,25 @@ async def test_neutral_metadata_publication_pairs_version_and_preserved_skill_sn
|
|||
assert first["version"] == "1.0.0"
|
||||
assert latest["content"].decode() == first["content"].decode()
|
||||
_assert_portable(await hub.client.get(updated.json()["download_url"]))
|
||||
preserved: Final = await _edit_metadata(hub, f"{HUB}/{NAME}", {"source": updated.json()["source"]}, MASTER_KEY)
|
||||
assert preserved.status_code == 200, preserved.text
|
||||
assert {field: preserved.json()[field] for field in metadata} == metadata
|
||||
assert preserved.json()["version"] == "1.0.2"
|
||||
cleared: Final = await _edit_metadata(hub, f"{HUB}/{NAME}", dict.fromkeys(metadata), MASTER_KEY)
|
||||
assert cleared.status_code == 200, cleared.text
|
||||
assert {field: cleared.json()[field] for field in metadata} == dict.fromkeys(metadata)
|
||||
assert not metadata.keys() & json.loads(hub.plugins.find_unique.return_value.manifest_json).keys()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key,status", ((MASTER_KEY, 200), (GRANTED_KEY, 200), (PLAIN_KEY, 404)))
|
||||
@pytest.mark.parametrize("portable", (True, False))
|
||||
@pytest.mark.asyncio
|
||||
async def test_neutral_history_list_detail_and_portable_download_share_current_visibility(
|
||||
hub: HubClient, key: str, status: int,
|
||||
async def test_neutral_history_list_detail_and_archive_download_share_current_visibility(
|
||||
hub: HubClient, key: str, status: int, portable: bool,
|
||||
) -> None:
|
||||
assert (await _upload(hub, _zip(FILES), version=None)).status_code == 200
|
||||
files: Final = FILES if portable else {"SKILL.md": b"Legacy skill instructions.\n"}
|
||||
uploaded: Final = await _upload(hub, _zip(files), version=None, metadata={"name": NAME})
|
||||
assert uploaded.status_code == 200, uploaded.text
|
||||
original: Final = _stored_upload(hub, enabled=False)
|
||||
data: Final = hub.database.litellm_claudecodepluginversion.create.await_args.kwargs["data"]
|
||||
version: Final = prisma_models.LiteLLM_ClaudeCodePluginVersion.model_validate({"id": "retained", **data})
|
||||
|
|
@ -581,9 +668,14 @@ async def test_neutral_history_list_detail_and_portable_download_share_current_v
|
|||
assert event["version"] == version.version != "3.0.0"
|
||||
assert event["digest"] == hashlib.sha256(downloaded.content).hexdigest()
|
||||
assert listed.json() == {"versions": [detail.json()], "next_offset": None}
|
||||
assert detail.json()["manifest"]["agent_skill"] == json.loads(original.manifest_json)["agent_skill"]
|
||||
assert ("agent_skill" in detail.json()["manifest"]) is portable
|
||||
assert detail.json()["download_url"] == f"http://test{HUB}/{NAME}/versions/retained/archive"
|
||||
_assert_portable(downloaded)
|
||||
if portable:
|
||||
assert detail.json()["manifest"]["agent_skill"] == json.loads(original.manifest_json)["agent_skill"]
|
||||
_assert_portable(downloaded)
|
||||
else:
|
||||
with zipfile.ZipFile(io.BytesIO(downloaded.content)) as archive:
|
||||
assert archive.read(f"skills/{NAME}/SKILL.md") == files["SKILL.md"]
|
||||
assert downloaded.headers["etag"] == f'"sha256:{hashlib.sha256(downloaded.content).hexdigest()}"'
|
||||
hub.database.query_raw.return_value = []
|
||||
assert (await hub.client.get(f"{HUB}/{NAME}/versions/missing", headers=_headers(key))).status_code == 404
|
||||
|
|
@ -609,6 +701,11 @@ async def test_neutral_history_labels_external_sources_and_bounds_pagination(hub
|
|||
assert len(listed.json()["versions"]) == 1
|
||||
assert listed.json()["versions"][0]["content_kind"] == "source_reference"
|
||||
assert listed.json()["versions"][0]["download_url"] is None
|
||||
downloaded: Final = await hub.client.get(f"{HUB}/{NAME}/versions/reference/archive", headers=_headers(MASTER_KEY))
|
||||
assert downloaded.status_code == 404, downloaded.text
|
||||
hub.downloads.create.assert_not_awaited()
|
||||
hub.upstream.assert_not_called()
|
||||
_assert_portable(await hub.client.get(f"{HUB}/{NAME}/archive"))
|
||||
assert (await hub.client.get(
|
||||
f"{HUB}/{NAME}/versions?limit=101", headers=_headers(MASTER_KEY),
|
||||
)).status_code == 422
|
||||
|
|
@ -675,26 +772,37 @@ async def test_member_archive_stays_private_until_admin_review(
|
|||
|
||||
|
||||
@pytest.mark.parametrize("replacement", (False, True), ids=("metadata", "archive"))
|
||||
async def test_member_updates_preserve_manifest_and_original_editor_base(pending_hub: HubClient, replacement: bool) -> None:
|
||||
@pytest.mark.parametrize("author", ("legacy author", {"name": 42}), ids=("legacy-author", "malformed-author"))
|
||||
@pytest.mark.parametrize("description,refreshed", (
|
||||
("Summarize synthetic notes.", "Summarize revised notes."), ("Registry override", "Registry override"), (None, None),
|
||||
))
|
||||
async def test_member_updates_preserve_manifest_and_original_editor_base(
|
||||
pending_hub: HubClient, replacement: bool, monkeypatch: pytest.MonkeyPatch, author: str | Mapping[str, int],
|
||||
description: str | None, refreshed: str | None,
|
||||
) -> None:
|
||||
hub: Final = pending_hub
|
||||
assert (await _upload(hub, _zip(FILES))).status_code == 200
|
||||
monkeypatch.setenv("PROXY_BASE_URL", "https://public.example")
|
||||
created: Final = await _upload(hub, _zip(FILES), metadata={"name": NAME, "description": description})
|
||||
assert created.status_code == 200, created.text
|
||||
original: Final = _stored_upload(hub)
|
||||
manifest: Final = {
|
||||
**json.loads(original.manifest_json), "domain": "Tools", "namespace": "research",
|
||||
"keywords": ["notes"], "extension": {"retained": True}, "author": "legacy author",
|
||||
"keywords": ["notes"], "extension": {"retained": True}, "author": author,
|
||||
}
|
||||
hub.plugins.find_unique.return_value = original.model_copy(update={"manifest_json": json.dumps(manifest)})
|
||||
before: Final = hub.database.litellm_claudecodepluginversion.create.await_count
|
||||
updated_files: Final = {**FILES, "references/guide.md": b"Updated supporting instructions.\n"}
|
||||
updated_files: Final = {
|
||||
**FILES, "references/guide.md": b"Updated supporting instructions.\n",
|
||||
"SKILL.md": MANIFEST.replace(b"Summarize synthetic notes.", b"Summarize revised notes."),
|
||||
}
|
||||
expected: Final = original.updated_at.isoformat()
|
||||
response: Final = (
|
||||
await hub.client.put(
|
||||
f"{HUB}/{NAME}/upload", headers=_headers(MEMBER_KEY),
|
||||
data={"expected_updated_at": expected}, files={"file": ("new.zip", _zip(updated_files), "application/zip")},
|
||||
) if replacement else await hub.client.put(
|
||||
await _replace_archive(hub, f"{HUB}/{NAME}", updated_files, {"expected_updated_at": expected})
|
||||
if replacement else await hub.client.put(
|
||||
f"{HUB}/{NAME}", headers=_headers(MEMBER_KEY),
|
||||
json={"description": "Reviewed description", "expected_updated_at": expected,
|
||||
"domain": "Tools", "namespace": "research", "keywords": ["notes"]},
|
||||
"domain": "Tools", "namespace": "research", "keywords": ["notes"],
|
||||
"source": created.json()["source"]},
|
||||
)
|
||||
)
|
||||
assert response.status_code == 200, response.text
|
||||
|
|
@ -704,12 +812,12 @@ async def test_member_updates_preserve_manifest_and_original_editor_base(pending
|
|||
assert detail["submission"]["proposal"]["domain"] == "Tools"
|
||||
assert detail["submission"]["proposal"]["keywords"] == ["notes"]
|
||||
assert detail["current_skill"]["namespace"] == "research"
|
||||
expected_author: Final = {"name": author, "email": None} if isinstance(author, str) else None
|
||||
assert detail["submission"]["proposal"]["author"] == detail["current_skill"]["author"] == expected_author
|
||||
for version in ("1.0.0", original.version):
|
||||
invalid: Final = await hub.client.put(
|
||||
path + ("/upload" if replacement else ""), headers=_headers(MEMBER_KEY),
|
||||
**({"data": {"expected_revision": "0", "version": version},
|
||||
"files": {"file": ("new.zip", _zip(updated_files), "application/zip")}}
|
||||
if replacement else {"json": {"expected_revision": 0, "version": version}}),
|
||||
invalid: Final = (
|
||||
await _replace_archive(hub, path, updated_files, {"expected_revision": "0", "version": version})
|
||||
if replacement else await _edit_metadata(hub, path, {"expected_revision": 0, "version": version})
|
||||
)
|
||||
assert invalid.status_code == 400, invalid.text
|
||||
assert (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json() == detail
|
||||
|
|
@ -717,6 +825,15 @@ async def test_member_updates_preserve_manifest_and_original_editor_base(pending
|
|||
hub.plugins.update.assert_not_awaited()
|
||||
approved: Final = await hub.client.put(path + "/approve", headers=_headers(MASTER_KEY))
|
||||
assert approved.status_code == 200, approved.text
|
||||
assert approved.json()["skill"]["description"] == (refreshed if replacement else "Reviewed description")
|
||||
listed: Final = await hub.client.get(HUB, headers=_headers(MASTER_KEY))
|
||||
catalog: Final = await hub.client.get("/claude-code/plugins", headers=_headers(MASTER_KEY))
|
||||
assert (listed.status_code, catalog.status_code) == (200, 200), (listed.text, catalog.text)
|
||||
assert listed.json()["skills"][0]["author"] == catalog.json()["plugins"][0]["author"] == expected_author
|
||||
legacy: Final = await hub.client.get(f"/claude-code/plugins/{NAME}", headers=_headers(MASTER_KEY))
|
||||
marketplace: Final = await hub.client.get("/claude-code/marketplace.json", headers=_headers(MASTER_KEY))
|
||||
assert (legacy.status_code, marketplace.status_code) == (200, 200), (legacy.text, marketplace.text)
|
||||
assert legacy.json()["author"] == marketplace.json()["plugins"][0]["author"] == author
|
||||
stored: Final = json.loads(hub.plugins.find_unique.return_value.manifest_json)
|
||||
assert (stored["extension"], stored["author"]) == (manifest["extension"], manifest["author"])
|
||||
assert stored["agent_skill"]["digest"] == response.json()["proposal"]["agent_skill"]["digest"]
|
||||
|
|
@ -731,16 +848,21 @@ async def test_member_updates_preserve_manifest_and_original_editor_base(pending
|
|||
assert stored["agent_skill"] == manifest["agent_skill"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,status", (("stale", 409), ("wrong-name", 422), ("viewer", 403)),
|
||||
ids=("stale", "wrong-name", "viewer"))
|
||||
@pytest.mark.parametrize("failure,status", (("stale", 409), ("wrong-name", 422), ("viewer", 403), ("unsafe-legacy", 422)))
|
||||
async def test_replacement_rejections_do_not_stage_or_change_files(pending_hub: HubClient, failure: str, status: int) -> None:
|
||||
hub: Final = pending_hub
|
||||
assert (await _upload(hub, _zip(FILES))).status_code == 200
|
||||
files: Final = {"SKILL.md": b"Legacy instructions.\n"} if failure == "unsafe-legacy" else FILES
|
||||
created: Final = await _upload(hub, _zip(files), version=None, metadata={"name": NAME})
|
||||
assert created.status_code == 200, created.text
|
||||
_stored_upload(hub)
|
||||
response: Final = await hub.client.put(
|
||||
f"{HUB}/{NAME}/upload", headers=_headers(VIEWER_KEY if failure == "viewer" else MEMBER_KEY),
|
||||
data={"expected_updated_at": "2020-01-01T00:00:00Z"} if failure == "stale" else {},
|
||||
files={"file": ("new.zip", _zip({"SKILL.md": MANIFEST.replace(NAME.encode(), b"different-name")}), "application/zip")},
|
||||
replacement: Final = (
|
||||
{**files, "../outside.txt": b"Unsafe replacement"} if failure == "unsafe-legacy"
|
||||
else {"SKILL.md": MANIFEST.replace(NAME.encode(), b"different-name")}
|
||||
)
|
||||
response: Final = await _replace_archive(
|
||||
hub, f"{HUB}/{NAME}", replacement,
|
||||
{"expected_updated_at": "2020-01-01T00:00:00Z"} if failure == "stale" else {},
|
||||
VIEWER_KEY if failure == "viewer" else MEMBER_KEY,
|
||||
)
|
||||
assert response.status_code == status, response.text
|
||||
assert hub.database.litellm_skillsubmission.rows == ()
|
||||
|
|
@ -1080,6 +1202,10 @@ async def test_pending_edits_preserve_owner_and_files_until_fresh_review(pending
|
|||
created: Final = await _upload(hub, _zip(FILES), MEMBER_KEY)
|
||||
path: Final = f"/skill-hub/submissions/{created.json()['submission_id']}"
|
||||
before: Final = (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json()["submission"]
|
||||
for field in ("installation_preference", "installationPreference", "descripton"):
|
||||
invalid: Final = await _edit_metadata(hub, path, {"expected_revision": 0, field: "required"})
|
||||
assert invalid.status_code == 422, invalid.text
|
||||
assert (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json()["submission"] == before
|
||||
edited: Final = await hub.client.put(path, headers=_headers(MEMBER_KEY), json={
|
||||
"expected_revision": 0, "description": "Revised metadata", "version": "3.0.0", "keywords": ["review"],
|
||||
})
|
||||
|
|
@ -1090,12 +1216,17 @@ async def test_pending_edits_preserve_owner_and_files_until_fresh_review(pending
|
|||
)
|
||||
assert result["proposal"]["description"] == "Revised metadata"
|
||||
_assert_portable(await hub.client.get(path + "/archive", headers=_headers(MEMBER_KEY)))
|
||||
retained: Final = await hub.client.put(path, headers=_headers(MEMBER_KEY), json={
|
||||
"expected_revision": 1, "version": "3.0.0",
|
||||
})
|
||||
assert retained.status_code == 200, retained.text
|
||||
assert retained.json()["proposal"] == result["proposal"]
|
||||
for body in ({}, {"expected_revision": 0}):
|
||||
stale: Final = await hub.client.put(path + "/approve", headers=_headers(MASTER_KEY), json=body or None)
|
||||
assert stale.status_code == 409, stale.text
|
||||
assert (await hub.client.put(path, headers=_headers(MEMBER_KEY), json={"expected_revision": 0})).status_code == 409
|
||||
hub.plugins.create.assert_not_awaited()
|
||||
approved: Final = await hub.client.put(path + "/approve", headers=_headers(MASTER_KEY), json={"expected_revision": 1})
|
||||
approved: Final = await hub.client.put(path + "/approve", headers=_headers(MASTER_KEY), json={"expected_revision": 2})
|
||||
assert approved.status_code == 200, approved.text
|
||||
assert approved.json()["skill"]["description"] == "Revised metadata"
|
||||
assert approved.json()["skill"]["version"] == "3.0.0"
|
||||
|
|
@ -1120,32 +1251,55 @@ async def test_withdrawn_submission_cannot_be_edited_reviewed_or_published(pendi
|
|||
hub.plugins.create.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_pending_archive_edit_revalidates_and_clears_scan(pending_hub: HubClient) -> None:
|
||||
@pytest.mark.parametrize("version,target,published", (
|
||||
(None, None, "1.0.0"), ("2.1.0", "2.1.0", "2.1.0"), ("", None, "1.0.0"),
|
||||
))
|
||||
@pytest.mark.parametrize("portable", (True, False))
|
||||
async def test_pending_archive_edit_revalidates_and_clears_scan(
|
||||
pending_hub: HubClient, version: str | None, target: str | None, published: str, portable: bool,
|
||||
) -> None:
|
||||
hub: Final = pending_hub
|
||||
created: Final = await _upload(hub, _zip(FILES), MEMBER_KEY)
|
||||
files: Final = FILES if portable else {"SKILL.md": b"Use the supplied notes.\n"}
|
||||
created: Final = await _upload(hub, _zip(files), MEMBER_KEY, metadata={"name": "registry-alias"})
|
||||
assert created.status_code == 200, created.text
|
||||
identifier: Final = created.json()["submission_id"]
|
||||
path: Final = f"/skill-hub/submissions/{identifier}"
|
||||
await hub.database.litellm_skillsubmission.update(where={"id": identifier}, data={"scan_json": "old scan"})
|
||||
invalid: Final = await hub.client.put(path + "/upload", headers=_headers(MEMBER_KEY),
|
||||
data={"expected_revision": "0"}, files={"file": ("invalid.zip", b"invalid")})
|
||||
assert invalid.status_code == 422, invalid.text
|
||||
updated_files: Final = {**FILES, "references/guide.md": b"Revised pending instructions.\n"}
|
||||
edited: Final = await hub.client.put(path + "/upload", headers=_headers(MEMBER_KEY),
|
||||
data={"expected_revision": "0", "version": "2.1.0"}, files={"file": ("edit.zip", _zip(updated_files))})
|
||||
updated_files: Final = {
|
||||
**files, "references/guide.md": b"Revised pending instructions.\n",
|
||||
"SKILL.md": files["SKILL.md"].replace(b"Summarize synthetic notes.", b"Summarize revised notes."),
|
||||
}
|
||||
edited: Final = await _replace_archive(
|
||||
hub, path, updated_files, {"expected_revision": "0", **({"version": version} if version is not None else {})},
|
||||
)
|
||||
assert edited.status_code == 200, edited.text
|
||||
assert edited.json()["revision"] == 1
|
||||
assert edited.json()["proposal"]["version"] == target
|
||||
assert edited.json()["proposal"]["description"] == ("Summarize revised notes." if portable else None)
|
||||
stored: Final = await hub.database.litellm_skillsubmission.find_unique(where={"id": identifier})
|
||||
assert stored.scan_json is None
|
||||
archive: Final = await hub.client.get(path + "/archive", headers=_headers(MEMBER_KEY))
|
||||
with zipfile.ZipFile(io.BytesIO(archive.content)) as content:
|
||||
assert content.read("references/guide.md") == updated_files["references/guide.md"]
|
||||
assert content.read("references/guide.md" if portable else "skills/registry-alias/references/guide.md") == (
|
||||
updated_files["references/guide.md"]
|
||||
)
|
||||
hub.plugins.create.assert_not_awaited()
|
||||
approved: Final = await _edit_metadata(hub, path + "/approve", {"expected_revision": 1}, MASTER_KEY)
|
||||
assert approved.status_code == 200, approved.text
|
||||
assert approved.json()["skill"]["version"] == published
|
||||
wrapper: Final = hub.archives.create.await_args.kwargs["data"]["content"].decode()
|
||||
with zipfile.ZipFile(io.BytesIO(wrapper)) as content:
|
||||
assert content.read("skills/registry-alias/SKILL.md") == updated_files["SKILL.md"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("published_version", (None, "legacy"))
|
||||
@pytest.mark.parametrize("published_version", (None, "legacy", "2.0.0"))
|
||||
@pytest.mark.parametrize("replacement", (False, True), ids=("metadata", "archive"))
|
||||
async def test_pending_legacy_update_keeps_explicit_version_requirement(
|
||||
pending_hub: HubClient, published_version: str | None, replacement: bool,
|
||||
@pytest.mark.parametrize("send_null", (False, True), ids=("omitted", "null"))
|
||||
async def test_pending_update_uses_automatic_version_unless_explicitly_supplied(
|
||||
pending_hub: HubClient, published_version: str | None, replacement: bool, send_null: bool,
|
||||
) -> None:
|
||||
hub: Final = pending_hub
|
||||
assert (await _upload(hub, _zip(FILES))).status_code == 200
|
||||
|
|
@ -1156,13 +1310,113 @@ async def test_pending_legacy_update_keeps_explicit_version_requirement(
|
|||
)
|
||||
assert created.status_code == 200, created.text
|
||||
path: Final = f"/skill-hub/submissions/{created.json()['submission_id']}"
|
||||
before: Final = (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json()
|
||||
edited: Final = await hub.client.put(
|
||||
path + ("/upload" if replacement else ""), headers=_headers(MEMBER_KEY),
|
||||
**({"data": {"expected_revision": "0"}, "files": {"file": ("new.zip", _zip(FILES))}}
|
||||
if replacement else {"json": {"expected_revision": 0}}),
|
||||
edited: Final = (
|
||||
await _replace_archive(hub, path, FILES, {"expected_revision": "0", "version": "3.0.0"})
|
||||
if replacement else await _edit_metadata(hub, path, {"expected_revision": 0, "version": "3.0.0"})
|
||||
)
|
||||
assert edited.status_code == 409, edited.text
|
||||
assert "explicit semantic version" in edited.json()["detail"]
|
||||
assert (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json() == before
|
||||
assert edited.status_code == 200, edited.text
|
||||
assert edited.json()["proposal"]["version"] == "3.0.0"
|
||||
retained: Final = (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json()
|
||||
cleared: Final = (
|
||||
await _replace_archive(hub, path, FILES, {"expected_revision": "1", **({"version": ""} if send_null else {})})
|
||||
if replacement else await _edit_metadata(hub, path, {"expected_revision": 1, **({"version": None} if send_null else {})})
|
||||
)
|
||||
if published_version == "2.0.0":
|
||||
assert cleared.status_code == 200, cleared.text
|
||||
assert cleared.json()["proposal"]["version"] is None
|
||||
approved: Final = await _edit_metadata(hub, path + "/approve", {"expected_revision": 2}, MASTER_KEY)
|
||||
assert approved.status_code == 200, approved.text
|
||||
assert approved.json()["skill"]["version"] == "2.0.1"
|
||||
return
|
||||
assert cleared.status_code == 409, cleared.text
|
||||
assert "explicit semantic version" in cleared.json()["detail"]
|
||||
assert (await hub.client.get(path, headers=_headers(MEMBER_KEY))).json() == retained
|
||||
hub.plugins.update.assert_not_awaited()
|
||||
|
||||
|
||||
REGISTRY_METADATA: Final = {
|
||||
"description": "Registered skill description",
|
||||
"author": {"name": "Example Author", "email": "author@example.org"},
|
||||
"category": "Development", "domain": "Engineering", "namespace": "tools",
|
||||
"keywords": ["review,build", "notes"], "homepage": "https://docs.example.org/skills",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", (MASTER_KEY, MEMBER_KEY))
|
||||
async def test_reference_registration_preserves_sources_and_metadata_without_fetching(
|
||||
pending_hub: HubClient, key: str,
|
||||
) -> None:
|
||||
hub: Final = pending_hub
|
||||
source: Final = {"source": "url", "url": "https://gitlab.com/example/skills"}
|
||||
created: Final = await hub.client.post(
|
||||
f"{HUB}/import", headers=_headers(key), json={"name": NAME, "source": source, **REGISTRY_METADATA},
|
||||
)
|
||||
assert created.status_code == 200, created.text
|
||||
if key == MEMBER_KEY:
|
||||
path: Final = f"/skill-hub/submissions/{created.json()['submission_id']}"
|
||||
hub.plugins.create.assert_not_awaited()
|
||||
approved: Final = await _edit_metadata(hub, path + "/approve", {"expected_revision": 0}, MASTER_KEY)
|
||||
assert approved.status_code == 200, approved.text
|
||||
_stored_plugin(hub)
|
||||
details: Final = await hub.client.get(f"{HUB}/{NAME}", headers=_headers(MASTER_KEY))
|
||||
listed: Final = await hub.client.get(HUB, headers=_headers(MASTER_KEY))
|
||||
assert details.json() == listed.json()["skills"][0]
|
||||
assert details.json()["version"] == "1.0.0" and details.json()["download_url"] is None
|
||||
assert {field: details.json()[field] for field in REGISTRY_METADATA} == REGISTRY_METADATA
|
||||
assert details.json()["source"] == source
|
||||
hub.upstream.assert_not_called()
|
||||
hub.archives.create.assert_not_awaited()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ("installation_preference", "installationPreference", "descripton"))
|
||||
@pytest.mark.parametrize("operation", ("register", "upload", "import", "import-metadata", "update"))
|
||||
@pytest.mark.parametrize("value", ("required", None))
|
||||
async def test_skill_hub_rejects_unknown_metadata_fields(
|
||||
hub: HubClient, field: str, operation: str, value: str | None,
|
||||
) -> None:
|
||||
preference: Final = {field: value}
|
||||
response: Final = (
|
||||
await _upload(hub, _zip(FILES), version=None, metadata={"name": NAME, **preference})
|
||||
if operation == "upload"
|
||||
else await hub.client.request(
|
||||
"PUT" if operation == "update" else "POST",
|
||||
f"{HUB}/{NAME}" if operation == "update" else f"{HUB}/import",
|
||||
headers=_headers(MASTER_KEY), json={
|
||||
"register": {"name": NAME, "source": {"source": "github", "repo": "example/skills"}, **preference},
|
||||
"import": {"url": "https://github.com/example/skills", **preference},
|
||||
"import-metadata": {
|
||||
"url": "https://github.com/example/skills", "metadata": {"name": NAME, **preference},
|
||||
},
|
||||
"update": preference,
|
||||
}[operation],
|
||||
)
|
||||
)
|
||||
assert response.status_code == 422, response.text
|
||||
hub.plugins.create.assert_not_awaited()
|
||||
hub.plugins.update.assert_not_awaited()
|
||||
hub.upstream.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("operation", ("upload", "import"))
|
||||
async def test_portable_creation_accepts_registry_overrides_and_rejects_conflicting_versions(
|
||||
hub: HubClient, operation: str,
|
||||
) -> None:
|
||||
hub.upstream.return_value = httpx.Response(200, content=_zip(FILES, "repository/"))
|
||||
metadata: Final = {"name": "registry-alias", "version": "3.0.0", **REGISTRY_METADATA}
|
||||
body: Final = {"url": "https://github.com/example/skills", "metadata": metadata}
|
||||
conflict: Final = (
|
||||
await _upload(hub, _zip(FILES), metadata=metadata) if operation == "upload"
|
||||
else await hub.client.post(f"{HUB}/import", headers=_headers(MASTER_KEY), json={**body, "version": "2.0.0"})
|
||||
)
|
||||
assert conflict.status_code == 400, conflict.text
|
||||
hub.plugins.create.assert_not_awaited()
|
||||
imported: Final = (
|
||||
await _upload(hub, _zip(FILES), version=None, metadata=metadata) if operation == "upload"
|
||||
else await hub.client.post(f"{HUB}/import", headers=_headers(MASTER_KEY), json=body)
|
||||
)
|
||||
assert imported.status_code == 200, imported.text
|
||||
assert imported.json()["name"] == "registry-alias" and imported.json()["version"] == "3.0.0"
|
||||
assert {field: imported.json()[field] for field in REGISTRY_METADATA} == REGISTRY_METADATA
|
||||
record: Final = _stored_upload(hub)
|
||||
assert json.loads(record.manifest_json)["agent_skill"]["name"] == NAME
|
||||
_assert_portable(await hub.client.get(imported.json()["download_url"]))
|
||||
|
|
|
|||
|
|
@ -45,6 +45,16 @@ def repository_zip(entries: tuple[tuple[str | zipfile.ZipInfo, bytes], ...]) ->
|
|||
GitHubSkillSource("author", "repo", "release/v2", "pdf-summarizer", NESTED)),
|
||||
(f"https://github.com/author/repo/tree/release%2Fv2/{NESTED}", None, "HEAD", None,
|
||||
GitHubSkillSource("author", "repo", "release/v2", None, NESTED)),
|
||||
("https://github.com/author/repo/blob/main/SKILL.md", None, "HEAD", None,
|
||||
GitHubSkillSource("author", "repo", "main", None, "")),
|
||||
("https://github.com/author/repo/blob/release%2Fv2/skills/pdf%2Dsummarizer/SKILL.md",
|
||||
"pdf-summarizer", "HEAD", None, GitHubSkillSource("author", "repo", "release/v2", "pdf-summarizer", NESTED)),
|
||||
("https://github.com/author/repo/blob/main/README.md", None, "HEAD", None, 400),
|
||||
(f"https://github.com/author/repo/blob/main/{NESTED}/skill.md", None, "HEAD", None, 400),
|
||||
(f"https://github.com/author/repo/blob/main/{NESTED}/SKILL.md/extra", None, "HEAD", None, 400),
|
||||
("https://github.com/author/repo/blob/main", None, "HEAD", None, 400),
|
||||
(f"https://github.com/author/repo/blob/main/{NESTED}/SKILL.md", None, "other", None, 400),
|
||||
(f"https://github.com/author/repo/blob/main/{NESTED}/SKILL.md", None, "HEAD", NESTED, 400),
|
||||
("http://github.com/author/repo", None, "HEAD", None, 400),
|
||||
("https://github.com.example/author/repo", None, "HEAD", None, 400),
|
||||
("https://user:secret@github.com/author/repo", None, "HEAD", None, 400),
|
||||
|
|
@ -138,6 +148,30 @@ def test_repository_selection(skill: str | None, path: str | None, root_name: by
|
|||
assert (result.status if isinstance(result, SkillImportError) else result.declared_name) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("blob_path", "expected_guide"), (
|
||||
("SKILL.md", b"Root PDF guide"),
|
||||
("skills/pdf%2Dsummarizer/SKILL.md", b"Nested PDF guide"),
|
||||
))
|
||||
def test_blob_url_selects_its_directory_among_matching_skill_names(blob_path: str, expected_guide: bytes) -> None:
|
||||
source: Final = parse_skill_source(
|
||||
f"https://github.com/author/repo/blob/release%2Fv2/{blob_path}",
|
||||
skill="pdf-summarizer", ref="HEAD", path=None,
|
||||
)
|
||||
assert isinstance(source, GitHubSkillSource)
|
||||
assert source.archive_url == "https://codeload.github.com/author/repo/zip/release%2Fv2"
|
||||
content: Final = repository_zip((
|
||||
("repo/SKILL.md", MANIFEST),
|
||||
("repo/references/guide.md", b"Root PDF guide"),
|
||||
(f"repo/{NESTED}/SKILL.md", MANIFEST),
|
||||
(f"repo/{NESTED}/references/guide.md", b"Nested PDF guide"),
|
||||
))
|
||||
result: Final = select_imported_skill(content, source)
|
||||
assert not isinstance(result, SkillImportError)
|
||||
with zipfile.ZipFile(io.BytesIO(result.content)) as archive:
|
||||
assert archive.read("SKILL.md") == MANIFEST
|
||||
assert archive.read("references/guide.md") == expected_guide
|
||||
|
||||
|
||||
def test_corrupt_manifest_compression_returns_an_import_error() -> None:
|
||||
content: Final = repository_zip(((f"repo/{NESTED}/SKILL.md", MANIFEST),))
|
||||
with zipfile.ZipFile(io.BytesIO(content)) as archive:
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
|
@ -96,7 +97,17 @@ def test_scanner_config_rejects_unsafe_credential_destinations(endpoint: str) ->
|
|||
SkillScannerConfig(endpoint=endpoint, api_key_env="SCANNER_TEST_KEY")
|
||||
|
||||
|
||||
def test_adapter_authentication_and_exact_remote_source(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@pytest.mark.parametrize("source", (
|
||||
{"source": "url", "url": "https://example.org/repo.git", "ref": "release"},
|
||||
{"source": "github", "repo": "example/skills", "sha": "a" * 40},
|
||||
{"source": "github", "repo": "example/skills", "sha": "a" * 40, "ref": "release"},
|
||||
{"source": "url", "url": "https://gitlab.com/example/skills", "sha": "a" * 40},
|
||||
{"source": "url", "url": "https://git.example.org/team/skills.git", "sha": "a" * 40},
|
||||
{"source": "git-subdir", "url": "https://github.com/example/skills", "path": "skills/review", "sha": "a" * 40},
|
||||
))
|
||||
def test_adapter_authentication_and_exact_remote_source(
|
||||
monkeypatch: pytest.MonkeyPatch, source: dict[str, str],
|
||||
) -> None:
|
||||
from litellm.proxy.discovery_endpoints.skill_scanner_adapter import server
|
||||
|
||||
monkeypatch.setenv("SKILL_SCANNER_API_KEY", "adapter-secret")
|
||||
|
|
@ -109,7 +120,7 @@ def test_adapter_authentication_and_exact_remote_source(monkeypatch: pytest.Monk
|
|||
assert client.post("/scan", data={"source": "{}"}).status_code == 401
|
||||
assert client.post("/scan", headers={"Authorization": "Bearer wrong"}, data={"source": "{}"}).status_code == 401
|
||||
response = client.post("/scan", headers={"Authorization": "Bearer adapter-secret"}, data={
|
||||
"source": '{"source":"git","url":"https://example.org/repo.git","ref":"release"}',
|
||||
"source": json.dumps(source), "expires_at": NOW.isoformat(),
|
||||
})
|
||||
assert response.status_code == 400
|
||||
for deadline, status in ((NOW.isoformat(), 504), (NOW.replace(tzinfo=None).isoformat(), 422)):
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue