Line data Source code
1 : import {
2 : MAX_DESCRIPTION_CODE_POINTS,
3 : MAX_NAME_LENGTH,
4 : PACK_NAME_PATTERN,
5 : codePointLength
6 : } from '@/platform/skills/types'
7 :
8 : import type { SkillReferenceMetadata } from '@/workbench/extensions/agent/types/skillReference'
9 : import type {
10 : PromptSnapshot,
11 : WorkflowReference
12 : } from '@/workbench/extensions/agent/types/workflowReference'
13 :
14 : // encodeURIComponent throws on an unpaired UTF-16 surrogate. The ES2023 lib
15 : // has no String#toWellFormed, so this applies the same U+FFFD replacement.
16 2356 : const LONE_SURROGATE =
17 : /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g
18 :
19 0 : export function serializeSkillReference(skill: SkillReferenceMetadata): string {
20 0 : const wellFormed = skill.description.replace(LONE_SURROGATE, '�')
21 0 : const description = encodeURIComponent(wellFormed)
22 : .replaceAll('(', '%28')
23 : .replaceAll(')', '%29')
24 0 : return `[Use the saved skill /${skill.name}](skill://${skill.name}?description=${description})`
25 : }
26 :
27 0 : export function parseSkillReferenceText(
28 : content: string,
29 : workflowReferences: WorkflowReference[] = []
30 : ): PromptSnapshot {
31 0 : for (const match of content.matchAll(
32 : // Tolerates a legacy `&id`; skills resolve by name.
33 : /(\[Use the saved skill \/([A-Za-z0-9._-]+)\]\(skill:\/\/\2\?description=([^\s)&]*))(?:&id=[A-Za-z0-9_-]{1,128})?\)/g
34 : )) {
35 0 : const [, canonical, name] = match
36 0 : if (name.length > MAX_NAME_LENGTH || !PACK_NAME_PATTERN.test(name)) continue
37 0 : let description: string
38 0 : try {
39 0 : description = decodeURIComponent(match[3])
40 : } catch {
41 0 : continue
42 : }
43 0 : if (codePointLength(description) > MAX_DESCRIPTION_CODE_POINTS) continue
44 0 : if (serializeSkillReference({ name, description }) !== `${canonical})`)
45 0 : continue
46 0 : const start = match.index
47 0 : const end = start + match[0].length
48 0 : return {
49 : text: content.slice(0, start) + content.slice(end),
50 : workflowReferences: workflowReferences.map((reference) => ({
51 : ...reference,
52 : textOffset:
53 : reference.textOffset <= start
54 : ? reference.textOffset
55 : : Math.max(start, reference.textOffset - match[0].length)
56 : })),
57 : skillReference: {
58 : name,
59 : description,
60 : textOffset: start,
61 : workflowIndex: workflowReferences.filter(
62 : (reference) => reference.textOffset <= start
63 : ).length
64 : }
65 : }
66 : }
67 0 : return { text: content, workflowReferences }
68 : }
|