Repository navigation
Expand file tree
/
Copy pathSkills.tsx
More file actions
535 lines (532 loc) · 16.7 KB
/
Copy pathSkills.tsx
File metadata and controls
535 lines (532 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import { product, useSkillCredentials } from "./lib/product";
import { CredentialNames } from "./Capabilities";
import { Select, SelectOption } from "./components/ui/select";
import { unzipSync, strFromU8 } from "fflate";
import { tr } from "./lib/i18n";
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Upload, Trash2 } from "lucide-react";
import type { Skill } from "@oac/agents-client";
import { api, readHistory } from "./lib/api";
import { Button } from "./components/ui/button";
import { Input } from "./components/ui/input";
import { Textarea } from "./components/ui/textarea";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from "./components/ui/dialog";
import { ErrorNotice, Field } from "./components/shared";
export const useSkills = () =>
useQuery({
queryKey: ["skills"],
queryFn: ({ signal }) =>
readHistory((options) => api.listSkills(options), signal),
});
export function SkillCreate({
close,
onSaved,
}: {
close: () => void;
onSaved?: (id: string) => void;
}) {
const cache = useQueryClient();
const [name, setName] = useState("");
const [description, setDescription] = useState("");
const [instructions, setInstructions] = useState("");
const save = useMutation({
mutationFn: () =>
api.uploadSkill({
kind: "directory",
files: [
{
path: `${name}/SKILL.md`,
file: new Blob(
[
`---\nname: ${JSON.stringify(name)}\ndescription: ${JSON.stringify(description)}\n---\n\n${instructions}\n`,
],
{ type: "text/markdown" },
),
},
],
}),
onSuccess: (skill) => {
onSaved?.(skill.id);
void cache.invalidateQueries({ queryKey: ["skills"] });
close();
},
});
return (
<Dialog
open
onOpenChange={(open) => {
if (!open && !save.isPending) close();
}}
>
<DialogContent
aria-describedby={undefined}
className="max-h-[90dvh] overflow-y-auto"
>
<DialogHeader>
<DialogTitle>{tr("创建 Skill")}</DialogTitle>
</DialogHeader>
<form
id="skill-form"
className="space-y-4"
onSubmit={(e) => {
e.preventDefault();
e.stopPropagation();
save.mutate();
}}
>
<Field label={tr("技能名称")} id="skill-name">
<Input
id="skill-name"
value={name}
required
maxLength={64}
pattern="[a-z0-9]+(-[a-z0-9]+)*"
placeholder={tr("例如 code-review")}
onChange={(e) => setName(e.target.value)}
/>
</Field>
<Field label={tr("用途")} id="skill-description">
<Input
id="skill-description"
value={description}
required
maxLength={500}
onChange={(e) => setDescription(e.target.value)}
/>
</Field>
<Field label={tr("执行方法")} id="skill-instructions">
<Textarea
id="skill-instructions"
value={instructions}
required
rows={9}
onChange={(e) => setInstructions(e.target.value)}
placeholder={tr("什么时候使用、具体步骤、预期输出")}
/>
</Field>
<ErrorNotice error={save.error} />
</form>
<DialogFooter>
<Button type="submit" form="skill-form" disabled={save.isPending}>
{tr("保存")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export function SkillDetail({
skill,
close,
}: {
skill: Skill;
close: () => void;
}) {
const cache = useQueryClient();
const [preview, setPreview] = useState<string>("");
const versions = useQuery({
queryKey: ["skill-versions", skill.id],
queryFn: ({ signal }) =>
readHistory(
(options) => api.listSkillVersions(skill.id, options),
signal,
),
});
const current = useQuery({
queryKey: ["skill", skill.id],
queryFn: () => api.retrieveSkill(skill.id),
initialData: skill,
});
const refresh = () => {
void cache.invalidateQueries({ queryKey: ["skills"] });
void cache.invalidateQueries({ queryKey: ["skill", skill.id] });
void cache.invalidateQueries({ queryKey: ["skill-versions", skill.id] });
};
const change = useMutation({
mutationFn: (version: string) =>
api.updateSkillDefaultVersion(skill.id, version),
onSuccess: refresh,
});
const upload = useMutation({
mutationFn: (file: File) =>
api.uploadSkillVersion(
skill.id,
{ kind: "zip", file, filename: file.name },
{ setDefault: true },
),
onSuccess: refresh,
});
const remove = useMutation({
mutationFn: () => api.deleteSkill(skill.id),
onSuccess: () => {
refresh();
close();
},
});
return (
<Dialog
open
onOpenChange={(open) => {
if (
!open &&
!remove.isPending &&
!upload.isPending &&
!change.isPending
)
close();
}}
>
<DialogContent
aria-describedby={undefined}
className="max-h-[90dvh] overflow-y-auto"
>
<DialogHeader>
<DialogTitle>{current.data.name}</DialogTitle>
</DialogHeader>
<p className="text-base leading-relaxed">{current.data.description}</p>
<SkillCredentials id={skill.id} />
<h3 className="font-semibold">{tr("版本")}</h3>
<ErrorNotice
error={
versions.error ||
current.error ||
change.error ||
upload.error ||
remove.error
}
/>
<div className="space-y-2">
{versions.data?.map((version) => (
<div
key={version.id}
className="flex items-center justify-between rounded-lg border border-line p-3"
>
<span>v{version.version}</span>
<Button
variant="ghost"
onClick={() => setPreview(version.version)}
>
{tr("查看文件")}
</Button>
{version.version === current.data.default_version ? (
<span>{tr("默认版本")}</span>
) : (
<Button
variant="outline"
disabled={change.isPending}
onClick={() => change.mutate(version.version)}
>
{tr("设为默认")}
</Button>
)}
</div>
))}
</div>
{preview && <SkillFiles id={skill.id} version={preview} />}
<DialogFooter>
<Button
variant="ghost"
aria-label={tr("删除 Skill")}
disabled={remove.isPending}
onClick={() => {
if (
confirm(
tr("删除此 Skill 及全部版本?请先解除 Agent 中的绑定。"),
)
)
remove.mutate();
}}
>
<Trash2 />
</Button>
<Button asChild>
<label className="cursor-pointer">
<Upload />
{upload.isPending ? tr("上传中\u2026") : tr("上传新版本")}
<input
aria-label={tr("上传 Skill 新版本")}
type="file"
accept=".zip"
className="sr-only"
disabled={upload.isPending}
onChange={(e) => {
const file = e.target.files?.[0];
if (file) upload.mutate(file);
e.target.value = "";
}}
/>
</label>
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function SkillFiles({ id, version }: { id: string; version: string }) {
const [selected, setSelected] = useState("");
const query = useQuery({
queryKey: ["skill-content", id, version],
queryFn: async () => {
const content = await api.downloadSkillVersion(id, version);
let total = 0;
return unzipSync(new Uint8Array(await content.data.arrayBuffer()), {
filter: (file) => {
total += file.originalSize;
if (total > 32 * 1024 * 1024)
throw new Error(tr("文件预览超过 32 MiB 限制。"));
return !file.name.endsWith("/");
},
});
},
});
const names = Object.keys(query.data || {}).sort();
const path = names.includes(selected)
? selected
: names.find((name) => name.endsWith("SKILL.md")) || names[0];
const bytes = path ? query.data?.[path] : undefined;
return (
<section className="border border-line">
<div className="border-b px-3 py-2 text-sm">
v{version} · {tr("文件预览")}
</div>
<ErrorNotice error={query.error} />
<div className="flex h-64">
<nav
aria-label={tr("技能文件")}
className="w-1/3 overflow-auto border-r border-line"
>
{names.map((name) => (
<button
type="button"
key={name}
className={`block w-full truncate px-2 py-1 text-left text-sm ${name === path ? "bg-surface-muted" : ""}`}
onClick={() => setSelected(name)}
title={name}
>
{name}
</button>
))}
</nav>
<pre className="min-w-0 flex-1 overflow-auto whitespace-pre-wrap p-3 text-sm">
{bytes
? bytes.length > 256 * 1024
? tr("文件过大,请下载查看。")
: bytes.includes(0)
? tr("二进制文件")
: strFromU8(bytes)
: tr("正在加载…")}
</pre>
</div>
</section>
);
}
interface RegistryPreview {
source: string;
slug: string;
archive: string;
files: string[];
instructions: string;
}
export function SkillsDirectory({ close }: { close: () => void }) {
const [search, setSearch] = useState(""),
[source, setSource] = useState(""),
[slug, setSlug] = useState(""),
[target, setTarget] = useState("");
const cache = useQueryClient(),
skills = useSkills();
const catalog = useQuery({
queryKey: ["skills-directory"],
staleTime: 300000,
queryFn: async ({ signal }) => {
const response = await fetch(
"https://agent-skill-index.vercel.app/data/latest/skills.json",
{ signal, credentials: "omit" },
);
if (!response.ok)
throw new Error(tr("技能目录暂不可用,可直接输入仓库和技能名称。"));
const value = await response.json();
if (!Array.isArray(value.data))
throw new Error(tr("技能目录返回了无法识别的数据。"));
return value.data.filter(
(item: { source?: unknown; slug?: unknown; name?: unknown }) =>
typeof item.source === "string" &&
typeof item.slug === "string" &&
typeof item.name === "string",
) as { source: string; slug: string; name: string }[];
},
});
const preview = useMutation({
mutationFn: () =>
product<RegistryPreview>("skills/registry/preview", "POST", {
source,
slug,
}),
});
const install = useMutation({
mutationFn: async () => {
const value = preview.data!;
const file = new Blob(
[Uint8Array.from(atob(value.archive), (char) => char.charCodeAt(0))],
{ type: "application/zip" },
);
const input = {
kind: "zip" as const,
file,
filename: `${value.slug}.zip`,
};
return target
? api.uploadSkillVersion(target, input, { setDefault: true })
: api.uploadSkill(input);
},
onSuccess: () => {
void cache.invalidateQueries({ queryKey: ["skills"] });
if (target) {
void cache.invalidateQueries({ queryKey: ["skill", target] });
void cache.invalidateQueries({ queryKey: ["skill-versions", target] });
}
close();
},
});
const busy = preview.isPending || install.isPending;
return (
<Dialog
open
onOpenChange={(open) => {
if (!open && !busy) close();
}}
>
<DialogContent
aria-describedby={undefined}
className="max-h-[90dvh] max-w-2xl overflow-auto"
>
<DialogHeader>
<DialogTitle>{tr("Skills 目录")}</DialogTitle>
</DialogHeader>
<ErrorNotice error={catalog.error || preview.error || install.error} />
<Input
aria-label={tr("搜索技能目录")}
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder={tr("搜索热门技能")}
/>
<div className="max-h-40 divide-y divide-line overflow-auto">
{catalog.data
?.filter((item) =>
`${item.name} ${item.source}`
.toLowerCase()
.includes(search.toLowerCase()),
)
.slice(0, 40)
.map((item) => (
<button
disabled={busy}
className="flex w-full items-center justify-between gap-3 py-2 text-left text-sm hover:bg-surface-subtle"
key={`${item.source}/${item.slug}`}
onClick={() => {
setSource(item.source);
setSlug(item.slug);
preview.reset();
}}
>
<span>{item.name}</span>
<span className="truncate text-sm text-fg-muted">
{item.source}
</span>
</button>
))}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={tr("GitHub 仓库")} id="registry-source">
<Input
id="registry-source"
disabled={busy}
value={source}
placeholder="owner/repo"
onChange={(event) => {
setSource(event.target.value);
preview.reset();
}}
/>
</Field>
<Field label={tr("Skill 名称")} id="registry-slug">
<Input
id="registry-slug"
disabled={busy}
value={slug}
onChange={(event) => {
setSlug(event.target.value);
preview.reset();
}}
/>
</Field>
</div>
<Button
variant="outline"
disabled={busy || !source || !slug}
onClick={() => preview.mutate()}
>
{preview.isPending ? tr("正在下载…") : tr("下载并预览")}
</Button>
{preview.data && (
<>
<div className="text-sm text-fg-muted">
{preview.data.files.join(" · ")}
</div>
<pre className="max-h-64 overflow-auto whitespace-pre-wrap rounded-lg border border-line p-3 text-sm">
{preview.data.instructions}
</pre>
<Field label={tr("安装目标")} id="registry-target">
<Select
id="registry-target"
value={target}
disabled={busy}
onValueChange={setTarget}
>
<SelectOption value="">{tr("创建新 Skill")}</SelectOption>
{skills.data?.map((skill) => (
<SelectOption key={skill.id} value={skill.id}>
{skill.name} · {tr("上传为新版本")}
</SelectOption>
))}
</Select>
</Field>
<Button disabled={busy} onClick={() => install.mutate()}>
{tr("安装 Skill")}
</Button>
</>
)}
</DialogContent>
</Dialog>
);
}
// The variables this Skill needs; Parsar keeps them beside the Core Skill.
function SkillCredentials({ id }: { id: string }) {
const cache = useQueryClient();
const saved = useSkillCredentials().data?.find((row) => row.id === id)?.credentials || [];
const [names, setNames] = useState<string[] | undefined>();
const save = useMutation({
mutationFn: () => product(`skills/${id}/credentials`, "PUT", { credentials: names }),
onSuccess: () => {
setNames(undefined);
void cache.invalidateQueries({ queryKey: ["skill-credentials"] });
},
});
return (
<div className="space-y-2">
<CredentialNames value={names ?? saved} change={setNames} />
{names !== undefined && (
<Button variant="outline" disabled={save.isPending} onClick={() => save.mutate()}>
{tr("保存凭据需求")}
</Button>
)}
<ErrorNotice error={save.error} />
</div>
);
}