feat(sandbox): install skills from ClawHub, SkillHub, and git URLs
Paste a registry or GitHub link in the skill sandbox instead of only uploading a zip. skillhub.cn pages resolve through api.skillhub.cn.main
parent
b4128552b4
commit
260057b5f4
|
|
@ -15,6 +15,7 @@
|
|||
7. **分块管理**:查询、更新和删除知识分块
|
||||
8. **消息管理**:获取和删除会话消息
|
||||
9. **模型管理**:创建、获取、更新和删除模型
|
||||
10. **沙箱技能**:向沙箱配置安装技能(zip 上传,或从 ClawHub / SkillHub / GitHub 等来源)
|
||||
|
||||
## 使用方法
|
||||
|
||||
|
|
@ -386,6 +387,17 @@ if err != nil {
|
|||
}
|
||||
```
|
||||
|
||||
### 示例:从托管平台安装沙箱技能
|
||||
|
||||
```go
|
||||
skillID, err := apiClient.InstallSandboxSkillFromSource(
|
||||
context.Background(), sandboxConfigID, "@owner/slug", "")
|
||||
if err != nil {
|
||||
// 处理错误
|
||||
}
|
||||
_ = skillID // 用 skillID 订阅 /sandbox-configs/{id}/skills/{skillID}/install-events
|
||||
```
|
||||
|
||||
## 完整示例
|
||||
|
||||
请参考 `example.go` 文件中的 `ExampleUsage` 函数,其中展示了客户端的完整使用流程。
|
||||
|
|
@ -15,6 +15,7 @@ The client includes the following main functional modules:
|
|||
7. **Message Management**: Retrieve and delete session messages
|
||||
8. **Model Management**: Create, retrieve, update, and delete models
|
||||
9. **Evaluation Function**: Start evaluation tasks and get evaluation results
|
||||
10. **Sandbox skills**: Install a skill onto a sandbox config (zip upload, or ClawHub / SkillHub / GitHub source)
|
||||
|
||||
## Usage
|
||||
|
||||
|
|
@ -199,6 +200,17 @@ if err != nil {
|
|||
}
|
||||
```
|
||||
|
||||
### Example: Install a sandbox skill from a registry
|
||||
|
||||
```go
|
||||
skillID, err := apiClient.InstallSandboxSkillFromSource(
|
||||
context.Background(), sandboxConfigID, "@owner/slug", "")
|
||||
if err != nil {
|
||||
// Handle error
|
||||
}
|
||||
_ = skillID // follow /sandbox-configs/{id}/skills/{skillID}/install-events
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
Please refer to the `ExampleUsage` function in the `example.go` file, which demonstrates the complete usage flow of the client.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,11 @@
|
|||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
|
@ -19,6 +23,14 @@ type SkillListResponse struct {
|
|||
SkillsAvailable bool `json:"skills_available"`
|
||||
}
|
||||
|
||||
// SandboxSkillInstallResponse is returned when a skill install is accepted.
|
||||
type SandboxSkillInstallResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
SkillID string `json:"skill_id"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// ListSkills lists the installed skills a chat turn can invoke on one sandbox
|
||||
// config. An empty sandboxConfigID returns an empty list.
|
||||
func (c *Client) ListSkills(ctx context.Context, sandboxConfigID string) ([]SkillInfo, bool, error) {
|
||||
|
|
@ -38,3 +50,72 @@ func (c *Client) ListSkills(ctx context.Context, sandboxConfigID string) ([]Skil
|
|||
|
||||
return response.Data, response.SkillsAvailable, nil
|
||||
}
|
||||
|
||||
// InstallSandboxSkillFromSource installs a skill onto a sandbox config from a
|
||||
// ClawHub / SkillHub / skills.sh / GitHub / GitLab locator or a direct archive
|
||||
// URL. The call is accepted asynchronously; follow progress on the skill ID.
|
||||
func (c *Client) InstallSandboxSkillFromSource(
|
||||
ctx context.Context, configID, source, token string,
|
||||
) (string, error) {
|
||||
if configID == "" {
|
||||
return "", fmt.Errorf("sandbox config ID is required")
|
||||
}
|
||||
body := map[string]string{"source": source}
|
||||
if token != "" {
|
||||
body["token"] = token
|
||||
}
|
||||
path := "/api/v1/sandbox-configs/" + url.PathEscape(configID) + "/skills"
|
||||
resp, err := c.doRequest(ctx, http.MethodPost, path, body, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var response SandboxSkillInstallResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return response.Data.SkillID, nil
|
||||
}
|
||||
|
||||
// UploadSandboxSkill installs a skill onto a sandbox config from a zip archive.
|
||||
func (c *Client) UploadSandboxSkill(
|
||||
ctx context.Context, configID, filename string, archive []byte,
|
||||
) (string, error) {
|
||||
if configID == "" {
|
||||
return "", fmt.Errorf("sandbox config ID is required")
|
||||
}
|
||||
if filename == "" {
|
||||
filename = "skill.zip"
|
||||
}
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
part, err := writer.CreateFormFile("file", filename)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("create skill upload part: %w", err)
|
||||
}
|
||||
if _, err := part.Write(archive); err != nil {
|
||||
return "", fmt.Errorf("write skill upload part: %w", err)
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return "", fmt.Errorf("close skill upload form: %w", err)
|
||||
}
|
||||
|
||||
path := "/api/v1/sandbox-configs/" + url.PathEscape(configID) + "/skills"
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||
c.applyAuthHeaders(ctx, req)
|
||||
req.Body = io.NopCloser(bytes.NewReader(body.Bytes()))
|
||||
req.ContentLength = int64(body.Len())
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var response SandboxSkillInstallResponse
|
||||
if err := parseResponse(resp, &response); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return response.Data.SkillID, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -156,6 +156,16 @@ Docker、Local、CubeSandbox、E2B 均通过同一套空间配置 CRUD、连接
|
|||
|
||||
**会话与配置的绑定是「随沙箱同生共死」的钉子。** 会话首次创建沙箱时,把当时用的配置 ID 记在 `sessions.sandbox_config_id` 上;此后该会话的附件上传、产物收集、沙箱销毁都锁定在这份配置上。改智能体的选择**只影响之后新建的沙箱**——否则管理员改一次配置,正在进行的会话就会去错误的账号里找产物,销毁也会打空,留下一个没人知道 ID 的 paused 沙箱持续计费。
|
||||
|
||||
### 安装租户技能
|
||||
|
||||
空间「技能沙箱」设置里可以把技能装进当前配置的镜像。除上传 zip 外,也支持从托管平台粘贴来源:
|
||||
|
||||
- ClawHub / SkillHub / [skillhub.cn](https://skillhub.cn) 页面链接或 slug(`@owner/slug`)
|
||||
- skills.sh、GitHub、GitLab 仓库或目录链接
|
||||
- 直接的 zip / `SKILL.md` URL
|
||||
|
||||
私有 SkillHub 可在同一次请求里带 Token,仅用于下载、不会落库。安装仍走原有镜像快照流程。
|
||||
|
||||
**有沙箱在跑时改不了身份字段。** 身份字段分两组,成因不同但后果都足够严重:
|
||||
|
||||
| 组 | 字段 | 一改会怎样 |
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@
|
|||
| 方法 | 路径 | 描述 |
|
||||
| ---- | --------- | ------------------ |
|
||||
| GET | `/skills` | 获取预装 Skills 列表 |
|
||||
| POST | `/sandbox-configs/{id}/skills` | 安装技能(zip 上传或托管平台 source) |
|
||||
|
||||
## GET `/skills` - 获取预装 Skills 列表
|
||||
|
||||
|
|
@ -50,3 +51,46 @@ curl --location 'http://localhost:8080/api/v1/skills' \
|
|||
"success": true
|
||||
}
|
||||
```
|
||||
|
||||
## POST `/sandbox-configs/{id}/skills` - 安装技能
|
||||
|
||||
把技能安装到指定沙箱配置的镜像上。安装会启动沙箱并运行数分钟,本接口只负责受理,随后通过
|
||||
`GET /sandbox-configs/{id}/skills/{skillId}/install-events` 跟随进度。
|
||||
|
||||
两种请求体二选一:
|
||||
|
||||
### 1. 上传 zip(multipart)
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills' \
|
||||
--header 'X-API-Key: sk-xxxxx' \
|
||||
--form 'file=@"skill.zip"'
|
||||
```
|
||||
|
||||
### 2. 从托管平台安装(JSON)
|
||||
|
||||
`source` 可以是:
|
||||
|
||||
- ClawHub / SkillHub / skillhub.cn 页面链接或 slug(`@owner/slug`、`my-team--skill`)
|
||||
- skills.sh / GitHub / GitLab 仓库或目录链接
|
||||
- 直接的 zip / `SKILL.md` URL
|
||||
|
||||
私有 SkillHub 可带 `token`,仅用于本次下载,服务端不保存。
|
||||
|
||||
```curl
|
||||
curl --location 'http://localhost:8080/api/v1/sandbox-configs/{id}/skills' \
|
||||
--header 'X-API-Key: sk-xxxxx' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data '{"source":"@owner/slug"}'
|
||||
```
|
||||
|
||||
**响应**(202):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"skill_id": "..."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
|||
|
|
@ -1036,6 +1036,15 @@ export function uploadConfigSkill(
|
|||
}, { timeout: 5 * 60 * 1000 })
|
||||
}
|
||||
|
||||
export function installConfigSkillFromSource(
|
||||
configId: string,
|
||||
payload: { source: string; token?: string },
|
||||
): Promise<{ data: { skill_id: string } }> {
|
||||
return post(`/api/v1/sandbox-configs/${configId}/skills`, payload, {
|
||||
timeout: 2 * 60 * 1000,
|
||||
}) as unknown as Promise<{ data: { skill_id: string } }>
|
||||
}
|
||||
|
||||
export function patchConfigSkill(
|
||||
configId: string,
|
||||
skillId: string,
|
||||
|
|
|
|||
|
|
@ -65,6 +65,39 @@
|
|||
|
||||
<section class="setting-drawer__section">
|
||||
<h4 class="setting-drawer__section-title">{{ $t('settings.sandbox.skillInstallGroup') }}</h4>
|
||||
<t-input-adornment class="skill-source-row">
|
||||
<t-input
|
||||
v-model="sourceInput"
|
||||
:placeholder="$t('settings.sandbox.skillSourcePlaceholder')"
|
||||
:disabled="installBusy"
|
||||
@enter="installFromSource"
|
||||
/>
|
||||
<template #append>
|
||||
<t-button
|
||||
theme="primary"
|
||||
:loading="installingFromSource"
|
||||
:disabled="!sourceInput.trim() || uploading"
|
||||
@click="installFromSource"
|
||||
>
|
||||
{{ $t('settings.sandbox.skillSourceInstall') }}
|
||||
</t-button>
|
||||
</template>
|
||||
</t-input-adornment>
|
||||
<div v-if="showRegistryToken" class="skill-token-row">
|
||||
<p class="skill-token-label">{{ $t('settings.sandbox.skillSourceTokenLabel') }}</p>
|
||||
<t-input
|
||||
v-model="sourceToken"
|
||||
type="password"
|
||||
size="small"
|
||||
autocomplete="off"
|
||||
:placeholder="$t('settings.sandbox.skillSourceTokenPlaceholder')"
|
||||
:disabled="installBusy"
|
||||
/>
|
||||
<p class="skill-token-hint">{{ $t('settings.sandbox.skillSourceTokenHint') }}</p>
|
||||
</div>
|
||||
<div class="skill-install-split">
|
||||
<span>{{ $t('settings.sandbox.skillInstallOr') }}</span>
|
||||
</div>
|
||||
<input
|
||||
ref="fileInputRef"
|
||||
type="file"
|
||||
|
|
@ -72,17 +105,16 @@
|
|||
class="file-input-hidden"
|
||||
@change="onFileInputChange"
|
||||
/>
|
||||
|
||||
<div
|
||||
class="file-upload-area"
|
||||
:class="{ 'has-file': uploading }"
|
||||
@click="fileInputRef?.click()"
|
||||
:class="{ 'has-file': uploading, 'is-disabled': installBusy }"
|
||||
@click="!installBusy && fileInputRef?.click()"
|
||||
@dragover.prevent
|
||||
@dragenter.prevent
|
||||
@drop.prevent="onFileDrop"
|
||||
>
|
||||
<div class="file-upload-content">
|
||||
<t-icon name="upload" size="28px" class="upload-icon" />
|
||||
<t-icon name="upload" size="18px" class="upload-icon" />
|
||||
<div class="upload-text">
|
||||
<span v-if="uploading" class="upload-file-name">
|
||||
{{ $t('settings.sandbox.skillUploading', { percent: uploadPercent }) }}
|
||||
|
|
@ -274,6 +306,7 @@ import {
|
|||
listConfigSkills,
|
||||
patchConfigSkill,
|
||||
uploadConfigSkill,
|
||||
installConfigSkillFromSource,
|
||||
type ConfigSkill,
|
||||
type ConfigSkillInstallEvent,
|
||||
type SandboxConfigRecord,
|
||||
|
|
@ -297,7 +330,11 @@ const { t, locale } = useI18n()
|
|||
|
||||
const loading = ref(false)
|
||||
const uploading = ref(false)
|
||||
const installingFromSource = ref(false)
|
||||
const uploadPercent = ref(0)
|
||||
const sourceInput = ref('')
|
||||
const sourceToken = ref('')
|
||||
const forceRegistryToken = ref(false)
|
||||
const skills = ref<ConfigSkill[]>([])
|
||||
const skillImage = ref<SandboxSkillImage | null>(null)
|
||||
const togglingId = ref('')
|
||||
|
|
@ -331,6 +368,9 @@ const uploadHint = computed(() =>
|
|||
? t('settings.sandbox.skillUploadHintNewSession')
|
||||
: t('settings.sandbox.skillUploadHint'),
|
||||
)
|
||||
const installBusy = computed(() => uploading.value || installingFromSource.value)
|
||||
const sourceNeedsRegistryToken = computed(() => looksLikePrivateSkillHub(sourceInput.value))
|
||||
const showRegistryToken = computed(() => sourceNeedsRegistryToken.value || forceRegistryToken.value)
|
||||
const deleteHint = computed(() =>
|
||||
skillRollout.value === 'new_session'
|
||||
? t('settings.sandbox.skillDeleteHintNewSession')
|
||||
|
|
@ -342,6 +382,48 @@ const runtimeTemplateId = computed(() => {
|
|||
})
|
||||
const hasSkillSnapshot = computed(() => Boolean(skillImage.value?.snapshot_id?.trim()))
|
||||
|
||||
const PUBLIC_SKILL_HOSTS = new Set([
|
||||
'github.com',
|
||||
'www.github.com',
|
||||
'codeload.github.com',
|
||||
'gitlab.com',
|
||||
'www.gitlab.com',
|
||||
'skills.sh',
|
||||
'www.skills.sh',
|
||||
'clawhub.ai',
|
||||
'www.clawhub.ai',
|
||||
'clawhub.com',
|
||||
'www.clawhub.com',
|
||||
'skillhub.cn',
|
||||
'www.skillhub.cn',
|
||||
'api.skillhub.cn',
|
||||
])
|
||||
|
||||
function looksLikePrivateSkillHub(raw: string): boolean {
|
||||
const input = raw.trim()
|
||||
if (!input.includes('://')) return false
|
||||
try {
|
||||
const parsed = new URL(input)
|
||||
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false
|
||||
return !PUBLIC_SKILL_HOSTS.has(parsed.hostname.toLowerCase())
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function isRegistryAuthError(err: unknown): boolean {
|
||||
const message = err && typeof err === 'object' && 'message' in err
|
||||
? String((err as { message?: unknown }).message)
|
||||
: String(err ?? '')
|
||||
return /\bHTTP 401\b/.test(message) || /\bHTTP 403\b/.test(message)
|
||||
}
|
||||
|
||||
watch(sourceInput, (value) => {
|
||||
if (!looksLikePrivateSkillHub(value)) {
|
||||
forceRegistryToken.value = false
|
||||
}
|
||||
})
|
||||
|
||||
function readLastChatModelID(): string {
|
||||
try {
|
||||
return localStorage.getItem(LAST_CHAT_MODEL_KEY) || ''
|
||||
|
|
@ -627,7 +709,7 @@ function isZipFile(file: File): boolean {
|
|||
}
|
||||
|
||||
async function uploadFile(file: File) {
|
||||
if (!props.record || uploading.value) return
|
||||
if (!props.record || installBusy.value) return
|
||||
if (!installerModelId.value) {
|
||||
MessagePlugin.warning(t('settings.sandbox.skillInstallerModelRequired'))
|
||||
return
|
||||
|
|
@ -657,6 +739,38 @@ async function uploadFile(file: File) {
|
|||
}
|
||||
}
|
||||
|
||||
async function installFromSource() {
|
||||
if (!props.record || installBusy.value) return
|
||||
const source = sourceInput.value.trim()
|
||||
if (!source) return
|
||||
if (!installerModelId.value) {
|
||||
MessagePlugin.warning(t('settings.sandbox.skillInstallerModelRequired'))
|
||||
return
|
||||
}
|
||||
installingFromSource.value = true
|
||||
try {
|
||||
await persistInstallerModel(installerModelId.value)
|
||||
const token = showRegistryToken.value ? sourceToken.value.trim() : ''
|
||||
const res = await installConfigSkillFromSource(props.record.id, {
|
||||
source,
|
||||
...(token ? { token } : {}),
|
||||
})
|
||||
MessagePlugin.success(t('settings.sandbox.skillUploadAccepted'))
|
||||
sourceInput.value = ''
|
||||
sourceToken.value = ''
|
||||
forceRegistryToken.value = false
|
||||
const skillId = res?.data?.skill_id
|
||||
await loadSkills()
|
||||
await refreshImage()
|
||||
if (skillId) followProgress(skillId)
|
||||
} catch (e: any) {
|
||||
if (isRegistryAuthError(e)) forceRegistryToken.value = true
|
||||
MessagePlugin.error(e?.message || t('settings.sandbox.skillSourceFailed'))
|
||||
} finally {
|
||||
installingFromSource.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onFileInputChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0]
|
||||
|
|
@ -664,6 +778,7 @@ function onFileInputChange(event: Event) {
|
|||
}
|
||||
|
||||
function onFileDrop(event: DragEvent) {
|
||||
if (installBusy.value) return
|
||||
const file = event.dataTransfer?.files?.[0]
|
||||
if (file) void uploadFile(file)
|
||||
}
|
||||
|
|
@ -794,17 +909,17 @@ onUnmounted(() => {
|
|||
.file-upload-area {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
min-height: 120px;
|
||||
border: 2px dashed var(--td-component-stroke);
|
||||
border-radius: 8px;
|
||||
min-height: 44px;
|
||||
border: 1px dashed var(--td-component-stroke);
|
||||
border-radius: 6px;
|
||||
background: var(--td-bg-color-secondarycontainer);
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
transition: border-color 0.2s ease, background 0.2s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
&:hover {
|
||||
&:hover:not(.is-disabled) {
|
||||
border-color: var(--td-brand-color);
|
||||
background: var(--td-success-color-light);
|
||||
}
|
||||
|
|
@ -814,31 +929,37 @@ onUnmounted(() => {
|
|||
background: var(--td-success-color-light);
|
||||
border-style: solid;
|
||||
}
|
||||
|
||||
&.is-disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
}
|
||||
}
|
||||
|
||||
.file-upload-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
text-align: center;
|
||||
padding: 16px;
|
||||
padding: 8px 12px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.upload-icon {
|
||||
color: var(--td-brand-color);
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.file-upload-area:hover .upload-icon {
|
||||
transform: translateY(-2px);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.upload-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
justify-content: center;
|
||||
gap: 4px 8px;
|
||||
}
|
||||
|
||||
.upload-primary-text {
|
||||
|
|
@ -858,6 +979,10 @@ onUnmounted(() => {
|
|||
color: var(--td-brand-color);
|
||||
}
|
||||
|
||||
.file-upload-content :deep(.t-progress) {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
|
||||
.upload-hint {
|
||||
margin: 8px 0 0;
|
||||
font-size: 12px;
|
||||
|
|
@ -865,6 +990,54 @@ onUnmounted(() => {
|
|||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.skill-source-row {
|
||||
width: 100%;
|
||||
|
||||
:deep(.t-input-adornment__append .t-button) {
|
||||
border-top-left-radius: 0;
|
||||
border-bottom-left-radius: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.skill-token-row {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.skill-token-label {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-secondary);
|
||||
}
|
||||
|
||||
.skill-token-hint {
|
||||
margin: 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
color: var(--td-text-color-placeholder);
|
||||
}
|
||||
|
||||
.skill-install-split {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin: 10px 0;
|
||||
font-size: 12px;
|
||||
color: var(--td-text-color-placeholder);
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: var(--td-component-stroke);
|
||||
}
|
||||
}
|
||||
|
||||
.skill-empty {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
|
|
|
|||
|
|
@ -1277,10 +1277,17 @@ export default {
|
|||
skillRolloutSaveFailed: 'Failed to save the rollout setting',
|
||||
skillInstallGroup: 'Install a new skill',
|
||||
skillInstalledGroup: 'Installed',
|
||||
skillUploadClick: 'Click to upload a skill bundle',
|
||||
skillUploadDrag: 'or drop a .zip file here',
|
||||
skillUploadHint: 'Upload installs the skill onto the current image and takes a new snapshot. This can take several minutes. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
|
||||
skillUploadHintNewSession: 'Upload installs the skill onto the current image and takes a new snapshot. This can take several minutes. Already-open sessions keep their current sandbox until they end; only newly started sessions pick up this install.',
|
||||
skillUploadClick: 'Click to upload a zip bundle',
|
||||
skillUploadDrag: 'or drop a file here',
|
||||
skillUploadHint: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. The current chat turn is not interrupted; open sessions rebuild their sandbox on the next turn, which clears the session workspace scratch.',
|
||||
skillUploadHintNewSession: 'Install writes the skill onto the current image and takes a new snapshot. This can take several minutes. Already-open sessions keep their current sandbox until they end; only newly started sessions pick up this install.',
|
||||
skillSourcePlaceholder: 'Paste a URL or {\'@\'}owner/slug',
|
||||
skillSourceTokenLabel: 'Private SkillHub token',
|
||||
skillSourceTokenPlaceholder: 'Optional',
|
||||
skillSourceTokenHint: 'Only needed for a self-hosted or private SkillHub. Used for this download only, not stored.',
|
||||
skillSourceInstall: 'Install',
|
||||
skillInstallOr: 'or',
|
||||
skillSourceFailed: 'Failed to install the skill from the registry',
|
||||
skillUploadFailed: 'Failed to upload the skill',
|
||||
skillUploading: 'Uploading {percent}%',
|
||||
skillUploadAccepted: 'Skill install started',
|
||||
|
|
@ -1309,7 +1316,7 @@ export default {
|
|||
skillLoadFailed: 'Failed to load skills',
|
||||
skillToggleFailed: 'Failed to update the skill',
|
||||
skillDeleteAccepted: 'Skill removal started',
|
||||
skillEmpty: 'No skills installed yet. Upload a zip bundle to install one.',
|
||||
skillEmpty: 'No skills installed yet. Paste a registry URL, or upload a zip.',
|
||||
skillVersion: 'Version',
|
||||
skillVersionEmpty: 'Not specified',
|
||||
skillError: 'Error',
|
||||
|
|
|
|||
|
|
@ -5116,10 +5116,17 @@ export default {
|
|||
skillRolloutSaveFailed: '적용 방식 저장에 실패했습니다',
|
||||
skillInstallGroup: '새 스킬 설치',
|
||||
skillInstalledGroup: '설치됨',
|
||||
skillUploadClick: 'Click to upload a skill bundle',
|
||||
skillUploadDrag: 'or drop a .zip file here',
|
||||
skillUploadHint: '업로드하면 현재 이미지에 스킬을 설치하고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
|
||||
skillUploadHintNewSession: '업로드하면 현재 이미지에 스킬을 설치하고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이번에 설치한 스킬은 새로 시작한 세션에만 적용됩니다.',
|
||||
skillUploadClick: 'zip 파일을 클릭해 업로드',
|
||||
skillUploadDrag: '또는 여기로 드래그',
|
||||
skillUploadHint: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 현재 대화 턴은 중단되지 않으며, 이미 열린 세션은 다음 턴에서 새 이미지로 샌드박스를 다시 만들고 그때 세션 작업 공간 초안이 지워집니다.',
|
||||
skillUploadHintNewSession: '설치하면 현재 이미지에 스킬을 쓰고 새 스냅샷을 만듭니다. 몇 분이 걸릴 수 있습니다. 이미 열린 세션은 세션이 끝날 때까지 기존 샌드박스를 유지하며, 이번에 설치한 스킬은 새로 시작한 세션에만 적용됩니다.',
|
||||
skillSourcePlaceholder: 'URL 또는 {\'@\'}owner/slug 붙여넣기',
|
||||
skillSourceTokenLabel: '비공개 SkillHub 토큰',
|
||||
skillSourceTokenPlaceholder: '선택 사항',
|
||||
skillSourceTokenHint: '자체 호스팅 또는 비공개 SkillHub에서만 필요합니다. 이번 다운로드에만 사용되며 저장되지 않습니다.',
|
||||
skillSourceInstall: '설치',
|
||||
skillInstallOr: '또는',
|
||||
skillSourceFailed: '레지스트리에서 스킬을 설치하지 못했습니다',
|
||||
skillUploadFailed: 'Failed to upload the skill',
|
||||
skillUploading: 'Uploading {percent}%',
|
||||
skillUploadAccepted: 'Skill install started',
|
||||
|
|
@ -5148,7 +5155,7 @@ export default {
|
|||
skillLoadFailed: 'Failed to load skills',
|
||||
skillToggleFailed: 'Failed to update the skill',
|
||||
skillDeleteAccepted: 'Skill removal started',
|
||||
skillEmpty: 'No skills installed yet. Upload a zip bundle to install one.',
|
||||
skillEmpty: '아직 설치된 스킬이 없습니다. 레지스트리 URL을 붙여넣거나 zip을 업로드하세요.',
|
||||
skillVersion: 'Version',
|
||||
skillVersionEmpty: 'Not specified',
|
||||
skillError: 'Error',
|
||||
|
|
|
|||
|
|
@ -5116,10 +5116,17 @@ export default {
|
|||
skillRolloutSaveFailed: 'Не удалось сохранить способ применения',
|
||||
skillInstallGroup: 'Установить навык',
|
||||
skillInstalledGroup: 'Установленные',
|
||||
skillUploadClick: 'Click to upload a skill bundle',
|
||||
skillUploadDrag: 'or drop a .zip file here',
|
||||
skillUploadHint: 'Загрузка устанавливает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
|
||||
skillUploadHintNewSession: 'Загрузка устанавливает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык появится только у новых сессий.',
|
||||
skillUploadClick: 'Нажмите, чтобы загрузить zip',
|
||||
skillUploadDrag: 'или перетащите файл сюда',
|
||||
skillUploadHint: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Текущий ход диалога не прерывается; открытые сессии пересоздадут песочницу при следующем сообщении, и тогда черновики рабочей области сессии будут очищены.',
|
||||
skillUploadHintNewSession: 'Установка записывает навык в текущий образ и создаёт новый снимок. Это может занять несколько минут. Уже открытые сессии продолжают использовать текущую песочницу до своего завершения; этот навык появится только у новых сессий.',
|
||||
skillSourcePlaceholder: 'Вставьте URL или {\'@\'}owner/slug',
|
||||
skillSourceTokenLabel: 'Токен закрытого SkillHub',
|
||||
skillSourceTokenPlaceholder: 'Необязательно',
|
||||
skillSourceTokenHint: 'Нужен только для собственного или закрытого SkillHub. Используется только для этой загрузки и не сохраняется.',
|
||||
skillSourceInstall: 'Установить',
|
||||
skillInstallOr: 'или',
|
||||
skillSourceFailed: 'Не удалось установить навык из реестра',
|
||||
skillUploadFailed: 'Failed to upload the skill',
|
||||
skillUploading: 'Uploading {percent}%',
|
||||
skillUploadAccepted: 'Skill install started',
|
||||
|
|
@ -5148,7 +5155,7 @@ export default {
|
|||
skillLoadFailed: 'Failed to load skills',
|
||||
skillToggleFailed: 'Failed to update the skill',
|
||||
skillDeleteAccepted: 'Skill removal started',
|
||||
skillEmpty: 'No skills installed yet. Upload a zip bundle to install one.',
|
||||
skillEmpty: 'Навыки ещё не установлены. Вставьте URL реестра или загрузите zip.',
|
||||
skillVersion: 'Version',
|
||||
skillVersionEmpty: 'Not specified',
|
||||
skillError: 'Error',
|
||||
|
|
|
|||
|
|
@ -5118,10 +5118,17 @@ export default {
|
|||
skillRolloutSaveFailed: '保存生效方式失败',
|
||||
skillInstallGroup: '安装新技能',
|
||||
skillInstalledGroup: '已安装',
|
||||
skillUploadClick: '点击上传技能压缩包',
|
||||
skillUploadDrag: '或将 .zip 拖到此处',
|
||||
skillUploadHint: '上传后会在当前镜像上安装该技能并生成新快照,可能需要数分钟。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙箱,会话工作区草稿会在那时清空。',
|
||||
skillUploadHintNewSession: '上传后会在当前镜像上安装该技能并生成新快照,可能需要数分钟。已打开的会话继续使用原沙箱,直到该会话结束;只有新打开的会话才会带上这次安装的技能。',
|
||||
skillUploadClick: '点击上传 zip 压缩包',
|
||||
skillUploadDrag: '或将文件拖到此处',
|
||||
skillUploadHint: '安装会在当前镜像上生成新快照,可能需要数分钟。当前这一轮对话不会中断;下一轮提问时才会按新镜像重建沙箱,会话工作区草稿会在那时清空。',
|
||||
skillUploadHintNewSession: '安装会在当前镜像上生成新快照,可能需要数分钟。已打开的会话继续使用原沙箱,直到该会话结束;只有新打开的会话才会带上这次安装的技能。',
|
||||
skillSourcePlaceholder: '粘贴链接或 {\'@\'}owner/slug',
|
||||
skillSourceTokenLabel: '私有 SkillHub 访问令牌',
|
||||
skillSourceTokenPlaceholder: '可选',
|
||||
skillSourceTokenHint: '只发给这个平台,不会保存。公开 ClawHub / GitHub 技能不用填。',
|
||||
skillSourceInstall: '安装',
|
||||
skillInstallOr: '或',
|
||||
skillSourceFailed: '从托管平台安装技能失败',
|
||||
skillUploadFailed: '技能上传失败',
|
||||
skillUploading: '正在上传 {percent}%',
|
||||
skillUploadAccepted: '已开始安装技能',
|
||||
|
|
@ -5150,7 +5157,7 @@ export default {
|
|||
skillLoadFailed: '加载技能列表失败',
|
||||
skillToggleFailed: '更新技能状态失败',
|
||||
skillDeleteAccepted: '已开始删除技能',
|
||||
skillEmpty: '尚未安装技能。上传压缩包即可安装。',
|
||||
skillEmpty: '尚未安装技能。粘贴托管平台链接,或上传 zip。',
|
||||
skillVersion: '版本',
|
||||
skillVersionEmpty: '未填写',
|
||||
skillError: '错误',
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
|
|
@ -43,10 +44,43 @@ type SkillBundle struct {
|
|||
Files map[string][]byte
|
||||
}
|
||||
|
||||
// SkillBundleParseOptions relaxes the uploaded-zip rules for archives pulled
|
||||
// from a git host or registry, which wrap the skill in a repo directory and
|
||||
// ship README/LICENSE next to it.
|
||||
type SkillBundleParseOptions struct {
|
||||
// Subdir is a skill-root path inside the archive (after any single wrap
|
||||
// directory). Empty means "find SKILL.md by the usual rules".
|
||||
Subdir string
|
||||
// AllowExtraFiles keeps files under the skill root and drops the rest,
|
||||
// instead of rejecting a GitHub zip that also contains the repo README.
|
||||
AllowExtraFiles bool
|
||||
// AllowNestedSkill accepts a unique SKILL.md nested deeper than one
|
||||
// directory, which is how monorepos and GitHub zipballs arrive.
|
||||
AllowNestedSkill bool
|
||||
}
|
||||
|
||||
// ParseSkillBundle validates an uploaded zip and extracts everything the
|
||||
// install flow needs. It accepts both a flat archive and one wrapped in a
|
||||
// single top-level directory, because both are what people actually upload.
|
||||
func ParseSkillBundle(archive []byte) (*SkillBundle, error) {
|
||||
return ParseSkillBundleWithOptions(archive, SkillBundleParseOptions{})
|
||||
}
|
||||
|
||||
// ParseSkillBundleWithOptions is ParseSkillBundle with the extra knobs remote
|
||||
// installs need. SHA256 is still over the input bytes, not the re-rooted view.
|
||||
func ParseSkillBundleWithOptions(archive []byte, opts SkillBundleParseOptions) (*SkillBundle, error) {
|
||||
raw, err := unzipSkillArchive(archive)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files, err := stripSkillRootPrefix(raw, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return skillBundleFromFiles(archive, files)
|
||||
}
|
||||
|
||||
func unzipSkillArchive(archive []byte) (map[string][]byte, error) {
|
||||
reader, err := zip.NewReader(bytes.NewReader(archive), int64(len(archive)))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: not a readable zip archive: %v", ErrSkillBundleInvalid, err)
|
||||
|
|
@ -103,12 +137,10 @@ func ParseSkillBundle(archive []byte) (*SkillBundle, error) {
|
|||
}
|
||||
raw[name] = content
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
files, err := stripSkillRootPrefix(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func skillBundleFromFiles(archive []byte, files map[string][]byte) (*SkillBundle, error) {
|
||||
manifest, ok := files["SKILL.md"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: SKILL.md is missing", ErrSkillBundleInvalid)
|
||||
|
|
@ -133,6 +165,32 @@ func ParseSkillBundle(archive []byte) (*SkillBundle, error) {
|
|||
}, nil
|
||||
}
|
||||
|
||||
// zipSkillFiles writes a deterministic skill-root zip so a remote archive that
|
||||
// had to be re-rooted can go through the same InstallSkill path as an upload.
|
||||
func zipSkillFiles(files map[string][]byte) ([]byte, error) {
|
||||
names := make([]string, 0, len(files))
|
||||
for name := range files {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
var buf bytes.Buffer
|
||||
writer := zip.NewWriter(&buf)
|
||||
for _, name := range names {
|
||||
entry, err := writer.Create(name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("write skill zip entry %q: %w", name, err)
|
||||
}
|
||||
if _, err := entry.Write(files[name]); err != nil {
|
||||
return nil, fmt.Errorf("write skill zip entry %q: %w", name, err)
|
||||
}
|
||||
}
|
||||
if err := writer.Close(); err != nil {
|
||||
return nil, fmt.Errorf("close skill zip: %w", err)
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// validateSkillEntryName bans control characters and nothing else.
|
||||
//
|
||||
// Shell safety is not this function's job: every interpolation of a bundle
|
||||
|
|
@ -193,36 +251,85 @@ func parseSkillBundleVersion(manifest string) (string, error) {
|
|||
}
|
||||
|
||||
// stripSkillRootPrefix re-roots the archive at the directory holding SKILL.md.
|
||||
func stripSkillRootPrefix(raw map[string][]byte) (map[string][]byte, error) {
|
||||
if _, ok := raw["SKILL.md"]; ok {
|
||||
return raw, nil
|
||||
}
|
||||
var prefix string
|
||||
for name := range raw {
|
||||
if path.Base(name) != "SKILL.md" {
|
||||
continue
|
||||
}
|
||||
dir := path.Dir(name)
|
||||
if dir == "." || strings.Contains(dir, "/") {
|
||||
// Either already handled above, or nested deeper than one level:
|
||||
// we refuse to guess which of several directories is the skill.
|
||||
continue
|
||||
}
|
||||
if prefix != "" && prefix != dir {
|
||||
return nil, fmt.Errorf("%w: archive holds more than one skill", ErrSkillBundleInvalid)
|
||||
}
|
||||
prefix = dir
|
||||
func stripSkillRootPrefix(raw map[string][]byte, opts SkillBundleParseOptions) (map[string][]byte, error) {
|
||||
prefix, err := skillRootPrefix(raw, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if prefix == "" {
|
||||
return nil, fmt.Errorf("%w: SKILL.md is missing", ErrSkillBundleInvalid)
|
||||
return raw, nil
|
||||
}
|
||||
out := make(map[string][]byte, len(raw))
|
||||
for name, content := range raw {
|
||||
if !strings.HasPrefix(name, prefix+"/") {
|
||||
if opts.AllowExtraFiles {
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("%w: archive holds files outside the skill directory %q",
|
||||
ErrSkillBundleInvalid, prefix)
|
||||
}
|
||||
out[strings.TrimPrefix(name, prefix+"/")] = content
|
||||
}
|
||||
if _, ok := out["SKILL.md"]; !ok {
|
||||
return nil, fmt.Errorf("%w: SKILL.md is missing", ErrSkillBundleInvalid)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func skillRootPrefix(raw map[string][]byte, opts SkillBundleParseOptions) (string, error) {
|
||||
subdir := path.Clean(strings.Trim(opts.Subdir, "/"))
|
||||
if subdir == "." {
|
||||
subdir = ""
|
||||
}
|
||||
// A SKILL.md at the zip root is the skill. Nested SKILL.md files are then
|
||||
// just extra files, the same way an uploaded bundle vendors them.
|
||||
if subdir == "" {
|
||||
if _, ok := raw["SKILL.md"]; ok {
|
||||
return "", nil
|
||||
}
|
||||
}
|
||||
|
||||
var matches []string
|
||||
for name := range raw {
|
||||
if path.Base(name) != "SKILL.md" {
|
||||
continue
|
||||
}
|
||||
dir := path.Dir(name)
|
||||
if dir == "." {
|
||||
dir = ""
|
||||
}
|
||||
if subdir != "" {
|
||||
if dir == subdir || strings.HasSuffix(dir, "/"+subdir) {
|
||||
matches = append(matches, dir)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if dir == "" || !strings.Contains(dir, "/") || opts.AllowNestedSkill {
|
||||
matches = append(matches, dir)
|
||||
}
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
if subdir != "" {
|
||||
return "", fmt.Errorf("%w: SKILL.md is missing under %q", ErrSkillBundleInvalid, subdir)
|
||||
}
|
||||
return "", fmt.Errorf("%w: SKILL.md is missing", ErrSkillBundleInvalid)
|
||||
}
|
||||
uniq := uniqueStrings(matches)
|
||||
if len(uniq) > 1 {
|
||||
return "", fmt.Errorf("%w: archive holds more than one skill", ErrSkillBundleInvalid)
|
||||
}
|
||||
return uniq[0], nil
|
||||
}
|
||||
|
||||
func uniqueStrings(in []string) []string {
|
||||
seen := make(map[string]struct{}, len(in))
|
||||
out := make([]string, 0, len(in))
|
||||
for _, v := range in {
|
||||
if _, ok := seen[v]; ok {
|
||||
continue
|
||||
}
|
||||
seen[v] = struct{}{}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -208,6 +208,23 @@ Use scripts/extract.py to pull text out of a PDF.
|
|||
"paths must be relative to the skill root, not to the archive root")
|
||||
})
|
||||
|
||||
t.Run("remote options re-root a nested unique skill and drop extras", func(t *testing.T) {
|
||||
data := zipBundle(t, map[string]string{
|
||||
"repo-main/README.md": "noise",
|
||||
"repo-main/skills/pdf/SKILL.md": validSkillMD,
|
||||
"repo-main/skills/pdf/run.py": "print(1)\n",
|
||||
})
|
||||
bundle, err := ParseSkillBundleWithOptions(data, SkillBundleParseOptions{
|
||||
Subdir: "skills/pdf",
|
||||
AllowExtraFiles: true,
|
||||
AllowNestedSkill: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "pdf-tools", bundle.Name)
|
||||
require.Contains(t, bundle.Files, "run.py")
|
||||
require.NotContains(t, bundle.Files, "README.md")
|
||||
})
|
||||
|
||||
t.Run("rejects files outside the wrapped skill directory", func(t *testing.T) {
|
||||
_, err := ParseSkillBundle(zipBundle(t, map[string]string{
|
||||
"pdf-tools/SKILL.md": validSkillMD,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package service
|
|||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
|
|
@ -78,6 +79,10 @@ type TenantSkillService struct {
|
|||
|
||||
now func() time.Time
|
||||
|
||||
// sourceHTTP pulls remote skill archives. Nil means the package SSRF-safe
|
||||
// default; tests inject httptest clients.
|
||||
sourceHTTP *http.Client
|
||||
|
||||
// cleanupTimeout bounds one piece of compensating work. Injectable so a
|
||||
// test can let an install outlast it, which every real install does.
|
||||
cleanupTimeout time.Duration
|
||||
|
|
|
|||
|
|
@ -0,0 +1,704 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// ErrSkillSourceInvalid marks every rejection of a registry / git / URL
|
||||
// source so the handler can map the class to 400 without matching on text.
|
||||
var ErrSkillSourceInvalid = errors.New("skill source is invalid")
|
||||
|
||||
const (
|
||||
defaultSkillRegistryOrigin = "https://clawhub.ai"
|
||||
skillSourceUserAgent = "WeKnora-SkillInstaller (+https://github.com/Tencent/WeKnora)"
|
||||
skillSourceFetchTimeout = 60 * time.Second
|
||||
skillSourceMaxHops = 3
|
||||
)
|
||||
|
||||
var (
|
||||
skillSourceHTTPOnce sync.Once
|
||||
skillSourceHTTPDefault *http.Client
|
||||
|
||||
semverLike = regexp.MustCompile(`^v?\d+\.\d+(\.\d+)?([.-][0-9A-Za-z.-]+)?$`)
|
||||
gitSHALike = regexp.MustCompile(`^[0-9a-fA-F]{7,40}$`)
|
||||
)
|
||||
|
||||
type skillSourceKind string
|
||||
|
||||
const (
|
||||
skillSourceRegistry skillSourceKind = "registry"
|
||||
skillSourceGitHub skillSourceKind = "github"
|
||||
skillSourceGitLab skillSourceKind = "gitlab"
|
||||
skillSourceDirect skillSourceKind = "direct"
|
||||
)
|
||||
|
||||
// parsedSkillSource is one install input after host-specific URL/slug rules
|
||||
// have been applied, and before any bytes are fetched.
|
||||
type parsedSkillSource struct {
|
||||
Kind skillSourceKind
|
||||
Registry string // origin, e.g. https://clawhub.ai or a SkillHub host
|
||||
Slug string
|
||||
Version string
|
||||
Owner string
|
||||
Repo string
|
||||
Ref string
|
||||
Subdir string
|
||||
DirectURL string
|
||||
}
|
||||
|
||||
type skillSourceHandoff struct {
|
||||
SourceRef string `json:"sourceRef"`
|
||||
Repo string `json:"repo"`
|
||||
Commit string `json:"commit"`
|
||||
Path string `json:"path"`
|
||||
ArchiveURL string `json:"archiveUrl"`
|
||||
DownloadURL string `json:"downloadUrl"`
|
||||
}
|
||||
|
||||
// InstallSkillFromSource resolves a ClawHub / SkillHub / skills.sh / git /
|
||||
// direct-zip locator to a skill bundle and runs the same install as an upload.
|
||||
func (s *TenantSkillService) InstallSkillFromSource(
|
||||
ctx context.Context, tenantID uint64, configID, source, token string,
|
||||
) (string, error) {
|
||||
archive, err := fetchSkillArchive(ctx, source, token, s.sourceHTTP)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.InstallSkill(ctx, tenantID, configID, archive)
|
||||
}
|
||||
|
||||
func skillSourceHTTPClient(override *http.Client) *http.Client {
|
||||
if override != nil {
|
||||
return override
|
||||
}
|
||||
skillSourceHTTPOnce.Do(func() {
|
||||
cfg := secutils.DefaultSSRFSafeHTTPClientConfig()
|
||||
cfg.Timeout = skillSourceFetchTimeout
|
||||
skillSourceHTTPDefault = secutils.NewSSRFSafeHTTPClient(cfg)
|
||||
})
|
||||
return skillSourceHTTPDefault
|
||||
}
|
||||
|
||||
func fetchSkillArchive(ctx context.Context, source, token string, client *http.Client) ([]byte, error) {
|
||||
parsed, err := parseSkillSource(source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
httpClient := skillSourceHTTPClient(client)
|
||||
body, contentType, err := fetchSkillSourceBytes(ctx, httpClient, parsed, token, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return normalizeFetchedSkillArchive(body, contentType, parsed.Subdir)
|
||||
}
|
||||
|
||||
func parseSkillSource(raw string) (parsedSkillSource, error) {
|
||||
input := strings.TrimSpace(raw)
|
||||
if input == "" {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: source is required", ErrSkillSourceInvalid)
|
||||
}
|
||||
input = strings.TrimRight(input, "/")
|
||||
|
||||
if strings.Contains(input, "://") {
|
||||
return parseSkillSourceURL(input)
|
||||
}
|
||||
if strings.HasPrefix(input, "@") {
|
||||
return parseRegistrySlug(defaultSkillRegistryOrigin, strings.TrimPrefix(input, "@"))
|
||||
}
|
||||
if looksLikeGitHubShorthand(input) {
|
||||
return parseGitHubShorthand(input)
|
||||
}
|
||||
return parseRegistrySlug(defaultSkillRegistryOrigin, input)
|
||||
}
|
||||
|
||||
func parseSkillSourceURL(raw string) (parsedSkillSource, error) {
|
||||
parsedURL, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: not a valid URL", ErrSkillSourceInvalid)
|
||||
}
|
||||
if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: only http(s) sources are allowed", ErrSkillSourceInvalid)
|
||||
}
|
||||
host := strings.ToLower(parsedURL.Hostname())
|
||||
switch {
|
||||
case host == "github.com" || host == "www.github.com" || host == "codeload.github.com":
|
||||
if host == "codeload.github.com" {
|
||||
return parsedSkillSource{Kind: skillSourceDirect, DirectURL: parsedURL.String()}, nil
|
||||
}
|
||||
return parseGitHubURL(parsedURL)
|
||||
case host == "gitlab.com" || host == "www.gitlab.com":
|
||||
return parseGitLabURL(parsedURL)
|
||||
case host == "skills.sh" || host == "www.skills.sh":
|
||||
return parseSkillsShURL(parsedURL)
|
||||
case isClawHubHost(host):
|
||||
return parseRegistryURL(parsedURL)
|
||||
case isSkillHubCNHost(host):
|
||||
return parseSkillHubCNURL(parsedURL)
|
||||
default:
|
||||
if isDirectArchivePath(parsedURL.Path) {
|
||||
return parsedSkillSource{Kind: skillSourceDirect, DirectURL: parsedURL.String()}, nil
|
||||
}
|
||||
return parseRegistryURL(parsedURL)
|
||||
}
|
||||
}
|
||||
|
||||
func isClawHubHost(host string) bool {
|
||||
switch host {
|
||||
case "clawhub.ai", "www.clawhub.ai", "clawhub.com", "www.clawhub.com":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
const skillHubCNAPIOrigin = "https://api.skillhub.cn"
|
||||
|
||||
func isSkillHubCNHost(host string) bool {
|
||||
switch strings.ToLower(host) {
|
||||
case "skillhub.cn", "www.skillhub.cn", "api.skillhub.cn":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// parseSkillHubCNURL maps public SkillHub.cn pages onto the download API.
|
||||
// Page URLs look like /skills/{slug} or /skills/{publisher}/{slug}; the API
|
||||
// keys downloads by the skill name only, on api.skillhub.cn (www is an SPA).
|
||||
func parseSkillHubCNURL(u *url.URL) (parsedSkillSource, error) {
|
||||
trimmed := strings.Trim(u.Path, "/")
|
||||
if strings.HasPrefix(trimmed, "api/v1/download") {
|
||||
direct := skillHubCNAPIOrigin + "/api/v1/download"
|
||||
if u.RawQuery != "" {
|
||||
direct += "?" + u.RawQuery
|
||||
}
|
||||
return parsedSkillSource{
|
||||
Kind: skillSourceDirect,
|
||||
Registry: skillHubCNAPIOrigin,
|
||||
DirectURL: direct,
|
||||
}, nil
|
||||
}
|
||||
parts := splitPath(trimmed)
|
||||
if len(parts) >= 1 && strings.EqualFold(parts[0], "skills") {
|
||||
parts = parts[1:]
|
||||
}
|
||||
if len(parts) == 0 || len(parts) > 2 {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: unrecognized registry path", ErrSkillSourceInvalid)
|
||||
}
|
||||
slug := parts[len(parts)-1]
|
||||
version := strings.TrimSpace(u.Fragment)
|
||||
if qVersion := strings.TrimSpace(u.Query().Get("version")); qVersion != "" {
|
||||
version = qVersion
|
||||
}
|
||||
slug, fromSpec := splitTrailingVersion(slug)
|
||||
if fromSpec != "" {
|
||||
version = fromSpec
|
||||
}
|
||||
if slug == "" {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: skill slug is required", ErrSkillSourceInvalid)
|
||||
}
|
||||
return parsedSkillSource{
|
||||
Kind: skillSourceRegistry,
|
||||
Registry: skillHubCNAPIOrigin,
|
||||
Slug: slug,
|
||||
Version: version,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseRegistryURL(u *url.URL) (parsedSkillSource, error) {
|
||||
origin := u.Scheme + "://" + u.Host
|
||||
trimmed := strings.Trim(u.Path, "/")
|
||||
if strings.HasPrefix(trimmed, "api/v1/download") {
|
||||
return parsedSkillSource{
|
||||
Kind: skillSourceDirect,
|
||||
Registry: origin,
|
||||
DirectURL: u.String(),
|
||||
}, nil
|
||||
}
|
||||
slug, version, err := slugAndVersionFromPath(trimmed, u.Fragment)
|
||||
if err != nil {
|
||||
return parsedSkillSource{}, err
|
||||
}
|
||||
if qVersion := strings.TrimSpace(u.Query().Get("version")); qVersion != "" {
|
||||
version = qVersion
|
||||
}
|
||||
return parsedSkillSource{
|
||||
Kind: skillSourceRegistry,
|
||||
Registry: origin,
|
||||
Slug: slug,
|
||||
Version: version,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseRegistrySlug(origin, spec string) (parsedSkillSource, error) {
|
||||
spec = strings.TrimSpace(strings.TrimPrefix(spec, "@"))
|
||||
if spec == "" {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: skill slug is required", ErrSkillSourceInvalid)
|
||||
}
|
||||
slug, version := splitTrailingVersion(spec)
|
||||
if slug == "" {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: skill slug is required", ErrSkillSourceInvalid)
|
||||
}
|
||||
return parsedSkillSource{
|
||||
Kind: skillSourceRegistry,
|
||||
Registry: origin,
|
||||
Slug: slug,
|
||||
Version: version,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func slugAndVersionFromPath(trimmed, fragment string) (string, string, error) {
|
||||
if trimmed == "" {
|
||||
return "", "", fmt.Errorf("%w: skill slug is required", ErrSkillSourceInvalid)
|
||||
}
|
||||
parts := splitPath(trimmed)
|
||||
if len(parts) >= 1 && strings.EqualFold(parts[0], "skills") {
|
||||
parts = parts[1:]
|
||||
}
|
||||
if len(parts) >= 3 && strings.EqualFold(parts[1], "skills") {
|
||||
parts = []string{parts[0], parts[2]}
|
||||
}
|
||||
if len(parts) > 2 {
|
||||
return "", "", fmt.Errorf("%w: unrecognized registry path", ErrSkillSourceInvalid)
|
||||
}
|
||||
slug := strings.Join(parts, "/")
|
||||
version := strings.TrimSpace(fragment)
|
||||
slug, fromSpec := splitTrailingVersion(slug)
|
||||
if fromSpec != "" {
|
||||
version = fromSpec
|
||||
}
|
||||
if slug == "" {
|
||||
return "", "", fmt.Errorf("%w: skill slug is required", ErrSkillSourceInvalid)
|
||||
}
|
||||
return slug, version, nil
|
||||
}
|
||||
|
||||
func parseGitHubURL(u *url.URL) (parsedSkillSource, error) {
|
||||
parts := splitPath(u.Path)
|
||||
if len(parts) < 2 {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: github URL must be owner/repo", ErrSkillSourceInvalid)
|
||||
}
|
||||
owner, repo := parts[0], strings.TrimSuffix(parts[1], ".git")
|
||||
src := parsedSkillSource{Kind: skillSourceGitHub, Owner: owner, Repo: repo, Ref: "HEAD"}
|
||||
rest := parts[2:]
|
||||
if len(rest) == 0 {
|
||||
return src, nil
|
||||
}
|
||||
switch rest[0] {
|
||||
case "tree", "blob":
|
||||
if len(rest) < 2 {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: github tree URL is missing a ref", ErrSkillSourceInvalid)
|
||||
}
|
||||
src.Ref = rest[1]
|
||||
src.Subdir = strings.Join(rest[2:], "/")
|
||||
if rest[0] == "blob" && strings.EqualFold(path.Base(src.Subdir), "SKILL.md") {
|
||||
src.Subdir = path.Dir(src.Subdir)
|
||||
if src.Subdir == "." {
|
||||
src.Subdir = ""
|
||||
}
|
||||
}
|
||||
case "archive":
|
||||
src.DirectURL = u.String()
|
||||
src.Kind = skillSourceDirect
|
||||
case "releases":
|
||||
src.DirectURL = u.String()
|
||||
src.Kind = skillSourceDirect
|
||||
default:
|
||||
src.Subdir = strings.Join(rest, "/")
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
func parseGitLabURL(u *url.URL) (parsedSkillSource, error) {
|
||||
trimmed := strings.Trim(u.Path, "/")
|
||||
project, extra, found := strings.Cut(trimmed, "/-/")
|
||||
if !found {
|
||||
project = trimmed
|
||||
}
|
||||
parts := splitPath(project)
|
||||
if len(parts) < 2 {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: gitlab URL must be group/project", ErrSkillSourceInvalid)
|
||||
}
|
||||
repo := strings.TrimSuffix(parts[len(parts)-1], ".git")
|
||||
owner := strings.Join(parts[:len(parts)-1], "/")
|
||||
src := parsedSkillSource{Kind: skillSourceGitLab, Owner: owner, Repo: repo, Ref: "HEAD"}
|
||||
if extra == "" {
|
||||
return src, nil
|
||||
}
|
||||
extraParts := splitPath(extra)
|
||||
switch extraParts[0] {
|
||||
case "tree", "blob":
|
||||
if len(extraParts) < 2 {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: gitlab tree URL is missing a ref", ErrSkillSourceInvalid)
|
||||
}
|
||||
src.Ref = extraParts[1]
|
||||
src.Subdir = strings.Join(extraParts[2:], "/")
|
||||
if extraParts[0] == "blob" && strings.EqualFold(path.Base(src.Subdir), "SKILL.md") {
|
||||
src.Subdir = path.Dir(src.Subdir)
|
||||
if src.Subdir == "." {
|
||||
src.Subdir = ""
|
||||
}
|
||||
}
|
||||
case "archive":
|
||||
src.DirectURL = u.String()
|
||||
src.Kind = skillSourceDirect
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
func parseSkillsShURL(u *url.URL) (parsedSkillSource, error) {
|
||||
parts := splitPath(u.Path)
|
||||
if len(parts) < 2 {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: skills.sh URL must be owner/repo", ErrSkillSourceInvalid)
|
||||
}
|
||||
src := parsedSkillSource{
|
||||
Kind: skillSourceGitHub,
|
||||
Owner: parts[0],
|
||||
Repo: strings.TrimSuffix(parts[1], ".git"),
|
||||
Ref: "HEAD",
|
||||
}
|
||||
if len(parts) > 2 {
|
||||
src.Subdir = strings.Join(parts[2:], "/")
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
func parseGitHubShorthand(spec string) (parsedSkillSource, error) {
|
||||
ownerRepo, suffix, ok := strings.Cut(spec, "@")
|
||||
parts := splitPath(ownerRepo)
|
||||
if len(parts) < 2 {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: expected owner/repo", ErrSkillSourceInvalid)
|
||||
}
|
||||
src := parsedSkillSource{
|
||||
Kind: skillSourceGitHub,
|
||||
Owner: parts[0],
|
||||
Repo: strings.TrimSuffix(parts[1], ".git"),
|
||||
Ref: "HEAD",
|
||||
}
|
||||
if len(parts) > 2 {
|
||||
src.Subdir = strings.Join(parts[2:], "/")
|
||||
}
|
||||
if !ok || suffix == "" {
|
||||
return src, nil
|
||||
}
|
||||
if looksLikeGitRef(suffix) {
|
||||
src.Ref = suffix
|
||||
return src, nil
|
||||
}
|
||||
// owner/repo@skill-name selects one skill out of a monorepo by directory
|
||||
// (or by matching the last path segment).
|
||||
if src.Subdir == "" {
|
||||
src.Subdir = suffix
|
||||
} else {
|
||||
src.Subdir = path.Join(src.Subdir, suffix)
|
||||
}
|
||||
return src, nil
|
||||
}
|
||||
|
||||
func looksLikeGitHubShorthand(spec string) bool {
|
||||
ownerRepo, _, _ := strings.Cut(spec, "@")
|
||||
parts := splitPath(ownerRepo)
|
||||
if len(parts) < 2 {
|
||||
return false
|
||||
}
|
||||
for _, p := range parts[:2] {
|
||||
if p == "" || strings.ContainsAny(p, " \\") {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func looksLikeGitRef(s string) bool {
|
||||
switch strings.ToLower(s) {
|
||||
case "head", "main", "master", "develop", "trunk":
|
||||
return true
|
||||
}
|
||||
if semverLike.MatchString(s) || gitSHALike.MatchString(s) {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(s, "refs/")
|
||||
}
|
||||
|
||||
func splitTrailingVersion(spec string) (slug, version string) {
|
||||
i := strings.LastIndex(spec, "@")
|
||||
if i <= 0 {
|
||||
return spec, ""
|
||||
}
|
||||
candidate := spec[i+1:]
|
||||
if strings.EqualFold(candidate, "latest") || semverLike.MatchString(candidate) {
|
||||
return spec[:i], candidate
|
||||
}
|
||||
return spec, ""
|
||||
}
|
||||
|
||||
func splitPath(p string) []string {
|
||||
var out []string
|
||||
for _, part := range strings.Split(strings.Trim(p, "/"), "/") {
|
||||
if part == "" || part == "." {
|
||||
continue
|
||||
}
|
||||
out = append(out, part)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func isDirectArchivePath(p string) bool {
|
||||
lower := strings.ToLower(p)
|
||||
for _, ext := range []string{".zip", ".tgz", ".tar.gz", ".tar", ".md"} {
|
||||
if strings.HasSuffix(lower, ext) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s parsedSkillSource) fetchURL() (string, error) {
|
||||
if s.DirectURL != "" {
|
||||
return s.DirectURL, nil
|
||||
}
|
||||
switch s.Kind {
|
||||
case skillSourceRegistry:
|
||||
u, err := url.Parse(strings.TrimRight(s.Registry, "/") + "/api/v1/download")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: invalid registry origin", ErrSkillSourceInvalid)
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("slug", s.Slug)
|
||||
if s.Version != "" && !strings.EqualFold(s.Version, "latest") {
|
||||
if semverLike.MatchString(s.Version) {
|
||||
q.Set("version", s.Version)
|
||||
} else {
|
||||
q.Set("tag", s.Version)
|
||||
}
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
return u.String(), nil
|
||||
case skillSourceGitHub:
|
||||
ref := s.Ref
|
||||
if ref == "" {
|
||||
ref = "HEAD"
|
||||
}
|
||||
return fmt.Sprintf("https://codeload.github.com/%s/%s/zip/%s",
|
||||
s.Owner, s.Repo, ref), nil
|
||||
case skillSourceGitLab:
|
||||
ref := s.Ref
|
||||
if ref == "" {
|
||||
ref = "HEAD"
|
||||
}
|
||||
return fmt.Sprintf("https://gitlab.com/%s/%s/-/archive/%s/%s-%s.zip",
|
||||
s.Owner, s.Repo, ref, s.Repo, ref), nil
|
||||
default:
|
||||
return "", fmt.Errorf("%w: cannot resolve source", ErrSkillSourceInvalid)
|
||||
}
|
||||
}
|
||||
|
||||
func fetchSkillSourceBytes(
|
||||
ctx context.Context, client *http.Client, src parsedSkillSource, token string, hop int,
|
||||
) ([]byte, string, error) {
|
||||
if hop > skillSourceMaxHops {
|
||||
return nil, "", fmt.Errorf("%w: too many source redirects", ErrSkillSourceInvalid)
|
||||
}
|
||||
target, err := src.fetchURL()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
body, contentType, err := getSkillURL(ctx, client, target, token, shouldSendSkillToken(src, token))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if isZipMagic(body) || looksLikeSkillMarkdown(body) {
|
||||
return body, contentType, nil
|
||||
}
|
||||
if !looksLikeJSON(contentType, body) {
|
||||
if isZipPayload(contentType, body) {
|
||||
return body, contentType, nil
|
||||
}
|
||||
return nil, "", fmt.Errorf("%w: remote did not return a skill archive", ErrSkillSourceInvalid)
|
||||
}
|
||||
var handoff skillSourceHandoff
|
||||
if err := json.Unmarshal(body, &handoff); err != nil {
|
||||
return nil, "", fmt.Errorf("%w: remote JSON is not a skill archive", ErrSkillSourceInvalid)
|
||||
}
|
||||
next, err := sourceFromHandoff(src, handoff)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
return fetchSkillSourceBytes(ctx, client, next, token, hop+1)
|
||||
}
|
||||
|
||||
func shouldSendSkillToken(src parsedSkillSource, token string) bool {
|
||||
if token == "" || src.Kind == skillSourceGitHub || src.Kind == skillSourceGitLab {
|
||||
return false
|
||||
}
|
||||
target, err := src.fetchURL()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
host := ""
|
||||
if u, err := url.Parse(target); err == nil {
|
||||
host = strings.ToLower(u.Hostname())
|
||||
}
|
||||
switch host {
|
||||
case "github.com", "www.github.com", "codeload.github.com",
|
||||
"gitlab.com", "www.gitlab.com", "skills.sh", "www.skills.sh":
|
||||
return false
|
||||
}
|
||||
return src.Kind == skillSourceRegistry || src.Kind == skillSourceDirect
|
||||
}
|
||||
|
||||
func sourceFromHandoff(prev parsedSkillSource, handoff skillSourceHandoff) (parsedSkillSource, error) {
|
||||
archiveURL := strings.TrimSpace(handoff.ArchiveURL)
|
||||
if archiveURL == "" {
|
||||
archiveURL = strings.TrimSpace(handoff.DownloadURL)
|
||||
}
|
||||
if archiveURL == "" {
|
||||
return parsedSkillSource{}, fmt.Errorf("%w: registry response has no archive URL", ErrSkillSourceInvalid)
|
||||
}
|
||||
if strings.HasPrefix(archiveURL, "/") {
|
||||
if prev.Registry == "" {
|
||||
return parsedSkillSource{}, fmt.Errorf(
|
||||
"%w: registry response has a relative archive URL", ErrSkillSourceInvalid)
|
||||
}
|
||||
archiveURL = strings.TrimRight(prev.Registry, "/") + archiveURL
|
||||
}
|
||||
next, err := parseSkillSourceURL(archiveURL)
|
||||
if err != nil {
|
||||
next = parsedSkillSource{Kind: skillSourceDirect, DirectURL: archiveURL}
|
||||
}
|
||||
if next.Subdir == "" && strings.TrimSpace(handoff.Path) != "" {
|
||||
next.Subdir = strings.Trim(handoff.Path, "/")
|
||||
}
|
||||
if next.Kind == skillSourceGitHub && next.Ref == "HEAD" && strings.TrimSpace(handoff.Commit) != "" {
|
||||
next.Ref = handoff.Commit
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
|
||||
func getSkillURL(
|
||||
ctx context.Context, client *http.Client, rawURL, token string, sendToken bool,
|
||||
) ([]byte, string, error) {
|
||||
if err := secutils.ValidateURLForSSRF(rawURL); err != nil {
|
||||
return nil, "", fmt.Errorf("%w: %s", ErrSkillSourceInvalid,
|
||||
secutils.FormatSSRFError("skill source", rawURL, err))
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("%w: invalid source URL", ErrSkillSourceInvalid)
|
||||
}
|
||||
req.Header.Set("User-Agent", skillSourceUserAgent)
|
||||
req.Header.Set("Accept", "application/zip, application/octet-stream, application/json, text/plain;q=0.9, */*;q=0.8")
|
||||
if sendToken && token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
if errors.Is(err, secutils.ErrSSRFRedirectBlocked) {
|
||||
return nil, "", fmt.Errorf("%w: %s", ErrSkillSourceInvalid,
|
||||
secutils.FormatSSRFError("skill source", rawURL, err))
|
||||
}
|
||||
return nil, "", fmt.Errorf("%w: download failed: %v", ErrSkillSourceInvalid, err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
maxBytes := secutils.GetMaxFileSize()
|
||||
if resp.ContentLength > maxBytes {
|
||||
return nil, "", fmt.Errorf("%w: skill bundle cannot exceed %d MB",
|
||||
ErrSkillSourceInvalid, secutils.GetMaxFileSizeMB())
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
preview, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
msg := strings.TrimSpace(string(preview))
|
||||
if msg == "" {
|
||||
msg = resp.Status
|
||||
}
|
||||
return nil, "", fmt.Errorf("%w: download returned HTTP %d: %s",
|
||||
ErrSkillSourceInvalid, resp.StatusCode, truncateSkillError(msg))
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBytes+1))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("%w: failed to read skill archive", ErrSkillSourceInvalid)
|
||||
}
|
||||
if int64(len(body)) > maxBytes {
|
||||
return nil, "", fmt.Errorf("%w: skill bundle cannot exceed %d MB",
|
||||
ErrSkillSourceInvalid, secutils.GetMaxFileSizeMB())
|
||||
}
|
||||
if len(body) == 0 {
|
||||
return nil, "", fmt.Errorf("%w: remote returned an empty body", ErrSkillSourceInvalid)
|
||||
}
|
||||
return body, resp.Header.Get("Content-Type"), nil
|
||||
}
|
||||
|
||||
func normalizeFetchedSkillArchive(body []byte, contentType, subdir string) ([]byte, error) {
|
||||
if looksLikeSkillMarkdown(body) {
|
||||
files := map[string][]byte{"SKILL.md": body}
|
||||
if _, err := skillBundleFromFiles(body, files); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return zipSkillFiles(files)
|
||||
}
|
||||
if !isZipPayload(contentType, body) {
|
||||
return nil, fmt.Errorf("%w: remote did not return a zip skill bundle", ErrSkillSourceInvalid)
|
||||
}
|
||||
opts := SkillBundleParseOptions{
|
||||
Subdir: subdir,
|
||||
AllowExtraFiles: true,
|
||||
AllowNestedSkill: true,
|
||||
}
|
||||
bundle, err := ParseSkillBundleWithOptions(body, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return zipSkillFiles(bundle.Files)
|
||||
}
|
||||
|
||||
func isZipMagic(body []byte) bool {
|
||||
return len(body) >= 4 && bytes.HasPrefix(body, []byte("PK\x03\x04"))
|
||||
}
|
||||
|
||||
func isZipPayload(contentType string, body []byte) bool {
|
||||
if isZipMagic(body) {
|
||||
return true
|
||||
}
|
||||
ct := strings.ToLower(contentType)
|
||||
return strings.Contains(ct, "zip")
|
||||
}
|
||||
|
||||
func looksLikeJSON(contentType string, body []byte) bool {
|
||||
ct := strings.ToLower(contentType)
|
||||
if strings.Contains(ct, "json") {
|
||||
return true
|
||||
}
|
||||
trimmed := bytes.TrimSpace(body)
|
||||
return len(trimmed) > 0 && trimmed[0] == '{'
|
||||
}
|
||||
|
||||
func looksLikeSkillMarkdown(body []byte) bool {
|
||||
trimmed := bytes.TrimSpace(body)
|
||||
if !bytes.HasPrefix(trimmed, []byte("---")) {
|
||||
return false
|
||||
}
|
||||
return bytes.Contains(trimmed, []byte("\nname:")) || bytes.Contains(trimmed, []byte("\nname :"))
|
||||
}
|
||||
|
||||
func truncateSkillError(msg string) string {
|
||||
msg = strings.Join(strings.Fields(msg), " ")
|
||||
if len(msg) > 200 {
|
||||
return msg[:200]
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
|
@ -0,0 +1,274 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParseSkillSource(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want parsedSkillSource
|
||||
}{
|
||||
{
|
||||
name: "clawhub at-slug",
|
||||
in: "@lyingbug/weknora",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: defaultSkillRegistryOrigin,
|
||||
Slug: "lyingbug/weknora",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "clawhub page url",
|
||||
in: "https://clawhub.ai/lyingbug/weknora",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: "https://clawhub.ai",
|
||||
Slug: "lyingbug/weknora",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "clawhub canonical skills path",
|
||||
in: "https://clawhub.ai/steipete/skills/github",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: "https://clawhub.ai",
|
||||
Slug: "steipete/github",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "skillhub team slug",
|
||||
in: "my-team--email-sender",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: defaultSkillRegistryOrigin,
|
||||
Slug: "my-team--email-sender",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "skillhub page with version",
|
||||
in: "https://skillhub.example.com/my-skill@1.2.0",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: "https://skillhub.example.com",
|
||||
Slug: "my-skill", Version: "1.2.0",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "skillhub.cn publisher page",
|
||||
in: "https://skillhub.cn/skills/clawhub_pskoett/self-improving-agent",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: skillHubCNAPIOrigin,
|
||||
Slug: "self-improving-agent",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "skillhub.cn slug page",
|
||||
in: "https://skillhub.cn/skills/evez-api-gateway",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: skillHubCNAPIOrigin,
|
||||
Slug: "evez-api-gateway",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "generic registry skills prefix",
|
||||
in: "https://skillhub.example.com/skills/my-skill",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceRegistry, Registry: "https://skillhub.example.com",
|
||||
Slug: "my-skill",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "github repo url",
|
||||
in: "https://github.com/vercel-labs/agent-skills",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceGitHub, Owner: "vercel-labs", Repo: "agent-skills", Ref: "HEAD",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "github tree path",
|
||||
in: "https://github.com/vercel-labs/agent-skills/tree/main/skills/web-design",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceGitHub, Owner: "vercel-labs", Repo: "agent-skills",
|
||||
Ref: "main", Subdir: "skills/web-design",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "skills.sh maps to github",
|
||||
in: "https://skills.sh/vercel-labs/agent-skills/web-design",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceGitHub, Owner: "vercel-labs", Repo: "agent-skills",
|
||||
Ref: "HEAD", Subdir: "web-design",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "github shorthand",
|
||||
in: "vercel-labs/agent-skills@frontend-design",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceGitHub, Owner: "vercel-labs", Repo: "agent-skills",
|
||||
Ref: "HEAD", Subdir: "frontend-design",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "gitlab project",
|
||||
in: "https://gitlab.com/group/project/-/tree/main/skills/foo",
|
||||
want: parsedSkillSource{
|
||||
Kind: skillSourceGitLab, Owner: "group", Repo: "project",
|
||||
Ref: "main", Subdir: "skills/foo",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "direct zip",
|
||||
in: "https://example.com/skills/demo.zip",
|
||||
want: parsedSkillSource{Kind: skillSourceDirect, DirectURL: "https://example.com/skills/demo.zip"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := parseSkillSource(tt.in)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSkillSourceRejects(t *testing.T) {
|
||||
_, err := parseSkillSource("")
|
||||
require.ErrorIs(t, err, ErrSkillSourceInvalid)
|
||||
|
||||
_, err = parseSkillSource("file:///etc/passwd")
|
||||
require.ErrorIs(t, err, ErrSkillSourceInvalid)
|
||||
require.ErrorContains(t, err, "http(s)")
|
||||
}
|
||||
|
||||
func TestSkillHubCNMapsToDownloadAPI(t *testing.T) {
|
||||
got, err := parseSkillSource("https://skillhub.cn/skills/clawhub_pskoett/self-improving-agent")
|
||||
require.NoError(t, err)
|
||||
u, err := got.fetchURL()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, skillHubCNAPIOrigin+"/api/v1/download?slug=self-improving-agent", u)
|
||||
}
|
||||
|
||||
func TestFetchSkillArchiveFromRegistry(t *testing.T) {
|
||||
archive := zipBundle(t, map[string]string{"SKILL.md": validSkillMD})
|
||||
var sawAuth string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sawAuth = r.Header.Get("Authorization")
|
||||
if r.URL.Path != "/api/v1/download" || r.URL.Query().Get("slug") != "owner/demo" {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
_, _ = w.Write(archive)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
allowLoopbackSkillFetch(t)
|
||||
|
||||
got, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", "sk_test", server.Client())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Bearer sk_test", sawAuth)
|
||||
|
||||
bundle, err := ParseSkillBundle(got)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "pdf-tools", bundle.Name)
|
||||
}
|
||||
|
||||
func TestFetchSkillArchiveFollowsGitHubHandoff(t *testing.T) {
|
||||
archive := zipBundle(t, map[string]string{
|
||||
"repo-main/README.md": "# repo",
|
||||
"repo-main/skills/foo/SKILL.md": validSkillMD,
|
||||
"repo-main/skills/foo/scripts/a.py": "print(1)\n",
|
||||
})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/download":
|
||||
_ = json.NewEncoder(w).Encode(skillSourceHandoff{
|
||||
SourceRef: "public-github",
|
||||
ArchiveURL: "http://" + r.Host + "/archive.zip",
|
||||
Path: "skills/foo",
|
||||
})
|
||||
case "/archive.zip":
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
_, _ = w.Write(archive)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
allowLoopbackSkillFetch(t)
|
||||
|
||||
got, err := fetchSkillArchive(t.Context(), server.URL+"/owner/demo", "", server.Client())
|
||||
require.NoError(t, err)
|
||||
bundle, err := ParseSkillBundle(got)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "pdf-tools", bundle.Name)
|
||||
require.Contains(t, bundle.Files, "scripts/a.py")
|
||||
require.NotContains(t, bundle.Files, "README.md")
|
||||
}
|
||||
|
||||
func TestFetchSkillArchiveFromSkillMarkdown(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/markdown")
|
||||
_, _ = w.Write([]byte(validSkillMD))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
allowLoopbackSkillFetch(t)
|
||||
|
||||
got, err := fetchSkillArchive(t.Context(), server.URL+"/SKILL.md", "", server.Client())
|
||||
require.NoError(t, err)
|
||||
bundle, err := ParseSkillBundle(got)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "pdf-tools", bundle.Name)
|
||||
}
|
||||
|
||||
func TestFetchSkillArchiveDoesNotSendTokenToGitHub(t *testing.T) {
|
||||
src := parsedSkillSource{
|
||||
Kind: skillSourceGitHub, Owner: "o", Repo: "r", Ref: "HEAD",
|
||||
}
|
||||
require.False(t, shouldSendSkillToken(src, "sk_secret"))
|
||||
src.Kind = skillSourceRegistry
|
||||
src.Registry = "https://skillhub.example.com"
|
||||
require.True(t, shouldSendSkillToken(src, "sk_secret"))
|
||||
}
|
||||
|
||||
func TestParseSkillBundleNestedRemoteArchive(t *testing.T) {
|
||||
data := zipBundle(t, map[string]string{
|
||||
"repo-abc/LICENSE": "MIT",
|
||||
"repo-abc/skills/pdf/SKILL.md": validSkillMD,
|
||||
"repo-abc/skills/pdf/extract.py": "print(1)\n",
|
||||
})
|
||||
bundle, err := ParseSkillBundleWithOptions(data, SkillBundleParseOptions{
|
||||
AllowExtraFiles: true,
|
||||
AllowNestedSkill: true,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "pdf-tools", bundle.Name)
|
||||
require.Contains(t, bundle.Files, "extract.py")
|
||||
|
||||
_, err = ParseSkillBundle(data)
|
||||
require.ErrorIs(t, err, ErrSkillBundleInvalid, "uploads stay strict about nesting")
|
||||
}
|
||||
|
||||
func allowLoopbackSkillFetch(t *testing.T) {
|
||||
t.Helper()
|
||||
utils.SetSSRFWhitelistFromRaw("127.0.0.1,::1")
|
||||
t.Cleanup(func() { utils.SetSSRFWhitelistFromRaw("") })
|
||||
}
|
||||
|
||||
func TestFetchSkillArchiveRejectsNonSkillHTML(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
_, _ = w.Write([]byte("<html>not a skill</html>"))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
allowLoopbackSkillFetch(t)
|
||||
|
||||
_, err := fetchSkillArchive(t.Context(), server.URL+"/demo.zip", "", server.Client())
|
||||
require.ErrorIs(t, err, ErrSkillSourceInvalid)
|
||||
require.True(t, strings.Contains(err.Error(), "skill archive") ||
|
||||
strings.Contains(err.Error(), "zip skill bundle"))
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
|
@ -47,6 +48,9 @@ type sandboxSkillService interface {
|
|||
ctx context.Context, tenantID uint64, configID, skillID string, enabled bool,
|
||||
) (*types.TenantSkillEntity, error)
|
||||
InstallSkill(ctx context.Context, tenantID uint64, configID string, archive []byte) (string, error)
|
||||
InstallSkillFromSource(
|
||||
ctx context.Context, tenantID uint64, configID, source, token string,
|
||||
) (string, error)
|
||||
RemoveSkill(ctx context.Context, tenantID uint64, configID, skillID string) error
|
||||
LastProgress(
|
||||
ctx context.Context, tenantID uint64, configID, skillID string,
|
||||
|
|
@ -127,7 +131,7 @@ func toSkillResponse(e *types.TenantSkillEntity) skillResponse {
|
|||
// 400. It is matched as a sentinel rather than by message so a reworded
|
||||
// validation error cannot silently start returning 500 for bad input.
|
||||
func respondSkillServiceError(c *gin.Context, err error) {
|
||||
if stderrors.Is(err, service.ErrSkillBundleInvalid) {
|
||||
if stderrors.Is(err, service.ErrSkillBundleInvalid) || stderrors.Is(err, service.ErrSkillSourceInvalid) {
|
||||
_ = c.Error(apperrors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
|
@ -183,16 +187,21 @@ func (h *SandboxSkillHandler) Get(c *gin.Context) {
|
|||
|
||||
// Upload godoc
|
||||
// @Summary Install a skill
|
||||
// @Description Upload a skill bundle. The install boots a sandbox from the
|
||||
// @Description config's current image and runs for minutes, so the upload is
|
||||
// @Description only accepted; follow it via the install-events stream.
|
||||
// @Description Install a skill onto this sandbox config's image. Send a zip
|
||||
// @Description as multipart form field "file", or JSON {"source":"..."} to
|
||||
// @Description pull from ClawHub, SkillHub, skills.sh, GitHub, GitLab, or a
|
||||
// @Description direct archive URL. The install boots a sandbox and runs for
|
||||
// @Description minutes, so the request is only accepted; follow it via the
|
||||
// @Description install-events stream.
|
||||
// @Tags SandboxConfig
|
||||
// @Accept json
|
||||
// @Accept multipart/form-data
|
||||
// @Produce json
|
||||
// @Param id path string true "Sandbox config ID"
|
||||
// @Param file formData file true "Skill bundle (zip)"
|
||||
// @Success 202 {object} map[string]interface{} "Install accepted"
|
||||
// @Failure 400 {object} apperrors.AppError "Missing, oversized or invalid bundle"
|
||||
// @Param id path string true "Sandbox config ID"
|
||||
// @Param file formData file false "Skill bundle (zip)"
|
||||
// @Param request body skillSourceRequest false "Install from a registry, git host, or archive URL"
|
||||
// @Success 202 {object} map[string]interface{} "Install accepted"
|
||||
// @Failure 400 {object} apperrors.AppError "Missing, oversized or invalid bundle or source"
|
||||
// @Failure 401 {object} map[string]interface{} "Unauthorized"
|
||||
// @Failure 404 {object} apperrors.AppError "Sandbox config not found"
|
||||
// @Security Bearer
|
||||
|
|
@ -205,6 +214,11 @@ func (h *SandboxSkillHandler) Upload(c *gin.Context) {
|
|||
// declared part size would let an unbounded body through first.
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes+skillUploadEnvelopeSlack)
|
||||
|
||||
if strings.HasPrefix(c.ContentType(), "application/json") {
|
||||
h.installFromSource(c)
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := c.Request.FormFile("file")
|
||||
if err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
|
|
@ -242,6 +256,42 @@ func (h *SandboxSkillHandler) Upload(c *gin.Context) {
|
|||
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"skill_id": skillID}})
|
||||
}
|
||||
|
||||
type skillSourceRequest struct {
|
||||
// Source is a ClawHub/SkillHub slug or page URL, a skills.sh / GitHub /
|
||||
// GitLab locator, or a direct zip/SKILL.md URL.
|
||||
Source string `json:"source"`
|
||||
// Token is an optional registry bearer token (private SkillHub). It is
|
||||
// used only for that fetch and is never stored.
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
func (h *SandboxSkillHandler) installFromSource(c *gin.Context) {
|
||||
var req skillSourceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if stderrors.As(err, &tooLarge) {
|
||||
_ = c.Error(skillTooLargeError())
|
||||
return
|
||||
}
|
||||
_ = c.Error(apperrors.NewBadRequestError("invalid skill source request"))
|
||||
return
|
||||
}
|
||||
source := strings.TrimSpace(req.Source)
|
||||
if source == "" {
|
||||
_ = c.Error(apperrors.NewBadRequestError("source is required"))
|
||||
return
|
||||
}
|
||||
|
||||
skillID, err := h.service.InstallSkillFromSource(
|
||||
c.Request.Context(), sandboxConfigTenantID(c), c.Param("id"), source, req.Token,
|
||||
)
|
||||
if err != nil {
|
||||
respondSkillServiceError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusAccepted, gin.H{"success": true, "data": gin.H{"skill_id": skillID}})
|
||||
}
|
||||
|
||||
func skillTooLargeError() error {
|
||||
return apperrors.NewBadRequestError(
|
||||
fmt.Sprintf("skill bundle cannot exceed %d MB", secutils.GetMaxFileSizeMB()))
|
||||
|
|
|
|||
|
|
@ -35,9 +35,12 @@ type fakeSandboxSkillService struct {
|
|||
getErr error
|
||||
patchErr error
|
||||
|
||||
installID string
|
||||
installErr error
|
||||
removeErr error
|
||||
installID string
|
||||
installErr error
|
||||
installSource string
|
||||
installToken string
|
||||
sourceErr error
|
||||
removeErr error
|
||||
|
||||
last service.SkillProgress
|
||||
hasLast bool
|
||||
|
|
@ -120,6 +123,14 @@ func (f *fakeSandboxSkillService) InstallSkill(
|
|||
return f.installID, f.installErr
|
||||
}
|
||||
|
||||
func (f *fakeSandboxSkillService) InstallSkillFromSource(
|
||||
_ context.Context, tenantID uint64, configID, source, token string,
|
||||
) (string, error) {
|
||||
f.installTenant, f.installConfig = tenantID, configID
|
||||
f.installSource, f.installToken = source, token
|
||||
return f.installID, f.sourceErr
|
||||
}
|
||||
|
||||
func (f *fakeSandboxSkillService) RemoveSkill(
|
||||
_ context.Context, tenantID uint64, configID, skillID string,
|
||||
) error {
|
||||
|
|
@ -266,6 +277,55 @@ func TestSandboxSkillUploadAcceptedReturnsSkillID(t *testing.T) {
|
|||
require.Equal(t, []byte("zip-bytes"), svc.installBytes)
|
||||
}
|
||||
|
||||
func TestSandboxSkillInstallFromSourceAcceptedReturnsSkillID(t *testing.T) {
|
||||
svc := &fakeSandboxSkillService{installID: "skill-9"}
|
||||
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
|
||||
|
||||
body := `{"source":"@owner/demo","token":"sk_test"}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/skills",
|
||||
strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusAccepted, w.Code)
|
||||
require.Equal(t, testSkillTenantID, svc.installTenant)
|
||||
require.Equal(t, "cfg-a", svc.installConfig)
|
||||
require.Equal(t, "@owner/demo", svc.installSource)
|
||||
require.Equal(t, "sk_test", svc.installToken)
|
||||
require.Nil(t, svc.installBytes, "a source install must not look like an upload")
|
||||
}
|
||||
|
||||
func TestSandboxSkillInstallFromSourceRequiresSource(t *testing.T) {
|
||||
svc := &fakeSandboxSkillService{}
|
||||
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/skills",
|
||||
strings.NewReader(`{"source":" "}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||
require.Empty(t, svc.installSource)
|
||||
}
|
||||
|
||||
func TestSandboxSkillInstallFromSourceInvalidReturns400(t *testing.T) {
|
||||
svc := &fakeSandboxSkillService{
|
||||
sourceErr: fmt.Errorf("%w: only http(s) sources are allowed", service.ErrSkillSourceInvalid),
|
||||
}
|
||||
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/sandbox-configs/cfg-a/skills",
|
||||
strings.NewReader(`{"source":"file:///etc/passwd"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusBadRequest, w.Code)
|
||||
require.Contains(t, w.Body.String(), "only http(s) sources are allowed")
|
||||
}
|
||||
|
||||
func TestSandboxSkillUploadWithoutFileReturns400(t *testing.T) {
|
||||
svc := &fakeSandboxSkillService{}
|
||||
router := newSkillTestRouter(NewSandboxSkillHandler(svc, nil))
|
||||
|
|
|
|||
Loading…
Reference in New Issue