diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 973f1ccd..cf238d46 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,6 +143,25 @@ jobs: if-no-files-found: error retention-days: 14 + - name: Verify the native skill library and owner preferences in two sandboxed Chrome logins + id: skills_ui + if: ${{ !cancelled() && steps.host_tests.outcome == 'success' }} + timeout-minutes: 5 + env: + DEVA_QA_SKILLS_CAPTURE: '1' + run: node scripts/workbench/e2e-skill-library.mjs + + - name: Publish the verified synthetic skill settings and document views + if: ${{ !cancelled() && steps.skills_ui.outcome == 'success' }} + uses: actions/upload-artifact@v4 + with: + name: workbench-skill-library + path: | + test-results/skill-library/skills-list.png + test-results/skill-library/skill-detail.png + if-no-files-found: error + retention-days: 14 + - name: Select the same installed Chrome for UI and worker run: bash scripts/workbench/ci-select-chromium.sh @@ -254,6 +273,77 @@ jobs: timeout-minutes: 6 run: node scripts/workbench/container-terminal-viewer.mjs + parity-workbook: + name: Export the capability workbook at the exact PR head + if: ${{ github.event_name == 'pull_request' }} + runs-on: ubuntu-latest + timeout-minutes: 5 + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: 1 + steps: + - uses: actions/checkout@v5 + with: + repository: ${{ github.event.pull_request.head.repo.full_name }} + ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false + - uses: pnpm/action-setup@v4 + - uses: actions/setup-node@v5 + with: + node-version: 22 + cache: pnpm + - run: pnpm install --frozen-lockfile --filter @deva/desktop + - name: Verify the preload AST and each linked Git blob, then generate the XLSX + env: + REPORT_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} + REPORT_LINK_REPOSITORY: ${{ github.repository }} + REPORT_PR: ${{ github.event.pull_request.number }} + REPORT_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -eu + test "$(git rev-parse HEAD)" = "$REPORT_SHA" + if [ "$REPORT_REPOSITORY" = "$REPORT_LINK_REPOSITORY" ]; then + node scripts/workbench/export-parity-workbook.mjs --repo "$REPORT_REPOSITORY" --pr "$REPORT_PR" + else + node scripts/workbench/export-parity-workbook.mjs --repo "$REPORT_REPOSITORY" + fi + - uses: actions/upload-artifact@v4 + with: + name: workbench-parity-workbook + path: test-results/parity-*/Deva-Web-*项能力验收清单.xlsx + if-no-files-found: error + retention-days: 14 + + packaged-skills: + name: Native skill preferences in the production amd64 workbench + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'feat/web-workbench-skill-library' }} + runs-on: ubuntu-latest + timeout-minutes: 14 + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v5 + with: + node-version: 22 + package-manager-cache: false + - name: Build the native Linux amd64 production image + timeout-minutes: 8 + run: | + set -eu + test "$(uname -m)" = x86_64 + docker build --platform linux/amd64 --target runtime -t deva-workbench:skills-verify . + docker image inspect -f '{{.Os}}/{{.Architecture}} {{.Id}} {{.Size}} bytes' deva-workbench:skills-verify + - name: Verify skill management and model isolation inside the packaged host + timeout-minutes: 3 + run: | + set -eu + test -f "$PWD/apps/headless/test/skill-library-http.test.mjs" + docker run --rm --init --network none --read-only --user 1000:1000 --cap-drop ALL --security-opt no-new-privileges:true \ + --pids-limit 128 --cpus 2 --memory 512m --tmpfs /tmp:rw,nosuid,nodev,noexec,mode=1777,size=96m \ + --mount "type=bind,src=$PWD/apps/headless/test/skill-library-http.test.mjs,dst=/opt/deva/apps/headless/ci/skill-library-http.test.mjs,readonly" \ + --entrypoint node deva-workbench:skills-verify --test /opt/deva/apps/headless/ci/skill-library-http.test.mjs + - name: Confirm real saved skill preferences across two distinct production containers + timeout-minutes: 3 + run: node scripts/workbench/container-skill-library.mjs + sandbox: name: Private human browser worker runs-on: ubuntu-latest diff --git a/README.en.md b/README.en.md index 4569845b..2f74aaa0 100644 --- a/README.en.md +++ b/README.en.md @@ -345,6 +345,7 @@ The [amd64 Docker Compose workbench](apps/headless/README.md) runs independently - **Conversations:** claim the instance, configure models, stream, stop and reconnect. Use the desktop message menu to copy a selection or quote it in an unsent draft. Clipboard, sidebar shortcuts and page fullscreen belong to the client browser. - **Library and projects:** manage profiles, roles, avatars and scoped notes. A conversation can inherit or explicitly attach an approved project; manually opening its files or notes does not send them to a model. +- **Skill settings:** inspect existing skills under Settings → Extensions and save their enabled preferences and role scopes. Opening a custom skill displays its document; web chat does not load or execute skills. - **Read-only terminal:** an optional [network-isolated PTY worker](apps/terminal-worker/README.md) displays a confirmed, saved workspace text file in the original file panel. Navigation, resize and exit come from a real native process; this is not a host command shell. - **Attachments and deliveries:** explicitly send supported text, static images or PDFs on compatible adapters. Export confirmed replies or use the desktop delivery card to download and reveal an authorized project file. - **Inspection:** view branches, first-parent history and staged or working-tree differences in separately approved repositories. Inspect recorded desktop tasks, preview a schedule in an explicit time zone, and pause an active record after confirmation. The server does not run a task scheduler. diff --git a/README.md b/README.md index ad09b4b9..cc1e9532 100644 --- a/README.md +++ b/README.md @@ -336,6 +336,7 @@ IM 机器人支持 `/new [角色名]`、`/list`、`/stop`、`/status`、`/help` - **对话**:在浏览器认领实例、配置模型,使用原会话列表和编辑器聊天、停止、刷新续接。选中文字可复制或加入当前草稿的引用条;剪贴板、侧栏快捷键和页面全屏都属于操作电脑。 - **资料与项目**:管理个人资料、角色、头像和分域记忆。会话可继承或显式关联管理员登记的项目;手动打开文件或笔记不会将内容发送给模型。 +- **技能设置**:在桌面同源的「设置 → 扩展」查看现有技能,保存启用偏好和角色范围。只有打开自定义条目才显示正文;Web 对话不会加载或运行这些技能。 - **只读终端**:可选的[无网络 PTY 工作器](apps/terminal-worker/README.md)在原文件面板中显示已保存的文本。翻页、调整行列、退出都由真实子进程响应;它不会提供宿主命令行。 - **附件与交付**:显式发送文本、静态图片或兼容协议的 PDF;导出已完成的回复,或在桌面同源交付卡下载、定位授权文件。 - **检查**:获准仓库可看分支、首父历史,以及暂存区和工作树的差异;任务页可查阅桌面记录、预览时区日程和确认暂停。它不会启动任务调度器。 diff --git a/apps/desktop/src/main/services/skill-document-format.ts b/apps/desktop/src/main/services/skill-document-format.ts new file mode 100644 index 00000000..126a29bb --- /dev/null +++ b/apps/desktop/src/main/services/skill-document-format.ts @@ -0,0 +1,17 @@ +import { fmArray, fmMap, fmString, parseFrontmatter } from './frontmatter' + +/** Native SKILL.md display fields. No directory, lifecycle or runtime concerns. */ +export function parseSkillDocument(id: string, raw: string) { + const { data, body } = parseFrontmatter(raw) + return { + id, + name: fmString(data, 'name') || id, + description: fmString(data, 'description'), + trigger: fmString(data, 'trigger'), + allowedTools: fmArray(data, 'allowed-tools'), + license: fmString(data, 'license'), + compatibility: fmString(data, 'compatibility'), + metadata: fmMap(data, 'metadata'), + instructions: body.trim() + } +} diff --git a/apps/desktop/src/main/services/skills.ts b/apps/desktop/src/main/services/skills.ts index 892afe2a..444fe35e 100644 --- a/apps/desktop/src/main/services/skills.ts +++ b/apps/desktop/src/main/services/skills.ts @@ -13,7 +13,11 @@ import { dirname, isAbsolute, join, resolve, sep } from 'path' import { unzipSync } from 'fflate' import { getConfig, getDevaHome, setConfig } from './config' import { allowsPersona, getRoles, setRoles } from './ext-roles' -import { fmArray, fmMap, fmScalar, fmString, parseFrontmatter } from './frontmatter' +import { fmScalar, fmString, parseFrontmatter } from './frontmatter' +import { parseSkillDocument } from './skill-document-format' +import { BUILTIN_SKILL_CATALOG } from '../../shared/skill-catalog' + +const [createSkillSummary, createAgentSummary, createMcpSummary] = BUILTIN_SKILL_CATALOG /** * 技能(Skills)服务:发现 / 解析 / 读写 `~/.deva/skills//SKILL.md`(全局,与项目无关)。 @@ -153,10 +157,7 @@ allowed-tools: run_command, read_file /** 内置、不可删、恒启用的元技能,合成在代码里(永不落盘)。随 listSkills() 自动进系统提示词与 /create-skill。 */ const BUILTIN_CREATE_SKILL: SkillRecord = { - id: 'create-skill', - name: 'create-skill', - description: - '引导用户从零创建一个新技能:从用例规划脚本、参考文档、模板等资源,落盘、校验并启用(单文件调 create_skill,多文件直接写进技能目录)。', + ...createSkillSummary, trigger: '输入 /create-skill,或表达「帮我做/创建一个技能」时触发。', allowedTools: ['create_skill', 'list_dir', 'write_file', 'read_file', 'run_command'], license: '', @@ -164,8 +165,7 @@ const BUILTIN_CREATE_SKILL: SkillRecord = { metadata: {}, instructions: CREATE_SKILL_INSTRUCTIONS, enabled: true, - roles: null, - source: 'builtin' + roles: null } /** @@ -191,9 +191,7 @@ const CREATE_AGENT_INSTRUCTIONS = `你正在帮助用户创建一个新的**角 /** 内置、不可删、恒启用的「对话创建角色」元技能。随 listSkills() 自动进系统提示词与 /create-agent。 */ const BUILTIN_CREATE_AGENT: SkillRecord = { - id: 'create-agent', - name: 'create-agent', - description: '引导用户用对话创建一个新角色:最多问一次厘清用途,随即调 propose_agent 生成名片供确认。', + ...createAgentSummary, trigger: '输入 /create-agent,或表达「帮我做/创建一个角色/性格/身份」时触发。', allowedTools: ['propose_agent'], license: '', @@ -201,8 +199,7 @@ const BUILTIN_CREATE_AGENT: SkillRecord = { metadata: {}, instructions: CREATE_AGENT_INSTRUCTIONS, enabled: true, - roles: null, - source: 'builtin' + roles: null } /** @@ -231,9 +228,7 @@ const CREATE_MCP_INSTRUCTIONS = `你正在帮助用户接入一个新的 **MCP /** 内置、不可删、恒启用的「对话接入 MCP 服务」元技能。随 listSkills() 自动进系统提示词与 /create-mcp。 */ const BUILTIN_CREATE_MCP: SkillRecord = { - id: 'create-mcp', - name: 'create-mcp', - description: '引导用户用对话接入一个 MCP 服务:厘清用途与传输方式、收集要素(密钥仅收字段名)、确认后调 create_mcp 工具落盘并启用。', + ...createMcpSummary, trigger: '输入 /create-mcp,或表达「帮我接入/添加/创建一个 MCP(服务)」时触发。', allowedTools: ['create_mcp'], license: '', @@ -241,8 +236,7 @@ const BUILTIN_CREATE_MCP: SkillRecord = { metadata: {}, instructions: CREATE_MCP_INSTRUCTIONS, enabled: true, - roles: null, - source: 'builtin' + roles: null } /** 内置元技能按 id 索引(generalize:不同保留 id 返回各自的内置常量,勿一律返回 create-skill)。 */ @@ -307,18 +301,8 @@ function makeId(name: string): string { } function parseSkill(id: string, raw: string, enabled: boolean): SkillRecord { - const { data, body } = parseFrontmatter(raw) - const name = fmString(data, 'name') || id return { - id, - name, - description: fmString(data, 'description'), - trigger: fmString(data, 'trigger'), - allowedTools: fmArray(data, 'allowed-tools'), - license: fmString(data, 'license'), - compatibility: fmString(data, 'compatibility'), - metadata: fmMap(data, 'metadata'), - instructions: body.trim(), + ...parseSkillDocument(id, raw), enabled, roles: getRoles('skills', id), source: 'custom' diff --git a/apps/desktop/src/renderer/src/redesign/SettingsPane.tsx b/apps/desktop/src/renderer/src/redesign/SettingsPane.tsx index eeb84f59..f1b46af2 100644 --- a/apps/desktop/src/renderer/src/redesign/SettingsPane.tsx +++ b/apps/desktop/src/renderer/src/redesign/SettingsPane.tsx @@ -5,7 +5,6 @@ import { useEffect, useMemo, useRef, useState } from 'react' import { Brain, ChevronLeft, - ChevronRight, Cog, Info, Lock, @@ -31,6 +30,7 @@ import { PersonaFace, parseAvatarSpec } from '../components/humation' import { useTheme } from '../theme/ThemeContext' import { readChatFontSize, saveChatFontSize, type ChatFontSize } from '../theme/chatFontSize' import { SettingsFrame } from './SettingsFrame' +import { ExtensionSettingsRow, SkillSettingsDetail } from './SkillSettingsParts' import { ModelSettings } from '../features/settings/ModelSettings' import { clipName, IS_MAC, AvatarStack, Segmented, Toggle } from './shell-common' @@ -224,37 +224,18 @@ function ExtensionsPane({
{t('cf.extEmpty')}
) : (
- {items.map((x) => { - const name = ( - - - {x.name} - - {x.badge} - {x.note && ( - - {x.note} - - )} - - ) - return ( -
- {x.locked ? ( - // 内置技能不展示详情:只读一行,开关禁用。 -
{name}
- ) : ( - // 主区做按钮(点开详情),开关作兄弟节点独立触发(互不干扰)。 - - )} - toggle(x.kind, x.id)} /> -
- ) - })} + {items.map((x) => ( + setOpen({ kind: x.kind, id: x.id })} + accessory={x.roles !== undefined && } + toggle={ toggle(x.kind, x.id)} />} + /> + ))}
)} @@ -409,26 +390,15 @@ function SkillDetail({ item, onBack }: { item: Skill; onBack: () => void }): Rea } return ( -
-
- -
+ {t('extensions.enable')} toggle('skill', item.id)} /> -
-
- - - -

{item.name}

-
- + + }>
@@ -441,7 +411,7 @@ function SkillDetail({ item, onBack }: { item: Skill; onBack: () => void }): Rea {t('extensions.instructionsEmpty')} )}
-
+ ) } diff --git a/apps/desktop/src/renderer/src/redesign/SkillSettingsParts.tsx b/apps/desktop/src/renderer/src/redesign/SkillSettingsParts.tsx new file mode 100644 index 00000000..8e4bf6d9 --- /dev/null +++ b/apps/desktop/src/renderer/src/redesign/SkillSettingsParts.tsx @@ -0,0 +1,66 @@ +import type { ComponentPropsWithRef, HTMLAttributes, MouseEventHandler, ReactNode } from 'react' +import { ChevronLeft, ChevronRight, Puzzle } from 'lucide-react' + +type DataAttributes = { [name: `data-${string}`]: string | undefined } + +/** The extension row keeps the drill-in button and the independent toggle as siblings. */ +export function ExtensionSettingsRow({ name, badge, note, noteWarn, accessory, toggle, onOpen, rowProps, openProps }: { + name: string; badge: string; note?: string; noteWarn?: boolean; accessory?: ReactNode; toggle: ReactNode + onOpen?: MouseEventHandler; rowProps?: HTMLAttributes & DataAttributes + openProps?: Omit, 'onClick'> & DataAttributes +}): React.JSX.Element { + const label = ( + + + {name} + + {badge} + {note && ( + + {note} + + )} + + ) + return ( +
+ {onOpen ? ( + + ) : ( +
{label}
+ )} + {toggle} +
+ ) +} + +/** The native skill detail surface; the caller supplies its policy, controls and body. */ +export function SkillSettingsDetail({ name, backLabel, onBack, controls, children, sectionProps, backProps }: { + name: string; backLabel: string; onBack: () => void; controls?: ReactNode; children: ReactNode + sectionProps?: HTMLAttributes & DataAttributes + backProps?: ComponentPropsWithRef<'button'> & DataAttributes +}): React.JSX.Element { + return ( +
+
+ +
+ {controls} +
+
+ + + +

{name}

+
+ {children} +
+ ) +} diff --git a/apps/desktop/src/shared/skill-catalog.ts b/apps/desktop/src/shared/skill-catalog.ts new file mode 100644 index 00000000..4726f459 --- /dev/null +++ b/apps/desktop/src/shared/skill-catalog.ts @@ -0,0 +1,22 @@ +// Display summaries only. Desktop owns the code-only instructions and runtime metadata. +export const BUILTIN_SKILL_CATALOG = Object.freeze([ + Object.freeze({ + id: 'create-skill', + name: 'create-skill', + description: + '引导用户从零创建一个新技能:从用例规划脚本、参考文档、模板等资源,落盘、校验并启用(单文件调 create_skill,多文件直接写进技能目录)。', + source: 'builtin' as const + }), + Object.freeze({ + id: 'create-agent', + name: 'create-agent', + description: '引导用户用对话创建一个新角色:最多问一次厘清用途,随即调 propose_agent 生成名片供确认。', + source: 'builtin' as const + }), + Object.freeze({ + id: 'create-mcp', + name: 'create-mcp', + description: '引导用户用对话接入一个 MCP 服务:厘清用途与传输方式、收集要素(密钥仅收字段名)、确认后调 create_mcp 工具落盘并启用。', + source: 'builtin' as const + }) +] as const) diff --git a/apps/desktop/src/workbench/desktop-settings.tsx b/apps/desktop/src/workbench/desktop-settings.tsx index 0a849a15..4f5af740 100644 --- a/apps/desktop/src/workbench/desktop-settings.tsx +++ b/apps/desktop/src/workbench/desktop-settings.tsx @@ -1,5 +1,5 @@ -import { lazy, Suspense, type ReactNode } from 'react' -import { Brain } from 'lucide-react' +import { lazy, Suspense, useLayoutEffect, useState, type ReactNode } from 'react' +import { Brain, Puzzle } from 'lucide-react' import { ToastProvider } from '../renderer/src/components/ToastProvider' import { DialogProvider } from '../renderer/src/components/DialogProvider' import { ModelSettings } from '../renderer/src/features/settings/ModelSettings' @@ -12,6 +12,7 @@ import { ServerPlatformLabel } from './server-platform' import type { Bootstrap, LibraryQueue, Transport } from './transport' const TextWorkbench = lazy(() => import('./text-workbench')) +const SkillLibrary = lazy(() => import('./skill-library')) export interface DesktopSettingsProps { chat?: { @@ -29,18 +30,42 @@ function ReadyModelSettings(): React.JSX.Element { function WorkbenchSettingsDialog({ chat, close }: { chat: NonNullable; close: () => void }): React.JSX.Element { const { t, locale } = useI18n() const labels = copy[locale] + const [section, setSection] = useState<'models' | 'skills'>('models') + const skillLibrary = chat.bootstrap.capabilities?.skillLibrary === true + const showSkills = skillLibrary && section === 'skills' && !chat.locked + useLayoutEffect(() => { + const previous = document.activeElement + document.querySelector('button[data-testid="workbench-settings-close"]')?.focus() + return () => { if (previous instanceof HTMLElement && previous.isConnected) previous.focus() } + }, []) + useLayoutEffect(() => { + if (chat.locked || !skillLibrary) setSection('models') + }, [chat.locked, skillLibrary]) + const modelLabel = <>{t('settings.models')} return - {t('settings.models')} + {skillLibrary ? <> + + + : {modelLabel}} }> {chat.notice} {chat.logoutFailed &&

{labels.logoutFailure}

} -
- -
-

Deva {chat.bootstrap.version} ·

+ {showSkills ? {labels.settingsLoading}

}> + +
: <> +
+ +
+

Deva {chat.bootstrap.version} ·

+ }
} diff --git a/apps/desktop/src/workbench/skill-library-controller.ts b/apps/desktop/src/workbench/skill-library-controller.ts new file mode 100644 index 00000000..b72721d1 --- /dev/null +++ b/apps/desktop/src/workbench/skill-library-controller.ts @@ -0,0 +1,338 @@ +import { matchesSkillEdit, retryableSkillRead, sameSkillRoles, skillProblem, type Catalog, type RoleOption, type SkillDocument, + type SkillEdit, type SkillLibraryTransport, type SkillProblem, type SkillRoles, type SkillSummary } from './skill-library-transport' + +export type RoleMode = 'all' | 'none' | 'selected' +export type RoleDraft = { base: string; mode: RoleMode; picked: string[]; review: boolean } +type RoleEditor = { draft: RoleDraft; options?: RoleOption[]; loading: boolean; error?: SkillProblem } +type Detail = { item: SkillSummary; document?: SkillDocument; loading: boolean; error?: SkillProblem } +type Feedback = { id: string; edit: SkillEdit; status: 'saving' | 'saved' | SkillProblem } +type ReadIssue = { problem: SkillProblem; retryable: boolean } +export type SkillLibraryState = { + catalog?: Catalog; listing: boolean; listError?: SkillProblem; syncError?: SkillProblem; reconnecting?: boolean; + selected?: Detail; roles?: RoleEditor; feedback?: Feedback +} + +export function draftRoles(draft: RoleDraft): SkillRoles { + return draft.mode === 'all' ? null : draft.mode === 'none' ? [] : draft.picked +} +function newDraft(item: SkillSummary): RoleDraft { + return { base: item.revision, mode: item.roles === null ? 'all' : item.roles.length ? 'selected' : 'none', + picked: item.roles ? [...item.roles] : [], review: false } +} +export function roleNeedsReview(draft: RoleDraft, item: SkillSummary): boolean { + return draft.review || draft.base !== item.revision +} +export function invalidDraftRoles(editor: RoleEditor, item: SkillSummary): boolean { + if (editor.draft.mode !== 'selected') return false + return !editor.draft.picked.length || editor.draft.picked.some((id) => + !editor.options?.some((option) => option.id === id) && !item.roles?.includes(id)) +} + +// Keep a minimum spacing between empty waits even if a server answers immediately. +function pause(ms: number, signal: AbortSignal): Promise { + if (ms <= 0) return Promise.resolve() + return new Promise((resolve) => { + if (signal.aborted) { resolve(); return } + const timer = setTimeout(done, ms) + function done(): void { clearTimeout(timer); signal.removeEventListener('abort', done); resolve() } + signal.addEventListener('abort', done, { once: true }) + }) +} + +/** One instance per open Skills pane. Only methods invoked by the pane's explicit controls open details or the role roster. */ +export function createSkillLibrary(api: SkillLibraryTransport, onExpired: () => void, retryDelays: readonly number[] = [800, 1600, 3200]) { + const lifetime = new AbortController() + const listeners = new Set<() => void>() + let state: SkillLibraryState = { listing: true } + let listing: Promise | undefined + let listIssue: ReadIssue | undefined + let monitoring = false + let started = false + let detailRead: AbortController | undefined + let rolesRead: AbortController | undefined + + const set = (patch: Partial): void => { + if (lifetime.signal.aborted) return + state = { ...state, ...patch } + listeners.forEach((listener) => listener()) + } + const failure = (error: unknown): SkillProblem => { + const problem = skillProblem(error) + if (problem === 'expired' && !lifetime.signal.aborted) { + set({ catalog: undefined, selected: undefined, roles: undefined, feedback: undefined, listing: false, + listError: 'expired', syncError: undefined, reconnecting: false }) + dispose() + onExpired() + } + return problem + } + const readIssue = (error: unknown): ReadIssue => ({ problem: failure(error), retryable: retryableSkillRead(error) }) + const current = (id: string): SkillSummary | undefined => state.catalog?.skills.find((item) => item.id === id) + const saving = (): boolean => state.feedback?.status === 'saving' + + function acceptCatalog(catalog: Catalog): void { + set({ catalog, listError: undefined }) + if (state.syncError) return // Reconnect reconfirms even an unchanged selected revision. + const selected = state.selected + if (!selected) return + const item = current(selected.item.id) + if (!item || item.source !== 'custom') { + detailRead?.abort() + set({ selected: { item: selected.item, loading: false, error: 'missing' } }) + } else if (item.revision !== selected.item.revision || selected.error === 'missing') { + void loadDetail(item) + } + } + + async function readCatalog(fresh = false): Promise { + if (fresh) while (listing) await listing + if (lifetime.signal.aborted) return undefined + if (listing) return listing + set({ listing: true }) + listing = api.list(lifetime.signal).then((catalog) => { + if (lifetime.signal.aborted) return undefined + listIssue = undefined + acceptCatalog(catalog) + return catalog + }).catch((error: unknown) => { + if (!lifetime.signal.aborted) { + listIssue = readIssue(error) + set({ listError: listIssue.problem }) + } + return undefined + }).finally(() => { + listing = undefined + set({ listing: false }) + }) + return listing + } + + function pauseSync(issue: ReadIssue, reconnecting: boolean): void { + detailRead?.abort() + rolesRead?.abort() + const { selected, roles } = state + set({ syncError: issue.problem, reconnecting, selected: selected ? { item: selected.item, loading: false } : undefined, + roles: roles ? { ...roles, loading: false, draft: { ...roles.draft, review: true } } : undefined }) + } + + async function reconfirm(): Promise { + if (!await readCatalog(true) || lifetime.signal.aborted) return listIssue ?? { problem: 'unavailable', retryable: true } + const selected = state.selected + if (selected) { + const item = current(selected.item.id) + if (item?.source === 'custom') { + const issue = await loadDetail(item, false) + if (issue && state.selected && issue.problem !== 'missing') return issue + } else { + set({ selected: { item: selected.item, loading: false, error: 'missing' } }) + } + } + set({ syncError: undefined, reconnecting: false }) + return undefined + } + + async function monitor(): Promise { + if (monitoring || !state.catalog || state.syncError || lifetime.signal.aborted) return + monitoring = true + let attempts = 0 + try { + while (!lifetime.signal.aborted && state.catalog) { + const began = Date.now() + let issue: ReadIssue | undefined + try { + const change = await api.changes(state.catalog.revision, 8000, lifetime.signal) + if (lifetime.signal.aborted) break + attempts = 0 // A real Changes receipt re-arms the bounded reconnect allowance. + if (change.changed && state.catalog.revision !== change.revision && !await readCatalog()) issue = listIssue + } catch (error) { + if (lifetime.signal.aborted) break + issue = readIssue(error) + } + while (issue && !lifetime.signal.aborted) { + const delay = issue.retryable ? retryDelays[attempts] : undefined + pauseSync(issue, delay !== undefined) + if (delay === undefined) return + attempts++ + await pause(delay, lifetime.signal) + if (!lifetime.signal.aborted) issue = await reconfirm() + } + const remaining = 400 - (Date.now() - began) + if (remaining > 0 && attempts === 0) await pause(remaining, lifetime.signal) + } + } finally { + monitoring = false + } + } + + async function loadDetail(item: SkillSummary, mayReconcile = true): Promise { + detailRead?.abort() + const read = new AbortController() + detailRead = read + set({ selected: { item, loading: true } }) + const reject = (issue: ReadIssue): ReadIssue => { + set({ selected: { item, loading: false, error: issue.problem } }) + return issue + } + try { + const document = await api.detail(item.id, read.signal) + if (read.signal.aborted) return undefined + if (!document || document.detail !== 'document') return reject({ problem: 'missing', retryable: false }) + if (document.revision !== item.revision) { + // The document advanced after the catalog read. Show neither a stale document nor a stale write target. + if (mayReconcile) void readCatalog(true) + return reject({ problem: 'stale', retryable: false }) + } + if (document.canConfigure !== item.canConfigure || document.enabled !== item.enabled || + !sameSkillRoles(document.roles, item.roles) || document.name !== item.name || document.description !== item.description) + return reject({ problem: 'invalid', retryable: false }) + set({ selected: { item, document, loading: false } }) + return undefined + } catch (error) { + return read.signal.aborted ? undefined : reject(readIssue(error)) + } + } + + function open(id: string): boolean { + const item = current(id) + if (lifetime.signal.aborted || state.selected || state.listError || state.syncError || item?.source !== 'custom') return false + void loadDetail(item) + return true + } + + function closeRoles(): void { + rolesRead?.abort() + set({ roles: undefined }) + } + function back(): void { + detailRead?.abort() + closeRoles() + set({ selected: undefined }) + } + + async function refresh(): Promise { + if (lifetime.signal.aborted || state.reconnecting) return + if (state.syncError) { + set({ reconnecting: true }) + const issue = await reconfirm() + if (issue && !lifetime.signal.aborted) pauseSync(issue, false) + if (!issue) void monitor() + return + } + if (await readCatalog(true)) { + const selected = state.selected + const item = selected && current(selected.item.id) + if (item?.source === 'custom' && selected?.error && !selected.loading) void loadDetail(item) + void monitor() + } + } + + function selectedWritable(): SkillSummary | undefined { + const selected = state.selected + const item = selected && current(selected.item.id) + return item?.canConfigure === true && item.source === 'custom' && selected?.document?.revision === item.revision && + !state.listError && !state.syncError && !selected.error ? item : undefined + } + + async function readRoles(review: boolean): Promise { + const editor = state.roles + const item = selectedWritable() + if (!editor || !item || saving() || lifetime.signal.aborted) return + rolesRead?.abort() + const read = new AbortController() + rolesRead = read + set({ roles: { ...editor, loading: true, error: undefined } }) + try { + // A conflict review uses a fresh catalog and roster; reviewing never writes. + const catalog = review ? await readCatalog(true) : state.catalog + if (read.signal.aborted || !state.roles) return + const latest = catalog?.skills.find((s) => s.id === item.id) + if (!latest || latest.source !== 'custom' || !latest.canConfigure) { + set({ roles: { ...state.roles, loading: false, error: state.listError ?? (latest ? 'readonly' : 'missing') } }) + return + } + const options = await api.roles(read.signal) + if (read.signal.aborted || !state.roles) return + const draft = state.roles.draft + set({ roles: { draft: review ? { ...draft, base: latest.revision, review: false } : draft, options, loading: false }, + ...(review ? { feedback: undefined } : {}) }) + if (review) void monitor() + } catch (error) { + if (!read.signal.aborted && state.roles) set({ roles: { ...state.roles, loading: false, error: failure(error) } }) + } + } + + function openRoles(): boolean { + const item = selectedWritable() + if (!item || state.roles || saving()) return false + set({ roles: { draft: newDraft(item), loading: true }, feedback: undefined }) + void readRoles(false) + return true + } + function setRoleMode(mode: RoleMode): void { + if (!state.roles?.options || state.roles.loading || saving()) return + set({ roles: { ...state.roles, draft: { ...state.roles.draft, mode } } }) + } + function pickRole(id: string, checked: boolean): void { + const editor = state.roles + if (!editor?.options || editor.loading || saving() || editor.draft.mode !== 'selected') return + const picked = editor.draft.picked + if (checked ? !editor.options.some((item) => item.id === id) || picked.includes(id) : !picked.includes(id)) return + const next = checked ? [...picked, id] : picked.filter((old) => old !== id) + set({ roles: { ...editor, draft: { ...editor.draft, picked: next, mode: next.length ? 'selected' : 'none' } } }) + } + + async function save(item: SkillSummary, edit: SkillEdit): Promise { + if (lifetime.signal.aborted || saving() || state.listError || state.syncError || item.source !== 'custom' || !item.canConfigure || + current(item.id)?.revision !== item.revision || matchesSkillEdit(item, edit)) return + set({ feedback: { id: item.id, edit, status: 'saving' } }) + try { + await api.patch(item, edit, lifetime.signal) + if (lifetime.signal.aborted) return + // Confirm the projection actually visible after writing. A list toggle never reads private document text. + const result = await readCatalog(true) + if (lifetime.signal.aborted) return + const saved = result?.skills.find((s) => s.id === item.id) + if (!result) throw new Error('Could not confirm skill preferences') + if (!saved) { rejectSave(item, edit, 'missing'); return } + if (!saved.canConfigure || saved.source !== 'custom') { rejectSave(item, edit, 'readonly'); return } + if (!matchesSkillEdit(saved, edit)) { rejectSave(item, edit, 'stale'); return } + if ('roles' in edit) closeRoles() + set({ feedback: { id: item.id, edit, status: 'saved' } }) + } catch (error) { + if (lifetime.signal.aborted) return + const problem = failure(error) + rejectSave(item, edit, problem) + // A dropped receipt or conflict may already have changed disk. Refresh reads only, never replay PATCH. + void readCatalog(true) + } + } + function rejectSave(item: SkillSummary, edit: SkillEdit, problem: SkillProblem): void { + const editor = state.roles + set({ feedback: { id: item.id, edit, status: problem }, + ...(editor && 'roles' in edit ? { roles: { ...editor, draft: { ...editor.draft, review: true } } } : {}) }) + } + function toggle(id: string): void { + const item = current(id) + if (item && (!state.selected || selectedWritable()?.id === id) && !state.roles) void save(item, { enabled: !item.enabled }) + } + function saveRoles(): void { + const item = selectedWritable() + const editor = state.roles + if (!item || !editor?.options || editor.loading || editor.error || roleNeedsReview(editor.draft, item) || invalidDraftRoles(editor, item)) return + void save(item, { roles: draftRoles(editor.draft) }) + } + function dispose(): void { + lifetime.abort() + detailRead?.abort() + rolesRead?.abort() + listeners.clear() + } + return { + snapshot: () => state, + subscribe(listener: () => void): () => void { listeners.add(listener); return () => { listeners.delete(listener) } }, + start(): void { if (!started) { started = true; void refresh() } }, + dispose, refresh, open, back, toggle, openRoles, closeRoles, setRoleMode, pickRole, saveRoles, + reviewRoles: () => readRoles(true) + } +} +export type SkillLibraryController = ReturnType diff --git a/apps/desktop/src/workbench/skill-library-copy.ts b/apps/desktop/src/workbench/skill-library-copy.ts new file mode 100644 index 00000000..f90a4a06 --- /dev/null +++ b/apps/desktop/src/workbench/skill-library-copy.ts @@ -0,0 +1,45 @@ +import type { SkillProblem } from './skill-library-transport' + +const english = { + inactive: 'These are saved preferences. Web chat does not run skills or their tools.', + refresh: 'Refresh', loading: 'Loading skills…', detailLoading: 'Loading skill…', rolesLoading: 'Loading roles…', + empty: 'No skills yet.', custom: 'Custom', readonly: 'Read-only', savedEnabled: 'Saved enabled preference', + savedOn: 'Saved: enabled', savedOff: 'Saved: disabled', source: 'Source', + editRoles: 'Edit available roles', noRoles: 'No roles', oneRole: '1 role', rolesCount: '{n} roles', + selectedRoles: 'Selected roles', unrecognized: 'Unrecognized role', + disabledRole: 'Disabled role', saveRoles: 'Save roles', review: 'Review latest', reviewHint: 'Review your choices against the latest saved preferences before saving.', + emptySelected: 'Choose at least one role or select No roles.', unknownSelected: 'Remove roles that are no longer available before saving.', + saving: 'Saving preferences…', saved: 'Preferences saved.', sync: 'Live updates paused. Refresh to resume.', + reconnecting: 'Reconnecting to the skill library…', + requestedOn: 'Requested preference: enabled.', requestedOff: 'Requested preference: disabled.', + problem: { + stale: 'This skill changed elsewhere. Review the latest saved preferences before trying again.', + missing: 'This skill is no longer available.', readonly: 'This skill is read-only.', + restricted: 'This preference is restricted.', unknownRole: 'A selected role is no longer available. Review your choices.', + expired: 'Your session expired.', invalid: 'The skill library returned an invalid response.', + unavailable: 'The skill library could not confirm the latest information. Refresh to check the saved preferences.' + } satisfies Record +} + +export const skillCopy: { 'en': typeof english; 'zh-CN': typeof english } = { + en: english, + 'zh-CN': { + inactive: '此处仅记录已保存的偏好。Web 对话不会运行技能或技能工具。', + refresh: '刷新', loading: '正在加载技能…', detailLoading: '正在加载技能详情…', rolesLoading: '正在加载角色…', + empty: '暂无技能。', custom: '自定义', readonly: '只读', savedEnabled: '保存的启用偏好', + savedOn: '已保存:启用', savedOff: '已保存:停用', source: '来源', + editRoles: '编辑可用角色', noRoles: '无可用角色', oneRole: '1 个角色', rolesCount: '{n} 个角色', + selectedRoles: '指定角色', unrecognized: '未识别的角色', + disabledRole: '已停用的角色', saveRoles: '保存角色范围', review: '核对最新版本', reviewHint: '保存前请根据最新偏好核对你的选择。', + emptySelected: '请选择至少一个角色,或选择「无可用角色」。', unknownSelected: '请先移除已失效的角色。', + saving: '正在保存偏好…', saved: '偏好已保存。', sync: '实时更新已暂停,刷新后继续。', + reconnecting: '正在重新连接技能库…', + requestedOn: '所选偏好:启用。', requestedOff: '所选偏好:停用。', + problem: { + stale: '此技能已在别处更新。请先核对最新的已保存偏好。', + missing: '此技能已失效或被移除。', readonly: '此技能为只读。', restricted: '此偏好的修改受限。', + unknownRole: '所选角色已失效。请核对角色选择。', expired: '会话已过期。', + invalid: '技能库返回了格式错误的响应。', unavailable: '技能库未能确认最新信息。请刷新后核对已保存偏好。' + } + } +} diff --git a/apps/desktop/src/workbench/skill-library-transport.ts b/apps/desktop/src/workbench/skill-library-transport.ts new file mode 100644 index 00000000..b26cc702 --- /dev/null +++ b/apps/desktop/src/workbench/skill-library-transport.ts @@ -0,0 +1,139 @@ +import { HttpFailure, type Bootstrap, type Transport } from './transport' + +type Obj = Record +export type SkillRoles = string[] | null +export type SkillSummary = { + id: string; name: string; description: string; source: 'builtin' | 'custom' + enabled: boolean; roles: SkillRoles; revision: string; canConfigure: boolean +} +export type SkillDocument = SkillSummary & { + detail: 'document'; instructions: string; trigger: string; license: string; compatibility: string + allowedTools: string[]; metadata: Record +} +export type Catalog = { skills: SkillSummary[]; revision: string } +export type RoleOption = { id: string; name: string; enabled: boolean } +export type SkillEdit = { enabled: boolean } | { roles: SkillRoles } +export type SkillProblem = 'stale' | 'missing' | 'readonly' | 'restricted' | 'unknownRole' | 'expired' | 'invalid' | 'unavailable' + +const summaryFields = ['id', 'name', 'description', 'source', 'enabled', 'roles', 'revision', 'canConfigure'] +const documentFields = ['instructions', 'trigger', 'license', 'compatibility', 'allowedTools', 'metadata'] +class InvalidSkillResponse extends Error { + constructor() { super('Invalid skill library response') } +} +function invalid(): never { throw new InvalidSkillResponse() } +function object(v: unknown): v is Obj { return v !== null && typeof v === 'object' && !Array.isArray(v) } +function exact(v: unknown, keys: readonly string[]): v is Obj { + return object(v) && Object.keys(v).length === keys.length && keys.every((k) => Object.hasOwn(v, k)) +} +function strings(v: unknown): v is string[] { return Array.isArray(v) && v.every((x) => typeof x === 'string') } +const reservedIds = new Set(['prototype', ...Object.getOwnPropertyNames(Object.prototype).map((key) => key.toLowerCase())]) +function roleId(v: unknown): v is string { + return typeof v === 'string' && v.length > 0 && v.length <= 256 && v === v.trim() && !/[\u0000-\u001f\u007f\ud800-\udfff]/u.test(v) +} +function roles(v: unknown): v is SkillRoles { return v === null || Array.isArray(v) && Array.from(v).every(roleId) } +function revision(v: unknown): v is string { return typeof v === 'string' && /^[a-f0-9]{64}$/u.exec(v)?.[0] === v } +function id(v: unknown): v is string { + return typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/u.exec(v)?.[0] === v && + !v.endsWith('.') && !v.includes('..') && !reservedIds.has(v.toLowerCase()) +} +function summary(v: unknown, extra: readonly string[] = []): SkillSummary { + if (!exact(v, [...summaryFields, ...extra]) || !id(v.id) || typeof v.name !== 'string' || !v.name || + typeof v.description !== 'string' || (v.source !== 'builtin' && v.source !== 'custom') || + typeof v.enabled !== 'boolean' || !roles(v.roles) || !revision(v.revision) || typeof v.canConfigure !== 'boolean' || + (v.source === 'builtin' && (v.canConfigure || !v.enabled || v.roles !== null))) return invalid() + return { id: v.id, name: v.name, description: v.description, source: v.source, enabled: v.enabled, + roles: v.roles === null ? null : [...new Set(v.roles)], revision: v.revision, canConfigure: v.canConfigure } +} +function detail(value: unknown, wanted: string): SkillDocument | SkillSummary & { detail: 'builtin' } | null { + if (!exact(value, ['skill', 'execution']) || value.execution !== 'inactive') return invalid() + const v = value.skill + if (v === null) return null + if (!object(v) || v.id !== wanted) return invalid() + if (v.detail === 'builtin' && v.source === 'builtin') return { ...summary(v, ['detail']), detail: 'builtin' } + if (v.detail !== 'document' || v.source !== 'custom' || + typeof v.instructions !== 'string' || typeof v.trigger !== 'string' || typeof v.license !== 'string' || + typeof v.compatibility !== 'string' || !strings(v.allowedTools) || !object(v.metadata) || + !Object.values(v.metadata).every((x) => typeof x === 'string')) return invalid() + return { ...summary(v, ['detail', ...documentFields]), detail: 'document', instructions: v.instructions, trigger: v.trigger, + license: v.license, compatibility: v.compatibility, allowedTools: v.allowedTools, metadata: v.metadata as Record } +} + +export function sameSkillRoles(a: SkillRoles, b: SkillRoles): boolean { + return a === null || b === null ? a === b : a.length === b.length && a.every((value) => b.includes(value)) +} +export function matchesSkillEdit(skill: SkillSummary, edit: SkillEdit): boolean { + return 'enabled' in edit ? skill.enabled === edit.enabled : sameSkillRoles(skill.roles, edit.roles) +} +export function retryableSkillRead(error: unknown): boolean { + return error instanceof TypeError || error instanceof HttpFailure && (error.status === 429 || error.status >= 500) +} + +export function skillProblem(error: unknown): SkillProblem { + if (error instanceof HttpFailure) { + switch (error.status) { + case 401: return 'expired' + case 403: return 'readonly' + case 404: return 'missing' + case 409: + if (error.code === 'skill_unknown_role') return 'unknownRole' + if (error.code === 'skill_builtin') return 'readonly' + return error.code === 'skill_unsupported' ? 'restricted' : 'stale' + case 413: + case 422: return 'restricted' + case 400: return 'invalid' + } + } + return error instanceof InvalidSkillResponse || error instanceof SyntaxError ? 'invalid' : 'unavailable' +} + +export function createSkillLibraryTransport(transport: Transport, session: Pick) { + if (session.capabilities?.skillLibrary !== true || !session.csrf) return undefined + const csrf = session.csrf + const read = (path: string, signal: AbortSignal) => transport.request(path, 'GET', undefined, undefined, { signal, expectedStatus: 200 }) + const write = (path: string, method: 'PATCH' | 'POST', body: unknown, signal: AbortSignal) => + transport.request(path, method, body, csrf, { signal, expectedStatus: 200, referrerPolicy: 'same-origin' }) + return { + async list(signal: AbortSignal): Promise { + const v = await read('/skills', signal) + if (!exact(v, ['skills', 'revision', 'execution']) || v.execution !== 'inactive' || !revision(v.revision) || !Array.isArray(v.skills)) return invalid() + const skills = v.skills.map((item) => summary(item)) + if (new Set(skills.map((s) => s.id)).size !== skills.length) return invalid() + return { skills, revision: v.revision } + }, + async detail(skillId: string, signal: AbortSignal): Promise> { + if (!id(skillId)) return invalid() + return detail(await read(`/skills/${encodeURIComponent(skillId)}`, signal), skillId) + }, + async roles(signal: AbortSignal): Promise { + const v = await read('/skills/-/roles', signal) + if (!exact(v, ['roles']) || !Array.isArray(v.roles)) return invalid() + const rows = v.roles.map((row): RoleOption => { + if (!exact(row, ['id', 'name', 'enabled']) || !roleId(row.id) || typeof row.name !== 'string' || typeof row.enabled !== 'boolean') return invalid() + return { id: row.id, name: row.name, enabled: row.enabled } + }) + if (new Set(rows.map((r) => r.id)).size !== rows.length) return invalid() + return rows + }, + async patch(target: SkillSummary, edit: SkillEdit, signal: AbortSignal): Promise { + if (!id(target.id) || target.source !== 'custom' || target.canConfigure !== true || !revision(target.revision)) return invalid() + let body: SkillEdit & { revision: string } + if (exact(edit, ['enabled']) && 'enabled' in edit && typeof edit.enabled === 'boolean') body = { revision: target.revision, enabled: edit.enabled } + else if (exact(edit, ['roles']) && 'roles' in edit && roles(edit.roles) && + (edit.roles === null || (edit.roles.length <= 64 && new Set(edit.roles).size === edit.roles.length))) body = { revision: target.revision, roles: edit.roles } + else return invalid() + const v = await write(`/skills/${encodeURIComponent(target.id)}/preferences`, 'PATCH', body, signal) + if (!exact(v, ['skill', 'execution']) || v.execution !== 'inactive') return invalid() + const saved = summary(v.skill) + if (saved.id !== target.id || saved.source !== 'custom' || saved.canConfigure !== true || !matchesSkillEdit(saved, body) || + (saved.revision === target.revision && !matchesSkillEdit(target, body))) return invalid() + return saved + }, + async changes(after: string, waitMs: number, signal: AbortSignal): Promise<{ changed: boolean; revision: string }> { + if (!revision(after) || !Number.isInteger(waitMs) || waitMs < 0 || waitMs > 8000) return invalid() + const v = await write('/skills/-/changes', 'POST', { after, waitMs }, signal) + if (!exact(v, ['changed', 'revision']) || !revision(v.revision) || v.changed !== (v.revision !== after)) return invalid() + return { changed: v.changed, revision: v.revision } + } + } +} +export type SkillLibraryTransport = NonNullable> diff --git a/apps/desktop/src/workbench/skill-library.css b/apps/desktop/src/workbench/skill-library.css new file mode 100644 index 00000000..4fa13a16 --- /dev/null +++ b/apps/desktop/src/workbench/skill-library.css @@ -0,0 +1,89 @@ +.wb-skill { + min-width: 0; + height: 100%; + line-height: 1.5; +} + +.wb-skill__toolbar, .wb-skill__actions { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: var(--space-2); +} + +.wb-skill__toolbar { justify-content: space-between; } +.wb-skill__actions { justify-content: flex-end; margin-block-start: var(--space-3); } +.wb-skill__notice, .wb-skill__status { margin: 0 0 var(--space-2); font-size: 12px; color: var(--fg-muted); } +.wb-skill__status:empty { margin: 0; } +.wb-skill__status[data-error] { color: var(--warning); } + +.wb-skill__toggle { + display: inline-flex; + margin-inline-start: auto; + width: fit-content; + align-items: center; + flex: none; +} + +.wb-skill .provider-detail__topbar { flex-wrap: wrap; } +.wb-skill .provider-detail__topbar .wb-skill__toggle { margin-inline-start: 0; } +.wb-skill :is(button, input, pre):focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.wb-skill .ext-detail__name { overflow-wrap: anywhere; } + +.wb-skill__sr { + position: absolute; + inline-size: 1px; + block-size: 1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} + +.wb-skill__summary { + margin: 0 0 var(--space-3); + overflow-wrap: anywhere; + font-size: 13px; +} + +.wb-skill__summary > div { margin-block: var(--space-2); } +.wb-skill__summary dt { color: var(--fg-muted); font-size: 12px; font-weight: 600; } +.wb-skill__summary dd { margin: 0; } +.wb-skill__summary dd button { margin-inline-start: var(--space-2); } + +.wb-skill__roles { + margin: 0 0 var(--space-3); + min-inline-size: 0; + padding: var(--space-2); + border: 1px solid var(--border); + border-radius: var(--radius); +} + +.wb-skill__modes, .wb-skill__options { display: flex; gap: var(--space-2); } +.wb-skill__modes { flex-wrap: wrap; } +.wb-skill__options { + flex-direction: column; + margin-block: var(--space-2); + max-block-size: 10rem; + overflow: auto; + padding: var(--space-1); +} + +.wb-skill__roles label { + display: inline-flex; + align-items: baseline; + gap: var(--space-1); + cursor: pointer; +} + +.wb-skill__options span { min-width: 0; overflow-wrap: anywhere; } +.wb-skill__roles small { color: var(--fg-muted); margin-inline-start: var(--space-1); } +.wb-skill__instructions { min-block-size: 8rem; } +.wb-skill__literal { + margin: 0; + overflow: auto; + user-select: text; + white-space: pre-wrap; + overflow-wrap: anywhere; + font: 13px/1.55 var(--font-mono); + unicode-bidi: plaintext; +} diff --git a/apps/desktop/src/workbench/skill-library.tsx b/apps/desktop/src/workbench/skill-library.tsx new file mode 100644 index 00000000..e86d7a96 --- /dev/null +++ b/apps/desktop/src/workbench/skill-library.tsx @@ -0,0 +1,241 @@ +import { useId, useLayoutEffect, useRef, useState, useSyncExternalStore, type Ref, type RefObject } from 'react' +import { RotateCw } from 'lucide-react' +import { useI18n } from '../renderer/src/i18n/i18n' +import { Toggle } from '../renderer/src/redesign/shell-common' +import { ExtensionSettingsRow, SkillSettingsDetail } from '../renderer/src/redesign/SkillSettingsParts' +import { createSkillLibrary, draftRoles, invalidDraftRoles, roleNeedsReview, + type RoleMode, type SkillLibraryController, type SkillLibraryState } from './skill-library-controller' +import { skillCopy } from './skill-library-copy' +import { createSkillLibraryTransport, sameSkillRoles, type SkillSummary } from './skill-library-transport' +import type { Bootstrap, Transport } from './transport' +import './skill-library.css' + +function useCopy() { + const { locale } = useI18n() + return skillCopy[locale] +} + +function SavedToggle({ item, busy, disabled, onChange }: { + item: SkillSummary; busy: boolean; disabled: boolean; onChange: () => void +}): React.JSX.Element { + const labels = useCopy() + return +} + +function SkillStatus({ state }: { state: SkillLibraryState }): React.JSX.Element { + const labels = useCopy() + const feedback = state.feedback?.status + const problem = state.listError ?? (feedback === 'saving' || feedback === 'saved' ? undefined : feedback) ?? state.selected?.error ?? state.roles?.error + const review = !!state.roles && !!state.selected && roleNeedsReview(state.roles.draft, state.selected.item) + let text = '' + if (state.reconnecting) text = labels.reconnecting + else if (state.syncError) text = state.syncError === 'unavailable' ? labels.sync : `${labels.problem[state.syncError]} ${labels.sync}` + else if (feedback === 'saving') text = labels.saving + else if (problem) { + const edit = state.feedback?.edit + text = labels.problem[problem] + (feedback === problem && edit && 'enabled' in edit ? ` ${edit.enabled ? labels.requestedOn : labels.requestedOff}` : '') + } else if (review) text = labels.reviewHint + else if (state.selected?.loading) text = labels.detailLoading + else if (state.roles?.loading) text = labels.rolesLoading + else if (state.listing && !state.catalog) text = labels.loading + else if (feedback === 'saved') text = labels.saved + return

{text}

+} + +function Refresh({ disabled, refresh }: { disabled: boolean; refresh: () => void }): React.JSX.Element { + const labels = useCopy() + return +} + +function CatalogList({ controller, state, heading, onOpen, trackRow }: { + controller: SkillLibraryController; state: SkillLibraryState; heading: Ref + onOpen: (id: string) => void; trackRow: (id: string, node: HTMLButtonElement | null) => void +}): React.JSX.Element { + const { t } = useI18n() + const labels = useCopy() + const saving = state.feedback?.status === 'saving' + return <> +
+

{t('extensions.skills')}

+ void controller.refresh()} /> +
+

{labels.inactive}

+ + {state.catalog?.skills.length === 0 && !state.listError &&
{labels.empty}
} + {!!state.catalog?.skills.length &&
+ {state.catalog.skills.map((item) => + {item.roles.length === 0 ? labels.noRoles : item.roles.length === 1 ? labels.oneRole : labels.rolesCount.replace('{n}', String(item.roles.length))} + } + rowProps={{ 'data-testid': 'workbench-skill-row', 'data-skill-id': item.id, 'data-source': item.source, 'data-enabled': String(item.enabled) }} + openProps={{ 'data-testid': 'workbench-skill-open', type: 'button', disabled: !!(state.listError || state.syncError), ref: (node) => trackRow(item.id, node) }} + onOpen={item.source === 'custom' ? (event) => { if (event.nativeEvent.isTrusted) onOpen(item.id) } : undefined} + toggle={ controller.toggle(item.id)} />} />)} +
} + +} + +function ScopeText({ item }: { item: SkillSummary }): React.JSX.Element { + const { t, locale } = useI18n() + const labels = useCopy() + if (item.roles === null) return {t('extensions.rolesGeneral')} + if (item.roles.length === 0) return {labels.noRoles} + return {item.roles.join(locale === 'zh-CN' ? '、' : ', ')} +} + +function RolePicker({ controller, state, item, focusRef, writable }: { + controller: SkillLibraryController; state: SkillLibraryState; item: SkillSummary; focusRef: Ref; writable: boolean +}): React.JSX.Element | null { + const { t } = useI18n() + const labels = useCopy() + const radioName = useId() + const form = state.roles + if (!form) return null + const { draft, options } = form + const saving = state.feedback?.status === 'saving' + const review = roleNeedsReview(draft, item) + const invalid = invalidDraftRoles(form, item) + const roleModes: { value: RoleMode; label: string }[] = [ + { value: 'all', label: t('extensions.rolesGeneral') }, { value: 'none', label: labels.noRoles }, { value: 'selected', label: labels.selectedRoles } + ] + return
+ {labels.editRoles} + {options && <> +
+ {roleModes.map(({ value, label }) => )} +
+ {draft.mode === 'selected' &&
+ {options.map((option) => )} + {draft.picked.filter((id) => !options.some((option) => option.id === id)).map((id) => )} +
} + } + {options && invalid && !review &&

{draft.picked.length ? labels.unknownSelected : labels.emptySelected}

} +
+ + {(review || form.error) && } + +
+
+} + +function SkillDetail({ controller, state, onBack, backRef }: { + controller: SkillLibraryController; state: SkillLibraryState & { selected: NonNullable } + onBack: () => void; backRef: RefObject +}): React.JSX.Element { + const { t } = useI18n() + const labels = useCopy() + const instructionsId = useId() + const summary = state.selected.item + const latest = state.catalog?.skills.find((s) => s.id === summary.id) + const document = state.selected.document + const writable = !!document && latest?.revision === document.revision && latest.canConfigure && !state.selected.error && !state.listError && !state.syncError + const saving = state.feedback?.status === 'saving' + const roleButton = useRef(null) + const roleEditor = useRef(null) + const returnToRoleButton = useRef(false) + const inRoles = !!state.roles + useLayoutEffect(() => { + if (inRoles) { + roleEditor.current?.focus() + returnToRoleButton.current = true + } + }, [inRoles]) + useLayoutEffect(() => { + if (inRoles || !returnToRoleButton.current || state.selected.loading) return + const target = roleButton.current && !roleButton.current.disabled ? roleButton.current : backRef.current + target?.focus() + returnToRoleButton.current = false + }, [backRef, inRoles, saving, state.selected.loading, writable]) + return + void controller.refresh()} /> + {summary.enabled ? labels.savedOn : labels.savedOff} + controller.toggle(summary.id)} /> + }> +

{labels.inactive}

+ + {document &&
+
{labels.source}
{labels.custom}{!summary.canConfigure && ` · ${labels.readonly}`}
+ {summary.description &&
{t('extensions.description')}
{summary.description}
} +
{t('extensions.roles')}
+ {summary.canConfigure && !inRoles && } +
+
} + + {document &&
+

{t('extensions.instructions')}

+
{document.instructions}
+ {!document.instructions && {t('extensions.instructionsEmpty')}} +
} +
+} + +function OpenPanel({ controller }: { controller: SkillLibraryController }): React.JSX.Element { + const { t } = useI18n() + const state = useSyncExternalStore(controller.subscribe, controller.snapshot, controller.snapshot) + const heading = useRef(null) + const backRef = useRef(null) + const openedFrom = useRef(undefined) + const rows = useRef(new Map()) + const selected = state.selected?.item.id + useLayoutEffect(() => { + if (selected) backRef.current?.focus() + else if (openedFrom.current) { + (rows.current.get(openedFrom.current) ?? heading.current)?.focus() + openedFrom.current = undefined + } + }, [selected]) + return
+ {state.selected ? : + { if (controller.open(id)) openedFrom.current = id }} + trackRow={(id, node) => { if (node) rows.current.set(id, node); else rows.current.delete(id) }} />} +
+} + +export default function SkillLibrary({ transport, bootstrap, onExpired }: { transport: Transport; bootstrap: Bootstrap; onExpired: () => void }): React.JSX.Element | null { + const [controller, setController] = useState() + const { t } = useI18n() + const labels = useCopy() + useLayoutEffect(() => { + const api = createSkillLibraryTransport(transport, bootstrap) + if (!api) return + const runtime = createSkillLibrary(api, onExpired) + setController(runtime) + runtime.start() + return runtime.dispose + }, [transport, bootstrap, onExpired]) + if (bootstrap.capabilities?.skillLibrary !== true) return null + return controller ? : +
+

{labels.loading}

+
+} diff --git a/apps/desktop/src/workbench/transport.ts b/apps/desktop/src/workbench/transport.ts index 885e9c2b..6efb7793 100644 --- a/apps/desktop/src/workbench/transport.ts +++ b/apps/desktop/src/workbench/transport.ts @@ -14,7 +14,7 @@ export interface Bootstrap { config: RecordValue csrf: string expiresAt: number - capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true; gitInspect?: true; sessionWorkspaces?: true; taskInspection?: true; terminalViewer?: true } + capabilities?: { textChat?: true; library?: true; workspaceFiles?: true; attachments?: true; browserPanel?: true; sessionPreferences?: true; deliveries?: true; gitInspect?: true; sessionWorkspaces?: true; taskInspection?: true; terminalViewer?: true; skillLibrary?: true } } export type SessionScreen = { mode: 'authenticated'; bootstrap: Bootstrap } | { mode: 'claim' | 'login' } @@ -130,6 +130,7 @@ export function createTransport(send: Fetch = fetch) { if (result.capabilities.sessionWorkspaces === true) capabilities.sessionWorkspaces = true if (result.capabilities.taskInspection === true) capabilities.taskInspection = true if (result.capabilities.terminalViewer === true) capabilities.terminalViewer = true + if (result.capabilities.skillLibrary === true) capabilities.skillLibrary = true } return { protocol, version, platform, config, csrf, expiresAt, ...(Object.keys(capabilities).length ? { capabilities } : {}) } } diff --git a/apps/headless/README.md b/apps/headless/README.md index 177c92f0..f1e73007 100644 --- a/apps/headless/README.md +++ b/apps/headless/README.md @@ -22,6 +22,18 @@ - 全局、角色和项目记忆分别管理。可以手动新增、查看、编辑、删除或确认清空选中范围。项目只以管理员登记的目录 ID 选择;在此阶段选择项目不授予聊天读取目录文件或执行命令的权限。旧记忆的首次实际修改会在数据卷内留下迁移备份。 - 默认无授权项目。若要使用项目范围,在服务器上准备一个**专用**项目父目录,只放准备开放的项目子目录。设置 `DEVA_WORKSPACE_PARENT` 为其绝对路径,并将 `-f compose.workspaces.yaml` 追加到下面采用的 Compose 命令;该可选文件把目录只读挂载到 `/workspaces`。机器上的其他目录、个人家目录和 Docker socket 均不应挂入。 +## 管理已保存的技能 + +打开 **设置 → 扩展**。列表来自当前实例的数据卷,使用桌面的扩展行和详情组件。三个应用内置项只显示目录信息与固定状态;选择自定义技能才打开它的 `SKILL.md` 详情。页面展示来源、说明、角色范围和纯文本正文;详情接口返回的建议工具等字段是文档资料,并非运行许可。文件里的图片、链接、脚本和其他资源都不会被自动打开。 + +开关保存的是桌面格式的启用偏好。在技能详情中打开 **可用角色**,可选择「全部角色」「不指定任何角色」或勾选具体角色,确认后保存。全部和零个是两种不同状态:前者删除此项在角色映射中的覆盖,后者保存空数组。已删除的旧角色引用保留原值,只有人工修改才会改变。另一个登录或宿主先改了文件时,页面会提示核对新版本,旧操作不会自动重放。只在面板打开时检查目录变化。 + +**这些设置不启动技能。** Web 对话不会因为某项记录为启用就加载其正文或开放额外工具。此页没有安装、导入、删除、执行脚本、MCP 连接或修改技能正文的操作;已有普通技能记录可与停写后的桌面数据副本一同迁移。 + +- 默认 Compose 容器内原生位置为 `/data/skills//SKILL.md`,偏好位于 `/data/config.json` 下的 `skills.enabled` 与 `skills.roles`。列表不会创建缺失的技能目录。配置有修订号和单写者保护,写后需读回;源 Markdown、旁边的资源和配置文件中的其他字段保持原样。 +- 支持当前应用用户拥有的、与数据目录在同一文件系统挂载中的普通单链接文档,最多 128 个自定义技能、每份文档 128 KiB、文件首部元数据 16 KiB、目录中文档合计 4 MiB。扫描最多检查 512 个直接条目。链接、同名冲突、超限和未支持的结构会显示错误,而非显示成空列表。常见凭据字段或明显的私钥内容会被拦截;这项检查并非通用敏感信息识别器。 +- 适用于专属数据卷,配置作为普通文件通过临时文件替换写入,保留安全的原 UID/GID 和传统 Unix 权限。依赖自定义扩展 ACL、xattr 或多写者语义的原件应保留独立备份。配置只读时仍可查看合格记录。 + ## 把附件发给对话模型 选择、粘贴或拖入文件时,浏览器先把字节暂存在**当前会话**中。输入区显示可预览或撤回的附件卡;只有点击发送,才会将选定文件纳入模型请求。文件名是显示标签,不是客户端或服务器路径。不要把“在项目里浏览文件”与“将文件发给模型”混为一谈。 diff --git a/apps/headless/scripts/library-core.ts b/apps/headless/scripts/library-core.ts index ed0f6e63..e6af629f 100644 --- a/apps/headless/scripts/library-core.ts +++ b/apps/headless/scripts/library-core.ts @@ -3,3 +3,5 @@ export * from '../../desktop/src/main/services/profile-core' export * from '../../desktop/src/main/services/avatar-image-core' export * from '../../desktop/src/main/services/memory-core' export * from '../../desktop/src/main/services/persona-format' +export { parseSkillDocument } from '../../desktop/src/main/services/skill-document-format' +export { BUILTIN_SKILL_CATALOG } from '../../desktop/src/shared/skill-catalog' diff --git a/apps/headless/src/business/handlers.mjs b/apps/headless/src/business/handlers.mjs index 38245942..1e22f99c 100644 --- a/apps/headless/src/business/handlers.mjs +++ b/apps/headless/src/business/handlers.mjs @@ -18,6 +18,9 @@ import { HttpError, json, readJson } from '../http/policy.mjs' import { openSettings } from './settings.mjs' import { allowedModelOrigins } from './provider-fetch.mjs' import { openLibrary } from './library-routes.mjs' +import { openSkillDocuments } from '../skills/documents.mjs' +import { openSkillLibrary } from '../skills/store.mjs' +import { skillLibraryRoutes } from '../skills/routes.mjs' const keyPath = /^\/api\/v1\/provider-keys\/([A-Za-z0-9_.-]{1,128})$/ const names = new Set(['/api/v1/settings', '/api/v1/provider-keys', '/api/v1/provider-models']) @@ -56,9 +59,13 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi const lifetime = new AbortController() const journal = createEventJournal() let library, turns, uploads, browser, closingBrowser, git, closingGit, taskStore, preview, tasks, closingTasks - let terminalService, closingTerminals + let terminalService, closingTerminals, skills, closingSkills try { library = await openLibrary({ dataDir, workspaceRoot, workspaceWritable, privateRoots, gitProjects }) + // Discover native documents only upon explicit owner requests (never feed this catalog to turns). + const documents = openSkillDocuments({ dataDir }) + skills = skillLibraryRoutes({ auth, documents, store: openSkillLibrary({ dataDir, documents, + withRoleChoices: library.withSkillRoleChoices }) }) if (library.gitGrants.enabled) git = openGitService({ grants: library.gitGrants, auth }) // No scheduler is installed in this process. Task records are read only on a human request. taskStore = openTaskStore({ dataDir }); preview = openTaskPreview() @@ -79,7 +86,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi } } catch (err) { journal.close() - await Promise.allSettled([terminalService?.close(), git?.close(), ...(tasks ? [tasks.close()] : [preview?.close(), taskStore?.close?.()]), + await Promise.allSettled([skills?.close(), terminalService?.close(), git?.close(), ...(tasks ? [tasks.close()] : [preview?.close(), taskStore?.close?.()]), turns?.close(), uploads?.close(), library?.close()]); throw err } const terminals = terminalRoutes(terminalService) @@ -90,6 +97,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi const deliveries = deliveryRoutes({ turns, files: library.deliveryFiles }) function beginShutdown() { lifetime.abort(); attachments.close() + if (!closingSkills) { closingSkills=skills.close();void closingSkills.catch(()=>{}) } if (!closingTerminals) { closingTerminals = terminals.close(); void closingTerminals.catch(() => {}) } if (!closingTasks) { closingTasks = tasks.close(); void closingTasks.catch(() => {}) } if (git && !closingGit) { closingGit = git.close(); void closingGit.catch(() => {}) } @@ -99,13 +107,14 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi beginShutdown, capabilities: Object.freeze({ textChat: true, library: true, workspaceFiles: library.workspaceFilesEnabled, attachments: true, browserPanel: !!browser, gitInspect: !!git, taskInspection: Boolean(tasks), deliveries: typeof turns.deliverySnapshot === 'function', - terminalViewer: Boolean(terminalService), + terminalViewer: Boolean(terminalService), skillLibrary: Boolean(skills), sessionWorkspaces: typeof turns.getWorkspace === 'function' && typeof turns.setWorkspace === 'function', sessionPreferences: typeof turns.patchPreferences === 'function' && typeof journal.watchSessions === 'function' }), createRealtime: ({ auth, policy }) => createChatWebSocket({ turns, journal, auth, policy }), getConfig: () => settings.getPublicConfig(), async handle(req, res, { auth, policy }) { const path = (req.url ?? '').split('?', 1)[0] + if ((path === '/api/v1/skills' || path.startsWith('/api/v1/skills/')) && await skills.handle(req,res,{auth,policy})) return true if ((path === '/api/v1/terminal/profiles' || (path.startsWith('/api/v1/workspaces/') && path.includes('/terminals'))) && await terminals.handle(req,res,{auth,policy})) return true if ((path === '/api/v1/tasks' || path.startsWith('/api/v1/tasks/')) && await tasks.handle(req, res, { auth, policy })) return true @@ -161,7 +170,7 @@ export async function openBusiness({ dataDir, vault, auth, version, allowedOrigi try { await turns.close() } finally { journal.close() try { - const results = await Promise.allSettled([closingBrowser, closingGit, closingTasks, closingTerminals]) + const results = await Promise.allSettled([closingBrowser, closingGit, closingTasks, closingTerminals, closingSkills]) if (results.some(row => row.status === 'rejected')) throw Error('Optional service shutdown unconfirmed') } finally { try { await uploads.close() } finally { await library.close() } } } diff --git a/apps/headless/src/business/library-routes.mjs b/apps/headless/src/business/library-routes.mjs index 0647bdcd..56859128 100644 --- a/apps/headless/src/business/library-routes.mjs +++ b/apps/headless/src/business/library-routes.mjs @@ -104,6 +104,10 @@ export async function openLibrary({ dataDir, workspaceRoot, workspaceWritable = deliveryFiles: workspaceRoot ? openDeliveryFiles({ catalog }) : undefined, resolveRole: id => serial(() => enabledRole(id)), withWorkspace: workspaceBindingResolver(catalog), + withSkillRoleChoices: action => serial(async () => { + const { roles, verify } = await personas.listSkillRoleChoices() + return action(roles,verify) + }), withRoleForChat: (id, action) => serial(async () => action(await enabledRole(id, true))), async handle(req, res, { auth, policy }) { const path = (req.url ?? '').split('?', 1)[0] diff --git a/apps/headless/src/business/personas.mjs b/apps/headless/src/business/personas.mjs index c35b9398..2f4b5b36 100644 --- a/apps/headless/src/business/personas.mjs +++ b/apps/headless/src/business/personas.mjs @@ -10,6 +10,7 @@ import { assertWritable, fail, publishCheckedFile, readCheckedText, removeChecke verifyFile, withChildDirectory } from './personas-files.mjs' import { assertNoReferences } from './personas-references.mjs' import { personaImagesIn } from './persona-images.mjs' +import { skillRoleChoiceVerifier } from './skill-role-choice-stamps.mjs' import { avatarDirectoryAccess, checkedAvatarUpload } from './profile.mjs' export { PersonaError } from './personas-files.mjs' @@ -399,6 +400,26 @@ export async function openPersonas(options) { } return Object.freeze({ list: () => access(index => publicRoster(workspaceCatalog, index)), + // Internal, short-lived metadata proof used by the saved skill role selector only. + // Reading choices does not resolve persona default folders or return prompts/images. + listSkillRoleChoices() { + return access(async index => { + const parent = await index.root.stat({bigint:true}), directory = await index.directory.stat({bigint:true}) + const ranks = new Map(index.config.order.map((id, rank) => [id,rank])) + const roles = [], files = [] + for (const id of index.ids) { + const binding = await readRole(index.directory,id) + if (!binding) fail('CONFLICT') + roles.push({id,name:binding.parsed.name,enabled:index.config.enabled[id] === true}) + files.push({id,info:binding.info}) + } + await index.verifyUnchanged() + const verify = skillRoleChoiceVerifier(path,parent,directory,files) + verify() + roles.sort((a,b)=>(ranks.get(a.id)??Number.MAX_SAFE_INTEGER)-(ranks.get(b.id)??Number.MAX_SAFE_INTEGER) || a.name.localeCompare(b.name) || a.id.localeCompare(b.id)) + return {roles,verify} + }) + }, async getAvatarImage(id) { requireId(id) return access(index => withRole(index, id, undefined, async binding => { diff --git a/apps/headless/src/business/settings-file.mjs b/apps/headless/src/business/settings-file.mjs index f1129612..b14402c9 100644 --- a/apps/headless/src/business/settings-file.mjs +++ b/apps/headless/src/business/settings-file.mjs @@ -1,20 +1,20 @@ import { createHash, randomBytes } from 'node:crypto' -import { constants, promises as fs } from 'node:fs' +import { constants, fstatSync, lstatSync, promises as fs } from 'node:fs' import { TextDecoder } from 'node:util' import { childPath, openDirectory } from '../storage/private-files.mjs' import { SettingsError, record } from './settings-schema.mjs' const CONFIG = 'config.json' -const MAX_BYTES = 4 * 1024 * 1024 +export const MAX_SETTINGS_FILE_BYTES = 4 * 1024 * 1024 const decoder = new TextDecoder('utf-8', { fatal: true }) const READ_FLAGS = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK const WRITE_FLAGS = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW const queues = new Map() -export async function withSettingsDirectory(path, expectedIdentity, task) { +export async function withSettingsDirectory(path, expectedIdentity, task, { create = !expectedIdentity } = {}) { let handle try { - const opened = await openDirectory(path, { create: !expectedIdentity, owned: true }) + const opened = await openDirectory(path, { create, owned: true }) handle = opened.directory if (expectedIdentity && opened.identity !== expectedIdentity) throw new SettingsError('STORAGE') // One queue per directory inode for all instances inside this server. The host takes @@ -63,7 +63,7 @@ export async function readSettingsFile(directory) { try { const info = await file.stat({ bigint: true }) verifyFile(info) - if (info.size < 1n || info.size > BigInt(MAX_BYTES)) throw new SettingsError('CORRUPT') + if (info.size < 1n || info.size > BigInt(MAX_SETTINGS_FILE_BYTES)) throw new SettingsError('CORRUPT') const bytes = Buffer.alloc(Number(info.size) + 1) try { let offset = 0 @@ -87,16 +87,27 @@ export async function readSettingsFile(directory) { } } -export async function assertWritable(directory, expected) { - const parent = await directory.stat({ bigint: true }) - if ((parent.mode & 0o300n) !== 0o300n || (expected && (expected.mode & 0o200n) === 0n)) { - throw new SettingsError('READ_ONLY') - } +function expectSnapshot(expected, current) { + if (current) verifyFile(current) + if ((!expected !== !current) || (expected && !sameSnapshot(expected, current))) throw new SettingsError('CONFLICT') +} + +async function assertSettingsCurrent(directory, expected) { let current = null try { current = await fs.lstat(childPath(directory, CONFIG), { bigint: true }) } catch (error) { if (error.code !== 'ENOENT') throw error } - if (current) verifyFile(current) - if ((!expected !== !current) || (expected && !sameSnapshot(expected, current))) throw new SettingsError('CONFLICT') + expectSnapshot(expected, current) +} + +function requireWritable(parent, expected) { + if ((parent.mode & 0o300n) !== 0o300n || (expected && (expected.mode & 0o200n) === 0n)) { + throw new SettingsError('READ_ONLY') + } +} + +export async function assertWritable(directory, expected) { + requireWritable(await directory.stat({ bigint: true }), expected) + await assertSettingsCurrent(directory, expected) } export function encodeSettings(raw) { @@ -105,7 +116,7 @@ export function encodeSettings(raw) { let bytes try { bytes = Buffer.from(JSON.stringify(raw) + '\n') } catch { throw new SettingsError('STORAGE') } - if (bytes.length > MAX_BYTES) throw new SettingsError('INVALID') + if (bytes.length > MAX_SETTINGS_FILE_BYTES) throw new SettingsError('INVALID') return bytes } @@ -117,7 +128,12 @@ async function cleanTemp(path, info) { } catch { /* Cleanup cannot undo a visible commit. */ } } -export async function publishSettingsFile(directory, bytes, expected) { +function namedFile(path) { + try { return lstatSync(path, { bigint: true }) } + catch (error) { if (error.code === 'ENOENT') return null; throw error } +} + +export async function publishSettingsFile(directory, bytes, expected, { beforePublish, authorize, preserveAccess } = {}) { const target = childPath(directory, CONFIG) const tmp = childPath(directory, `.config.${randomBytes(16).toString('hex')}.tmp`) let file, tempInfo, info @@ -126,9 +142,25 @@ export async function publishSettingsFile(directory, bytes, expected) { tempInfo = await file.stat({ bigint: true }) await file.chmod(0o600) await file.writeFile(bytes) + if (preserveAccess && expected) { + if (expected.gid !== tempInfo.gid) await file.chown(Number(expected.uid), Number(expected.gid)) + if ((expected.mode & 0o777n) !== 0o600n) await file.chmod(Number(expected.mode & 0o777n)) + } await file.sync() await directory.sync() - await assertWritable(directory, expected) + if (beforePublish || authorize) { + const staged = await file.stat({ bigint: true }) + await beforePublish?.() + authorize?.() // Intentionally synchronous: no event-loop yield until submitting rename/link. + requireWritable(fstatSync(directory.fd, { bigint: true }), expected) + expectSnapshot(expected, namedFile(target)) + const named = namedFile(tmp) + verifyFile(staged) + if (!named || !sameSnapshot(staged, named) || !sameSnapshot(staged, fstatSync(file.fd, { bigint: true })) || + (preserveAccess && expected && (staged.mode !== expected.mode || staged.uid !== expected.uid || staged.gid !== expected.gid))) { + throw new SettingsError('STORAGE') + } + } else await assertWritable(directory, expected) if (expected) await fs.rename(tmp, target) else { try { await fs.link(tmp, target) } diff --git a/apps/headless/src/business/skill-role-choice-stamps.mjs b/apps/headless/src/business/skill-role-choice-stamps.mjs new file mode 100644 index 00000000..119123e7 --- /dev/null +++ b/apps/headless/src/business/skill-role-choice-stamps.mjs @@ -0,0 +1,34 @@ +import { openSync } from 'node:fs' +import { resolve } from 'node:path' +import { HttpError } from '../http/policy.mjs' +import { DIRECTORY, PATH, close, fdPath, mountId, openAbsoluteDirectory, sameInode, stat } from '../files/workspace-files-fd.mjs' + +const conflict = () => new HttpError(409,'skill_conflict') +const sameMode = (a,b) => sameInode(a,b) && a.mode===b.mode && a.uid===b.uid && a.gid===b.gid +const sameSnapshot = (a,b) => sameMode(a,b) && a.nlink===b.nlink && a.size===b.size && a.mtimeNs===b.mtimeNs && a.ctimeNs===b.ctimeNs + +/** A short-lived selection proof for the caller's serialized preference operation. No + * persona text or external workspace is reread while publishing native role preferences. */ +export function skillRoleChoiceVerifier(dataDir, parentInfo, roleInfo, files) { + const rootPath=resolve(dataDir) + return () => { + let parent,roles + try { + parent=openAbsoluteDirectory(rootPath) + const mount=mountId(parent) + if(!sameMode(parentInfo,stat(parent))) throw conflict() + roles=openSync(fdPath(parent,'personas'),DIRECTORY) + if(mountId(roles)!==mount || !sameSnapshot(roleInfo,stat(roles))) throw conflict() + for(const {id,info} of files){ + let fd + try { + fd=openSync(fdPath(roles,id+'.md'),PATH) + const current=stat(fd) + if(!current.isFile() || current.nlink!==1n || !sameSnapshot(info,current) || mountId(fd)!==mount) throw conflict() + } finally {close(fd)} + } + if(!sameSnapshot(roleInfo,stat(roles))) throw conflict() + return true + } catch {throw conflict()} finally {close(roles);close(parent)} + } +} diff --git a/apps/headless/src/http/session-routes.mjs b/apps/headless/src/http/session-routes.mjs index 7dfdd9aa..60f82bd0 100644 --- a/apps/headless/src/http/session-routes.mjs +++ b/apps/headless/src/http/session-routes.mjs @@ -52,7 +52,8 @@ export function sessionRoutes({ auth, policy, version, getConfig, capabilities } browserPanel: capabilities?.browserPanel === true, sessionPreferences: capabilities?.sessionPreferences === true, deliveries: capabilities?.deliveries === true, gitInspect: capabilities?.gitInspect === true, sessionWorkspaces: capabilities?.sessionWorkspaces === true, - taskInspection: capabilities?.taskInspection === true, terminalViewer: capabilities?.terminalViewer === true } }) + taskInspection: capabilities?.taskInspection === true, terminalViewer: capabilities?.terminalViewer === true, + skillLibrary: capabilities?.skillLibrary === true } }) return true } if (path === '/api/v1/auth/logout') { diff --git a/apps/headless/src/skills/changes.mjs b/apps/headless/src/skills/changes.mjs new file mode 100644 index 00000000..a5141a46 --- /dev/null +++ b/apps/headless/src/skills/changes.mjs @@ -0,0 +1,93 @@ +import { performance } from 'node:perf_hooks' +import { HttpError } from '../http/policy.mjs' + +const tag = value => typeof value === 'string' && value.length === 64 && !/[^0-9a-f]/u.test(value) +const fail = (status,code) => new HttpError(status,code) + +/** One shared metadata sample per interval for all visible panels. Dormant when no one + * is waiting: no permanent directory watcher, body cache, filesystem polling or model work. */ +export function openSkillChanges({revision,auth,intervalMs=1000,readBudgetMs=4500,now=()=>performance.now()}) { + const waiters = new Set() + let closed=false, reading=false, queued=false, again=false, timer, sampling + + function authorized(w) { + try { return w.actor?.role==='owner' && auth.isLoginActive(w.actor)===true && w.verify()!==false && auth.isLoginActive(w.actor)===true } + catch { return false } + } + function finish(w, error, value) { + if (!waiters.delete(w)) return + clearTimeout(w.budget); w.signal?.removeEventListener('abort', w.cancel) + if (!waiters.size) { clearTimeout(timer);timer=undefined } + if (error) w.reject(error) + else w.resolve(value) + } + function later() { + clearTimeout(timer);timer=undefined + if (closed || !waiters.size) return + const due=Math.min(intervalMs,...[...waiters].map(w=>Math.max(0,w.end-now()))) + timer=setTimeout(wake,Math.max(1,Math.ceil(due)));timer.unref?.() + } + async function sample() { + queued=false + if (closed || !waiters.size) return + reading=true;again=false + const batch=[...waiters] + try { + for(const w of batch) if(!authorized(w)) finish(w,fail(401,'auth')) + if (!waiters.size) return + const value=await revision() + if (!tag(value)) throw fail(503,'skill_unavailable') + for(const w of batch) { + if (!waiters.has(w)) continue + if (!authorized(w)) finish(w,fail(401,'auth')) + else if (value!==w.after || now()>=w.end) finish(w,null,{changed:value!==w.after,revision:value}) + } + } catch (error) { + // Routes further restrict the error vocabulary; never leak native filesystem/parse diagnostics. + const safe = error instanceof HttpError ? error : fail(503,'skill_unavailable') + for(const w of batch) if(waiters.has(w)) finish(w,authorized(w)?safe:fail(401,'auth')) + } finally { + reading=false + if(again) wake(); else later() + } + } + function wake() { + if(closed || !waiters.size)return + clearTimeout(timer);timer=undefined + if(reading){again=true;return} + if(!queued){ + queued=true + queueMicrotask(()=>{ sampling=sample() }) + } + } + const off=auth.onSessionRevoked(sessionId=>{ + for (const w of waiters) if(w.actor.loginSessionId===sessionId) finish(w,fail(401,'auth')) + }) + return { + async wait(actor,body,verify,signal) { + if (closed) throw fail(503,'skill_unavailable') + if (!body || typeof body!=='object' || Object.keys(body).length!==2 || !Object.hasOwn(body,'after') || + !Object.hasOwn(body,'waitMs') || !tag(body.after) || !Number.isSafeInteger(body.waitMs) || body.waitMs<0 || body.waitMs>8000) throw fail(400,'skill_invalid') + if (!authorized({actor,verify})) throw fail(401,'auth') + if (signal?.aborted) throw fail(503,'skill_unavailable') + if(waiters.size>=16 || [...waiters].filter(w=>w.actor.loginSessionId===actor.loginSessionId).length>=2) throw fail(429,'skill_busy') + return new Promise((resolve,reject)=>{ + const w={actor,after:body.after,end:now()+body.waitMs,verify,signal,resolve,reject} + w.cancel=()=>finish(w,fail(503,'skill_unavailable')) + // Keep one deadline referenced while a caller is actually waiting. Otherwise + // an embedded Node host with no other active handle can exit before it gets a reply. + w.budget=setTimeout(w.cancel,body.waitMs+readBudgetMs) + waiters.add(w);signal?.addEventListener('abort',w.cancel,{once:true}) + wake() + }) + }, + wake, + close() { + if(!closed){ + closed=true;off();clearTimeout(timer) + for (const w of waiters) finish(w,fail(503,'skill_unavailable')) + } + return sampling + } + } +} diff --git a/apps/headless/src/skills/config-file.mjs b/apps/headless/src/skills/config-file.mjs new file mode 100644 index 00000000..808c5319 --- /dev/null +++ b/apps/headless/src/skills/config-file.mjs @@ -0,0 +1,58 @@ +import { constants, openSync, promises as fs } from 'node:fs' +import { MAX_SETTINGS_FILE_BYTES } from '../business/settings-file.mjs' +import { PATH, close, fdPath, mountId, stat } from '../files/workspace-files-fd.mjs' +import { skillError } from './errors.mjs' + +const readFlags = constants.O_RDONLY | constants.O_NONBLOCK +const fields = ['dev', 'ino', 'uid', 'gid', 'mode', 'nlink', 'size', 'ctimeNs', 'mtimeNs'] +export const sameConfig = (a, b) => a && b ? fields.every(field => a[field] === b[field]) : a === b + +function openPin(root) { + try { return openSync(fdPath(root.directory.fd, 'config.json'), PATH) } + catch (error) { if (error.code === 'ENOENT') return; throw error } +} + +function verify(root, pin) { + const info = stat(pin) + if (!info.isFile() || mountId(pin) !== root.mount || info.nlink !== 1n || info.uid !== root.info.uid || + (info.mode & 0o7133n) !== 0n || (info.mode & 0o400n) === 0n || info.size === 0n) throw skillError('skill_unsupported') + if (info.size > BigInt(MAX_SETTINGS_FILE_BYTES)) throw skillError('skill_limit') + return info +} + +/** Metadata-only observation for the watcher and final inode checks; no config payload is opened. */ +export function configurationInfo(root) { + const pin = openPin(root) + try { return pin === undefined ? null : verify(root, pin) } + finally { close(pin) } +} + +/** Hold the regular inode before opening it for an exact-byte read. */ +export async function readSkillConfiguration(root) { + const pin = openPin(root) + if (pin === undefined) return { info: null, bytes: null } + let file, bytes + try { + const info = verify(root, pin) + file = await fs.open(fdPath(pin), readFlags) + if (!sameConfig(info, stat(file.fd)) || mountId(file.fd) !== root.mount) throw skillError('skill_conflict') + const size = Number(info.size) + bytes = Buffer.alloc(size + 1) + let offset = 0 + while (offset < bytes.length) { + const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset) + if (!bytesRead) break + offset += bytesRead + } + if (offset !== size || !sameConfig(info, stat(file.fd)) || !sameConfig(info, configurationInfo(root))) { + throw skillError('skill_conflict') + } + return { info, bytes: bytes.subarray(0, size) } + } catch (error) { + bytes?.fill(0) + throw error + } finally { + try { await file?.close().catch(() => {}) } + finally { close(pin) } + } +} diff --git a/apps/headless/src/skills/config.mjs b/apps/headless/src/skills/config.mjs new file mode 100644 index 00000000..0269f087 --- /dev/null +++ b/apps/headless/src/skills/config.mjs @@ -0,0 +1,125 @@ +import { TextDecoder } from 'node:util' +import { MAX_SETTINGS_FILE_BYTES } from '../business/settings-file.mjs' +import { skillError } from './errors.mjs' +import { validRoleId } from './validation.mjs' + +const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) +const unsupported = () => skillError('skill_unsupported') +const whitespace = char => char === ' ' || char === '\t' || char === '\r' || char === '\n' +function skipWhitespace(text, i) { + while (whitespace(text[i])) i++ + return i +} + +// The text has already passed the bounded, fatal UTF-8 and strict JSON checks below. +// Find token boundaries without decoding or reserializing unrelated values. +function stringEnd(text, i) { + while (text[++i] !== '"') { if (text[i] === '\\') i++ } + return i + 1 +} + +function valueEnd(text, i) { + if (text[i] === '"') return stringEnd(text, i) + if (text[i] === '{' || text[i] === '[') { + let depth = 1 + while (depth) { + const char = text[++i] + if (char === '"') i = stringEnd(text, i) - 1 + else if (char === '{' || char === '[') depth++ + else if (char === '}' || char === ']') depth-- + } + return i + 1 + } + while (i < text.length && !whitespace(text[i]) && !',}]'.includes(text[i])) i++ + return i +} + +function objectSpans(text, start, select) { + if (text[start] !== '{') throw unsupported() + const members = new Map() + let i = skipWhitespace(text, start + 1), prevComma = null, appendAt = start + 1, count = 0 + while (text[i] !== '}') { + const keyStart = i + const keyEnd = stringEnd(text, i) + const key = JSON.parse(text.slice(keyStart, keyEnd)) + const startValue = skipWhitespace(text, skipWhitespace(text, keyEnd) + 1) + const endValue = valueEnd(text, startValue) + i = skipWhitespace(text, endValue) + const nextComma = text[i] === ',' ? i : null + if (select(key)) { + if (members.has(key)) throw unsupported() // Avoid editing through ambiguous native keys. + members.set(key, { keyStart, startValue, endValue, prevComma, nextComma }) + } + count++ + appendAt = endValue + if (nextComma !== null) i = skipWhitespace(text, nextComma + 1) + prevComma = nextComma + } + return { members, appendAt, count } +} + +export function parseSkillConfig(bytes, ids) { + let text, rootStart + try { + text = bytes ? decoder.decode(bytes) : '{}' + // Desktop's shared reader accepts the optional UTF-8 BOM. Keep it in the text + // so we never strip it from an otherwise valid original on a preference edit. + const first = text.charCodeAt(0) === 0xfeff ? 1 : 0 + JSON.parse(first ? text.slice(first) : text) + rootStart = skipWhitespace(text, first) + } catch { throw unsupported() } + + const root = objectSpans(text, rootStart, key => key === 'skills') + const section = root.members.get('skills') + const skills = section ? objectSpans(text, section.startValue, key => key === 'enabled' || key === 'roles') : null + const map = field => { + const span = skills?.members.get(field) + return span ? objectSpans(text, span.startValue, id => ids.has(id)) : null + } + return { text, root, skills, enabled: map('enabled'), roles: map('roles') } +} + +function storedValue(config, field, id) { + const span = config[field]?.members.get(id) + return span && JSON.parse(config.text.slice(span.startValue, span.endValue)) +} + +export function skillPreferences(config, id) { + const enabled = storedValue(config, 'enabled', id) !== false + const roles = storedValue(config, 'roles', id) + // Missing is all roles. Treat an invalid present scope as unsupported rather than + // silently widening it; preserve stale legacy IDs (including deleted roles) as saved. + if (roles !== undefined && (!Array.isArray(roles) || !roles.every(validRoleId))) throw unsupported() + return { enabled, roles: roles ?? null } +} + +function insert(text, object, key, encoded) { + const { appendAt, count } = object + return text.slice(0, appendAt) + (count ? ',' : '') + JSON.stringify(key) + ':' + encoded + text.slice(appendAt) +} + +function remove(text, { keyStart, endValue, prevComma, nextComma }) { + if (nextComma !== null) return text.slice(0, keyStart) + text.slice(endValue, nextComma) + text.slice(nextComma + 1) + if (prevComma !== null) return text.slice(0, prevComma) + text.slice(prevComma + 1, keyStart) + text.slice(endValue) + return text.slice(0, keyStart) + text.slice(endValue) +} + +export function encodeSkillPreference(config, id, { field, value }) { + const { text } = config + const object = config[field] + const span = object?.members.get(id) + let next + if (value === null) { + if (!span) return null + next = remove(text, span) + } else { + const encoded = JSON.stringify(value) + const entry = `{${JSON.stringify(id)}:${encoded}}` + if (span) next = text.slice(0, span.startValue) + encoded + text.slice(span.endValue) + else if (object) next = insert(text, object, id, encoded) + else if (config.skills) next = insert(text, config.skills, field, entry) + else next = insert(text, config.root, 'skills', `{${JSON.stringify(field)}:${entry}}`) + } + if (Buffer.byteLength(next) > MAX_SETTINGS_FILE_BYTES) throw skillError('skill_limit') + return Buffer.from(next) +} diff --git a/apps/headless/src/skills/documents-errors.mjs b/apps/headless/src/skills/documents-errors.mjs new file mode 100644 index 00000000..c07a922d --- /dev/null +++ b/apps/headless/src/skills/documents-errors.mjs @@ -0,0 +1,17 @@ +const statusByCode = Object.freeze({ + skill_invalid: 400, + skill_unsupported: 409, + skill_limit: 413, + skill_restricted: 422 +}) + +export class SkillDocumentError extends Error { + constructor(code) { + super(code) + this.name = 'SkillDocumentError' + this.code = code + this.status = this.statusCode = statusByCode[code] + } +} + +export function fail(code = 'skill_unsupported') { throw new SkillDocumentError(code) } diff --git a/apps/headless/src/skills/documents-format.mjs b/apps/headless/src/skills/documents-format.mjs new file mode 100644 index 00000000..7b14e0b9 --- /dev/null +++ b/apps/headless/src/skills/documents-format.mjs @@ -0,0 +1,99 @@ +import { TextDecoder } from 'node:util' +import { parseSkillDocument } from '../../dist/library-core.mjs' +import { fail } from './documents-errors.mjs' +import { isBuiltinAlias, isPrototypeName } from './documents-ids.mjs' + +export const MAX_HEADER_BYTES = 16 * 1024 +const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }) + +// Recognizable credential forms only, not a general secret scanner. Prose, paths, +// resource references, and placeholders stay literal; they are never dereferenced. +const obviousKeyMaterial = /-----BEGIN (?:(?:RSA|EC|DSA|OPENSSH|ENCRYPTED) )?PRIVATE KEY-----|\b(?:gh[pousr]_[A-Za-z0-9]{24,}|github_pat_[A-Za-z0-9_]{30,}|sk-(?:proj-|svcacct-|ant-api\d+-)?[A-Za-z0-9_-]{24,}|(?:AKIA|ASIA)[A-Z0-9]{16}|xox[baprs]-[A-Za-z0-9-]{16,}|(?:sk|rk)_live_[A-Za-z0-9]{16,})\b/u +const sensitiveKey = name => { + const words = name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[_.\-\s]+/) + return words.some(word => /^(?:auth|authorization|bearer|cookies?|credentials?|pass(?:word|phrase|wd)|secrets?|tokens?|apikey|accesskey|privatekey|clientsecret)$/.test(word)) || + /(?:^| )(?:api|access|private|signing|ssh) keys?(?: |$)/.test(words.join(' ')) +} + +function checkedText(bytes) { + let text + try { text = utf8.decode(bytes) } catch { fail() } + text = text.replace(/^\uFEFF/u, '').replace(/\r\n/g, '\n') + if (/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/u.test(text)) fail() + return text +} + +function inspectHeader(header, selected) { + const outer = new Set() + let inner = new Set() + for (const line of header.trimEnd().split('\n').slice(1, -1)) { + const entry = /^([ \t]*)(?:(['"])([A-Za-z0-9_.-]+)\2|([A-Za-z0-9_.-]+))[ \t]*:/u.exec(line) + if (!entry) continue + const name = entry[3] ?? entry[4] + if (isPrototypeName(name)) fail() + const seen = entry[1] ? inner : outer + const folded = name.toLowerCase() + if (seen.has(folded)) fail() + seen.add(folded) + if (!entry[1]) inner = new Set() + if (selected && sensitiveKey(name)) fail('skill_restricted') + } +} + +// The only byte-reading entry point for a catalog row. Read in small chunks and +// stop on the closing marker (or as soon as the first line is not an opener). +// The final read can overlap the body; only bytes up to the marker are decoded or +// parsed. Stamp callers never enter this module's read paths. +function readHeader(size, read) { + const bytes = Buffer.alloc(Math.min(size, MAX_HEADER_BYTES + 1)) + let used = 0, start = 0, opened = false + while (used < bytes.length) { + const n = Math.min(bytes.length - used, 512) + read(bytes, used, n, used) + used += n + while (start < used) { + const lf = bytes.indexOf(10, start) + const newline = lf !== -1 && lf < used + if (!newline && used < size) break + const end = newline ? lf + 1 : used + const marker = bytes.toString('utf8', start, end).trim() === '---' + if (start === 0) { + if (!marker) return '' + opened = true + } else if (marker) { + if (end > MAX_HEADER_BYTES) fail('skill_limit') + return checkedText(bytes.subarray(0, end)) + } + start = end + } + } + // A long first prose line is not a long metadata header. + if (!opened && !/^\s*(?:-{0,2}|---\s*)$/u.test(bytes.toString('utf8', 0, used))) return '' + if (!opened && size <= MAX_HEADER_BYTES) return '' + if (size > MAX_HEADER_BYTES) fail('skill_limit') + fail() // Opening delimiter without a closing delimiter. +} + +function checkedSummary({ name, description }) { + if (isBuiltinAlias(name)) fail() + if (obviousKeyMaterial.test(name) || obviousKeyMaterial.test(description)) fail('skill_restricted') + return { name, description } +} + +export function readSkillSummary(id, size, read) { + const header = readHeader(size, read) + inspectHeader(header, false) + return checkedSummary(parseSkillDocument(id, header)) +} + +export function readSkillDetail(id, size, read) { + const bytes = Buffer.alloc(size) + read(bytes, 0, size, 0) + const header = readHeader(size, (dst, offset, length, start) => bytes.copy(dst, offset, start, start + length)) + inspectHeader(header, true) + const raw = checkedText(bytes) + if (obviousKeyMaterial.test(raw)) fail('skill_restricted') + const parsed = parseSkillDocument(id, raw) + checkedSummary(parsed) + return parsed +} diff --git a/apps/headless/src/skills/documents-ids.mjs b/apps/headless/src/skills/documents-ids.mjs new file mode 100644 index 00000000..7d4ec8a0 --- /dev/null +++ b/apps/headless/src/skills/documents-ids.mjs @@ -0,0 +1,14 @@ +import { BUILTIN_SKILL_CATALOG } from '../../dist/library-core.mjs' + +const nativeId = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/u +const prototypeNames = new Set([...Object.getOwnPropertyNames(Object.prototype), 'prototype'].map(k => k.toLowerCase())) +const builtinIds = new Set(BUILTIN_SKILL_CATALOG.map(s => s.id)) + +export const isPrototypeName = name => prototypeNames.has(name.toLowerCase()) +export const isBuiltinAlias = name => builtinIds.has(name.normalize('NFKC').trim().toLowerCase() + .replace(/^\//u, '').replace(/[\s_.\p{Dash_Punctuation}]+/gu, '-')) + +export function isSkillId(id) { + return typeof id === 'string' && nativeId.exec(id)?.[0] === id && !id.endsWith('.') && !id.includes('..') && + !isPrototypeName(id) && (builtinIds.has(id) || !isBuiltinAlias(id)) +} diff --git a/apps/headless/src/skills/documents-native.mjs b/apps/headless/src/skills/documents-native.mjs new file mode 100644 index 00000000..2c28e40d --- /dev/null +++ b/apps/headless/src/skills/documents-native.mjs @@ -0,0 +1,220 @@ +import { createHash } from 'node:crypto' +import { accessSync, constants as C, openSync, opendirSync, readSync } from 'node:fs' +import { DIRECTORY, PATH, close, decodeUtf8, fdPath, mountId, stat } from '../files/workspace-files-fd.mjs' +import { fail, SkillDocumentError } from './documents-errors.mjs' +import { isBuiltinAlias, isSkillId } from './documents-ids.mjs' + +const MAX_ENTRIES = 512 +const MAX_SKILLS = 128 +const MAX_FILE_BYTES = 128 * 1024 +const MAX_TOTAL_BYTES = 4 * 1024 * 1024 +const SKILL_FILE = 'SKILL.md' +export const revision = parts => createHash('sha256').update(JSON.stringify(parts)).digest('hex') + +function at(fd, name, flags = PATH) { + try { return openSync(fdPath(fd, name), flags) } catch (error) { + if (error?.code !== 'ENOENT') throw error + return undefined + } +} + +function snapshot(fd) { + const info = stat(fd), mount = mountId(fd) + // Older Linux can substitute ctime for birthtime. Directory identities must + // survive ordinary sibling entry changes; file versions retain all file times. + const identity = [mount, info.dev, info.ino].join(':') + const permission = [info.uid, info.gid, info.mode].join(':') + const birthtime = info.isFile() ? info.birthtimeNs : '' + const version = [identity, permission, info.nlink, info.size, birthtime, info.ctimeNs, info.mtimeNs].join(':') + return { info, mount, identity, permission, version } +} + +function ownedDirectory(record, fd, uid, mount) { + const { info } = record + if (!info.isDirectory() || (mount !== undefined && record.mount !== mount) || info.uid !== uid || + (info.mode & 0o7022n) !== 0n || (info.mode & 0o500n) !== 0o500n) fail() + accessSync(fdPath(fd), C.R_OK | C.X_OK) +} + +function ownedDocument(record, fd, uid, mount) { + const { info } = record + if (!info.isFile() || record.mount !== mount || info.uid !== uid || info.nlink !== 1n || + (info.mode & 0o7133n) !== 0n || (info.mode & 0o400n) === 0n) fail() + accessSync(fdPath(fd), C.R_OK) + if (info.size > BigInt(MAX_FILE_BYTES)) fail('skill_limit') +} + +function assertEntry(parent, name, expected, compare) { + const fd = at(parent, name) + try { + if (fd === undefined) { if (expected) fail(); return } + if (!expected) fail() + const current = snapshot(fd) + if (current[compare] !== expected[compare] || current.permission !== expected.permission) fail() + } finally { close(fd) } +} + +function assertChain(chain) { + for (const { parent, name, fd, record } of chain) { + const held = snapshot(fd) + // Changes to unrelated siblings above the data root are immaterial, but the + // pathname binding and permissions of every traversed ancestor must stay put. + if (held.identity !== record.identity || held.permission !== record.permission) fail() + if (parent !== undefined) assertEntry(parent, name, record, 'identity') + } +} + +function withDataRoot(parts, task) { + const chain = [] + let fd = openSync('/', DIRECTORY) + try { + chain.push({ fd }) + chain[0].record = snapshot(fd) + for (const name of parts) { + const parent = fd + fd = at(parent, name, DIRECTORY) + if (fd === undefined) fail() + const step = { parent, name, fd } + chain.push(step) + step.record = snapshot(fd) + } + const root = chain.at(-1).record, uid = BigInt(process.geteuid()) + ownedDirectory(root, fd, uid) + assertChain(chain) + task({ fd, root, uid }) + assertChain(chain) + } finally { + for (let i = chain.length - 1; i >= 0; i--) close(chain[i].fd) + } +} + +function namesIn(skills) { + const dir = opendirSync(fdPath(skills, '.'), { encoding: 'buffer', bufferSize: 32 }) + const names = new Set(), folded = new Set() + let scanned = 0 + try { + for (let entry; (entry = dir.readSync()) !== null;) { + if (++scanned > MAX_ENTRIES) fail('skill_limit') + if (entry.name[0] === 46) continue // Hidden native entries are outside the catalog. + if (entry.isSymbolicLink()) fail() + if (!entry.isDirectory()) continue // Foreign files still count against the scan bound. + const name = decodeUtf8(entry.name) + const lower = name.toLowerCase() + if (!isSkillId(name) || isBuiltinAlias(name) || folded.has(lower)) fail() + names.add(name) + folded.add(lower) + } + } finally { dir.closeSync() } + return names +} + +function reader(file, expected, use) { + // Reopen only the held, checked inode, never an untrusted pathname. In particular, + // stat-only callers never open a document for reading (or invoke a device handler). + const fd = openSync(fdPath(file), C.O_RDONLY | C.O_NONBLOCK) + try { + if (snapshot(fd).version !== expected.version) fail() + const result = use(Number(expected.info.size), (bytes, offset, length, pos) => { + let done = 0 + while (done < length) { + const n = readSync(fd, bytes, offset + done, length - done, pos + done) + if (n === 0) fail() + done += n + } + }) + if (snapshot(fd).version !== expected.version) fail() + return result + } finally { close(fd) } +} + +function inspect(skills, scope, id, visit) { + const dir = at(skills, id, DIRECTORY) + if (dir === undefined) fail() + let file + try { + const directory = snapshot(dir) + ownedDirectory(directory, dir, scope.uid, scope.root.mount) + file = at(dir, SKILL_FILE) + if (file === undefined) return { id, directory, document: null } + const document = snapshot(file) + ownedDocument(document, file, scope.uid, scope.root.mount) + const documentRevision = revision(['deva-skill-document-v1', id, scope.root.identity, + scope.skillsRoot.identity, directory.identity, document.version]) + visit(id, documentRevision, Number(document.info.size), use => reader(file, document, use)) + if (snapshot(file).version !== document.version) fail() + return { id, directory, document } + } finally { close(file); close(dir) } +} + +function assertInspected(skills, { id, directory, document }) { + const dir = at(skills, id, DIRECTORY) + if (dir === undefined) fail() + try { + if (snapshot(dir).version !== directory.version) fail() + assertEntry(dir, SKILL_FILE, document, 'version') + if (snapshot(dir).version !== directory.version) fail() + } finally { close(dir) } +} + +function inspectSkills(scope, selected, visit) { + const skills = at(scope.fd, 'skills', DIRECTORY) + try { + if (skills === undefined) { + assertEntry(scope.fd, 'skills', null, 'version') + return + } + scope.skillsRoot = snapshot(skills) + ownedDirectory(scope.skillsRoot, skills, scope.uid, scope.root.mount) + const names = namesIn(skills) + const inspected = [] + let count = 0, total = 0 + for (const id of selected === undefined ? names : names.has(selected) ? [selected] : []) { + inspected.push(inspect(skills, scope, id, (id, rev, bytes, read) => { + total += bytes + if (++count > MAX_SKILLS || total > MAX_TOTAL_BYTES) fail('skill_limit') + visit(id, rev, read) + })) + } + for (const entry of inspected) assertInspected(skills, entry) + assertEntry(scope.fd, 'skills', scope.skillsRoot, 'version') + } finally { close(skills) } +} + +/** Hold one canonical data-root inode after the first successful native access. */ +export function nativeSkillDocuments(parts) { + let rootPin, closed = false + function assertOpen() { if (closed) fail() } + function inspect(selected, visit) { + assertOpen() + let candidate + try { + if (process.platform !== 'linux' || typeof process.geteuid !== 'function') fail() + withDataRoot(parts, scope => { + if (rootPin !== undefined && snapshot(rootPin).identity !== scope.root.identity) fail() + inspectSkills(scope, selected, visit) + if (rootPin === undefined) { + candidate = openSync(fdPath(scope.fd, '.'), DIRECTORY) + if (snapshot(candidate).identity !== scope.root.identity) fail() + } + }) + if (candidate !== undefined) { + rootPin = candidate + candidate = undefined + } + } catch (error) { + if (error instanceof SkillDocumentError) throw error + fail() // Kernel paths and raw filesystem error text never reach callers. + } finally { close(candidate) } + } + return { + assertOpen, + inspect, + close() { + if (closed) return + closed = true + const fd = rootPin + rootPin = undefined + close(fd) + } + } +} diff --git a/apps/headless/src/skills/documents.mjs b/apps/headless/src/skills/documents.mjs new file mode 100644 index 00000000..82f7e247 --- /dev/null +++ b/apps/headless/src/skills/documents.mjs @@ -0,0 +1,59 @@ +import { isAbsolute, resolve } from 'node:path' +import { BUILTIN_SKILL_CATALOG } from '../../dist/library-core.mjs' +import { fail } from './documents-errors.mjs' +import { readSkillDetail, readSkillSummary } from './documents-format.mjs' +import { isSkillId } from './documents-ids.mjs' +import { nativeSkillDocuments, revision } from './documents-native.mjs' + +const byId = (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0 +const builtin = BUILTIN_SKILL_CATALOG.map(summary => Object.freeze({ + ...summary, + documentRevision: revision(['deva-builtin-skill-summary-v1', summary.id, summary.name, summary.description, summary.source]) +})) +const builtinById = new Map(builtin.map(item => [item.id, item])) +const asStamp = ({ id, documentRevision }) => ({ id, documentRevision }) + +/** Owner-only native document projection. The synchronous factory performs no filesystem IO. */ +export function openSkillDocuments({ dataDir } = {}) { + if (typeof dataDir !== 'string' || !dataDir.isWellFormed() || dataDir.includes('\0') || !isAbsolute(dataDir) || + dataDir === '/' || Buffer.byteLength(dataDir) > 4095 || resolve(dataDir) !== dataDir) fail('skill_invalid') + const { inspect, assertOpen, close } = nativeSkillDocuments(dataDir.slice(1).split('/')) + return Object.freeze({ + list() { + const custom = [] + inspect(undefined, (id, documentRevision, read) => { + const { name, description } = read((size, bytes) => readSkillSummary(id, size, bytes)) + custom.push({ id, name, description, source: 'custom', documentRevision }) + }) + custom.sort((a, b) => a.name.localeCompare(b.name) || byId(a, b)) + return [...builtin.map(item => ({ ...item })), ...custom] + }, + get(id) { + assertOpen() + if (!isSkillId(id)) fail('skill_invalid') + const item = builtinById.get(id) + if (item) return { ...item, detail: 'builtin' } + let document = null + inspect(id, (id, documentRevision, read) => { + const fields = read((size, bytes) => readSkillDetail(id, size, bytes)) + document = { ...fields, source: 'custom', documentRevision, detail: 'document' } + }) + return document + }, + stamps() { + const rows = builtin.map(asStamp) + inspect(undefined, (id, documentRevision) => rows.push({ id, documentRevision })) + return rows.sort(byId) + }, + stamp(id) { + assertOpen() + if (!isSkillId(id)) fail('skill_invalid') + const item = builtinById.get(id) + if (item) return item.documentRevision + let current = null + inspect(id, (_id, revision) => { current = revision }) + return current + }, + close + }) +} diff --git a/apps/headless/src/skills/errors.mjs b/apps/headless/src/skills/errors.mjs new file mode 100644 index 00000000..af0ee57f --- /dev/null +++ b/apps/headless/src/skills/errors.mjs @@ -0,0 +1,35 @@ +import { HttpError } from '../http/policy.mjs' + +const status = Object.freeze({ + auth: 401, + skill_invalid: 400, + skill_not_found: 404, + skill_builtin: 409, + skill_conflict: 409, + skill_unknown_role: 409, + skill_unsupported: 409, + skill_limit: 413, + skill_read_only: 403, + skill_restricted: 422, + skill_storage_unconfirmed: 503 +}) + +export const skillError = (code = 'skill_storage_unconfirmed') => new HttpError(status[code], code) + +// Never forward native paths, untrusted error messages, or parse results to this API. +export function publicSkillError(error) { + const code = error?.code + if (Object.hasOwn(status, code) && status[code] === error?.status) return skillError(code) + switch (code) { + case 'ERR_PERSONA_LIMIT': return skillError('skill_limit') + case 'ERR_SETTINGS_CORRUPT': + case 'ERR_PERSONA_CORRUPT': return skillError('skill_unsupported') + case 'ERR_SETTINGS_CONFLICT': + case 'ERR_PERSONA_CONFLICT': return skillError('skill_conflict') + case 'ERR_SETTINGS_READ_ONLY': + case 'EACCES': + case 'EPERM': + case 'EROFS': return skillError('skill_read_only') + default: return skillError() + } +} diff --git a/apps/headless/src/skills/routes.mjs b/apps/headless/src/skills/routes.mjs new file mode 100644 index 00000000..e7a59e56 --- /dev/null +++ b/apps/headless/src/skills/routes.mjs @@ -0,0 +1,77 @@ +import { HttpError, json, readJson } from '../http/policy.mjs' +import { openSkillChanges } from './changes.mjs' + +const base='/api/v1/skills' +const item=/^\/api\/v1\/skills\/([A-Za-z0-9][A-Za-z0-9_.-]{0,63})(\/preferences)?$/u +const errors = new Map([ + ['auth',401],['origin',403],['method',405],['unexpected_query',400],['invalid_json',400],['too_large',413],['json_required',415], + ['skill_invalid',400],['skill_not_found',404],['skill_conflict',409],['skill_unknown_role',409],['skill_unsupported',409], + ['skill_builtin',409],['skill_limit',413],['skill_restricted',422],['skill_read_only',403],['skill_busy',429], + ['skill_unavailable',503],['skill_storage_unconfirmed',503] +]) +const tag = value => typeof value==='string' && value.length===64 && !/[^0-9a-f]/u.test(value) + +/** Read-only catalog plus two typed persistence operations; neither reads auxiliary resources, + * invokes a skill nor grants tool access. Changes carry only an opaque catalog revision. */ +export function skillLibraryRoutes({store,auth,documents}) { + const changes=openSkillChanges({revision:()=>store.revision(),auth}) + const active = new Set(), lifetime=new AbortController() + let closing=false,drain + async function serve(req,res,policy,path,op,id) { + const method=op==='set'?'PATCH':op==='changes'?'POST':'GET' + const cancel=new AbortController(),signal=AbortSignal.any([cancel.signal,lifetime.signal]) + const disconnected=()=>{if(!res.writableFinished)cancel.abort()} + res.once('close',disconnected) + try { + policy.check(req,req.method!=='GET' && req.method!=='HEAD') + if(req.url!==path)throw new HttpError(400,'unexpected_query') + if(req.method!==method){json(res,405,{error:'method'},{allow:method});return} + const cookie=policy.cookie(req);let actor + const verify=()=>{ + if(signal.aborted||closing||res.destroyed)throw new HttpError(503,'skill_unavailable') + const current=method==='GET'?auth.identify(cookie):auth.identify(cookie,req.headers['x-deva-csrf']) + if(!current || current.role!=='owner' || (actor && (current.ownerId!==actor.ownerId || current.loginSessionId!==actor.loginSessionId)))throw new HttpError(401,'auth') + actor??=current;return actor + } + verify();let result + if(op==='list')result=await store.list() + else if(op==='get')result=await store.get(id) + else if(op==='roles')result=await store.roles() + else { + const body=await readJson(req,op==='changes'?512:8192);verify() + if(op==='changes')result=await changes.wait(actor,body,verify,signal) + else { + const on=Object.hasOwn(body,'enabled'),scoped=Object.hasOwn(body,'roles') + if(Object.keys(body).length!==2 || !Object.hasOwn(body,'revision') || !tag(body.revision) || on===scoped || + (on && typeof body.enabled!=='boolean') || (scoped && body.roles!==null && !Array.isArray(body.roles)))throw new HttpError(400,'skill_invalid') + result=await store.set(id,body,verify) + // A no-op retains the same revision: waking an existing waiter just rechecks its cursor. + changes.wake() + } + } + verify();json(res,200,result) + } catch (error) { + const code=error?.code==='AUTH_FAILED'?'auth':errors.has(error?.code)?error.code:'skill_storage_unconfirmed' + if(!res.destroyed && !res.headersSent)json(res,errors.get(code),{error:code},method==='GET'?{}:{connection:'close'}) + } finally {res.off('close',disconnected)} + } + return Object.freeze({ + async handle(req,res,{policy}) { + const path=(req.url??'').split('?',1)[0], match=item.exec(path) + const op=path===base?'list':path===base+'/-/roles'?'roles':path===base+'/-/changes'?'changes':match?(match[2]?'set':'get'):null + if(!op)return false + if(closing || active.size>=32){json(res,closing?503:429,{error:closing?'skill_unavailable':'skill_busy'},{connection:'close'});return true} + const job=serve(req,res,policy,path,op,match?.[1]);active.add(job) + try{await job}finally{active.delete(job)}return true + }, + close(){ + if (!drain) { + closing=true; lifetime.abort() + drain=Promise.allSettled([changes.close(),...active]).then(async()=>{ + try { await store.close?.() } finally { documents?.close() } + }) + } + return drain + } + }) +} diff --git a/apps/headless/src/skills/store.mjs b/apps/headless/src/skills/store.mjs new file mode 100644 index 00000000..03ce6c67 --- /dev/null +++ b/apps/headless/src/skills/store.mjs @@ -0,0 +1,263 @@ +import { createHash } from 'node:crypto' +import { isAbsolute, resolve } from 'node:path' +import { assertWritable, publishSettingsFile, revisionFor, withSettingsDirectory } from '../business/settings-file.mjs' +import { close, mountId, openAbsoluteDirectory, stat } from '../files/workspace-files-fd.mjs' +import { configurationInfo, readSkillConfiguration, sameConfig } from './config-file.mjs' +import { encodeSkillPreference, parseSkillConfig, skillPreferences } from './config.mjs' +import { publicSkillError, skillError } from './errors.mjs' +import { assertSkillId, assertSkillOwner, skillPreferenceEdit, validRoleId } from './validation.mjs' + +const execution = 'inactive' +const conflict = () => skillError('skill_conflict') +const hash = parts => createHash('sha256').update(JSON.stringify(parts)).digest('hex') +const rootId = info => [info.dev, info.ino].join(':') +const accessMode = info => [info.uid, info.gid, info.mode].join(':') +const configRevision = (root, config) => revisionFor(`${root.id}:${root.access}`, config.info) + +function stampsOf(rows) { + const stamps = rows.map(({ id, documentRevision }) => [id, documentRevision]) + return stamps.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0) +} + +const catalogRevision = (root, config, stamps) => hash(['deva-skill-catalog-v1', configRevision(root, config), stamps]) +const noPreferences = Object.freeze({ enabled: true, roles: null }) + +function canWrite(root, config) { + // The legacy desktop writer often produces 0644. Preserve safe owner modes, rather + // than replacing an imported file with different access permissions as a side effect. + return (root.info.mode & 0o700n) === 0o700n && (!config.info || + ((config.info.mode & 0o7133n) === 0n && (config.info.mode & 0o600n) === 0o600n)) +} + +function summary(raw, root, snapshot, preferences) { + const { id, name, description, source, documentRevision } = raw + const custom = source === 'custom' + const revision = hash(['deva-skill-preferences-v1', id, source, documentRevision, + custom ? configRevision(root, snapshot) : null]) + return { id, name, description, source, ...preferences, revision, canConfigure: custom && canWrite(root, snapshot) } +} + +function detail(raw, projection) { + if (raw.source === 'builtin') return { ...projection, detail: 'builtin' } + const { instructions, trigger, license, compatibility, allowedTools, metadata } = raw + return { ...projection, detail: 'document', instructions, trigger, license, compatibility, + allowedTools: [...allowedTools], metadata: { ...metadata } } +} + +function roleChoices(choices) { + const ids = new Set() + return choices.map(({ id, name, enabled }) => { + if (!validRoleId(id) || ids.has(id) || typeof name !== 'string' || typeof enabled !== 'boolean') throw skillError() + ids.add(id) + return { id, name, enabled } + }) +} + +function verifyRoleRoster(verify) { + const result = verify?.() + if (result === false) throw conflict() + if (result && typeof result.then === 'function') { + Promise.resolve(result).catch(() => {}) + throw skillError() + } +} + +function unchanged(preferences, { field, value }) { + const before = preferences[field] + return before === value || (Array.isArray(before) && Array.isArray(value) && + before.length === value.length && before.every((id, i) => id === value[i])) +} + +/** Human-owned control plane for saved native skill preferences; no execution state. */ +export function openSkillLibrary(options = {}) { + if (!options || typeof options !== 'object') throw skillError('skill_invalid') + const { dataDir, documents, withRoleChoices } = options + if (typeof dataDir !== 'string' || !dataDir.isWellFormed() || !isAbsolute(dataDir) || dataDir.includes('\0') || + dataDir === '/' || Buffer.byteLength(dataDir) > 4095 || resolve(dataDir) !== dataDir || + !documents || !['list', 'get', 'stamps', 'stamp'].every(method => typeof documents[method] === 'function') || + typeof withRoleChoices !== 'function') throw skillError('skill_invalid') + const path = dataDir + let pinnedRoot, closed = false + + function verifyRoot(root) { + if (closed) throw skillError() + let live + try { + live = openAbsoluteDirectory(path) + const info = stat(live) + if (root.id !== rootId(info) || root.mount !== mountId(live) || root.access !== accessMode(info) || + (pinnedRoot !== undefined && (root.id !== rootId(stat(pinnedRoot)) || root.mount !== mountId(pinnedRoot)))) throw conflict() + if (pinnedRoot === undefined) { + // Keep the first inode alive so an external replacement cannot recycle it. + // Directory ctime (and synthesized birthtime) can change on any sibling edit. + pinnedRoot = live + live = undefined + } + } finally { close(live) } + } + + async function access(operation, metadataOnly = false) { + try { + if (closed) throw skillError() + const result = await withSettingsDirectory(path, null, async directory => { + let snapshot + try { + const info = stat(directory.fd) + if ((info.mode & 0o500n) !== 0o500n) throw skillError('skill_unsupported') + const root = { directory, info, id: rootId(info), access: accessMode(info), mount: mountId(directory.fd) } + verifyRoot(root) + snapshot = metadataOnly ? { info: configurationInfo(root) } : await readSkillConfiguration(root) + return { value: await operation(root, snapshot) } + } catch (error) { + // Keep the shared queue's existing SettingsError behavior for other clients. + return { error: publicSkillError(error) } + } finally { snapshot?.bytes?.fill(0) } + }, { create: false }) + if (result.error) throw result.error + return result.value + } catch (error) { throw publicSkillError(error) } + } + + function verifySnapshot(root, snapshot) { + verifyRoot(root) + if (!sameConfig(snapshot.info, configurationInfo(root))) throw conflict() + } + + async function verifyDocument(raw) { + if (await documents.stamp(raw.id) !== raw.documentRevision) throw conflict() + } + + async function publish(root, snapshot, raw, bytes, checkOwner, verifyChoices) { + await assertWritable(root.directory, snapshot.info) + const committed = await publishSettingsFile(root.directory, bytes, snapshot.info, { + preserveAccess: true, + async beforePublish() { + checkOwner() + await verifyDocument(raw) + }, + authorize() { + verifySnapshot(root, snapshot) + verifyRoleRoster(verifyChoices) + checkOwner() + } + }) + let observed + try { + observed = await readSkillConfiguration(root) + await verifyDocument(raw) + verifySnapshot(root, observed) + const { info } = observed + if (!committed.durable || !info || !sameConfig(committed.info, info) || !observed.bytes.equals(bytes) || + (snapshot.info && accessMode(info) !== accessMode(snapshot.info)) || !canWrite(root, observed)) throw skillError() + return info + } catch { + // Publication may be visible: never acknowledge an unconfirmed save or roll back + // over an external writer. The volume lock covers cooperating Workbench writers; + // filesystem rename itself has no compare-and-swap precondition. + throw skillError() + } finally { observed?.bytes?.fill(0) } + } + + function setPreference(id, edit, checkOwner, choices, verifyChoices) { + return access(async (root, snapshot) => { + // Loading a detail is unnecessary for a preference edit; read only summaries. + const raw = (await documents.list()).find(row => row.id === id) + if (!raw) throw skillError('skill_not_found') + if (raw.source === 'builtin') throw skillError('skill_builtin') + const config = parseSkillConfig(snapshot.bytes, new Set([id])) + const current = skillPreferences(config, id) + const skill = summary(raw, root, snapshot, current) + if (edit.revision !== skill.revision) throw conflict() + if (edit.field === 'roles' && edit.value?.length) { + const known = new Set(roleChoices(choices).map(role => role.id)) + // Historical IDs can be retained verbatim from this exact CAS snapshot. + // A newly added ID must always be present in the authoritative roster. + const saved = new Set(current.roles ?? []) + if (edit.value.some(role => !known.has(role) && !saved.has(role))) throw skillError('skill_unknown_role') + } + if (unchanged(current, edit)) { + checkOwner() + await verifyDocument(raw) + verifySnapshot(root, snapshot) + verifyRoleRoster(verifyChoices) + checkOwner() + return { skill, execution } + } + if (!skill.canConfigure) throw skillError('skill_read_only') + const bytes = encodeSkillPreference(config, id, edit) + try { + const info = await publish(root, snapshot, raw, bytes, checkOwner, verifyChoices) + checkOwner() + try { verifyRoleRoster(verifyChoices) } catch { throw skillError() } + const preferences = { ...current, [edit.field]: edit.value } + return { skill: summary(raw, root, { info }, preferences), execution } + } finally { bytes.fill(0) } + }) + } + + return Object.freeze({ + async list() { + return access(async (root, snapshot) => { + const records = await documents.list() + const config = parseSkillConfig(snapshot.bytes, new Set(records.filter(row => row.source === 'custom').map(row => row.id))) + const skills = records.map(raw => summary(raw, root, snapshot, + raw.source === 'builtin' ? noPreferences : skillPreferences(config, raw.id))) + const stamps = stampsOf(records) + if (JSON.stringify(stamps) !== JSON.stringify(stampsOf(await documents.stamps()))) throw conflict() + verifySnapshot(root, snapshot) + return { skills, revision: catalogRevision(root, snapshot, stamps), execution } + }) + }, + async get(id) { + assertSkillId(id) + return access(async (root, snapshot) => { + const raw = await documents.get(id) + let skill = null + if (raw) { + const preferences = raw.source === 'builtin' ? noPreferences : + skillPreferences(parseSkillConfig(snapshot.bytes, new Set([id])), id) + skill = detail(raw, summary(raw, root, snapshot, preferences)) + } + if (await documents.stamp(id) !== (raw?.documentRevision ?? null)) throw conflict() + verifySnapshot(root, snapshot) + return { skill, execution } + }) + }, + async roles() { + try { + if (closed) throw skillError() + return await withRoleChoices(async (choices, verify) => { + const roles = roleChoices(choices) + verifyRoleRoster(verify) + return { roles } + }) + } catch (error) { throw publicSkillError(error) } + }, + async set(id, input, verifyOwner) { + assertSkillId(id) + const edit = skillPreferenceEdit(input) + const checkOwner = () => assertSkillOwner(verifyOwner, id) + checkOwner() + try { + // The roster gate must be outermost: its own roster read uses the same + // settings directory queue as this preference write. + if (edit.field === 'roles') return await withRoleChoices((choices, verify) => setPreference(id, edit, checkOwner, choices, verify)) + return await setPreference(id, edit, checkOwner) + } catch (error) { throw publicSkillError(error) } + }, + async revision() { + return access(async (root, snapshot) => { + const stamps = stampsOf(await documents.stamps()) + verifySnapshot(root, snapshot) + return catalogRevision(root, snapshot, stamps) + }, true) + }, + close() { + if (closed) return + closed = true + const fd = pinnedRoot + pinnedRoot = undefined + close(fd) + } + }) +} diff --git a/apps/headless/src/skills/validation.mjs b/apps/headless/src/skills/validation.mjs new file mode 100644 index 00000000..eb0e9af9 --- /dev/null +++ b/apps/headless/src/skills/validation.mjs @@ -0,0 +1,53 @@ +import { isSkillId } from './documents-ids.mjs' +import { skillError } from './errors.mjs' +const own = Object.hasOwn +const invalid = () => skillError('skill_invalid') + +export function assertSkillId(id) { + if (!isSkillId(id)) throw invalid() +} + +// Role IDs are opaque, and the authoritative roster—not the preference file—defines membership. +export const validRoleId = id => typeof id === 'string' && id.length > 0 && id.length <= 256 && + id === id.trim() && id.isWellFormed() && !/[\u0000-\u001f\u007f]/u.test(id) + +export function skillPreferenceEdit(input) { + if (input === null || typeof input !== 'object' || ![Object.prototype, null].includes(Object.getPrototypeOf(input))) throw invalid() + const fields = Reflect.ownKeys(input) + if (fields.length !== 2 || !fields.includes('revision') || (!fields.includes('enabled') && !fields.includes('roles'))) throw invalid() + for (const key of fields) { + const descriptor = Object.getOwnPropertyDescriptor(input, key) + if (!descriptor?.enumerable || !own(descriptor, 'value')) throw invalid() + } + const { revision } = input + if (typeof revision !== 'string' || revision.length !== 64 || !/^[a-f0-9]{64}$/.test(revision)) throw invalid() + if (own(input, 'enabled')) { + if (typeof input.enabled !== 'boolean') throw invalid() + return { revision, field: 'enabled', value: input.enabled } + } + const roles = input.roles + if (roles === null) return { revision, field: 'roles', value: null } + if (!Array.isArray(roles) || Object.getPrototypeOf(roles) !== Array.prototype) throw invalid() + if (roles.length > 64) throw skillError('skill_limit') + if (Reflect.ownKeys(roles).length !== roles.length + 1) throw invalid() + const result = new Set() + for (let i = 0; i < roles.length; i++) { + const property = Object.getOwnPropertyDescriptor(roles, String(i)) + if (!property?.enumerable || !own(property, 'value') || !validRoleId(property.value) || result.has(property.value)) throw invalid() + result.add(property.value) + } + return { revision, field: 'roles', value: [...result] } +} + +export function assertSkillOwner(verifyOwner, id) { + if (typeof verifyOwner !== 'function') throw skillError('auth') + try { + const result = verifyOwner(id) + if (result && typeof result.then === 'function') { + Promise.resolve(result).catch(() => {}) + throw skillError('auth') + } + // Support assertion-style callbacks (undefined after a successful recheck). + if (result === false) throw skillError('auth') + } catch { throw skillError('auth') } +} diff --git a/apps/headless/test/skill-changes.test.mjs b/apps/headless/test/skill-changes.test.mjs new file mode 100644 index 00000000..32907307 --- /dev/null +++ b/apps/headless/test/skill-changes.test.mjs @@ -0,0 +1,43 @@ +import assert from 'node:assert/strict' +import {setImmediate as tick, setTimeout as delay} from 'node:timers/promises' +import test from 'node:test' +import {openSkillChanges} from '../src/skills/changes.mjs' + +const a='a'.repeat(64), b='b'.repeat(64), id={role:'owner',ownerId:'owner',loginSessionId:'A'}, other={...id,loginSessionId:'B'} +const noDeep=()=>true +function fixture(extra={}) { + const listeners=new Set(), active=new Set(['A','B']);let tag=a,samples=0 + const watch=openSkillChanges({auth:{isLoginActive:x=>active.has(x.loginSessionId), onSessionRevoked(fn){listeners.add(fn);return()=>listeners.delete(fn)}}, + revision:async()=>{samples++;return tag},intervalMs:80,readBudgetMs:1000,...extra}) + return {watch,set(value){tag=value},get samples(){return samples},revoke(key){active.delete(key);for(const cb of listeners)cb(key)},listeners} +} + +test('only an open owner poll samples metadata; concurrent views share one probe and one opaque change',async t=>{ + const f=fixture();t.after(()=>f.watch.close());assert.equal(f.samples,0) + const p=f.watch.wait(id,{after:a,waitMs:4000},noDeep);const q=f.watch.wait(other,{after:a,waitMs:4000},noDeep) + await tick();assert.equal(f.samples,1);f.set(b);f.watch.wake() + assert.deepEqual(await Promise.all([p,q]),[{changed:true,revision:b},{changed:true,revision:b}]);assert.equal(f.samples,2) + await delay(110);assert.equal(f.samples,2,'no idle core watcher or file poll after departure') + assert.deepEqual(await f.watch.wait(id,{after:b,waitMs:0},noDeep),{changed:false,revision:b}) +}) + +test('external metadata changes, disconnect, cap, and owner revocation are separate outcomes',async t=>{ + const f=fixture({intervalMs:22});t.after(()=>f.watch.close());const abort=new AbortController() + const external=f.watch.wait(other,{after:a,waitMs:600},noDeep);await tick();f.set(b) + assert.deepEqual(await external,{changed:true,revision:b}) + const p=assert.rejects(f.watch.wait(id,{after:b,waitMs:4000},noDeep,abort.signal),{code:'skill_unavailable'}); + const q=assert.rejects(f.watch.wait(id,{after:b,waitMs:4000},noDeep),{code:'auth'}); + await assert.rejects(f.watch.wait(id,{after:b,waitMs:4000},noDeep),{code:'skill_busy'});abort.abort();f.revoke('A');await Promise.all([p,q]); + await assert.rejects(f.watch.wait(id,{after:b,waitMs:0},noDeep),{code:'auth'}) + for(const wrong of [{after:b,waitMs:8001},{after:b,waitMs:-1},{after:b,waitMs:0,path:'/invalid'},{after:b+'\n',waitMs:0}]){ + await assert.rejects(f.watch.wait(other,wrong,noDeep),{code:'skill_invalid'}) + } + const stop=assert.rejects(f.watch.wait(other,{after:b,waitMs:4000},noDeep),{code:'skill_unavailable'});f.watch.close();await stop;assert.equal(f.listeners.size,0) +}) + +test('late metadata from a blocked read is never delivered to a revoked or already closed client',async()=>{ + const deferred=Promise.withResolvers(),f=fixture({revision:()=>deferred.promise}) + const revoked=assert.rejects(f.watch.wait(id,{after:a,waitMs:1000},noDeep),{code:'auth'}) + const closed=assert.rejects(f.watch.wait(other,{after:a,waitMs:1000},noDeep),{code:'skill_unavailable'}) + await tick();f.revoke('A');f.watch.close();await Promise.all([revoked,closed]);deferred.resolve(b);await tick();assert.equal(f.listeners.size,0) +}) diff --git a/apps/headless/test/skill-documents.test.mjs b/apps/headless/test/skill-documents.test.mjs new file mode 100644 index 00000000..735334ba --- /dev/null +++ b/apps/headless/test/skill-documents.test.mjs @@ -0,0 +1,346 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import { syncBuiltinESMExports } from 'node:module' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { BUILTIN_SKILL_CATALOG } from '../dist/library-core.mjs' +import { openSkillDocuments } from '../src/skills/documents.mjs' + +const protectedIds = ['create-skill', 'create-agent', 'create-mcp'] +const statuses = { skill_invalid: 400, skill_unsupported: 409, skill_limit: 413, skill_restricted: 422 } +const revision = /^[a-f0-9]{64}$/ +const skillMd = (name, body = 'Prose.') => `---\nname: ${name}\ndescription: Display summary\n---\n\n${body}\n` + +function sandbox(t) { + const dir = fs.mkdtempSync(join(tmpdir(), 'deva-skill-documents-')) + const dataDir = join(dir, 'data'), skillsDir = join(dataDir, 'skills') + const documents = openSkillDocuments({ dataDir }) // Roots are deliberately absent at construction. + t.after(() => { + documents.close() + fs.rmSync(dir, { recursive: true, force: true }) + }) + fs.mkdirSync(dataDir, { mode: 0o700 }) + function folder(id) { + const path = join(skillsDir, id) + fs.mkdirSync(path, { mode: 0o700, recursive: true }) + return path + } + function put(id, value) { + const path = join(folder(id), 'SKILL.md') + fs.writeFileSync(path, value, { mode: 0o600 }) + return path + } + return { dir, dataDir, skillsDir, documents, folder, put } +} + +function fails(code, action) { + assert.throws(action, { name: 'SkillDocumentError', code, message: code, status: statuses[code], statusCode: statuses[code] }) +} + +function watchDocumentReads(path, task, onRead) { + const old = fs.readSync, info = fs.statSync(path, { bigint: true }) + let read = 0 + fs.readSync = function (fd, ...args) { + const n = old.call(this, fd, ...args) + const current = fs.fstatSync(fd, { bigint: true }) + if (current.dev === info.dev && current.ino === info.ino) { + read += n + onRead?.(read) + } + return n + } + syncBuiltinESMExports() + try { return task(() => read) } finally { fs.readSync = old; syncBuiltinESMExports() } +} + +test('native builtin rows are immutable display metadata and load with absent custom storage', t => { + const { documents, folder } = sandbox(t) + const rows = documents.list() + assert.deepEqual(rows.map(item => item.id), protectedIds) + assert.deepEqual(rows.map(({ documentRevision, ...summary }) => summary), BUILTIN_SKILL_CATALOG) + assert(BUILTIN_SKILL_CATALOG.every(Object.isFrozen)) + for (const row of rows) { + assert.match(row.documentRevision, revision) + assert.deepEqual(documents.get(row.id), { ...row, detail: 'builtin' }) + assert.equal(documents.stamp(row.id), row.documentRevision) + } + assert.deepEqual(documents.stamps(), protectedIds.toSorted().map(id => ({ id, documentRevision: documents.stamp(id) }))) + rows[0].description = 'edited returned value' + assert.equal(documents.get('create-skill').description, BUILTIN_SKILL_CATALOG[0].description) + folder('ordinary.empty') + assert.equal(documents.list().length, 3) + assert.equal(documents.get('ordinary.empty'), null) + assert.equal(documents.stamp('ordinary.empty'), null) + assert.equal(documents.get('missing'), null) +}) + +test('ordinary native notes share parser, projections and revisions; resources stay literal', t => { + const { documents, folder, put } = sandbox(t) + put('z-late', skillMd('Zulu')) + put('same-b', skillMd('Same')) + put('same-a', skillMd('Same')) + const raw = '\uFEFF' + [ + '---', 'name: Alpha', 'description: "Résumé goes here"', 'trigger: On request', 'license: MIT', + 'compatibility: Local prose', 'allowed-tools: Bash(git add:*) Read', 'metadata:', + ' author: "Owner"', ' reference: scripts/read.sh', 'private_field: ignored', '---', '', + 'Read `scripts/read.sh` and `/etc/example.conf` as references.', '', 'A secret-like ordinary placeholder: password=hello.', '' + ].join('\r\n') + put('some.Notes-2', raw) + fs.symlinkSync('/missing-resource', join(folder('some.Notes-2'), 'scripts')) + fs.symlinkSync('/missing-foreign', join(folder('.hide-me'), 'SKILL.md')) + const rows = documents.list() + assert.deepEqual(rows.map(x => x.id), [...protectedIds, 'some.Notes-2', 'same-a', 'same-b', 'z-late']) + const row = rows[3] + assert.deepEqual(Object.keys(row).sort(), ['description', 'documentRevision', 'id', 'name', 'source']) + assert.deepEqual(documents.get(row.id), { + ...row, detail: 'document', trigger: 'On request', license: 'MIT', compatibility: 'Local prose', + allowedTools: ['Bash(git add:*)', 'Read'], metadata: { author: 'Owner', reference: 'scripts/read.sh' }, + instructions: 'Read `scripts/read.sh` and `/etc/example.conf` as references.\n\nA secret-like ordinary placeholder: password=hello.' + }) + const stamps = documents.stamps() + assert.deepEqual(stamps, rows.map(({ id, documentRevision }) => ({ id, documentRevision })).sort((a, b) => a.id < b.id ? -1 : 1)) + for (const { id, documentRevision } of rows) { + assert.match(documentRevision, revision) + assert.equal(documents.stamp(id), documentRevision) + } + assert.equal(documents.get('some.notes-2'), null) +}) + +test('stamps are stat-only; list reads headers and selected detail reads exactly one body', t => { + const { documents, put } = sandbox(t) + const invalidBody = Buffer.concat([Buffer.from(skillMd('Healthy header', 'a'.repeat(8000))), Buffer.from([0xff, 0])]) + const path = put('body', invalidBody) + put('other', skillMd('Other', 'Safe detail')) + watchDocumentReads(path, read => { + const stamped = documents.stamp('body') + assert.equal(documents.stamps().find(x => x.id === 'body').documentRevision, stamped) + assert.equal(read(), 0) + assert.equal(documents.get('other').instructions, 'Safe detail') + assert.equal(read(), 0) + assert.equal(documents.list().find(x => x.id === 'body').documentRevision, stamped) + assert(read() > 0 && read() <= 512) + const before = read() + fails('skill_unsupported', () => documents.get('body')) + assert.equal(read() - before, invalidBody.length) + }) + const plain = put('plain', '\uFEFF# Plain body\r\n\r\nNo frontmatter.\r\n') + assert.equal(documents.get('plain').instructions, '# Plain body\n\nNo frontmatter.') + fs.writeFileSync(plain, 'Only LF or CRLF\rInvalid.') + fails('skill_unsupported', () => documents.get('plain')) + put('unterminated', '---\nname: Missing closing marker') + assert.match(documents.stamp('unterminated'), revision) + fails('skill_unsupported', () => documents.get('unterminated')) + fails('skill_unsupported', () => documents.list()) +}) + +test('selected restrictions distinguish obvious key forms from mere prose and references', t => { + const { documents, put } = sandbox(t) + put('sensitive-header', '---\nname: Summary remains visible\nmetadata:\n apiKey: REPLACE_ME\n---\nManual note.\n') + put('sensitive-body', skillMd('Header is ordinary', '-----BEGIN OPENSSH PRIVATE KEY-----\nsynthetic key marker\n-----END OPENSSH PRIVATE KEY-----')) + put('other', skillMd('Other', 'No credential material, merely a reference to credentials.env')) + assert.equal(documents.list().length, 6) + fails('skill_restricted', () => documents.get('sensitive-header')) + fails('skill_restricted', () => documents.get('sensitive-body')) + assert.equal(documents.get('other').instructions, 'No credential material, merely a reference to credentials.env') + const token = 'ghp_' + 'X'.repeat(36) + put('sensitive-title', skillMd(token)) + assert.match(documents.stamp('sensitive-title'), revision) + fails('skill_restricted', () => documents.get('sensitive-title')) + fails('skill_restricted', () => documents.list()) +}) + +test('unsafe identifiers, reserved aliases, and prototype/duplicate fields fail closed', t => { + const { documents, folder, put } = sandbox(t) + for (const id of ['../ordinary', 'x/other', 'x\\other', '.hidden', 'x\n', 'x\r\n', 'x.', 'a..b', + '__proto__', 'constructor', 'toString', 'CREATE-SKILL', 'create_agent', 'create.mcp']) { + fails('skill_invalid', () => documents.get(id)) + fails('skill_invalid', () => documents.stamp(id)) + } + put('alias-title', skillMd('CREATE_SKILL')) + fails('skill_unsupported', () => documents.get('alias-title')) + fails('skill_unsupported', () => documents.list()) + put('alias-title', skillMd('An ordinary name')) + put('unsafe-fields', '---\nname: Fields\nmetadata:\n __proto__: sentinel\n---\nOther text.\n') + fails('skill_unsupported', () => documents.get('unsafe-fields')) + fails('skill_unsupported', () => documents.list()) + put('unsafe-fields', '---\nname: Fields\nname: duplicate\n---\nOther text.\n') + fails('skill_unsupported', () => documents.get('unsafe-fields')) + folder('Same') + folder('same') + fails('skill_unsupported', () => documents.stamps()) + fs.rmdirSync(folder('same')) + put('CREATE-SKILL', skillMd('Shadow')) + assert.equal(documents.get('create-skill').detail, 'builtin') + fails('skill_invalid', () => documents.get('CREATE-SKILL')) + fails('skill_unsupported', () => documents.get('alias-title')) + fails('skill_unsupported', () => documents.stamps()) +}) + +test('native symlinks, hard links, and unsafe owner permissions never produce rows', t => { + const { documents, dataDir, folder, dir, put, skillsDir } = sandbox(t) + const outside = join(dir, 'outside.md') + fs.writeFileSync(outside, skillMd('Outside')) + const skill = folder('selected'), file = join(skill, 'SKILL.md') + fs.symlinkSync(outside, file) + fails('skill_unsupported', () => documents.get('selected')) + fails('skill_unsupported', () => documents.stamps()) + fs.unlinkSync(file) + fs.linkSync(outside, file) + fails('skill_unsupported', () => documents.stamp('selected')) + fs.unlinkSync(file) + put('selected', skillMd('Owned')) + for (const mode of [0o666, 0o200, 0o700]) { + fs.chmodSync(file, mode) + fails('skill_unsupported', () => documents.stamp('selected')) + } + fs.chmodSync(file, 0o600) + fs.chmodSync(skill, 0o777) + fails('skill_unsupported', () => documents.get('selected')) + fs.chmodSync(skill, 0o700) + fs.symlinkSync(skill, join(skillsDir, 'symlink')) + fails('skill_unsupported', () => documents.stamps()) + fs.unlinkSync(join(skillsDir, 'symlink')) + const old = join(dir, 'outside-skills') + fs.renameSync(skillsDir, old) + fs.symlinkSync(old, skillsDir) + fails('skill_unsupported', () => documents.list()) + const alias = join(dir, 'alias') + fs.symlinkSync(dataDir, alias) + fails('skill_unsupported', () => openSkillDocuments({ dataDir: alias }).stamps()) +}) + +test('revisions track native file/directory identity and same-length edits, not auxiliary resources', t => { + const { documents, put, folder, skillsDir } = sandbox(t) + const path = put('note', skillMd('Name', 'First')) + const first = documents.stamp('note') + fs.writeFileSync(join(folder('note'), 'private-resource'), 'Ignored.') + assert.equal(documents.stamp('note'), first) + fs.utimesSync(path, 1, 1) + fs.writeFileSync(path, skillMd('Name', 'Other')) + fs.utimesSync(path, 1, 1) + const edited = documents.stamp('note') + assert.notEqual(edited, first) + const other = join(skillsDir, 'old-note') + fs.renameSync(folder('note'), other) + fs.renameSync(join(other, 'SKILL.md'), join(folder('note'), 'SKILL.md')) + const replaced = documents.stamp('note') + assert.notEqual(replaced, edited) + assert.equal(documents.get('note').documentRevision, replaced) +}) + +test('a mid-read native replacement and a changed configured root fail revalidation', t => { + const { documents, put, dir, dataDir } = sandbox(t) + const path = put('note', skillMd('Name', 'Old note')) + let changed = false + watchDocumentReads(path, () => fails('skill_unsupported', () => documents.get('note')), () => { + if (changed) return + changed = true + fs.renameSync(path, join(dir, 'old-note')) + put('note', skillMd('Name', 'Replacement')) + }) + assert.equal(documents.get('note').instructions, 'Replacement') + fs.renameSync(dataDir, join(dir, 'old-data')) + put('note', skillMd('Other native root')) + fails('skill_unsupported', () => documents.get('note')) + const replacement = openSkillDocuments({ dataDir }) + t.after(() => replacement.close()) + assert.equal(replacement.get('note').name, 'Other native root') +}) + +test('native ancestor swaps and permission changes during reads give fixed errors', async t => { + const changes = [ + ['skills root', ({ dir, skillsDir, put }) => { + fs.renameSync(skillsDir, join(dir, 'old-skills')) + put('note', skillMd('New skills root')) + }], + ['direct skill directory', ({ dir, folder, put }) => { + fs.renameSync(folder('note'), join(dir, 'old-directory')) + put('note', skillMd('New directory')) + }], + ['configured root', ({ dir, dataDir, put }) => { + fs.renameSync(dataDir, join(dir, 'old-root')) + put('note', skillMd('New root')) + }], + ['document mode', (_fixture, path) => fs.chmodSync(path, 0o666)] + ] + for (const [label, change] of changes) { + await t.test(label, child => { + const fixture = sandbox(child) + const path = fixture.put('note', skillMd('Origin')) + watchDocumentReads(path, () => fails('skill_unsupported', () => fixture.documents.get('note')), () => change(fixture, path)) + }) + } +}) + +test('old-kernel synthetic directory birthtime survives unrelated native writes', t => { + const { documents, dir, dataDir, put } = sandbox(t) + const path = put('stable', skillMd('Stable')) + const fstat = fs.fstatSync + fs.fstatSync = function (...args) { + const info = fstat.apply(this, args) + if (info.isDirectory() && typeof info.ctimeNs === 'bigint') info.birthtimeNs = info.ctimeNs + return info + } + syncBuiltinESMExports() + try { + const before = documents.stamp('stable') + fs.writeFileSync(join(dataDir, 'config.json'), '{}') + assert.equal(documents.stamp('stable'), before) + watchDocumentReads(path, () => { + assert.equal(documents.list().find(item => item.id === 'stable').documentRevision, before) + }, () => { + fs.writeFileSync(join(dir, 'unrelated-ancestor-sibling'), '') + fs.writeFileSync(join(dataDir, 'config-next.json'), '{}') + }) + } finally { fs.fstatSync = fstat; syncBuiltinESMExports() } +}) + +test('the canonical root descriptor is lazy, singular, and released by idempotent close', t => { + const { documents, dataDir, put } = sandbox(t) + const root = fs.statSync(dataDir, { bigint: true }) + const rootFds = () => fs.readdirSync('/proc/self/fd').filter(fd => { + try { + const info = fs.statSync(`/proc/self/fd/${fd}`, { bigint: true }) + return info.dev === root.dev && info.ino === root.ino + } catch (error) { + if (error.code !== 'ENOENT') throw error + return false + } + }).length + const initial = rootFds() + assert.equal(documents.get('create-skill').detail, 'builtin') + assert.equal(rootFds(), initial) + put('note', '---\nunterminated') + fails('skill_unsupported', () => documents.get('note')) + assert.equal(rootFds(), initial) + put('note', skillMd('Ordinary')) + assert.equal(documents.get('note').name, 'Ordinary') + assert.equal(rootFds(), initial + 1) + documents.list() + documents.stamps() + assert.equal(rootFds(), initial + 1) + documents.close() + documents.close() + assert.equal(rootFds(), initial) + for (const action of [() => documents.get('create-skill'), () => documents.stamp('create-skill'), + () => documents.list(), () => documents.stamps()]) fails('skill_unsupported', action) +}) + +test('bounds cover foreign entries, documents, header bytes, and aggregate stat size', t => { + const { documents, put, folder, skillsDir } = sandbox(t) + const header = put('large-header', `---\nname: ${'x'.repeat(16 * 1024)}\n---\nSmall body.`) + assert.match(documents.stamp('large-header'), revision) + fails('skill_limit', () => documents.list()) + fails('skill_limit', () => documents.get('large-header')) + fs.truncateSync(header, 128 * 1024 + 1) + fails('skill_limit', () => documents.stamp('large-header')) + fs.unlinkSync(header) + for (let i = 0; i < 33; i++) fs.truncateSync(put(`aggregate-${i}`, skillMd('Name')), 128 * 1024) + fails('skill_limit', () => documents.stamps()) + for (let i = 0; i < 33; i++) fs.unlinkSync(join(folder(`aggregate-${i}`), 'SKILL.md')) + for (let i = 0; i < 129; i++) put(`visible-${i}`, '') + fails('skill_limit', () => documents.stamps()) + for (let i = 0; i < 352; i++) fs.writeFileSync(join(skillsDir, `.foreign-${i}`), '') + fails('skill_limit', () => documents.stamp('missing')) +}) diff --git a/apps/headless/test/skill-library-http.test.mjs b/apps/headless/test/skill-library-http.test.mjs new file mode 100644 index 00000000..77e03366 --- /dev/null +++ b/apps/headless/test/skill-library-http.test.mjs @@ -0,0 +1,563 @@ +import assert from 'node:assert/strict' +import childProcess from 'node:child_process' +import { randomBytes, randomUUID } from 'node:crypto' +import { once } from 'node:events' +import { chmod, lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, rmdir, symlink, unlink, writeFile } from 'node:fs/promises' +import { createServer, request } from 'node:http' +import { syncBuiltinESMExports } from 'node:module' +import { tmpdir } from 'node:os' +import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path' +import test from 'node:test' +import { setTimeout as delay } from 'node:timers/promises' +import { requestControl } from '../src/control/socket.mjs' +import { startWorkbench } from '../src/server.mjs' +import { initializeMasterKey } from '../src/storage/vault.mjs' + +const builtins = ['create-agent', 'create-mcp', 'create-skill'] +const skillId = 'native-skill-fixture' +const skillName = 'Skill Fixture Name 884add' +const description = 'Skill fixture summary 9d82e1' +const instruction = 'SKILL_BODY_MARKER_4e8cc1' +const privateMarker = 'PRIVATE_CONFIG_MARKER_d149cd' +const outsideMarker = 'OUTSIDE_RESOURCE_MARKER_78ba01' +const roleName = 'Fixture Editor' +const rolePrompt = 'Keep the reply concise.' +const pref = `skills/${skillId}/preferences` +const changes = 'skills/-/changes' +const hex = /^[0-9a-f]{64}$/ +const summaryKeys = ['canConfigure', 'description', 'enabled', 'id', 'name', 'revision', 'roles', 'source'] +const detailKeys = [...summaryKeys, 'allowedTools', 'compatibility', 'detail', 'instructions', 'license', 'metadata', 'trigger'].sort() +const noChange = Object.freeze({}) +const encode = value => Buffer.from(`${JSON.stringify(value)}\n`) +const markdown = (name, marker) => `---\nname: ${name}\ndescription: ${description}\ntrigger: fixture cue\nallowed-tools: [read_file, run_command, skill]\nlicense: MIT\ncompatibility: fixture only\nmetadata:\n flavor: mint\n---\n${marker}\n\nThis fixture has an optional helper at scripts/helper.mjs.\n` + +function expectStatus(result, status, label) { + assert.equal(result.status, status, `${label ?? result.method + ' ' + result.path}: ${JSON.stringify(result.body)}`) + return result.body +} + +function assertRevision(value) { assert.match(value, hex) } +function assertKeys(value, keys) { assert.deepEqual(Object.keys(value).sort(), keys) } +function assertClean(payload, ...markers) { + const wire = JSON.stringify(payload) + for (const marker of markers) assert.equal(wire.includes(marker), false, `unexpected response content: ${marker}`) +} + +async function tempRoot() { + const parent = await realpath(tmpdir()) + const root = await mkdtemp(join(parent, 'deva-skill-http-')) + const identity = await lstat(root, { bigint: true }) + const assertIdentity = async () => { + assert.ok(isAbsolute(root) && dirname(root) === parent && /^deva-skill-http-[A-Za-z0-9]{6}$/.test(basename(root))) + assert.equal(await realpath(root), root) + const current = await lstat(root, { bigint: true }) + assert.ok(current.isDirectory() && current.uid === BigInt(process.getuid()) && (current.mode & 0o077n) === 0n) + assert.deepEqual([current.dev, current.ino], [identity.dev, identity.ino]) + } + const cleanup = async () => { await assertIdentity(); await rm(root, { recursive: true }) } + return { root, assertIdentity, cleanup } +} + +// Observe real launch entrypoints in this dedicated Node test process. Node's required, +// startup-only flock remains real; ordinary HTTP, the disk watcher and the adapter are untouched. +function observeProcesses() { + const attempts = [] + const methods = ['spawnSync', 'execSync', 'execFileSync'] + const originals = new Map(methods.map(name => [name, childProcess[name]])) + const prototype = childProcess.ChildProcess.prototype + const spawn = prototype.spawn + const restore = () => { + prototype.spawn = spawn + for (const [name, original] of originals) childProcess[name] = original + syncBuiltinESMExports() + } + prototype.spawn = function (options) { + attempts.push(['spawn', options?.file]) + return Reflect.apply(spawn, this, arguments) + } + for (const [name, original] of originals) childProcess[name] = function (file) { + attempts.push([name, file]) + return Reflect.apply(original, this, arguments) + } + syncBuiltinESMExports() + return { attempts, restore } +} + +async function openUpstream(syntheticResource) { + const requests = [] + const server = createServer(async (req, res) => { + try { + const chunks = [] + for await (const chunk of req) chunks.push(chunk) + const payload = JSON.parse(Buffer.concat(chunks)) + requests.push({ method: req.method, path: req.url, authorization: req.headers.authorization, payload }) + if (req.url !== '/v1/chat/completions') return res.writeHead(404).end() + // Even if a provider sends a tool invocation on its own, the text-only host rejects it. + const rows = [ + { index: 0, delta: { tool_calls: [{ index: 0, id: 'call_local_fixture', type: 'function', + function: { name: 'read_file', arguments: JSON.stringify({ path: syntheticResource }) } }] }, finish_reason: null }, + { index: 0, delta: {}, finish_reason: 'tool_calls' } + ] + res.writeHead(200, { 'content-type': 'text/event-stream' }) + res.end(`${rows.map(row => `data: ${JSON.stringify({ choices: [row] })}\n\n`).join('')}data: [DONE]\n\n`) + } catch (error) { + requests.push({ error: error.message }) + res.writeHead(400).end() + } + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + return { + origin: `http://127.0.0.1:${server.address().port}`, requests, + close: () => new Promise((resolveClose, reject) => { + server.close(error => error ? reject(error) : resolveClose()) + server.closeAllConnections() + }) + } +} + +async function fixture(t) { + const { root, assertIdentity, cleanup } = await tempRoot() + let app, upstream, restoreProcesses + t.after(async () => { + try { await app?.close() } + finally { + try { await upstream?.close() } + finally { restoreProcesses?.(); await cleanup() } + } + }) + await assertIdentity() + const { attempts, restore } = observeProcesses() + restoreProcesses = restore + const dataDir = join(root, 'data'), keyFile = join(root, 'master.key'), runDir = join(root, 'run'), webDir = join(root, 'web') + const config = join(dataDir, 'config.json'), skills = join(dataDir, 'skills'), folder = join(skills, skillId) + const document = join(folder, 'SKILL.md'), helper = join(folder, 'scripts', 'helper.mjs') + const reference = join(folder, 'references', 'synthetic.txt'), canary = join(folder, 'canary.txt') + const outside = join(root, 'elsewhere'), outsideFile = join(outside, 'SKILL.md') + const password = randomBytes(24).toString('hex') + const upstreamKey = randomBytes(24).toString('hex') + const seed = { + locale: 'en', theme: 'dark', + desktopOnly: { secret: privateMarker, preserve: ' café\t🧪\r\n ', path: outsideFile, nested: [null, 0, false] }, + mcp: { privateExample: { enabled: true, note: privateMarker } }, + skills: { + enabled: { [skillId]: false, 'uninstalled-example': true }, + roles: { [skillId]: ['general'], 'uninstalled-example': ['general'] }, + unrelated: { note: privateMarker, bytes: ' ✨\n ' } + } + } + upstream = await openUpstream(outsideFile) + await Promise.all([mkdir(dataDir, { mode: 0o700 }), mkdir(webDir, { mode: 0o700 }), mkdir(outside, { mode: 0o700 })]) + await Promise.all([ + initializeMasterKey(keyFile), writeFile(config, encode(seed), { mode: 0o600 }), + writeFile(join(webDir, 'index.html'), '\n'), + writeFile(join(webDir, 'workbench.js'), 'export {};\n'), + writeFile(join(webDir, 'manifest.json'), JSON.stringify({ workbench: { file: 'workbench.js', isEntry: true } })), + writeFile(outsideFile, markdown(outsideMarker, outsideMarker), { mode: 0o600 }) + ]) + const options = { dataDir, keyFile, runDir, webDir, host: '127.0.0.1', port: 0, businessOptions: { allowedOrigins: [upstream.origin] } } + const boot = async () => { + app = await startWorkbench(options) + assert.deepEqual(attempts.splice(0), [['spawnSync', '/usr/bin/flock']], 'expected only the native writer lock helper at startup') + } + await boot() + + // Use the raw request path so the client does not normalize traversal probes before the host sees them. + function call(path, { method = 'GET', body, login, headers = noChange } = {}) { + const mutation = method !== 'GET' + const bytes = body === undefined ? undefined : Buffer.from(JSON.stringify(body)) + const wireHeaders = { + ...(login ? { cookie: login.cookie } : {}), + ...(mutation ? { origin: app.origin, 'content-type': 'application/json', ...(login ? { 'x-deva-csrf': login.csrf } : {}) } : {}), + ...(bytes ? { 'content-length': bytes.length } : {}), ...headers + } + for (const [key, value] of Object.entries(wireHeaders)) if (value === null) delete wireHeaders[key] + return new Promise((resolveCall, reject) => { + const req = request({ host: app.address.address, port: app.address.port, agent: false, method, + path: path.startsWith('/') ? path : '/api/v1/' + path, headers: wireHeaders, signal: AbortSignal.timeout(11_000) }, res => { + const parts = [] + res.on('data', chunk => parts.push(chunk)) + res.on('error', reject) + res.on('end', () => { + const text = Buffer.concat(parts).toString('utf8') + try { resolveCall({ status: res.statusCode, method, path, body: JSON.parse(text), cookie: res.headers['set-cookie']?.[0]?.split(';')[0] }) } + catch (error) { reject(Error(`${method} ${path}: expected JSON (${res.statusCode})`, { cause: error })) } + }) + }) + req.on('error', reject) + req.end(bytes) + }) + } + async function signIn(claim = false) { + const credentials = claim ? { password, credential: (await requestControl({ runDir, op: 'claim' })).credential } : { password } + const response = await call(claim ? 'auth/claim' : 'auth/login', { method: 'POST', body: credentials }) + const { csrf } = expectStatus(response, 200) + assert.ok(typeof csrf === 'string' && csrf.length > 0 && typeof response.cookie === 'string') + return { csrf, cookie: response.cookie } + } + + const owner = await signIn(true), peer = await signIn() + assert.notEqual(peer.cookie, owner.cookie) + assert.notEqual(peer.csrf, owner.csrf) + const send = (path, method, body, headers, login = owner) => call(path, { method, body, headers, login }) + const role = expectStatus(await send('personas', 'POST', { name: roleName, prompt: rolePrompt, enabled: true }), 200).role + const disabledRole = expectStatus(await send('personas', 'POST', { name: 'Disabled Fixture Role', prompt: privateMarker, enabled: false }), 200).role + const first = expectStatus(await send('settings', 'GET'), 200) + const provider = { id: 'skill-http-fixture', name: 'Local SSE fixture', kind: 'custom', purpose: 'llm', accent: '#123456', adapter: 'openai', + apiHost: upstream.origin + '/v1', enabled: true, models: [{ id: 'local-text', name: 'Local text', enabled: true }] } + const model = `${provider.id}:local-text` + const settings = expectStatus(await send('settings', 'PATCH', { revision: first.revision, + set: { models: { providers: [provider], activeModelId: model, activeEffort: 'default' } } }), 200) + expectStatus(await send(`provider-keys/${provider.id}`, 'PUT', { value: upstreamKey, revision: settings.revision }), 200) + // Use valid but deliberately non-canonical native JSON after the ordinary settings + // setup. This catches lossy reserialization, not just loss of parsed fields. + const sentinels = [seed.desktopOnly, seed.mcp, seed.skills.unrelated] + const preservedBytes = sentinels.map(value => JSON.stringify(value, null, '\t').replace('café', 'caf\\u00e9')) + let native = await readFile(config, 'utf8') + for (const [i, sentinel] of sentinels.entries()) { + const compact = JSON.stringify(sentinel) + assert.ok(native.includes(compact)) + native = native.replace(compact, preservedBytes[i]) + } + await writeFile(config, native) + + async function installDocument() { + await Promise.all([mkdir(dirname(helper), { recursive: true, mode: 0o700 }), mkdir(dirname(reference), { recursive: true, mode: 0o700 })]) + await Promise.all([ + writeFile(document, markdown(skillName, instruction), { mode: 0o600 }), + writeFile(helper, `import { writeFileSync } from 'node:fs';\nwriteFileSync(new URL('../canary.txt', import.meta.url), 'executed');\n`, { mode: 0o700 }), + writeFile(reference, 'INERT_REFERENCE_MARKER_fdfa5b\n', { mode: 0o600 }), + symlink(outsideFile, join(dirname(reference), 'outside-link.txt'), 'file') + ]) + } + + async function rejectNativeLinks() { + async function tracked(path, target) { + await assertIdentity() + assert.ok(isAbsolute(path) && relative(skills, path).split(sep).every(part => part && part !== '..')) + assert.equal(await realpath(dirname(path)), dirname(path)) + assert.equal(await realpath(path), target ?? path) + const info = await lstat(path, { bigint: true }) + assert.ok((target ? info.isSymbolicLink() : info.isDirectory()) && info.uid === BigInt(process.getuid())) + return info + } + async function dispose(path, original, target) { + const current = await tracked(path, target) + assert.deepEqual([current.dev, current.ino], [original.dev, original.ino]) + await (target ? unlink(path) : rmdir(path)) + } + const unsupported = async path => assert.deepEqual(expectStatus(await send(path, 'GET'), 409), { error: 'skill_unsupported' }) + const linkedSkill = join(skills, 'linked-skill') + await symlink(outside, linkedSkill, 'dir') + const linkedSkillInfo = await tracked(linkedSkill, outside) + await unsupported('skills') + await unsupported('skills/linked-skill') + await dispose(linkedSkill, linkedSkillInfo, outside) + + const linkedFolder = join(skills, 'linked-document'), linkedFile = join(linkedFolder, 'SKILL.md') + await mkdir(linkedFolder, { mode: 0o700 }) + const folderInfo = await tracked(linkedFolder) + await symlink(outsideFile, linkedFile, 'file') + const fileInfo = await tracked(linkedFile, outsideFile) + await unsupported('skills') + await unsupported('skills/linked-document') + await dispose(linkedFile, fileInfo, outsideFile) + await dispose(linkedFolder, folderInfo) + + const collision = join(skills, 'create-skill') + await mkdir(collision, { mode: 0o700 }) + const collisionInfo = await tracked(collision) + await unsupported('skills') + const builtin = expectStatus(await send('skills/create-skill', 'GET'), 200) + assert.equal(builtin.skill.source, 'builtin') + await dispose(collision, collisionInfo) + } + + async function replaceDocument(bytes) { + await assertIdentity() + const temp = join(folder, 'editor-replacement.md') + assert.equal(relative(root, document), ['data', 'skills', skillId, 'SKILL.md'].join(sep)) + assert.ok(isAbsolute(temp) && dirname(temp) === dirname(document)) + await writeFile(temp, bytes, { mode: 0o600, flag: 'wx' }) + for (const path of [document, temp]) { + assert.equal(await realpath(path), path) + const flags = await lstat(path) + assert.ok(flags.isFile() && flags.nlink === 1 && flags.uid === process.getuid()) + } + await rename(temp, document) + } + + return { root, skills, config, document, helper, reference, canary, outsideFile, attempts, upstream, upstreamKey, model, + role, disabledRole, owner, peer, call, send, signIn, installDocument, replaceDocument, rejectNativeLinks, preservedBytes, + restart: async () => { await app.close(); await boot() } } +} + +async function list(f) { + const result = expectStatus(await f.send('skills', 'GET'), 200) + assertKeys(result, ['execution', 'revision', 'skills']) + assert.equal(result.execution, 'inactive') + assertRevision(result.revision) + for (const summary of result.skills) { + assertKeys(summary, summaryKeys) + assertRevision(summary.revision) + } + assertClean(result, f.root, instruction, privateMarker, outsideMarker, 'instructions', 'allowedTools', 'INERT_REFERENCE_MARKER') + return result +} + +async function selected(f, id = skillId) { return expectStatus(await f.send(`skills/${id}`, 'GET'), 200) } +function poll(f, after, waitMs, login) { return f.send(changes, 'POST', { after, waitMs }, undefined, login) } +function checkedPoll(result, changed) { + const body = expectStatus(result, 200) + assertKeys(body, ['changed', 'revision']) + assert.equal(body.changed, changed) + assertRevision(body.revision) + return body.revision +} +async function pending(promise) { + const tick = Symbol('pending') + assert.equal(await Promise.race([promise, delay(200, tick)]), tick, 'long poll returned before the inducing write') +} +async function woken(promise, signal = 'the change') { + const controller = new AbortController() + try { + return await Promise.race([promise, delay(4500, undefined, { signal: controller.signal }).then(() => { + assert.fail(`long poll did not wake promptly after ${signal}`) + })]) + } finally { controller.abort() } +} + +async function projections(f) { + assert.equal(expectStatus(await f.call('/readyz'), 200).status, 'ready') + assert.equal(expectStatus(await f.send('bootstrap', 'GET'), 200).capabilities.skillLibrary, true) + const before = await readFile(f.config) + await assert.rejects(lstat(f.skills), { code: 'ENOENT' }) + for (const path of ['skills', `skills/${skillId}`, 'skills/-/roles']) expectStatus(await f.call(path), 401) + const absent = await list(f) + assert.deepEqual(absent.skills.map(s => s.id).sort(), builtins) + assert.deepEqual(await selected(f), { skill: null, execution: 'inactive' }) + for (const row of absent.skills) { + assert.equal(row.source, 'builtin') + assert.equal(row.canConfigure, false) + const detail = await selected(f, row.id) + assert.deepEqual(detail, { skill: { ...row, detail: 'builtin' }, execution: 'inactive' }) + } + await assert.rejects(lstat(f.skills), { code: 'ENOENT' }) + assert.deepEqual(await readFile(f.config), before) + + await f.installDocument() + await f.rejectNativeLinks() + const installed = await list(f) + assert.deepEqual(installed.skills.map(s => s.id).sort(), [...builtins, skillId].sort()) + const custom = installed.skills.find(s => s.id === skillId) + assert.deepEqual(custom, { id: skillId, name: skillName, description, source: 'custom', enabled: false, roles: ['general'], + revision: custom.revision, canConfigure: true }) + const detail = await selected(f) + assertKeys(detail, ['execution', 'skill']) + assertKeys(detail.skill, detailKeys) + assert.deepEqual(detail, { execution: 'inactive', skill: { ...custom, detail: 'document', + instructions: markdown(skillName, instruction).split('---\n').at(-1).trim(), trigger: 'fixture cue', + allowedTools: ['read_file', 'run_command', 'skill'], license: 'MIT', compatibility: 'fixture only', metadata: { flavor: 'mint' } } }) + assertClean(detail, f.root, privateMarker, outsideMarker, 'INERT_REFERENCE_MARKER') + for (const id of ['linked-skill', 'linked-document', 'missing-skill']) assert.deepEqual(await selected(f, id), { skill: null, execution: 'inactive' }) + const roster = expectStatus(await f.send('skills/-/roles', 'GET'), 200) + assertKeys(roster, ['roles']) + assert.deepEqual([...roster.roles].sort((a, b) => a.id.localeCompare(b.id)), [ + { id: 'general', name: 'General', enabled: true }, + { id: f.role.id, name: roleName, enabled: true }, + { id: f.disabledRole.id, name: 'Disabled Fixture Role', enabled: false } + ].sort((a, b) => a.id.localeCompare(b.id))) + assert.ok(roster.roles.every(r => typeof r.name === 'string' && r.name.length > 0)) + assertClean(roster, rolePrompt, privateMarker, f.root) + assert.deepEqual(await readFile(f.config), before) + return installed +} + +async function preferences(f, installed) { + const bytes = await readFile(f.config) + const original = JSON.parse(bytes) + const docs = await Promise.all([f.document, f.helper, f.reference, f.outsideFile].map(path => readFile(path))) + let current = installed.skills.find(s => s.id === skillId) + const revision = current.revision + const turnOn = { revision, enabled: true } + const patch = (edit, login, headers) => f.send(pref, 'PATCH', { revision: current.revision, ...edit }, headers, login) + expectStatus(await f.call(pref, { method: 'PATCH', body: turnOn }), 401) + expectStatus(await f.send(pref, 'PATCH', turnOn, { origin: 'http://127.0.0.1:1' }), 403) + expectStatus(await f.send(pref, 'PATCH', turnOn, { origin: null }), 403) + expectStatus(await f.send(pref, 'PATCH', turnOn, { 'x-deva-csrf': f.peer.csrf }), 401) + expectStatus(await f.send(pref, 'PATCH', turnOn, { 'x-deva-csrf': null }), 401) + for (const body of [ + { revision }, { revision, enabled: true, roles: null }, { revision, enabled: 'true' }, + { revision, enabled: true, path: '../elsewhere/SKILL.md' }, { revision, enabled: true, id: 'linked-skill' }, + { revision, roles: [17] }, { revision, roles: 'general' }, { revision: 'short', enabled: true } + ]) expectStatus(await f.send(pref, 'PATCH', body), 400) + for (const path of [ + '/api/v1/skills/%2e%2e/preferences', '/api/v1/skills/../preferences', '/api/v1/skills/native%2foutside/preferences' + ]) expectStatus(await f.send(path, 'PATCH', turnOn), 400) + const builtin = installed.skills.find(s => s.id === 'create-skill') + assert.deepEqual(expectStatus(await f.send('skills/create-skill/preferences', 'PATCH', { revision: builtin.revision, enabled: false }), 409), + { error: 'skill_builtin' }) + assert.deepEqual(expectStatus(await patch({ roles: ['not-a-roster-role'] }), 409), { error: 'skill_unknown_role' }) + for (const path of [`skills/${skillId}/resources/references/synthetic.txt`, `skills/${skillId}/references/synthetic.txt`, + `skills/${skillId}/references/outside-link.txt`]) { + assertClean(expectStatus(await f.send(path, 'GET'), 404), 'INERT_REFERENCE_MARKER', f.root) + } + expectStatus(await f.send(`skills/${skillId}/execute`, 'POST', {}), 404) + expectStatus(await f.send(`skills/${skillId}`, 'DELETE'), 405) + assert.deepEqual(await readFile(f.config), bytes, 'reading and rejected mutations made no config write') + + await chmod(f.config, 0o400) + try { + const ro = await selected(f) + assert.equal(ro.skill.canConfigure, false) + const deniedWrite = await f.send(pref, 'PATCH', { revision: ro.skill.revision, enabled: true }) + assert.deepEqual(expectStatus(deniedWrite, 403), { error: 'skill_read_only' }) + assert.deepEqual(await readFile(f.config), bytes) + } finally { await chmod(f.config, 0o600) } + current = (await selected(f)).skill + const previous = current.revision + const before = (await list(f)).revision + assert.equal(checkedPoll(await poll(f, before, 0), false), before) + const waiting = poll(f, before, 8000, f.peer) + // Surface early transport rejection via pending(), and keep the promise observed on assertion failure. + void waiting.catch(() => {}) + await pending(waiting) + const apply = async (edit, expected) => { + const updated = expectStatus(await patch(edit), 200) + assertKeys(updated, ['execution', 'skill']) + assertKeys(updated.skill, summaryKeys) + assert.equal(updated.execution, 'inactive') + assertRevision(updated.skill.revision) + assert.notEqual(updated.skill.revision, current.revision) + for (const [key, value] of Object.entries(expected)) assert.deepEqual(updated.skill[key], value) + current = updated.skill + const stored = JSON.parse(await readFile(f.config)) + const native = structuredClone(original) + native.skills.enabled[skillId] = current.enabled + if (current.roles === null) delete native.skills.roles[skillId] + else native.skills.roles[skillId] = current.roles + assert.deepEqual(stored, native) + const wire = await readFile(f.config) + for (const sentinel of f.preservedBytes) { + assert.ok(wire.includes(sentinel), 'unrelated config spelling, whitespace and bytes survived the write') + } + return updated.skill + } + await apply({ enabled: true }, { enabled: true, roles: ['general'] }) + const changed = checkedPoll(await woken(waiting, 'the preference write'), true) + assert.notEqual(changed, before) + assert.equal(changed, (await list(f)).revision) + assert.deepEqual(expectStatus(await f.send(pref, 'PATCH', { revision: previous, enabled: false }, undefined, f.peer), 409), { error: 'skill_conflict' }) + await apply({ roles: null }, { enabled: true, roles: null }) + assert.equal((await selected(f)).skill.roles, null) + await apply({ roles: [] }, { enabled: true, roles: [] }) + assert.deepEqual((await selected(f)).skill.roles, []) + await apply({ roles: [f.role.id] }, { enabled: true, roles: [f.role.id] }) + assert.deepEqual(await Promise.all([f.document, f.helper, f.reference, f.outsideFile].map(path => readFile(path))), docs) +} + +async function changesAndDisk(f) { + const initial = (await list(f)).revision + const valid = { after: initial, waitMs: 0 } + expectStatus(await f.call(changes, { method: 'POST', body: valid }), 401) + expectStatus(await f.send(changes, 'POST', valid, { origin: 'https://invalid.example' }), 403) + expectStatus(await f.send(changes, 'POST', valid, { 'x-deva-csrf': null }), 401) + for (const input of [{ after: initial }, { ...valid, extra: true }, { ...valid, after: 'g'.repeat(64) }, + { ...valid, waitMs: -1 }, { ...valid, waitMs: 8001 }, { ...valid, waitMs: 0.5 }, { ...valid, waitMs: '0' }]) { + expectStatus(await f.send(changes, 'POST', input), 400) + } + assert.equal(checkedPoll(await poll(f, initial, 0), false), initial) + const revoked = poll(f, initial, 8000, f.peer) + const observing = poll(f, initial, 8000) + void revoked.catch(() => {}) + void observing.catch(() => {}) + await Promise.all([pending(revoked), pending(observing)]) + expectStatus(await f.send('auth/logout', 'POST', undefined, undefined, f.peer), 200) + expectStatus(await f.call('skills', { login: f.peer }), 401) + const original = await readFile(f.config) + const edited = markdown(skillName, 'EXTERNALLY_EDITED_BODY_2d630d') + await writeFile(f.document, edited) + assert.deepEqual(expectStatus(await woken(revoked, 'revocation'), 401), { error: 'auth' }) + const editedRevision = checkedPoll(await woken(observing, 'the external file edit'), true) + assert.notEqual(editedRevision, initial) + assert.equal((await selected(f)).skill.instructions.split('\n')[0], 'EXTERNALLY_EDITED_BODY_2d630d') + assert.deepEqual(await readFile(f.document), Buffer.from(edited)) + assert.deepEqual(await readFile(f.config), original) + + // No refresh, Send, or other writer runs between arming the long poll and atomic editor replacement. + const observingReplacement = poll(f, editedRevision, 8000) + void observingReplacement.catch(() => {}) + await pending(observingReplacement) + const replacedName = `${skillName} Replaced` + const replacement = markdown(replacedName, 'ATOMIC_REPLACEMENT_BODY_415173') + await f.replaceDocument(replacement) + const replacementRevision = checkedPoll(await woken(observingReplacement, 'the atomic document replacement'), true) + assert.notEqual(replacementRevision, editedRevision) + const after = await list(f) + assert.equal(after.revision, replacementRevision) + assert.equal(after.skills.find(s => s.id === skillId).name, replacedName) + assert.deepEqual(await readFile(f.document), Buffer.from(replacement)) + assert.deepEqual(await readFile(f.config), original, 'watcher did not rewrite native preferences') + assert.equal(f.upstream.requests.length, 0, 'idle library operations initiated no model requests') + assert.deepEqual(f.attempts, [], 'idle library operations spawned no processes') +} + +async function textOnly(f) { + const detail = (await selected(f)).skill + assert.equal(detail.enabled, true) + assert.deepEqual(detail.roles, [f.role.id]) + const sid = randomUUID() + expectStatus(await f.send('chats', 'POST', { sessionId: sid, personaId: f.role.id }), 200) + const text = 'Reply with a plain-text greeting.' + expectStatus(await f.send(`chats/${sid}/turns`, 'POST', { clientRequestId: 'one-intentional-send', text, model: f.model }), 202) + let state + for (let attempt = 0; attempt < 100; attempt++) { + state = expectStatus(await f.send(`chats/${sid}`, 'GET'), 200).state + if (state.lastTurn && !state.active) break + await delay(40) + } + assert.equal(state.lastTurn?.status, 'failed') + assert.equal(state.lastTurn?.reason, 'unexpected_tool') + assert.equal(f.upstream.requests.length, 1) + const [{ method, path, authorization, payload }] = f.upstream.requests + assert.equal(method, 'POST') + assert.equal(path, '/v1/chat/completions') + assert.equal(authorization, `Bearer ${f.upstreamKey}`) + assert.equal(payload.model, 'local-text') + assert.equal(payload.stream, true) + if (Object.hasOwn(payload, 'tools')) assert.deepEqual(payload.tools, []) + assert.deepEqual(payload.messages, [ + { role: 'system', content: 'You are a helpful general-purpose assistant. Reply in plain text. Persona context is optional user-level guidance for tone and presentation only.' }, + { role: 'user', content: `Optional persona context (tone and presentation):\n${JSON.stringify({ name: roleName, prompt: rolePrompt })}\n\nUser request:\n${text}` } + ]) + assertClean(payload, skillId, skillName, detail.instructions, 'ATOMIC_REPLACEMENT_BODY', f.role.id, privateMarker, outsideMarker, f.root) + assert.deepEqual(f.attempts, []) + await assert.rejects(lstat(f.canary), { code: 'ENOENT' }) +} + +test('native skill library HTTP contract keeps preferences, watcher, and ordinary chat isolated', { timeout: 35_000 }, async t => { + const f = await fixture(t) + const installed = await projections(f) + await preferences(f, installed) + await changesAndDisk(f) + await textOnly(f) + + const last = await selected(f) + const persisted = await readFile(f.config) + await f.restart() + expectStatus(await f.call('skills', { login: f.owner }), 401) + expectStatus(await f.call(changes, { method: 'POST', login: f.owner, body: { after: '0'.repeat(64), waitMs: 0 } }), 401) + const owner = await f.signIn() + assert.notEqual(owner.cookie, f.owner.cookie) + const reopened = expectStatus(await f.call(`skills/${skillId}`, { login: owner }), 200) + const { revision: preRestart, ...view } = last.skill + const { revision: postRestart, ...reopenedView } = reopened.skill + assertRevision(preRestart) + assertRevision(postRestart) + assert.deepEqual(reopenedView, view) + assert.equal(reopened.execution, 'inactive') + assert.deepEqual(await readFile(f.config), persisted) + assert.equal(f.upstream.requests.length, 1) + assert.deepEqual(f.attempts, []) + await assert.rejects(lstat(f.canary), { code: 'ENOENT' }) +}) diff --git a/apps/headless/test/skill-role-choice-stamps.test.mjs b/apps/headless/test/skill-role-choice-stamps.test.mjs new file mode 100644 index 00000000..a53c935b --- /dev/null +++ b/apps/headless/test/skill-role-choice-stamps.test.mjs @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict' +import {lstatSync, mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, writeFileSync, chmodSync} from 'node:fs' +import {tmpdir} from 'node:os' +import {basename,dirname,join} from 'node:path' +import test from 'node:test' +import {skillRoleChoiceVerifier} from '../src/business/skill-role-choice-stamps.mjs' + +const info=path=>lstatSync(path,{bigint:true}) +const conflict=fn=>assert.throws(fn, {code:'skill_conflict',status:409}) +test('native role choice proof ignores unrelated config publications but fails on changed or swapped role binding',t=>{ + const temp=realpathSync.native(tmpdir()), root=mkdtempSync(join(temp,'deva-skill-role-')), original=info(root) + t.after(()=>{ + const current=info(root) + assert.equal(dirname(root),temp);assert.match(basename(root),/^deva-skill-role-[A-Za-z0-9]{6}$/) + assert.equal(realpathSync.native(root),root);assert.deepEqual([current.dev,current.ino,current.uid],[original.dev,original.ino,BigInt(process.geteuid())]); + rmSync(root,{recursive:true}) + }) + const roster=join(root,'personas'), file=join(roster,'editor.md') + mkdirSync(roster,{mode:0o700});writeFileSync(file,'# Original editorial role',{mode:0o600,flag:'wx'}) + const proof=()=>skillRoleChoiceVerifier(root,info(root),info(roster),[{id:'editor',info:info(file)}]) + const first=proof();assert.equal(first(),true) + writeFileSync(join(root,'config.json'),'{}',{flag:'wx',mode:0o600});assert.equal(first(),true) + const next=join(roster,'new-editor');writeFileSync(next,'# Same role name, different binding',{mode:0o600,flag:'wx'}); + assert.equal(realpathSync.native(file),file);assert.equal(dirname(next),roster);renameSync(next,file);conflict(first) + const second=proof();chmodSync(file,0o400);conflict(second) + const third=proof();const retired=join(root,'old-roles');assert.equal(realpathSync.native(roster),roster);assert.equal(dirname(retired),root) + renameSync(roster,retired);mkdirSync(roster,{mode:0o700});writeFileSync(file,'# Replacement',{flag:'wx',mode:0o600});conflict(third) +}) diff --git a/apps/headless/test/skill-store.test.mjs b/apps/headless/test/skill-store.test.mjs new file mode 100644 index 00000000..85f8ad0c --- /dev/null +++ b/apps/headless/test/skill-store.test.mjs @@ -0,0 +1,406 @@ +import assert from 'node:assert/strict' +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { constants, promises as fs } from 'node:fs' +import { createServer } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import test from 'node:test' +import { promisify } from 'node:util' +import { openSettings } from '../src/business/settings.mjs' +import { withSettingsDirectory } from '../src/business/settings-file.mjs' +import { HttpError } from '../src/http/policy.mjs' +import { openSkillLibrary } from '../src/skills/store.mjs' + +const hex = /^[0-9a-f]{64}$/ +const owner = () => true +const execution = 'inactive' +const err = (status, code) => ({ status, code, message: code }) +const invalid = err(400, 'skill_invalid') +const conflict = err(409, 'skill_conflict') +const unconfirmed = err(503, 'skill_storage_unconfirmed') +const readOnly = err(403, 'skill_read_only') +const auth = err(401, 'auth') +const exec = promisify(execFile) + +const builtin = Object.freeze({ id: 'create-skill', name: 'Create Skill', description: 'Built in', source: 'builtin', documentRevision: 'builtin-stamp' }) +const alpha = Object.freeze({ id: 'alpha', name: 'Alpha', description: 'Native', source: 'custom', documentRevision: 'alpha-v1' }) +const beta = Object.freeze({ id: 'beta', name: 'Beta', description: 'Native', source: 'custom', documentRevision: 'beta-v1' }) +const details = { instructions: 'A native document body', trigger: 'When asked', license: 'MIT', compatibility: 'native', + allowedTools: ['inspect'], metadata: { author: 'human' } } + +async function fixture(t, text, mode = 0o600) { + const parent = await fs.mkdtemp(join(tmpdir(), 'deva-skill-prefs-')) + t.after(() => fs.rm(parent, { recursive: true, force: true })) + const dataDir = join(parent, 'data') + await fs.mkdir(dataDir, { mode: 0o700 }) + const path = join(dataDir, 'config.json') + if (text !== undefined) await fs.writeFile(path, text, { mode }) + const records = new Map([builtin, alpha, beta].map(row => [row.id, { ...row, privatePath: '/fixture/private/SKILL.md' }])) + let choices = [{ id: 'general', name: 'General', enabled: true, internalPrompt: 'hidden' }, + { id: 'chosen', name: 'Disabled but known', enabled: false }] + const calls = { list: 0, get: 0, stamps: 0, stamp: 0 } + const documents = { + async list() { calls.list++; return [...records.values()].map(record => ({ ...record })) }, + async get(id) { + calls.get++ + const raw = records.get(id) + return raw ? { ...raw, ...(raw.source === 'custom' ? details : { privateBuiltinBody: 'hidden' }) } : null + }, + async stamps() { calls.stamps++; return [...records.values()].map(({ id, documentRevision }) => ({ id, documentRevision })) }, + async stamp(id) { calls.stamp++; return records.get(id)?.documentRevision ?? null } + } + const options = { dataDir, documents, withRoleChoices: async callback => callback(choices) } + function open(overrides) { + const library = openSkillLibrary({ ...options, ...overrides }) + t.after(() => library.close()) + return library + } + return { parent, dataDir, path, records, calls, options, open, library: open(), setChoices: next => { choices = next } } +} + +const revisionOf = async (library, id = 'alpha') => (await library.get(id)).skill.revision + +function deferred() { + let resolve + const promise = new Promise(done => { resolve = done }) + return { promise, resolve } +} + +test('lazy factory, catalog/detail projections, stable restart receipts, protected builtins and missing native files', async t => { + const { dataDir, library, open, calls } = await fixture(t) + assert.deepEqual(calls, { list: 0, get: 0, stamps: 0, stamp: 0 }) + assert.deepEqual(await fs.readdir(dataDir), []) + const catalog = await library.list() + assert.equal(catalog.execution, execution) + assert.match(catalog.revision, hex) + assert.equal(await library.revision(), catalog.revision) + assert.deepEqual(await open().list(), catalog) + const [built, native, second] = catalog.skills + assert.deepEqual(built, { id: builtin.id, name: builtin.name, description: builtin.description, source: 'builtin', + enabled: true, roles: null, revision: built.revision, canConfigure: false }) + assert.deepEqual(native, { id: alpha.id, name: alpha.name, description: alpha.description, source: 'custom', + enabled: true, roles: null, revision: native.revision, canConfigure: true }) + for (const view of [built, native, second]) assert.match(view.revision, hex) + assert.notEqual(second.revision, native.revision) + assert.deepEqual(await library.get('create-skill'), { skill: { ...built, detail: 'builtin' }, execution }) + assert.deepEqual(await library.get('alpha'), { skill: { ...native, detail: 'document', ...details }, execution }) + assert.deepEqual(await library.get('missing'), { skill: null, execution }) + assert.deepEqual(await library.roles(), { roles: [{ id: 'general', name: 'General', enabled: true }, + { id: 'chosen', name: 'Disabled but known', enabled: false }] }) + await assert.rejects(library.set(built.id, { revision: built.revision, enabled: true }, owner), err(409, 'skill_builtin')) + await assert.rejects(library.set('missing', { revision: native.revision, enabled: false }, owner), err(404, 'skill_not_found')) + assert.deepEqual(await library.set(native.id, { revision: native.revision, enabled: true }, owner), { skill: native, execution }) + assert.deepEqual(await fs.readdir(dataDir), []) + const updated = await library.set(native.id, { revision: native.revision, enabled: false }, owner) + assert.deepEqual(await fs.readdir(dataDir), ['config.json']) + assert.equal((await fs.stat(join(dataDir, 'config.json'))).mode & 0o777, 0o600) + assert.deepEqual(updated, { skill: { ...native, enabled: false, revision: await revisionOf(library) }, execution }) +}) + +test('surgical edits preserve exact unrelated bytes, escaped keys, precision, BOM, and safe legacy permissions', async t => { + const original = '\ufeff{\r\n' + String.raw` "future": {"huge":123456789012345678909876543210,"negative":-0,"exp":3.310000e+31,"float":0.100000000000000009,"pair": ["}\\\"🙂", {"b":"\uD800"}]}, + "sk\u0069lls" : { "private":9999999999999999999990,"enabled" : { "\u0061lpha" : true , "beta": false } , "other":[1, 2] }, + "secret" : "fixture-personal", "z": "\u00E9" }` + '\r\n' + const { path, dataDir, library } = await fixture(t, original, 0o644) + const previous = await fs.stat(path) + const before = await library.list() + assert.equal(before.skills[1].canConfigure, true) + assert.equal(before.skills[2].enabled, false) + const result = await library.set('alpha', { revision: before.skills[1].revision, enabled: false }, owner) + const expected = original.replace(': true , "beta"', ': false , "beta"') + assert.equal(await fs.readFile(path, 'utf8'), expected) + const saved = await fs.stat(path) + assert.notEqual(saved.ino, previous.ino) + assert.equal(saved.mode, previous.mode) + assert.equal(saved.uid, previous.uid) + assert.equal(saved.gid, previous.gid) + assert.equal(result.skill.enabled, false) + assert.equal(result.skill.revision, await revisionOf(library)) + assert.notEqual(before.revision, await library.revision()) + assert.ok(!JSON.stringify(await library.list()).includes('fixture-personal')) + const digest = createHash('sha256').update(expected).digest('hex') + assert.ok(!JSON.stringify(await library.list()).includes(digest)) + assert.deepEqual(await fs.readdir(dataDir), ['config.json']) +}) + +test('native role scopes preserve stale IDs, unset vs empty, and authoritative picked choices', async t => { + const original = '{"skills":{"enabled":{"beta":false},"roles":{ "alpha" : ["retired"] , "beta" : ["retired-two"] },"x":3},"mcp":{"roles":{"alpha":["remote-role"]}}}' + const { path, library, setChoices } = await fixture(t, original) + const before = await library.get('alpha') + assert.deepEqual(before.skill.roles, ['retired']) + await assert.rejects(library.set('alpha', { revision: before.skill.revision, roles: ['retired', 'new-unknown'] }, owner), err(409, 'skill_unknown_role')) + assert.equal(await fs.readFile(path, 'utf8'), original) + const preserved = await library.set('alpha', { revision: before.skill.revision, roles: ['retired', 'general'] }, owner) + assert.deepEqual(preserved.skill.roles, ['retired', 'general']) + assert.equal(await fs.readFile(path, 'utf8'), original.replace('["retired"]', '["retired","general"]')) + const none = await library.set('alpha', { revision: preserved.skill.revision, roles: [] }, owner) + assert.deepEqual(none.skill.roles, []) + assert.equal(await fs.readFile(path, 'utf8'), original.replace('["retired"]', '[]')) + const picked = await library.set('alpha', { revision: none.skill.revision, roles: ['chosen', 'general'] }, owner) + assert.deepEqual(picked.skill.roles, ['chosen', 'general']) + const pickedText = original.replace('["retired"]', '["chosen","general"]') + assert.equal(await fs.readFile(path, 'utf8'), pickedText) + const current = await fs.stat(path) + assert.deepEqual(await library.set('alpha', { revision: picked.skill.revision, roles: ['chosen', 'general'] }, owner), picked) + assert.equal((await fs.stat(path)).ino, current.ino) + setChoices([{ id: 'general', name: 'General', enabled: true }]) + assert.deepEqual((await library.get('alpha')).skill.roles, ['chosen', 'general']) + await assert.rejects(library.set('alpha', { revision: picked.skill.revision, roles: ['chosen', 'retired'] }, owner), err(409, 'skill_unknown_role')) + assert.deepEqual(await library.set('alpha', { revision: picked.skill.revision, roles: ['chosen', 'general'] }, owner), picked) + const all = await library.set('alpha', { revision: picked.skill.revision, roles: null }, owner) + assert.equal(all.skill.roles, null) + assert.equal(await fs.readFile(path, 'utf8'), pickedText.replace('"alpha" : ["chosen","general"] ,', ' ')) + assert.deepEqual((await library.get('beta')).skill.roles, ['retired-two']) +}) + +test('strict config/ID-bound revisions reject old logins, replaced docs/config and no-op stale retries', async t => { + const { dataDir, path, library, open, records } = await fixture(t, '{"future":"same bytes"}') + const old = await revisionOf(library) + const secondLogin = open() + const different = await revisionOf(secondLogin, 'beta') + await assert.rejects(secondLogin.set('alpha', { revision: different, enabled: true }, owner), conflict) + const disabled = await secondLogin.set('alpha', { revision: old, enabled: false }, owner) + await assert.rejects(library.set('alpha', { revision: old, enabled: false }, owner), conflict) + const config = await fs.readFile(path) + await fs.writeFile(join(dataDir, 'replacement'), config, { mode: 0o600 }) + await fs.rename(join(dataDir, 'replacement'), path) + await assert.rejects(library.set('alpha', { revision: disabled.skill.revision, enabled: false }, owner), conflict) + const current = await revisionOf(library) + records.get('alpha').documentRevision = 'replacement-document' + await assert.rejects(library.set('alpha', { revision: current, enabled: false }, owner), conflict) + const restarted = await library.list() + const moduleUrl = new URL('../src/skills/store.mjs', import.meta.url).href + const { stdout } = await exec(process.execPath, ['--input-type=module', '--eval', ` + import { openSkillLibrary } from ${JSON.stringify(moduleUrl)} + const rows = ${JSON.stringify([...records.values()])} + const documents = { list: () => rows, stamps: () => rows, stamp: () => null, get: () => null } + const library = openSkillLibrary({ dataDir: ${JSON.stringify(dataDir)}, documents, withRoleChoices: cb => cb([]) }) + console.log(JSON.stringify({ revision: await library.revision(), list: await library.list() })) + `]) + assert.deepEqual(JSON.parse(stdout), { revision: restarted.revision, list: restarted }) +}) + +test('validated shapes, request caps and unsupported native scopes fail closed', async t => { + const { path, library } = await fixture(t, '{"skills":{"roles":{"alpha":[]}}}') + const revision = await revisionOf(library) + for (const change of [{ enabled: true }, { revision, enabled: 1 }, { revision, enabled: false, roles: null }, + { revision, roles: [null] }, { revision, roles: [''] }, { revision, roles: ['general', 'general'] }, + { revision, roles: new Array(1) }, { revision: revision + '\n', enabled: true }, { revision, roles: {} }]) { + await assert.rejects(library.set('alpha', change, owner), invalid) + } + await assert.rejects(library.get('constructor'), invalid) + await assert.rejects(library.get('alpha\n'), invalid) + await assert.rejects(library.get('../alpha'), invalid) + await assert.rejects(library.set('alpha', { revision, roles: Array.from({ length: 65 }, (_, i) => `id-${i}`) }, owner), err(413, 'skill_limit')) + for (const native of ['{"skills":[],"password":"fixture-private"}', '{"skills":{"roles":{"alpha":[null]}}}', + '{"skills":{"roles":{"alpha":null}}}', '{"skills":{},"sk\\u0069lls":{}}', + '{"skills":{"roles":{"alpha":[],"\\u0061lpha":[]}}}', '{"skills":{},}']) { + await fs.writeFile(path, native) + await assert.rejects(library.get('alpha'), err(409, 'skill_unsupported')) + assert.equal(await fs.readFile(path, 'utf8'), native) + } + const max = 4 * 1024 * 1024 + await fs.writeFile(path, '{}' + ' '.repeat(max - 1)) + await assert.rejects(library.get('alpha'), err(413, 'skill_limit')) + await fs.writeFile(path, '{}' + ' '.repeat(max - 2)) + const atLimit = await revisionOf(library) + await assert.rejects(library.set('alpha', { revision: atLimit, enabled: false }, owner), err(413, 'skill_limit')) + assert.equal((await fs.stat(path)).size, max) +}) + +test('original owner is rechecked, vetoes both no-op and staged writes, and native exceptions stay private', async t => { + const original = '{"private":"fixture-private"}' + const { path, dataDir, library } = await fixture(t, original) + const revision = await revisionOf(library) + for (const verify of [undefined, () => false, async () => true, () => { throw Error('/native/private/path') }]) { + await assert.rejects(library.set('alpha', { revision, enabled: false }, verify), auth) + } + for (const enabled of [true, false]) { + let calls = 0 + await assert.rejects(library.set('alpha', { revision, enabled }, id => { + assert.equal(id, 'alpha') + if (++calls > 1) throw Error('original owner revoked, newer login active') + }), auth) + assert.equal(calls, 2) + assert.equal(await fs.readFile(path, 'utf8'), original) + assert.deepEqual(await fs.readdir(dataDir), ['config.json']) + } + let final = 0 + await assert.rejects(library.set('alpha', { revision, enabled: false }, () => ++final < 3), auth) + assert.equal(final, 3) + assert.equal(await fs.readFile(path, 'utf8'), original) +}) + +test('read-only mode remains inspectable, preserves exact bytes, and root replacement cannot publish', async t => { + const original = '{"unrelated":true}' + const { dataDir, parent, path, library } = await fixture(t, original, 0o400) + const current = (await library.get('alpha')).skill + assert.equal(current.canConfigure, false) + await assert.rejects(library.set('alpha', { revision: current.revision, enabled: false }, owner), readOnly) + assert.equal(await fs.readFile(path, 'utf8'), original) + await fs.chmod(path, 0o600) + await fs.chmod(dataDir, 0o500) + const parentLocked = (await library.get('alpha')).skill + assert.equal(parentLocked.canConfigure, false) + await assert.rejects(library.set('alpha', { revision: parentLocked.revision, enabled: false }, owner), readOnly) + await fs.chmod(dataDir, 0o700) + await fs.rename(dataDir, join(parent, 'original-root')) + await fs.mkdir(dataDir, { mode: 0o700 }) + await assert.rejects(library.set('alpha', { revision: parentLocked.revision, enabled: false }, owner), conflict) + assert.deepEqual(await fs.readdir(dataDir), []) +}) + +test('role serial is outermost; stale authoritative roster and document/env mutations veto writes', { timeout: 5000 }, async t => { + const original = '{"unrelated":true}' + const { dataDir, path, open, records } = await fixture(t, original) + const library = open({ async withRoleChoices(action) { + const choices = await withSettingsDirectory(dataDir, null, async () => [{ id: 'general', name: 'General', enabled: true }]) + return action(choices, () => { throw new HttpError(409, 'skill_conflict') }) + } }) + const revision = await revisionOf(library) + await assert.rejects(library.set('alpha', { revision, roles: ['general'] }, owner), conflict) + assert.equal(await fs.readFile(path, 'utf8'), original) + assert.deepEqual(await fs.readdir(dataDir), ['config.json']) + let authCalls = 0 + await assert.rejects(library.set('alpha', { revision, enabled: false }, () => { + if (++authCalls === 2) records.get('alpha').documentRevision = 'new-native-document' + return true + }), conflict) + assert.equal(await fs.readFile(path, 'utf8'), original) + const newRev = await revisionOf(library) + const replace = fs.rename.bind(fs) + t.mock.method(fs, 'rename', async (from, to) => { + await replace(from, to) + if (from.includes('.config.')) records.get('alpha').documentRevision = 'changed-after-publish' + }) + await assert.rejects(library.set('alpha', { revision: newRev, enabled: false }, owner), unconfirmed) + assert.equal(JSON.parse(await fs.readFile(path, 'utf8')).skills.enabled.alpha, false) + assert.deepEqual(await fs.readdir(dataDir), ['config.json']) +}) + +test('checks roster changes and the original owner again before confirming a visible publication', async t => { + const { path, open, library } = await fixture(t, '{"other":true}') + let verifies = 0 + const roles = open({ async withRoleChoices(action) { + return action([{ id: 'general', name: 'General', enabled: true }], () => { + if (++verifies === 2) throw new HttpError(409, 'skill_conflict') + }) + } }) + const revision = await revisionOf(roles) + await assert.rejects(roles.set('alpha', { revision, roles: ['general'] }, owner), unconfirmed) + assert.equal(verifies, 2) + assert.deepEqual(JSON.parse(await fs.readFile(path, 'utf8')).skills.roles.alpha, ['general']) + let authChecks = 0 + await assert.rejects(library.set('alpha', { revision: await revisionOf(library), enabled: false }, () => ++authChecks < 4), auth) + assert.equal(authChecks, 4) + assert.equal(JSON.parse(await fs.readFile(path, 'utf8')).skills.enabled.alpha, false) +}) + +test('shared settings inode queue serializes edits and sibling preferences survive', { timeout: 5000 }, async t => { + const { dataDir, path, open, options } = await fixture(t, '{"skills":{"roles":{"alpha":["general"]},"enabled":{"beta":false}},"mcp":{"ready":true}}') + const hold = deferred(), release = deferred() + const readList = options.documents.list.bind(options.documents) + let pause = false + options.documents.list = async () => { + if (pause) { hold.resolve(); await release.promise } + return readList() + } + const library = open() + const settings = await openSettings({ dataDir }) + const revision = await revisionOf(library) + pause = true + const skillWrite = library.set('alpha', { revision, enabled: false }, owner) + await hold.promise + const siblingWrite = settings.patch({ set: { theme: 'dark' } }) + release.resolve() + assert.equal((await skillWrite).skill.enabled, false) + assert.equal((await siblingWrite).theme, 'dark') + const current = JSON.parse(await fs.readFile(path, 'utf8')) + assert.deepEqual(current, { theme: 'dark', skills: { roles: { alpha: ['general'] }, enabled: { beta: false, alpha: false } }, mcp: { ready: true } }) + assert.equal((await library.get('beta')).skill.enabled, false) +}) + +test('idle revision reads config metadata only, ignores root ctime churn, and safely rejects nonregular nodes', async t => { + const { dataDir, path, calls, library } = await fixture(t, '{"private":"exact bytes"}') + const saved = join(dataDir, 'saved-config') + const open = fs.open.bind(fs) + let payloads = 0 + t.mock.method(fs, 'open', async (name, flags, ...rest) => { + if (flags === (constants.O_RDONLY | constants.O_NONBLOCK) && /^\/proc\/self\/fd\/\d+$/.test(name)) payloads++ + return open(name, flags, ...rest) + }) + const baseline = await library.revision() + assert.equal(payloads, 0) + assert.deepEqual(calls, { list: 0, get: 0, stamps: 1, stamp: 0 }) + const { revision } = await library.list() + assert.equal(revision, baseline) + assert.equal(payloads, 1) + await fs.mkdir(join(dataDir, 'unrelated-role-sibling')) + assert.equal(await library.revision(), baseline) + assert.equal(payloads, 1) + + await fs.rename(path, saved) + await fs.symlink(saved, path) + await assert.rejects(library.revision(), err(409, 'skill_unsupported')) + await assert.rejects(library.list(), err(409, 'skill_unsupported')) + await fs.unlink(path) + const socket = createServer() + t.after(() => { socket.close() }) + await new Promise((resolve, reject) => socket.once('error', reject).listen(path, resolve)) + await assert.rejects(library.revision(), err(409, 'skill_unsupported')) + await assert.rejects(library.list(), err(409, 'skill_unsupported')) + assert.equal(payloads, 1) + library.close() + library.close() + await assert.rejects(library.revision(), unconfirmed) +}) + +test('publication only confirms durable readback of the inode it actually staged', async t => { + await t.test('directory fsync failed after rename', async t => { + const { path, dataDir, library } = await fixture(t, '{"future":true}') + const revision = await revisionOf(library) + const nativeRename = fs.rename.bind(fs), nativeOpen = fs.open.bind(fs) + let renamed = false, postRead = false + t.mock.method(fs, 'rename', async (from, to) => { + await nativeRename(from, to) + if (from.includes('.config.')) renamed = true + }) + t.mock.method(fs, 'open', async (path, flags, ...rest) => { + const file = await nativeOpen(path, flags, ...rest) + if (flags === (constants.O_RDONLY | constants.O_NONBLOCK) && renamed) postRead = true + if (flags & constants.O_DIRECTORY) { + const sync = file.sync.bind(file) + file.sync = async () => { + if (renamed) throw Object.assign(new Error('fixture directory failure'), { code: 'EIO' }) + return sync() + } + } + return file + }) + await assert.rejects(library.set('alpha', { revision, enabled: false }, owner), unconfirmed) + assert.equal(renamed, true) + assert.equal(postRead, true) + assert.equal(JSON.parse(await fs.readFile(path, 'utf8')).skills.enabled.alpha, false) + assert.deepEqual(await fs.readdir(dataDir), ['config.json']) + }) + + await t.test('equivalent bytes on foreign inode', async t => { + const { path, dataDir, library } = await fixture(t, '{"future":true}') + const revision = await revisionOf(library) + const nativeRename = fs.rename.bind(fs) + let swapped = false + t.mock.method(fs, 'rename', async (from, to) => { + await nativeRename(from, to) + if (!from.includes('.config.')) return + const alternative = join(dataDir, 'foreign') + await fs.writeFile(alternative, await fs.readFile(path), { mode: 0o600 }) + await nativeRename(alternative, path) + swapped = true + }) + await assert.rejects(library.set('alpha', { revision, enabled: false }, owner), unconfirmed) + assert.equal(swapped, true) + assert.equal(JSON.parse(await fs.readFile(path, 'utf8')).skills.enabled.alpha, false) + assert.deepEqual(await fs.readdir(dataDir), ['config.json']) + }) +}) diff --git a/docs/development/web-workbench/README.md b/docs/development/web-workbench/README.md index 1da0494b..52a210ef 100644 --- a/docs/development/web-workbench/README.md +++ b/docs/development/web-workbench/README.md @@ -1,11 +1,13 @@ # Web Workbench 能力清单与门禁 -[能力清单](./parity-manifest.json)按桌面 [preload 运行时 `const api`](../../../apps/desktop/src/preload/index.ts)逐项登记:**21 组、186 个方法(含 18 个订阅)、1 个值 `platform`**。当前有 **43 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目文件读取 2 项、网页文件选择与粘贴上传 2 项、会话模型与归档及列表订阅 3 项、授权交付清单与定位 2 项、Git 只读能力探测 1 项、项目选择与会话绑定 2 项、原生任务详情与日程预览 2 项、客户端页面全屏状态与订阅 2 项、客户端文本复制与粘贴 2 项、PTY 回收与退出事件 2 项;其余 **139 个 `pending`、4 个 `desktop-only`**。其中 36 个 `pending` 有明确的部分实现和测试记录,103 个仍待实现;这些数不是用户工作流的完成百分比。任务列表按需读取,状态变化目前仅支持对既有活动任务的人工确认暂停;这两项登记为部分覆盖。Git 的已跟踪状态、暂存与工作树差异、分支和首父历史按部分覆盖登记;写入及远程操作仍待移植。交付下载覆盖明确的成品格式;静态图预览与整个桌面缩略图机制仍有差别。空闲会话可以改名;在途改名和非默认思考档位仍属部分覆盖。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。选择授权项目、保存会话关联和手动打开该项目的资料已接通;文件保存仍限于现有文本。角色私有默认目录的创建与完整工具授权未计入。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。单独的 `platform` 值已实现:设置显示经过认证的启动投影中的宿主平台,Linux 容器不会因客户端使用 macOS 而显示为 macOS。浏览器全屏、布局和侧栏快捷键使用客户端状态,而不把宿主平台当作操作电脑。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。 +[能力清单](./parity-manifest.json)按桌面 [preload 运行时 `const api`](../../../apps/desktop/src/preload/index.ts)逐项登记:**21 组、186 个方法(含 18 个订阅)、1 个值 `platform`**。当前有 **47 个 `implemented`**:模型与设置 9 项、个人资料 3 项、分域记忆 4 项、角色管理 7 项、授权项目文件读取 2 项、网页文件选择与粘贴上传 2 项、会话模型与归档及列表订阅 3 项、授权交付清单与定位 2 项、Git 只读能力探测 1 项、项目选择与会话绑定 2 项、原生任务详情与日程预览 2 项、客户端页面全屏状态与订阅 2 项、客户端文本复制与粘贴 2 项、PTY 回收与退出事件 2 项、技能目录及已保存的启用和角色偏好与目录失效订阅 4 项;其余 **135 个 `pending`、4 个 `desktop-only`**。其中 37 个 `pending` 有明确的部分实现和测试记录,98 个仍待实现;这些数不是用户工作流的完成百分比。任务列表按需读取,状态变化目前仅支持对既有活动任务的人工确认暂停;这两项登记为部分覆盖。Git 的已跟踪状态、暂存与工作树差异、分支和首父历史按部分覆盖登记;写入及远程操作仍待移植。交付下载覆盖明确的成品格式;静态图预览与整个桌面缩略图机制仍有差别。空闲会话可以改名;在途改名和非默认思考档位仍属部分覆盖。上传格式与模型协议限制在部署说明中列出;目录拖放及图片缩略资源仍按部分覆盖登记。选择授权项目、保存会话关联和手动打开该项目的资料已接通;文件保存仍限于现有文本。角色私有默认目录的创建与完整工具授权未计入。角色删除可处理未被引用的自定义角色,对受保护的默认角色和已有引用报冲突;未将其列为桌面级联删除已完成。单独的 `platform` 值已实现:设置显示经过认证的启动投影中的宿主平台,Linux 容器不会因客户端使用 macOS 而显示为 macOS。浏览器全屏、布局和侧栏快捷键使用客户端状态,而不把宿主平台当作操作电脑。已有手机版 PWA/relay 和桌面 IPC 都是参照,不是 Workbench 覆盖证明。 通用文本阶段另外给七个 `chat` 条目登记了 `web.partial`:`createSession`、`send`、`abort`、`listSessions`、`loadSession`、`attachSession`、`onEvent`。每项记录已验证范围、专有测试和仍缺的桌面行为;它们仍计入 `pending`,不等同于附件、工具、成员或审批均已接通。[通用文本协议与阶段限制](../../../apps/headless/src/chat/README.md)。 [可选人工浏览器](../../../apps/browser-worker/README.md) 仅对当前真实登录、已绑定会话和工作器页面发放短租约。`browser.getState`、`ready`、`open`、`liveStart`、`liveStop`、`onLiveFrame`、`handoff` 和 `closeTab` 已登记具体人工操作范围,仍按部分覆盖计算。它不是多标签自动化、团队转交,也不是让模型读取人工页面内容。 +**技能管理与技能执行分别计数。** `skills.list` 返回真实来源、启用和角色范围的目录摘要;`setEnabled` 和 `setRoles` 保存原生配置并读回;`onChanged` 向已打开的设置页发送修订号,页面重取列表,断线后重新确认选中的文档。`skills.get` 针对自定义文档已接通,但不下发内置运行指令,因此登记为部分覆盖。导入和删除仍待实现。此处没有把目录偏好登记为 Web 聊天已能执行技能。 + ## 本地与 CI 依赖准备好后,从仓库根目录执行;脚本使用桌面已有的 `typescript` 开发依赖,运行无需网络或启动 Electron: @@ -17,6 +19,10 @@ node --test scripts/workbench/parity.test.mjs 执行 `node scripts/workbench/check-parity.mjs --coverage` 可在校验通过后读到 JSON 报表,按模块区分完整、部分、有待实现、桌面原生四种互斥计数。也可用 `node scripts/workbench/check-parity.mjs --extract` 查看 AST 提取的 JSON(用于人工逐项比对,不改文件)。[门禁](../../../scripts/workbench/check-parity.mjs)对比组名、方法名、IPC 模式/通道和顶层值来源,检查订阅是否返回匹配的清理函数,并校验清单的计数、状态、路径和用例引用。新增、删除、改名、改通道或无法可靠解析的形状均非零退出。仅移动 DTO/类型声明不应影响门禁;方法内部业务、参数/返回类型兼容、授权与端到端行为须由相应业务测试覆盖。 +### 导出可复核的 Excel 验收表 + +在已安装锁定依赖的检出目录里执行 `node scripts/workbench/export-parity-workbook.mjs`。命令按当前 **Git HEAD** 核对真实 preload、清单和每个证据文件:源码与索引或提交内容不一致时退出,避免把工作树里的改动标成已发布版本。输出位于 `test-results/parity-<提交前7位>/`,含总览、逐方法验收、跨功能流程和平台值四张工作表,源码与用例链接固定到完整提交。相同版本和参数可重复执行;已有文件内容不同则原样保留。`--repo owner/repo` 可指定证据链接所属仓库,只有已知 PR 编号时才加 `--pr 15`。仓库的 PR 工作流直接从 PR 的 head commit 生成同一份附件。 + ## 如何维护清单 1. 按 `组名.方法名` 补齐对应条目;`kind` 与 `channel` 记录桌面 IPC 事实,并非 Web RPC 名称。`desktop.surface` 区分 `ui`(链接到实际调用入口)、`bridge-only`(现有桥接,未见调用入口)与 `legacy-bridge`(历史桌面桥)。默认 `host` 在组上,特殊注册/推送位置可逐项覆盖。 diff --git a/docs/development/web-workbench/parity-manifest.json b/docs/development/web-workbench/parity-manifest.json index e8fb46c8..8e5b2437 100644 --- a/docs/development/web-workbench/parity-manifest.json +++ b/docs/development/web-workbench/parity-manifest.json @@ -43,13 +43,13 @@ "name": "skills", "host": "apps/desktop/src/main/services/skills.ts", "methods": [ - {"name":"list","kind":"invoke","channel":"skills:list","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"扩展列表加载技能记录"},"web":{"status":"pending","target":"rpc","semantic":"列出技能来源、启停及可用角色,以区别内置和自定义条目。"}}, - {"name":"get","kind":"invoke","channel":"skills:get","desktop":{"surface":"bridge-only","use":"按 ID 读取单条技能记录的桥接"},"web":{"status":"pending","target":"rpc","semantic":"详情按 ID 查询,保留已删除或不存在的空结果。"}}, + {"name":"list","kind":"invoke","channel":"skills:list","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"扩展列表加载技能记录"},"web":{"status":"implemented","target":"rpc","semantic":"列出技能来源、启停及可用角色,以区别内置和自定义条目。","implementation":{"handler":"apps/headless/src/skills/store.mjs","test":"apps/headless/test/skill-library-http.test.mjs"}}}, + {"name":"get","kind":"invoke","channel":"skills:get","desktop":{"surface":"bridge-only","use":"按 ID 读取单条技能记录的桥接"},"web":{"status":"pending","target":"rpc","semantic":"详情按 ID 查询,保留已删除或不存在的空结果。","partial":{"scope":"按 ID 读取选中的自定义 SKILL.md 及其元数据;缺失返回 null。内置项返回只读目录资料。","remaining":"不向 Web 下发桌面内置元技能的运行指令;此接口也不加载附件、脚本和其他技能资源。","handler":"apps/headless/src/skills/documents.mjs","test":"apps/headless/test/skill-documents.test.mjs"}}}, {"name":"import","kind":"invoke","channel":"skills:import","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"扩展页使用原生文件选择导入技能"},"web":{"status":"pending","target":"upload","semantic":"按技能包格式上传并交宿主验证;保留导入错误码与成功记录。"}}, {"name":"remove","kind":"invoke","channel":"skills:remove","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"移除自定义技能并按结果刷新列表"},"web":{"status":"pending","target":"rpc","semantic":"删除保留来源校验和失败反馈,界面不提前隐藏移除失败的技能。"}}, - {"name":"setEnabled","kind":"invoke","channel":"skills:set-enabled","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"扩展列表切换自定义技能启用态"},"web":{"status":"pending","target":"rpc","semantic":"写入启停后刷新有效状态,并保留内置技能限制。"}}, - {"name":"setRoles","kind":"invoke","channel":"skills:set-roles","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"扩展页设置技能可用角色范围"},"web":{"status":"pending","target":"rpc","semantic":"区分全角色、仅选定角色和空名单;内置项保持只读。"}}, - {"name":"onChanged","kind":"subscription","channel":"skills:changed","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"技能目录变化后更新扩展页全量列表"},"web":{"status":"pending","target":"events","semantic":"订阅列表失效或全快照,断线重连后重新拉取技能目录。"}} + {"name":"setEnabled","kind":"invoke","channel":"skills:set-enabled","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"扩展列表切换自定义技能启用态"},"web":{"status":"implemented","target":"rpc","semantic":"写入启停后刷新有效状态,并保留内置技能限制。","implementation":{"handler":"apps/headless/src/skills/store.mjs","test":"apps/headless/test/skill-store.test.mjs"}}}, + {"name":"setRoles","kind":"invoke","channel":"skills:set-roles","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"扩展页设置技能可用角色范围"},"web":{"status":"implemented","target":"rpc","semantic":"区分全角色、仅选定角色和空名单;内置项保持只读。","implementation":{"handler":"apps/headless/src/skills/store.mjs","test":"apps/headless/test/skill-library-http.test.mjs"}}}, + {"name":"onChanged","kind":"subscription","channel":"skills:changed","desktop":{"surface":"ui","entry":"apps/desktop/src/renderer/src/store/extensions.tsx","use":"技能目录变化后更新扩展页全量列表"},"web":{"status":"implemented","target":"events","semantic":"订阅列表失效或全快照,断线重连后重新拉取技能目录。","implementation":{"handler":"apps/headless/src/skills/changes.mjs","test":"scripts/workbench/e2e-skill-library-browser.mjs"}}} ] }, { diff --git a/scripts/workbench/container-skill-library-probe.mjs b/scripts/workbench/container-skill-library-probe.mjs new file mode 100644 index 00000000..f3af6f9c --- /dev/null +++ b/scripts/workbench/container-skill-library-probe.mjs @@ -0,0 +1,191 @@ +// Fixed probe evaluated by `docker exec` as the image user; neither read nor served from a host mount. +async function probe() { + let stage = 'probe-input' + function check(ok) { if (!ok) throw Error('verification failed') } + const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) + try { + const { createHash, randomBytes } = await import('node:crypto') + const { lstat, mkdir, readFile, readdir, realpath, writeFile } = await import('node:fs/promises') + const { setTimeout: delay } = await import('node:timers/promises') + const { requestControl } = await import('/opt/deva/apps/headless/src/control/socket.mjs') + const [phase] = process.argv.slice(1) + const first = phase === 'first' + check(first || phase === 'second') + const chunks = []; let size = 0 + for await (const bytes of process.stdin) { size += bytes.length; check(size <= 8192); chunks.push(bytes) } + const input = JSON.parse(Buffer.concat(chunks).toString()) + const digest = bytes => createHash('sha256').update(bytes).digest('hex') + const revision = value => typeof value === 'string' && /^[a-f0-9]{64}$/u.test(value) + const origin = 'http://127.0.0.1:8787', web = '/opt/deva/web' + const id = 'proofreading', description = 'Demo document for the installed skill library.' + const instructions = 'Demo text: check punctuation in the selected sentence.' + const document = '/data/skills/proofreading/SKILL.md', config = '/data/config.json', persona = '/data/personas/general.md' + const fixture = `---\nname: ${id}\ndescription: ${description}\n---\n\n${instructions}\n` + const numeric = '"nativeQaMarker":-1.2300e+04' + const privateFile = async path => { + const info = await lstat(path) + check(await realpath(path) === path && info.isFile() && info.uid === 1000 && info.nlink === 1 && (info.mode & 0o077) === 0) + return readFile(path) + } + const http = (path, options) => fetch(origin + path, { redirect: 'error', signal: AbortSignal.timeout(5000), ...options }) + let cookie, csrf + async function api(path, { method = 'GET', body, expected = 200, session = cookie } = {}) { + const res = await http('/api/v1/' + path, { method, + headers: { ...(session ? { cookie: session } : {}), ...(body === undefined ? {} : { + origin, 'content-type': 'application/json', ...(csrf ? { 'x-deva-csrf': csrf } : {}) }) }, + body: body === undefined ? undefined : JSON.stringify(body) }) + check(res.status === expected && res.headers.get('content-type') === 'application/json; charset=utf-8') + return { payload: await res.json(), cookie: res.headers.get('set-cookie')?.split(';', 1)[0] } + } + + stage = 'ready-and-isolation' + let ready = false + const readyBy = performance.now() + 12_000 + while (!ready && performance.now() < readyBy) { + try { const r = await http('/readyz', { signal: AbortSignal.timeout(750) }); ready = r.status === 200 && (await r.json()).status === 'ready' } + catch { /* The default CLI may still be opening the volumes and compiled bundle. */ } + if (!ready) await delay(125) + } + check(ready && process.platform === 'linux' && process.arch === 'x64' && process.getuid() === 1000) + check((await readFile('/proc/1/cmdline', 'utf8')) === 'node\0/opt/deva/apps/headless/src/cli.mjs\0serve\0') + const status = await readFile('/proc/1/status', 'utf8') + check(/^Uid:\s+1000\s+1000\s+1000\s+1000$/m.test(status) && /^NoNewPrivs:\s+1$/m.test(status) && + ['Eff', 'Prm', 'Bnd', 'Amb'].every(key => new RegExp(`^Cap${key}:\\s+0+$`, 'm').test(status))) + const mounts = (await readFile('/proc/1/mountinfo', 'utf8')).split('\n').map(line => line.split(' ')) + check([['/', 'ro'], ['/data', 'rw'], ['/keys', 'ro']].every(([mount, mode]) => + mounts.some(v => v[4] === mount && v[5].split(',').includes(mode))) && same(await readdir('/sys/class/net'), ['lo'])) + const key = await lstat('/keys/master.key') + check(key.isFile() && key.uid === 1000 && key.size === 32 && (key.mode & 0o777) === 0o600) + + let initialConfig + if (first) { + stage = 'native-fixture' + initialConfig = JSON.parse(await privateFile(config)) + check(!Object.hasOwn(initialConfig, 'skills') && !Object.hasOwn(initialConfig, 'nativeQaMarker')) + initialConfig.skills = { enabled: { [id]: false }, roles: {} } + await mkdir('/data/skills', { mode: 0o700 }) + await mkdir('/data/skills/proofreading', { mode: 0o700 }) + await writeFile(document, fixture, { mode: 0o600, flag: 'wx' }) + await writeFile(config, JSON.stringify(initialConfig).slice(0, -1) + ',' + numeric + '}\n') + initialConfig.nativeQaMarker = -12300 + } + + stage = 'http-owner-session' + const password = first ? randomBytes(24).toString('base64url') : input.password + check(typeof password === 'string' && /^[A-Za-z0-9_-]{32}$/u.test(password)) + const state = await api('auth/state') + check(state.payload.claimed === !first) + if (!first) check(/^deva-workbench-local=[A-Za-z0-9_-]{43}$/u.test(input.cookie)) + const stale = await api('skills', { session: first ? undefined : input.cookie, expected: 401 }) + check(stale.payload.error === 'auth') + const auth = first + ? await api('auth/claim', { method: 'POST', body: { password, credential: (await requestControl({ runDir: '/run/deva', op: 'claim' })).credential } }) + : await api('auth/login', { method: 'POST', body: { password } }) + cookie = auth.cookie; csrf = auth.payload.csrf + check(/^deva-workbench-local=[A-Za-z0-9_-]{43}$/u.test(cookie) && cookie !== input.cookie && typeof csrf === 'string' && csrf.length > 0) + + stage = 'catalog-role-and-detail' + const noInstructions = payload => { + const wire = JSON.stringify(payload) + check(!wire.includes(instructions) && !wire.includes('"instructions"') && !wire.includes('/data/') && !wire.includes('nativeQaMarker')) + } + const boot = (await api('bootstrap')).payload + check(boot.capabilities.skillLibrary === true && boot.capabilities.terminalViewer === false && + boot.capabilities.browserPanel === false && boot.capabilities.workspaceFiles === false && !Object.hasOwn(boot, 'skills')) + noInstructions(boot) + const roster = (await api('skills/-/roles')).payload + check(same(roster, { roles: [{ id: 'general', name: 'General', enabled: true }] })) + const role = (await api('personas/general')).payload.role + check(role.id === 'general' && role.name === 'General' && role.enabled === true && role.protected === true && + role.workspaceId === '' && !Object.hasOwn(role, 'skills') && !Object.hasOwn(role, 'allowedTools') && !JSON.stringify(role).includes(id)) + const list = async () => { + const body = (await api('skills')).payload + check(body.execution === 'inactive' && revision(body.revision) && body.skills.every(v => revision(v.revision))) + check(body.skills.filter(v => v.source === 'custom').length === 1 && body.skills.some(v => v.source === 'builtin' && !v.canConfigure)) + noInstructions(body) + return body + } + const selected = async (catalog, enabled, roles) => { + const row = catalog.skills.find(v => v.id === id) + check(row?.name === id && row.description === description && row.source === 'custom' && row.canConfigure === true && + row.enabled === enabled && same(row.roles, roles)) + const detail = (await api('skills/' + id)).payload + check(detail.execution === 'inactive' && detail.skill.detail === 'document' && detail.skill.instructions === instructions && + same(detail.skill.allowedTools, []) && !JSON.stringify(detail).includes('/data/') && + Object.entries(row).every(([key, value]) => same(detail.skill[key], value))) + return detail + } + const initial = await list() + const detail = await selected(initial, !first, first ? null : ['general']) + + let writeRevision + if (first) { + stage = 'confirmed-preference-patches' + const patch = async (before, edit, scope) => { + const result = (await api('skills/' + id + '/preferences', { method: 'PATCH', body: { revision: before.revision, ...edit } })).payload + check(result.execution === 'inactive' && result.skill.enabled === true && same(result.skill.roles, scope) && + revision(result.skill.revision) && result.skill.revision !== before.revision) + noInstructions(result) + return result.skill + } + const enabled = await patch(detail.skill, { enabled: true }, null) + writeRevision = (await patch(enabled, { roles: ['general'] }, ['general'])).revision + initialConfig.skills = { enabled: { [id]: true }, roles: { [id]: ['general'] } } + } + + stage = 'native-bytes-and-fresh-revision' + const catalog = await list() + const confirmed = await selected(catalog, true, ['general']) + if (first) check(catalog.revision !== initial.revision && confirmed.skill.revision === writeRevision) + const bytes = await privateFile(config), persisted = JSON.parse(bytes) + check(bytes.includes(numeric) && same(persisted.skills, { enabled: { [id]: true }, roles: { [id]: ['general'] } }) && + (!first || same(persisted, initialConfig))) + const source = digest(await privateFile(document)), nativeRole = digest(await privateFile(persona)) + check(source === digest(fixture) && same(await readdir('/data/skills'), [id]) && same(await readdir('/data/skills/proofreading'), ['SKILL.md'])) + const stable = row => { const { revision: _, ...rest } = row; return rest } + const evidence = { config: digest(bytes), source, nativeRole, skills: catalog.skills.map(stable), detail: stable(confirmed.skill), roster } + if (!first) { + check(same(evidence, input.evidence)) + const cursor = (await api('skills/-/changes', { method: 'POST', body: { after: catalog.revision, waitMs: 0 } })).payload + check(cursor.changed === false && cursor.revision === catalog.revision) + } + + if (first) { + stage = 'packaged-web-entry-assets' + async function asset(path, type) { + const res = await http('/' + path) + check(res.status === 200 && res.headers.get('content-type') === `${type}; charset=utf-8` && res.headers.get('x-content-type-options') === 'nosniff') + const served = Buffer.from(await res.arrayBuffer()) + check(served.length > 0 && served.equals(await readFile(web + '/' + (path || 'index.html')))) + return { text: served.toString(), csp: res.headers.get('content-security-policy') } + } + const page = await asset('', 'text/html') + const policy = page.csp?.split('; ') + check(/ policy?.includes(v))) + const manifest = JSON.parse(await readFile(web + '/manifest.json', 'utf8')) + const scripts = [...page.text.matchAll(/]*\bsrc="\.\/(assets\/[\w-]+-[\w-]{6,}\.js)"[^>]*><\/script>/gu)].map(m => m[1]) + check(scripts.length > 0 && scripts.length <= 6 && scripts.length === (page.text.match(/ Object.values(manifest).some(row => row.file === file)) && scripts.some(file => /^assets\/index-/u.test(file))) + for (const file of scripts) await asset(file, 'text/javascript') + const skill = manifest['skill-library.tsx'] + check(manifest['desktop-settings.tsx']?.dynamicImports?.includes('skill-library.tsx') && skill?.isDynamicEntry === true && + /^assets\/[\w-]+-[\w-]{6,}\.js$/u.test(skill.file) && skill.css?.length > 0 && skill.css.length <= 6) + await asset(skill.file, 'text/javascript') + let css = '' + for (const file of skill.css) { + check(/^assets\/[\w-]+-[\w-]{6,}\.css$/u.test(file)) + css += (await asset(file, 'text/css')).text + } + check(css.includes('.wb-skill')) + } + stage = 'idle-runtime' + check((await readFile('/proc/1/task/1/children', 'utf8')).trim() === '') + // The parent consumes this only from a private pipe and passes it to the second probe via stdin. + process.stdout.write(JSON.stringify(first ? { password, cookie, evidence } : { verified: true })) + } catch { + process.stderr.write(`skill-library probe: ${stage}\n`) + process.exitCode = 1 + } +} + +export const probeProgram = `await (${probe.toString()})();` diff --git a/scripts/workbench/container-skill-library.mjs b/scripts/workbench/container-skill-library.mjs new file mode 100644 index 00000000..fd1c9ca8 --- /dev/null +++ b/scripts/workbench/container-skill-library.mjs @@ -0,0 +1,181 @@ +// Native hosted Linux/amd64 gate. Requires only Node, the local Docker socket, and the prebuilt tag. +import { execFile } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import { lstat, mkdtemp, realpath, rmdir } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { probeProgram } from './container-skill-library-probe.mjs' + +const tag = 'deva-workbench:skills-verify' +const cli = '/opt/deva/apps/headless/src/cli.mjs' +const project = `deva-skill-ci-${randomUUID()}` +const labelKey = 'deva.workbench.skill-library-ci' +const label = `${labelKey}=${project}` +const names = Object.fromEntries(['data', 'keys', 'init', 'first', 'second'].map(kind => [kind, `${project}-${kind}`])) +const ids = new Map(), volumes = new Map(), volumeTokens = new Map() +const fullId = /^[a-f0-9]{64}$/u +const same = (a, b) => JSON.stringify(a) === JSON.stringify(b) +const lines = text => text.split('\n').filter(Boolean) +class Failure extends Error {} +function check(ok, message) { if (!ok) throw new Failure(message) } +let root, rootIdentity, image, stage = 'runner preflight' + +function docker(args, { input, logs = false } = {}) { + return new Promise((resolve, reject) => { + // Ignore the runner's Docker contexts, default credential stores, proxies and CI environment. + const child = execFile('docker', ['--host=unix:///var/run/docker.sock', ...args], { + env: { PATH: '/usr/bin:/bin:/usr/local/bin', LANG: 'C.UTF-8', DOCKER_CONFIG: root }, cwd: root, + encoding: 'utf8', timeout: 45_000, maxBuffer: 512 * 1024 + }, (error, out, err) => { + if (!error) return resolve(logs ? (out + err).trim() : out.trim()) + // Arguments, output and thrown causes can contain private probe data. Expose only fixed phase labels. + const probe = /^skill-library probe: ([a-z-]{1,32})$/mu.exec(err)?.[1] + const cause = error.code === 'ENOENT' ? 'Docker executable missing' : error.killed ? 'Docker command timed out' : 'Docker command failed' + reject(new Failure(probe ? `probe failed at ${probe}` : `${args[0]}: ${cause}`)) + }) + child.stdin.on('error', () => {}) + child.stdin.end(input === undefined ? undefined : JSON.stringify(input)) + }) +} +async function inspect(kind, id) { + const result = JSON.parse(await docker([kind, 'inspect', id])) + check(Array.isArray(result) && result.length === 1, `Expected one ${kind}`) + return result[0] +} +const listContainers = filter => docker(['container', 'ls', '-aq', '--no-trunc', '--filter', filter]).then(lines) +const listVolumes = filter => docker(['volume', 'ls', '-q', '--filter', filter]).then(lines) +const containerName = kind => `name=^/${names[kind]}$` + +async function ownedVolume(kind) { + const name = names[kind], volume = await inspect('volume', name) + const signature = [volume.CreatedAt, volume.Mountpoint] + check(volume.Name === name && volume.Labels?.[labelKey] === project && volume.Labels?.[labelKey + '.volume'] === volumeTokens.get(kind) && + volume.Driver === 'local' && volume.Scope === 'local' && !Object.keys(volume.Options ?? {}).length && + Number.isFinite(Date.parse(signature[0])) && signature[1]?.startsWith('/') && + (!volumes.has(kind) || same(volumes.get(kind), signature)), 'Volume identity changed') + return signature +} +async function createVolume(kind) { + const name = names[kind] + check(!(await listVolumes(`name=^${name}$`)).length, 'Volume name already exists') + const token = randomUUID() + volumeTokens.set(kind, token) + check(await docker(['volume', 'create', '--driver', 'local', '--label', label, '--label', `${labelKey}.volume=${token}`, name]) === name, + 'Volume creation was unconfirmed') + volumes.set(kind, await ownedVolume(kind)) +} +async function ownedContainer(id) { + check(fullId.test(id), 'Invalid container ID') + const meta = await inspect('container', id) + const kind = ['init', 'first', 'second'].find(key => meta.Name === '/' + names[key]) + check(kind && meta.Id === id && meta.Image === image.Id && meta.Config.Labels?.[labelKey] === project && + (!ids.has(kind) || ids.get(kind) === id), 'Container identity changed') + return meta +} +const mount = (kind, ro) => `type=volume,src=${names[kind]},dst=/${kind}${ro ? ',readonly' : ''}` +async function createContainer(kind) { + const init = kind === 'init' + check(!(await listContainers(containerName(kind))).length, 'Container name already exists') + await ownedVolume('data'); await ownedVolume('keys') + const id = await docker(['create', '--name', names[kind], '--label', label, '--platform', 'linux/amd64', + '--network', 'none', '--user', '1000:1000', '--read-only', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true', + '--init=false', '--pids-limit', '128', '--log-driver', 'local', + '--tmpfs', '/tmp:rw,nosuid,nodev,noexec,mode=1777,size=64m', + '--tmpfs', '/run/deva:rw,nosuid,nodev,noexec,mode=0700,uid=1000,gid=1000,size=4m', + '--mount', mount('data', init), '--mount', mount('keys', !init), image.Id, ...(init ? ['init-key'] : [])]) + check(fullId.test(id), 'Container creation was unconfirmed') + check(![...ids.values()].includes(id), 'Container ID was reused') + ids.set(kind, id) + const m = await ownedContainer(id), h = m.HostConfig + await ownedVolume('data'); await ownedVolume('keys') + check(m.Path === 'node' && same(m.Args, [cli, init ? 'init-key' : 'serve']) && same(m.Config.Env, image.Config.Env) && + m.Config.User === '1000:1000' && h.NetworkMode === 'none' && h.ReadonlyRootfs && !h.Privileged && + same(h.CapDrop, ['ALL']) && !h.CapAdd?.length && h.SecurityOpt.includes('no-new-privileges:true') && + !h.PublishAllPorts && !Object.keys(h.PortBindings ?? {}).length && !h.Binds?.length && !h.VolumesFrom?.length && + !h.Devices?.length && !h.DeviceRequests?.length, 'Container isolation or default command differs') + const mounts = m.Mounts.filter(v => v.Type === 'volume') + check(mounts.length === 2 && ['data', 'keys'].every(key => mounts.some(v => v.Name === names[key] && v.Destination === '/' + key && + v.Driver === 'local' && v.Source === volumes.get(key)[1] && v.RW === (key === 'data' ? !init : init))) && + m.Mounts.every(v => v.Type === 'volume' || (v.Type === 'tmpfs' && Object.hasOwn(h.Tmpfs, v.Destination))), 'Unexpected container mounts') + return id +} +async function removeContainer(id, kind) { + const before = await ownedContainer(id) + if (before.State.Running) await docker(['stop', '--time', '12', id]) + const after = await ownedContainer(id) + check(!after.State.Running, 'Owned container is still running') + if (kind) check(after.State.Status === 'exited' && after.State.ExitCode === 0 && !after.State.OOMKilled, 'Production CLI did not close cleanly') + if (kind && kind !== 'init') { + // An exact benign banner also catches credentials in either app log stream without exposing them. + check(await docker(['logs', id], { logs: true }) === 'Workbench listening on 127.0.0.1:8787 for http://127.0.0.1:8787', + 'Unexpected production CLI log output') + } + await docker(['rm', id]) + if (kind) check(!(await listContainers(containerName(kind))).length, 'Stopped container was not removed') +} +async function runProbe(kind, input) { + const id = await createContainer(kind) + await docker(['start', id]) + check((await ownedContainer(id)).State.Running, 'Production CLI is not running') + const result = JSON.parse(await docker(['exec', '-i', id, 'node', '--input-type=module', '--eval', probeProgram, kind], { input })) + await removeContainer(id, kind) + return result +} +async function cleanup() { + let failed = false + if (volumeTokens.size) { + for (const id of await listContainers('label=' + label).catch(() => { failed = true; return [] })) { + try { await removeContainer(id) } catch { failed = true } + } + for (const name of await listVolumes('label=' + label).catch(() => { failed = true; return [] })) { + try { + const kind = ['data', 'keys'].find(key => names[key] === name) + check(kind && volumeTokens.has(kind), 'Unrecognized owned volume') + await ownedVolume(kind) + await docker(['volume', 'rm', name]) + } catch { failed = true } + } + check(!failed && !(await listContainers('label=' + label)).length && !(await listVolumes('label=' + label)).length && + !(await Promise.all([...ids.keys()].map(key => listContainers(containerName(key))))).flat().length && + !(await Promise.all([...volumeTokens.keys()].map(key => listVolumes(`name=^${names[key]}$`)))).flat().length, 'Docker cleanup unconfirmed') + } +} +async function main() { + check(process.argv.length === 2 && process.platform === 'linux' && process.arch === 'x64' && process.getuid() > 0, 'Expected nonroot Linux/amd64 runner') + root = await mkdtemp(join(await realpath(tmpdir()), 'deva-skill-docker-')) + rootIdentity = await lstat(root, { bigint: true }) + const server = JSON.parse(await docker(['version', '--format', '{{json .Server}}'])) + check(server.Os === 'linux' && server.Arch === 'amd64', 'Expected a native Linux/amd64 Docker Engine') + const built = await inspect('image', tag) + check(built.Os === 'linux' && built.Architecture === 'amd64' && /^sha256:[a-f0-9]{64}$/u.test(built.Id) && + Number.isSafeInteger(built.Size) && built.Size > 0 && same(built.Config.Entrypoint, ['node', cli]) && same(built.Config.Cmd, ['serve']) && + built.Config.Env.includes('NODE_ENV=production') && same(built.Config.Env.filter(v => v.startsWith('DEVA_')).sort(), [ + 'DEVA_HOME=/data', 'DEVA_HOST=127.0.0.1', 'DEVA_MASTER_KEY_FILE=/keys/master.key', 'DEVA_PORT=8787', + 'DEVA_RUN_DIR=/run/deva', 'DEVA_WEB_DIR=/opt/deva/web']), 'Expected the prebuilt production runtime image') + image = built + stage = 'provision private volumes and key' + await createVolume('data'); await createVolume('keys') + const init = await createContainer('init') + check(await docker(['start', '--attach', init]) === 'Master key ready', 'CLI master key initialization unconfirmed') + await removeContainer(init, 'init') + stage = 'first production container' + const first = await runProbe('first', {}) + stage = 'recreated production container' + const second = await runProbe('second', first) + check(second?.verified === true && ids.get('first') !== ids.get('second'), 'Recreation was unconfirmed') +} +let passed = false +try { await main(); passed = true } +catch (error) { console.error(`Skill library image gate (${stage}): ${error instanceof Failure ? error.message : 'verification failed'}`) } +try { await cleanup() } +catch { passed = false; console.error('Skill library Docker cleanup unconfirmed') } +try { + if (root) { + const now = await lstat(root, { bigint: true }) + check(await realpath(root) === root && now.isDirectory() && now.ino === rootIdentity?.ino && now.dev === rootIdentity?.dev && + now.uid === BigInt(process.getuid()) && (now.mode & 0o777n) === 0o700n, 'Docker configuration directory identity changed') + await rmdir(root) // Private empty configuration directory only; no recursive deletion. + } +} catch { passed = false; console.error('Skill library private directory cleanup unconfirmed') } +if (passed) console.log(`PASS skill library ${image.Id} (${image.Size} bytes, linux/amd64); CLI ${ids.get('first').slice(0, 12)} → ${ids.get('second').slice(0, 12)}; authenticated native persistence, stale cookie revoked, packaged web/CSP; zero residual owned containers or volumes.`) +else process.exitCode = 1 diff --git a/scripts/workbench/e2e-skill-library-browser.mjs b/scripts/workbench/e2e-skill-library-browser.mjs new file mode 100644 index 00000000..e4059085 --- /dev/null +++ b/scripts/workbench/e2e-skill-library-browser.mjs @@ -0,0 +1,406 @@ +import { constants } from 'node:fs' +import { lstat, mkdir, open, realpath } from 'node:fs/promises' +import { dirname } from 'node:path' +import { fileURLToPath } from 'node:url' +import { builtinIds, check, guide, marker, notes, revisedGuide, roleName, SkillCheckError } from './e2e-skill-library-fixture.mjs' +import { waitFor, WebDriverError } from './webdriver-local.mjs' + +const id = name => `[data-testid="workbench-${name}"]` +const skill = name => id(`skill-${name}`) +const panel = id('skills-panel'), detail = skill('detail'), instructions = skill('instructions') +const row = sid => `${skill('row')}[data-skill-id="${sid}"]` +const toggle = sid => `${row(sid)} ${skill('toggle')} button[aria-pressed]` +const passwordField = mode => `.wb-auth input[type="password"][name="password"][autocomplete="${mode}-password"]` +const mode = value => `${skill('role-mode')}[data-role-mode="${value}"]` +const option = role => `${skill('role-option')}[data-role-id="${role}"]` +const api = '/api/v1', listPath = `${api}/skills`, selectedPath = `${listPath}/${guide.id}` +const changesPath = `${listPath}/-/changes`, rolesPath = `${listPath}/-/roles`, patchPath = `${selectedPath}/preferences` +const revision = value => typeof value === 'string' && /^[0-9a-f]{64}$/.test(value) +const sameRoles = (actual, expected) => expected === null ? actual === null : Array.isArray(actual) && + actual.length === expected.length && [...expected].every(role => actual.includes(role)) +const wait = (ctx, probe, description, timeout) => waitFor(probe, description, { signal: ctx.signal, timeout }) +const observe = (ctx, script, ...args) => ctx.browser.execute(script, ...args) +const present = (ctx, selector, description) => wait(ctx, () => observe(ctx, ` + return [...document.querySelectorAll(arguments[0])].find(node => node.getClientRects().length && + getComputedStyle(node).visibility === 'visible' && !node.matches(':disabled')) ?? null; +`, selector), description) +async function click(ctx, selector, description) { + try { await ctx.browser.click(await present(ctx, selector, description)) } catch (error) { + if (error instanceof WebDriverError) throw new WebDriverError(description, error.detail) + throw error + } +} +const gone = (ctx, selector, description) => wait(ctx, () => observe(ctx, 'return !document.querySelector(arguments[0]);', selector), description) + +// Explicit readbacks only. No cookie/CSRF values leave the browser, and this helper has no +// preference mutation route. POST changes is the read-only cursor check, not a UI action. +function readBack(ctx, path, after = null) { + return ctx.browser.executeAsync(` + const [path, after, done] = arguments; + const init = { credentials: 'same-origin', mode: 'same-origin', redirect: 'error', cache: 'no-store' }; + (async () => { + let response; + if (after !== null) { + const boot = await fetch('/api/v1/bootstrap', init); + if (!boot.ok) return null; + const { csrf } = await boot.json(); + response = await fetch('/api/v1/skills/-/changes', { ...init, referrerPolicy: 'same-origin', method: 'POST', + headers: { 'content-type': 'application/json', 'x-deva-csrf': csrf }, body: JSON.stringify({ after, waitMs: 0 }) }); + } else response = await fetch(path, init); + if (path === '/api/v1/bootstrap') return response.status; + return response.ok ? { status: response.status, body: await response.json() } : { status: response.status }; + })().then(done, () => done(null)); + `, path, after) +} + +async function authenticate(ctx, first) { + const { browser, origin, password } = ctx + if (first) { + const { credential } = await ctx.claim() + check(typeof credential === 'string' && /^[A-Za-z0-9_-]{43}$/.test(credential), 'Local control did not issue a claim receipt') + await browser.navigate(`${origin}/#claim=${encodeURIComponent(credential)}`) + } else await browser.navigate(`${origin}/`) + const field = await present(ctx, passwordField(first ? 'new' : 'current'), 'actual owner credentials form') + check(await observe(ctx, `return location.origin === arguments[0] && location.pathname === '/' && !location.hash && !location.search && + !document.querySelector('.wb-auth [name="credential"]') && navigator.webdriver && /HeadlessChrome/.test(navigator.userAgent);`, origin), + 'Expected the local sandboxed owner page with its claim fragment removed') + check(await readBack(ctx, `${api}/bootstrap`) === 401, 'Fresh browser could already read owner bootstrap') + await browser.keys(field, password) + await click(ctx, '.wb-auth button[type="submit"]', 'submit real claim/login form') + await present(ctx, id('chat'), 'authenticated text Workbench shell') + check(await readBack(ctx, `${api}/bootstrap`) === 200, 'Owner UI did not establish an authenticated session') + if (first) check(await ctx.ownerClaimed(), 'Local control did not confirm the browser owner claim') +} + +async function logout(ctx) { + if (!await observe(ctx, 'return !!document.querySelector(arguments[0]);', id('chat'))) return + if (!await observe(ctx, 'return !!document.querySelector(".wb-chat__logout");')) await click(ctx, id('settings'), 'open Settings to sign out') + await click(ctx, '.wb-chat__logout', 'sign out and revoke the real owner session') + await present(ctx, passwordField('current'), 'fresh owner login form after logout') + check(await readBack(ctx, `${api}/bootstrap`) === 401, 'Signed-out browser retained owner access') +} + +function traffic(ctx) { + return observe(ctx, `return performance.getEntriesByType('resource').map(row => { + const url = new URL(row.name); + return { sameOrigin: url.origin === location.origin, path: url.pathname, query: !!url.search, end: row.responseEnd, status: row.responseStatus }; + });`) +} +async function checkPageTraffic(ctx) { + const seen = await traffic(ctx) + check(seen.every(r => r.sameOrigin && !r.query && (/^\/(?:assets\/|api\/v1\/)/.test(r.path) || r.path === '/favicon.ico')), + 'Browser requested a foreign origin, linked resource or unexpected static file') + check(seen.every(r => r.path !== `${listPath}/${notes.id}`), 'Browser loaded an unselected skill document') +} +const requests = (ctx, path, method, since = 0) => ctx.rows.slice(since).filter(row => row.path === path && row.method === method) +const noSkillReads = (ctx, since) => !ctx.rows.slice(since).some(row => row.path === listPath || row.path.startsWith(`${listPath}/`)) + +async function openList(ctx, since, enabled, soleOwner = true) { + await click(ctx, id('settings'), 'open the original Settings') + await present(ctx, '.wb-settings .models', 'original model section opens before Skills') + const started = performance.now() + await wait(ctx, async () => { + const noBrowserReads = (await traffic(ctx)).every(r => r.path !== listPath && !r.path.startsWith(`${listPath}/`)) + check(noBrowserReads && (!soleOwner || noSkillReads(ctx, since)) && + await observe(ctx, 'return !document.querySelector(arguments[0]);', panel), 'Skills panel or traffic appeared before the explicit Settings tab click') + return performance.now() - started >= 400 + }, 'observe an idle first model section with no skill reads') + await click(ctx, id('skills-tab'), 'open Skills explicitly from Settings') + await verifyList(ctx, enabled) + check(requests(ctx, listPath, 'GET', since).some(r => r.status === 200), 'Real Settings tab did not fetch the skill list') +} + +async function verifyList(ctx, enabled) { + await present(ctx, panel, 'visible skill list panel') + await present(ctx, `${toggle(guide.id)}[aria-pressed="${enabled}"]`, 'saved Editorial Guide toggle') + await present(ctx, `${toggle(notes.id)}[aria-pressed="false"]`, 'saved disabled Release Notes toggle') + check(await observe(ctx, ` + const [panel, row, builtins, documents, button, toggle, instructions, marker] = arguments; + const rows = [...document.querySelectorAll(row)]; + return /Web chat does not run skills/i.test(document.querySelector(panel)?.textContent) && rows.length === 5 && builtins.every(id => { + const elem = rows.find(row => row.dataset.skillId === id); + const control = elem?.querySelector('button.cf-switch[aria-pressed="true"]'); + return elem?.getClientRects().length && elem.dataset.source === 'builtin' && elem.dataset.enabled === 'true' && + !elem.querySelector(button) && !elem.querySelector(toggle) && control?.disabled && /built.in/i.test(elem.textContent); + }) && documents.every(doc => { + const elem = rows.find(row => row.dataset.skillId === doc.id); + return elem?.getClientRects().length && elem.dataset.source === 'custom' && elem.dataset.enabled === String(doc.enabled) && + elem.querySelector(button)?.textContent.includes(doc.name); + }) && !document.querySelector(instructions) && !document.body.textContent.includes(marker); + `, panel, skill('row'), builtinIds, [{ ...guide, enabled }, { ...notes, enabled: false }].map(({ id, name, enabled }) => ({ id, name, enabled })), + skill('open'), skill('toggle'), instructions, marker), + 'Expected three read-only builtins and two titled custom records without document or resource content') +} + +async function readCatalog(ctx, enabled, roles, doc = guide) { + const reply = await readBack(ctx, listPath) + const data = reply?.body + check(reply?.status === 200 && data.execution === 'inactive' && revision(data.revision) && data.skills?.length === 5 && + builtinIds.every(id => data.skills.some(skill => skill.id === id && !skill.canConfigure && skill.source === 'builtin' && skill.enabled && skill.roles === null)), + 'Catalog did not preserve inactive execution or the native builtin rows') + const active = data.skills.find(skill => skill.id === guide.id), unrelated = data.skills.find(skill => skill.id === notes.id) + check(active?.name === doc.name && active.enabled === enabled && active.canConfigure && sameRoles(active.roles, roles) && revision(active.revision) && + unrelated?.name === notes.name && !unrelated.enabled && sameRoles(unrelated.roles, []) && + data.skills.every(skill => !Object.hasOwn(skill, 'instructions') && !Object.hasOwn(skill, 'detail')) && + !JSON.stringify(data).includes(marker), 'Catalog exposed document data or disagreed with the saved native skill preferences') + return { catalog: data.revision, target: active.revision } +} + +async function verifyDocument(ctx, doc) { + await wait(ctx, () => observe(ctx, ` + const [selector, inst, title, body, marker] = arguments; + const detail = document.querySelector(selector), pre = detail?.querySelector(inst); + return detail?.getClientRects().length && [...detail.querySelectorAll('h1,h2,h3,h4,[role=heading]')].some(h => h.textContent.trim() === title) && + pre?.getClientRects().length && pre.textContent.trim() === body && pre.childElementCount === 0 && !pre.isContentEditable && + !detail.querySelector('a[href],img,iframe,[data-fixture="editorial-phrase"]') && !document.body.textContent.includes(marker); + `, detail, instructions, doc.name, doc.body, marker), 'visible exact plain-text SKILL.md instructions with inert markup, links and reference text') +} + +async function openDocument(ctx) { + const from = ctx.rows.length + await click(ctx, `${row(guide.id)} ${skill('open')}`, 'select the Editorial Guide via its actual row control') + await verifyDocument(ctx, guide) + check(requests(ctx, selectedPath, 'GET', from).some(r => r.status === 200), 'Opening Editorial Guide did not fetch its authenticated detail') + const reply = await readBack(ctx, selectedPath), doc = reply?.body?.skill + check(reply?.status === 200 && reply.body.execution === 'inactive' && doc?.detail === 'document' && doc.id === guide.id && + doc.instructions === guide.body && doc.trigger === 'During editorial review' && doc.license === 'CC0-1.0' && doc.compatibility === 'Plain text' && + doc.allowedTools?.join() === 'read_file' && doc.metadata?.audience === 'editors', 'Actual detail receipt did not return the plain document and native optional fields') +} + +async function patchThrough(ctx, selector, description) { + const before = ctx.rows.length + await click(ctx, selector, description) + await wait(ctx, () => { + const calls = requests(ctx, patchPath, 'PATCH', before) + check(calls.length <= 1 && (!calls[0]?.status || calls[0].status === 200), 'One explicit owner control attempted more than one preference write or was rejected') + return calls[0]?.status === 200 + }, 'the one explicit preference PATCH returns HTTP 200') +} + +async function openRoles(ctx) { + await click(ctx, `${detail} ${skill('roles')}`, 'open the explicit role scope editor') + await present(ctx, mode('all'), 'All roles radio choice in the real editor') +} +async function chooseRoles(ctx, value, roles = []) { + await click(ctx, mode(value), `choose role scope ${value}`) + for (const role of roles) await click(ctx, `${option(role)}:not(:checked)`, 'check the named native role through W3C') + check(await observe(ctx, ` + const [mode, selector, expected] = arguments; + return document.querySelector(mode)?.checked && (expected === null || JSON.stringify([...document.querySelectorAll(selector + ':checked')] + .map(field => field.dataset.roleId).sort()) === JSON.stringify(expected)); + `, mode(value), skill('role-option'), value === 'selected' ? [...roles].sort() : null), 'Native editor did not reflect the explicit draft role choice') +} +async function confirmRoles(ctx, roles) { + await patchThrough(ctx, skill('roles-save'), 'commit the chosen role scope via the actual Save button') + await gone(ctx, skill('roles-save'), 'successful scope confirmation closes the role draft') + await confirmSaved(ctx) + const receipt = await readCatalog(ctx, false, roles) + await ctx.fixture.assertNative(false, roles) + return receipt +} + +async function confirmSaved(ctx) { + await wait(ctx, () => observe(ctx, `return [...document.querySelectorAll(arguments[0])].some(node => + node.getClientRects().length && /saved|recorded/i.test(node.textContent));`, skill('status')), + 'visible acknowledgement of the recorded preference') +} + +async function verifyChanges(ctx, from, changed, expected) { + const reply = await readBack(ctx, changesPath, from), body = reply?.body + check(reply?.status === 200 && Object.keys(body ?? {}).sort().join() === 'changed,revision' && body.changed === changed && body.revision === expected, + 'Read-only changes cursor did not return precisely changed and revision') +} + +async function verifyChat(ctx) { + await click(ctx, id('settings-close'), 'return to the text page without activating a skill') + await gone(ctx, panel, 'Settings and Skills dismissed') + check((await readBack(ctx, `${api}/chats`))?.body?.sessions?.length === 0 && await observe(ctx, ` + const chat = document.querySelector(arguments[0]); + return chat?.getClientRects().length && !arguments[1].some(value => chat.textContent.includes(value)) && !document.querySelector(arguments[2]); + `, id('chat'), [guide.name, notes.name, guide.body.split('\n')[1], notes.body.split('\n')[1], marker], id('turn-status')), + 'Skills settings populated prior instructions, started a model turn, or created a conversation') + await checkPageTraffic(ctx) +} + +async function capture(ctx, kind) { + if (process.env.DEVA_QA_SKILLS_CAPTURE !== '1') return + const selector = kind === 'list' ? panel : detail + check(await observe(ctx, ` + const [selector, kind, refresh, open, back, roles, guide, notes, instructions, marker] = arguments; + const panel = document.querySelector(selector), dialog = panel?.closest('[role=dialog]'); + if (!panel || !dialog || dialog.querySelector('input, textarea, [contenteditable]') || document.querySelector('.wb-auth, input[type=password]') || + [...document.querySelectorAll('input, textarea, [contenteditable=true]')].some(node => node.getClientRects().length && + (node.value || (node.isContentEditable && node.textContent.trim()))) || document.body.textContent.includes(marker)) return false; + const bounds = dialog.getBoundingClientRect(); + const inside = node => { + if (!node || getComputedStyle(node).visibility !== 'visible') return false; + const r = node.getBoundingClientRect(); + return r.width > 0 && r.height > 0 && r.top >= Math.max(0, bounds.top) && r.bottom <= Math.min(innerHeight, bounds.bottom) && + r.left >= Math.max(0, bounds.left) && r.right <= Math.min(innerWidth, bounds.right); + }; + const heading = [...panel.querySelectorAll('h1,h2,h3,h4,[role=heading]')].find(h => h.textContent.trim() === (kind === 'list' ? 'Skills' : guide.name)); + const primary = kind === 'list' ? [panel.querySelector(refresh), ...panel.querySelectorAll(open)] : + [dialog.querySelector(back), panel.querySelector(roles), panel.querySelector(instructions)]; + const ack = [...panel.querySelectorAll('p')].find(node => /Web chat does not run skills/i.test(node.textContent)); + return inside(heading) && inside(ack) && primary.length >= 3 && primary.every(inside) && + (kind === 'list' ? panel.textContent.includes(notes.name) && !panel.querySelector(instructions) : panel.querySelector(instructions)?.textContent.trim() === guide.body); + `, selector, kind, id('skills-refresh'), skill('open'), skill('back'), skill('roles'), guide, notes, instructions, marker), + 'Screenshot requires stable visible headings, primary controls and inactive acknowledgement with only known synthetic data') + const file = fileURLToPath(new URL(`../../test-results/skill-library/${kind === 'list' ? 'skills-list' : 'skill-detail'}.png`, import.meta.url)) + for (const dir of [dirname(dirname(file)), dirname(file)]) { + await mkdir(dir, { mode: 0o700 }).catch(error => { if (error.code !== 'EEXIST') throw error }) + check((await lstat(dir)).isDirectory() && await realpath(dir) === dir, 'Fixed screenshot location must be an ordinary directory') + } + const image = Buffer.from(await ctx.browser.fixtureScreenshot(), 'base64') + check(image.length > 8 && image.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')), 'Chrome did not return a PNG screenshot') + const handle = await open(file, constants.O_WRONLY | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600) + try { + const file = await handle.stat() + check(file.isFile() && file.nlink === 1 && file.uid === process.geteuid(), 'Fixed screenshot target must be a private ordinary file') + await handle.chmod(0o600) + await handle.truncate(0) + await handle.writeFile(image) + } finally { await handle.close() } +} + +export async function runSkillBrowser(ctx) { + const { fixture, mark, openBrowser } = ctx + mark('start sandboxed Chrome through local ChromeDriver') + const first = { ...ctx, browser: await openBrowser('owner-a') } + let second, failure + try { + mark('claim the local owner in Chrome and explicitly open Skills under Settings') + await authenticate(first, true) + await first.browser.fixtureViewport('wide') + await openList(first, 0, true) + const beforeRefresh = ctx.rows.length + await click(first, id('skills-refresh'), 'explicitly refresh the summary list') + await wait(first, () => requests(first, listPath, 'GET', beforeRefresh).some(r => r.status === 200), 'real skill list refresh returns HTTP 200') + check(!ctx.rows.some(r => r.method === 'GET' && r.path.startsWith(`${listPath}/`)), + 'The summary list fetched a skill document, builtin detail or role roster early') + const original = await readCatalog(first, true, null) + await capture(first, 'list') + mark('select one document, check plain-text display, and record the enabled preference') + await openDocument(first) + await capture(first, 'detail') + await click(first, skill('back'), 'return from document to its skill list before toggling') + const toggleAt = ctx.rows.length + await patchThrough(first, `${toggle(guide.id)}[aria-pressed="true"]`, 'turn off the recorded Editorial Guide preference') + await verifyList(first, false) + await confirmSaved(first) + const disabled = await readCatalog(first, false, null) + check(disabled.target !== original.target, 'Preference update left the skill revision unchanged') + await fixture.assertNative(false, null) + check(requests(first, selectedPath, 'GET', toggleAt).length === 0, 'Toggling a recorded preference fetched the document from the list') + await checkPageTraffic(first) + mark('reload the document and check the saved list and role choices') + const reloaded = ctx.rows.length + await first.browser.refresh() + await present(first, id('chat'), 'text shell after real page refresh') + await openList(first, reloaded, false) + await openDocument(first) + const beforeRoles = ctx.rows.length + await openRoles(first) + check(requests(first, rolesPath, 'GET', beforeRoles).some(r => r.status === 200), 'Opening role scope did not fetch the native role choices') + const roles = (await readBack(first, rolesPath))?.body?.roles + check(roles?.some(r => r.id === fixture.role.id && r.name === roleName && r.enabled) && roles.some(r => r.id === fixture.general.id && r.enabled), + 'Scope roster did not contain the native fixture role bindings') + await chooseRoles(first, 'none') + const none = await confirmRoles(first, []) + await openRoles(first) + await chooseRoles(first, 'selected', [fixture.role.id]) + const one = await confirmRoles(first, [fixture.role.id]) + check(none.target !== one.target, 'Choosing one role did not advance the revision') + await openRoles(first) + await click(first, `${option(fixture.general.id)}:not(:checked)`, 'add General alongside the saved ordinary role') + const two = await confirmRoles(first, [fixture.role.id, fixture.general.id]) + await verifyChanges(first, two.catalog, false, two.catalog) + mark('log in independently and exercise concurrent owner and manual document invalidation') + second = { ...ctx, browser: await openBrowser('owner-b') } + const newOwner = ctx.rows.length + await authenticate(second, false) + await openList(second, newOwner, false, false) + const fresh = await readCatalog(second, false, [fixture.role.id, fixture.general.id]) + check(fresh.target === two.target, 'Independent owner login did not see the durable state') + await openDocument(second) + await verifyConcurrent(first, second, two) + check(requests(first, patchPath, 'PATCH').length === 5, 'Expected just the toggle and four explicit scope confirmations') + mark('interrupt one pending read, scrub the preview and restore it from the unchanged native revision') + const beforeDrop=ctx.rows.length + await wait(first,()=>ctx.dropChanges(),'one live owner metadata request to interrupt',5000) + try { + await wait(first,()=>observe(first,`return !document.querySelector(arguments[0]) && + /reconnect/i.test(document.querySelector(arguments[1])?.textContent) && + !document.querySelector(arguments[2]) && document.querySelector(arguments[3])?.disabled === true;`, + instructions,skill('status'),skill('roles'),`${detail} ${skill('toggle')} button`),'document scrubbed and preferences frozen after genuine transport loss',8000) + } catch (error) { + const flags=await observe(first,`return [!!document.querySelector(arguments[0]),/reconnect/i.test(document.querySelector(arguments[1])?.textContent), + !!document.querySelector(arguments[2]),document.querySelector(arguments[3])?.disabled === true].map(Number).join('');`, + instructions,skill('status'),skill('roles'),`${detail} ${skill('toggle')} button`) + if(!/^[01]{4}$/.test(flags))throw error + throw new SkillCheckError(`Reconnect state: document=${flags[0]} reconnecting=${flags[1]} roleButton=${flags[2]} frozen=${flags[3]}`) + } finally {ctx.resumeChanges()} + await verifyDocument(first,revisedGuide) + await wait(first,()=>[listPath,selectedPath].every(path=>requests(first,path,'GET',beforeDrop).some(r=>r.status===200)), + 'reconnect independently verifies catalog and selected document even without a new revision') + check(requests(first,patchPath,'PATCH',beforeDrop).length===0,'Reconnecting replayed a preference write') + mark('verify no model, chat, resource or skill execution side effects') + for (const builtin of builtinIds) { + const reply = await readBack(first, `${listPath}/${builtin}`), value = reply?.body?.skill + check(reply?.status === 200 && reply.body.execution === 'inactive' && value?.detail === 'builtin' && !value.canConfigure && + !Object.hasOwn(value, 'instructions'), 'Builtin detail was not read-only metadata') + } + await verifyChat(first) + await verifyChat(second) + } catch (error) { failure = error } + for (const owner of [second, first].filter(Boolean)) { + try { await logout(owner) } catch (error) { failure ??= error } + } + if (failure) throw failure +} + +async function verifyConcurrent(first, second, two) { + await openRoles(first) + await chooseRoles(first, 'none') + const since = await observe(first, 'return performance.now();') + await openRoles(second) + await chooseRoles(second, 'all') + const all = await confirmRoles(second, null) + await staleDraft(first, since, 'none') + await verifyChanges(second, two.catalog, true, all.catalog) + await first.fixture.assertNative(false, null) + await reviewDraft(first, guide, 'none') + await openRoles(first) + await chooseRoles(first, 'selected', [first.fixture.role.id]) + const manualAt = await observe(first, 'return performance.now();') + await first.fixture.reviseGuide() + await staleDraft(first, manualAt, 'selected') + await reviewDraft(first, revisedGuide, 'selected') + const revised = await readCatalog(first, false, null, revisedGuide) + check(revised.target !== all.target && revised.catalog !== all.catalog, 'Manual document edit did not advance both selected record and catalog revisions') + await verifyChanges(first, all.catalog, true, revised.catalog) + await first.fixture.assertNative(false, null) +} + +async function staleDraft(ctx, since, draft) { + await wait(ctx, async () => { + const event = (await traffic(ctx)).some(r => r.path === changesPath && r.status === 200 && r.end >= since) + return event && await observe(ctx, ` + const [status, save, mode] = arguments; + return [...document.querySelectorAll(status)].some(node => node.getClientRects().length && /Review your choices against the latest saved preferences/i.test(node.textContent)) && + document.querySelector(save)?.disabled && document.querySelector(mode)?.checked; + `, `${detail} ${skill('status')}[data-error="stale"][role="status"]`, skill('roles-save'), mode(draft)) + }, 'authenticated invalidation blocks the retained stale draft before any refresh or review click', 20_000) + await checkPageTraffic(ctx) +} + +async function reviewDraft(ctx, doc, draft) { + await verifyDocument(ctx, doc) + const before = requests(ctx, patchPath, 'PATCH').length + await click(ctx, skill('role-review'), 'explicitly review the stale choice against the latest saved scope') + await present(ctx, skill('roles-save'), 'reviewed local draft must still require explicit Save') + check(await observe(ctx, 'return document.querySelector(arguments[0])?.checked;', mode(draft)), 'Review replaced the dirty role choice silently') + await click(ctx, skill('roles-cancel'), 'discard the reviewed draft without overwriting the saved scope') + await gone(ctx, skill('roles-save'), 'discarded draft no longer has a Save button') + check(requests(ctx, patchPath, 'PATCH').length === before, 'Reviewing or discarding a stale draft wrote a preference') +} diff --git a/scripts/workbench/e2e-skill-library-fixture.mjs b/scripts/workbench/e2e-skill-library-fixture.mjs new file mode 100644 index 00000000..3052ef81 --- /dev/null +++ b/scripts/workbench/e2e-skill-library-fixture.mjs @@ -0,0 +1,103 @@ +import { isDeepStrictEqual } from 'node:util' +import { lstat, mkdir, mkdtemp, readFile, realpath, rename, rm, stat, utimes, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { encodeSettings, publishSettingsFile, readSettingsFile, withSettingsDirectory } from '../../apps/headless/src/business/settings-file.mjs' + +export class SkillCheckError extends Error {} +export function check(value, message) { if (!value) throw new SkillCheckError(message) } + +export const roleName = 'Editorial Reviewer' +export const builtinIds = ['create-agent', 'create-skill', 'create-mcp'] +export const marker = 'EDITORIAL-RESOURCE-SENTINEL: private fixture text.' +export const guide = Object.freeze({ id: 'editorial-guide', name: 'Editorial Guide', body: [ + '# Proof copy', + 'Use sentence case for headings and keep captions short.', + '[Glossary](https://skills-fixture.invalid/glossary)', + 'literal markup', + '`https://skills-fixture.invalid/inline`', + '`references/editorial-notes.txt`' +].join('\n') }) +export const notes = Object.freeze({ id: 'release-notes', name: 'Release Notes', body: '# Release notes\nList user-facing changes in order.' }) +export const revisedGuide = Object.freeze({ ...guide, name: 'Editorial Guide – Revised', body: `${guide.body}\nCheck that figure numbers match the captions.` }) + +function documentBytes(doc) { + return Buffer.from([ + '---', `name: ${doc.name}`, 'description: Ordinary copy-editing notes for a synthetic publication.', + 'trigger: During editorial review', 'allowed-tools:', ' - read_file', 'license: CC0-1.0', + 'compatibility: Plain text', 'metadata:', ' audience: editors', '---', '', doc.body, '' + ].join('\n')) +} + +export async function privateRoot() { + const prefix = join(await realpath(tmpdir()), 'deva-wb-skills-') + const root = await mkdtemp(prefix) + const info = await lstat(root) + async function verify() { + const current = await lstat(root) + check(root.startsWith(prefix) && root.length > prefix.length && await realpath(root) === root && current.isDirectory() && + current.uid === process.geteuid() && (current.mode & 0o777) === 0o700 && info.ino === current.ino && info.dev === current.dev, + 'Expected the original private synthetic directory') + } + await verify() + return { root, async close() { await verify(); await rm(root, { recursive: true }) } } +} + +export async function createSkillFixture(root) { + const dataDir = join(root, 'data'), skillRoot = join(dataDir, 'skills') + const docPath = doc => join(skillRoot, doc.id, 'SKILL.md') + const resourceDir = join(skillRoot, guide.id, 'references') + const resource = join(resourceDir, 'editorial-notes.txt') + const create = (path, bytes) => writeFile(path, bytes, { mode: 0o600, flag: 'wx' }) + const rawConfig = () => withSettingsDirectory(dataDir, null, async dir => (await readSettingsFile(dir)).raw) + await mkdir(resourceDir, { recursive: true, mode: 0o700 }) + await mkdir(join(skillRoot, notes.id), { mode: 0o700 }) + await create(resource, marker) + // On normal Linux relatime mounts, a successful content read advances this deliberately old atime. + const old = new Date('2000-01-01T00:00:00Z') + await utimes(resource, old, old) + const resourceSnapshot = await stat(resource, { bigint: true }) + await Promise.all([guide, notes].map(doc => create(docPath(doc), documentBytes(doc)))) + await withSettingsDirectory(dataDir, null, async dir => { + const { info } = await readSettingsFile(dir) + check(!info, 'The synthetic native config must start fresh') + const published = await publishSettingsFile(dir, encodeSettings({ locale: 'en', theme: 'light', + skills: { enabled: { [guide.id]: true, [notes.id]: false }, roles: { [notes.id]: [] }, sidebarLabel: 'Editorial collection' } + }), info) + check(published.durable, 'Could not publish the synthetic native config') + }) + const { openPersonas } = await import('../../apps/headless/src/business/personas.mjs') + const personas = await openPersonas({ dataDir }) + const role = await personas.upsert({ name: roleName, description: 'Reviews copies of synthetic publications.', + prompt: 'Check spelling and punctuation.', enabled: true }) + const general = await personas.get('general') + check(role.enabled && !role.protected && general?.enabled && general.protected, 'Expected one ordinary role and the native General role') + const initial = await rawConfig() + let currentGuide = guide + return Object.freeze({ + dataDir, role, general, + async assertNative(enabled, roles) { + const raw = await rawConfig() + const expected = structuredClone(initial) + expected.skills.enabled[guide.id] = enabled + if (roles === null) delete expected.skills.roles[guide.id] + else expected.skills.roles[guide.id] = roles + check(isDeepStrictEqual(raw, expected), 'Raw native config changed outside the selected skill preference or stored a wrong scope') + for (const doc of [currentGuide, notes]) { + check((await readFile(docPath(doc))).equals(documentBytes(doc)), 'A preference changed the source SKILL.md bytes') + } + const now = await stat(resource, { bigint: true }) + for (const field of ['dev', 'ino', 'size', 'ctimeNs', 'mtimeNs', 'atimeNs']) { + check(now[field] === resourceSnapshot[field], 'Unrelated editorial resource was opened or changed') + } + }, + async reviseGuide() { + check(currentGuide === guide, 'Expected the original editorial document before manual edit') + const target = docPath(guide), temp = join(skillRoot, guide.id, '.editorial-draft') + check(await realpath(target) === target && (await lstat(target)).isFile(), 'Manual edit must target the private regular fixture file') + await create(temp, documentBytes(revisedGuide)) + await rename(temp, target) + currentGuide = revisedGuide + } + }) +} diff --git a/scripts/workbench/e2e-skill-library.mjs b/scripts/workbench/e2e-skill-library.mjs new file mode 100644 index 00000000..a1df43df --- /dev/null +++ b/scripts/workbench/e2e-skill-library.mjs @@ -0,0 +1,133 @@ +import { randomBytes } from 'node:crypto' +import { access, mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import { requestControl } from '../../apps/headless/src/control/socket.mjs' +import { DEFAULT_WEB_DIR, startWorkbench } from '../../apps/headless/src/server.mjs' +import { initializeMasterKey } from '../../apps/headless/src/storage/vault.mjs' +import { runSkillBrowser } from './e2e-skill-library-browser.mjs' +import { check, createSkillFixture, privateRoot, SkillCheckError } from './e2e-skill-library-fixture.mjs' +import { startLocalWebDriver, WebDriverError } from './webdriver-local.mjs' + +// Observe the real dispatcher without altering request bodies, response bodies or authorization. +// Capturing from request arrival also sees in-flight polls excluded from Resource Timing. +function observeBusiness(rows, openBusiness, disconnect) { + let firstLogin, recoveryGate + const firstPolls=new Set() + disconnect.resume = () => { recoveryGate?.resolve(); recoveryGate=undefined } + // Truncate an actual in-flight response *after headers*. A pooled socket dropped + // before headers may be retried transparently inside Chrome and never reach the UI. + // Hold the next catalog read until the browser observes its frozen, scrubbed state. + disconnect.once = () => { + for (const peer of firstPolls) if (!peer.res.destroyed && !peer.res.headersSent && performance.now()-peer.since>120) { + firstPolls.delete(peer) + recoveryGate=Promise.withResolvers() + const timer=setTimeout(disconnect.resume,9000); recoveryGate.promise.then(()=>clearTimeout(timer)) + peer.res.writeHead(200,{'content-type':'application/json','content-length':'160','cache-control':'no-store',connection:'close'}) + peer.res.write('{"changed":',()=>peer.res.destroy()) + return true + } + return false + } + return async options => { + const business = await openBusiness(options) + return { ...business, async handle(req, res, context) { + const [path, query] = (req.url ?? '').split('?', 2) + const row = { method: req.method, path, query: query !== undefined, authenticated: !!req.headers.cookie, status: 0 } + rows.push(row) + if (path === '/api/v1/skills/-/changes' && req.method === 'POST') { + const actor=context.auth.identify(context.policy.cookie(req),req.headers['x-deva-csrf']) + firstLogin??=actor.loginSessionId + if(actor.loginSessionId===firstLogin){ + const peer={res,since:performance.now()};firstPolls.add(peer) + res.once('close',()=>firstPolls.delete(peer)) + } + } + res.once('finish', () => { row.status = res.statusCode }) + if (recoveryGate && path==='/api/v1/skills' && req.method==='GET' && + context.auth.identify(context.policy.cookie(req)).loginSessionId===firstLogin) await recoveryGate.promise + return business.handle(req, res, context) + } } + } +} + +function assertOnlyAcceptedTraffic(rows) { + const reads = new Set(['settings', 'provider-keys', 'chats', 'personas', 'profile', 'workspaces', 'skills', + 'skills/-/roles', 'skills/editorial-guide', 'skills/create-agent', 'skills/create-skill', 'skills/create-mcp']) + for (const row of rows) { + const name = row.path.slice('/api/v1/'.length) + check(row.path.startsWith('/api/v1/') && !row.query && row.authenticated && + ((row.method === 'GET' && reads.has(name)) || (row.method === 'POST' && name === 'skills/-/changes') || + (row.method === 'PATCH' && name === 'skills/editorial-guide/preferences')), + 'Unexpected non-auth owner request (model, chat, write, resource, unselected skill, or query)') + } +} + +async function run({ fixtureOnly }) { + const stop = new AbortController() + const abort = () => stop.abort() + const signal = AbortSignal.any([stop.signal, AbortSignal.timeout(150_000)]) + process.once('SIGINT', abort) + process.once('SIGTERM', abort) + const rows = [], browsers = [], disconnect={} + let temp, server, failed, stage = 'prepare private native fixture' + const mark = next => { stage = next; signal.throwIfAborted() } + try { + check(process.platform === 'linux' && process.getuid?.() > 0 && process.geteuid?.() > 0, 'Run the skill library gate on Linux as a nonroot user') + await access(new URL('../../apps/headless/dist/library-core.mjs', import.meta.url)).catch(() => { + throw new SkillCheckError('Build the headless library core with pnpm --filter @deva/headless build') + }) + temp = await privateRoot() + const fixture = await createSkillFixture(temp.root) + await fixture.assertNative(true, null) + if (fixtureOnly) { + await fixture.reviseGuide() + await fixture.assertNative(true, null) + } else { + mark('start the built Workbench on a private IPv4 loopback origin') + await access(join(DEFAULT_WEB_DIR, 'index.html')).catch(() => { throw new SkillCheckError('Run pnpm workbench:build first') }) + const keyFile = join(temp.root, 'master.key'), runDir = join(temp.root, 'run'), workspaceRoot = join(temp.root, 'workspaces') + await mkdir(workspaceRoot, { mode: 0o700 }) + await initializeMasterKey(keyFile) + const { openBusiness } = await import('../../apps/headless/src/business/handlers.mjs') + server = await startWorkbench({ dataDir: fixture.dataDir, keyFile, runDir, host: '127.0.0.1', port: 0, + businessFactory: observeBusiness(rows, openBusiness, disconnect), businessOptions: { workspaceRoot } }) + const { origin, address } = server + check(address.address === '127.0.0.1' && origin === `http://127.0.0.1:${address.port}`, 'Expected the assigned private IPv4 origin') + const ready = await fetch(`${origin}/readyz`, { signal, redirect: 'error' }) + await ready.body?.cancel() + check(ready.status === 200, 'The isolated Workbench is not ready') + const password = randomBytes(24).toString('base64url') + const openBrowser = async name => { + const root = join(temp.root, name) + await mkdir(root, { mode: 0o700 }) + const browser = await startLocalWebDriver({ root, profile: join(root, 'profile'), origin, signal }) + browsers.push(browser) + return browser + } + await runSkillBrowser({ fixture, rows, origin, password, openBrowser, signal, mark, dropChanges:disconnect.once, resumeChanges:disconnect.resume, + claim: () => requestControl({ runDir, op: 'claim' }), ownerClaimed: async () => (await requestControl({ runDir, op: 'status' })).claimed }) + assertOnlyAcceptedTraffic(rows) + } + } catch (error) { + failed = true + const detail = error instanceof SkillCheckError || error instanceof WebDriverError ? error.message : 'unexpected error (raw diagnostics withheld)' + console.error(`Workbench Skill Library E2E failed while ${stage}: ${signal.aborted ? 'interrupted or timed out' : detail}`) + } finally { + for (const [name, cleanup] of [['browser close', () => Promise.all(browsers.map(browser => browser.close()))], + ['server shutdown', () => server?.close()], ['private fixture cleanup', () => temp?.close()]]) { + try { await cleanup() } catch { failed = true; console.error(`Workbench Skill Library E2E: ${name} failed`) } + } + process.removeListener('SIGINT', abort) + process.removeListener('SIGTERM', abort) + } + if (failed || signal.aborted) process.exitCode = 1 + else if (fixtureOnly) console.log('Workbench Skill Library fixture passed: native settings, two editorial documents and one ordinary added role.') + else console.log('Workbench Skill Library browser E2E passed: isolated owner claim/login, native skill preferences, cross-owner and external invalidation, and inactive execution.') +} + +const args = process.argv.slice(2) +if (!args.length || (args.length === 1 && args[0] === '--fixture-only')) await run({ fixtureOnly: args.length === 1 }) +else { + console.error('Usage: node scripts/workbench/e2e-skill-library.mjs [--fixture-only]') + process.exitCode = 1 +} diff --git a/scripts/workbench/export-parity-workbook.mjs b/scripts/workbench/export-parity-workbook.mjs new file mode 100644 index 00000000..c1f3530a --- /dev/null +++ b/scripts/workbench/export-parity-workbook.mjs @@ -0,0 +1,144 @@ +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { checkManifest, manifestPath, preloadPath, root } from './check-parity.mjs' +import { extractInventory } from './preload-inventory.mjs' +import { openSnapshot, publishWorkbook, validSha } from './parity-workbook-guard.mjs' +import { cell, zipWorkbook } from './parity-workbook-ooxml.mjs' + +export const defaultRepo = 'Facetomyself/deva' +const usage = 'Usage: node scripts/workbench/export-parity-workbook.mjs [--repo owner/repo] [--pr positive-safe-integer]' +const ownerPattern = /^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$/ +const repoPattern = /^[A-Za-z0-9_.-]{1,100}$/ +const required = [ + 'scripts/workbench/export-parity-workbook.mjs', 'scripts/workbench/parity-workbook-guard.mjs', + 'scripts/workbench/parity-workbook-ooxml.mjs', 'scripts/workbench/check-parity.mjs', + 'scripts/workbench/preload-inventory.mjs', 'apps/desktop/package.json', 'pnpm-lock.yaml', +] + +function verifyRepo(repo) { + const [owner, name, extra] = typeof repo === 'string' ? repo.split('/') : [] + if (!owner || !name || extra !== undefined || owner.length > 39 || !ownerPattern.test(owner) || + !repoPattern.test(name) || name === '.' || name === '..' || name.toLowerCase().endsWith('.git')) { + throw new Error('Invalid --repo: expected a GitHub owner/repo slug') + } + return repo +} + +export function parseOptions(args) { + const options = { repo: defaultRepo } + const seen = new Set() + for (let i = 0; i < args.length; i += 2) { + const [flag, value] = args.slice(i, i + 2) + if (!['--repo', '--pr'].includes(flag) || seen.has(flag) || value === undefined) throw new Error(usage) + seen.add(flag) + if (flag === '--repo') options.repo = verifyRepo(value) + else { + if (!/^[1-9][0-9]*$/.test(value) || !Number.isSafeInteger(Number(value))) throw new Error('Invalid --pr: expected a positive safe integer') + options.pr = Number(value) + } + } + return options +} + +export function loadParity(snapshot) { + for (const file of required) snapshot.read(file) + const manifest = JSON.parse(snapshot.read(manifestPath).toString('utf8')) + const inventory = extractInventory(snapshot.read(preloadPath).toString('utf8'), preloadPath) + const errors = checkManifest(manifest, inventory, (path) => { snapshot.read(path); return true }) + if (errors.length) throw new Error(`Workbench parity check failed (${errors.length}):\n- ${errors.join('\n- ')}`) + return manifest +} + +const labels = { implemented: '已实现', partial: '部分覆盖', pending: '待实现', desktop: '仅桌面' } +const buckets = Object.keys(labels) +const desktopLabels = { ui: '桌面界面', 'bridge-only': '仅桥接', 'legacy-bridge': '历史桥接' } +function bucket({ status, partial }) { + return status === 'implemented' ? 'implemented' : status === 'desktop-only' ? 'desktop' : partial ? 'partial' : 'pending' +} +const stats = (methods) => { + const counts = Object.fromEntries(buckets.map((key) => [key, 0])) + for (const { web } of methods) counts[bucket(web)]++ + return counts +} +const pathPart = (part) => encodeURIComponent(part).replace(/[!'()*]/g, (character) => + `%${character.charCodeAt(0).toString(16).toUpperCase()}`) + +export function buildWorkbook(manifest, { sha, repo = defaultRepo, pr } = {}) { + verifyRepo(repo) + if (!validSha(sha)) throw new Error('Expected an exact Git commit SHA') + if (pr !== undefined && (!Number.isSafeInteger(pr) || pr < 1)) throw new Error('Expected a positive safe PR number') + const base = `https://github.com/${repo}` + const evidence = (path) => path ? cell(path, 'link', `${base}/blob/${sha}/${path.split('/').map(pathPart).join('/')}`) : '' + const commit = cell(`固定提交:${sha}`, 'metaLink', `${base}/commit/${sha}`) + const methods = manifest.groups.flatMap((group) => group.methods) + const counts = stats(methods) + const subs = methods.filter(({ kind }) => kind === 'subscription').length + const totals = `方法 ${methods.length} 项 · ${manifest.groups.length} 个命名空间 · ${subs} 项订阅(已计入方法) · ${buckets.map((key) => `${labels[key]} ${counts[key]}`).join(' / ')}` + const status = (web) => cell(labels[bucket(web)], bucket(web)) + const countCells = (counts) => buckets.map((key) => cell(counts[key], key)) + const webCells = (web) => [status(web), web.target, web.semantic, + web.partial?.scope ?? (web.status === 'implemented' ? '按 Web 预期行为验收;见源码和测试。' : ''), + web.partial?.remaining ?? (web.status === 'pending' ? '待按 Web 预期行为实现及验证。' : ''), + evidence((web.implementation ?? web.partial)?.handler), evidence((web.implementation ?? web.partial)?.test)] + const webHeader = ['Web 状态', 'Web 落点', 'Web 预期行为', '已覆盖范围', '待补范围', 'Web 源码', 'Web 测试'] + const webWidths = [15, 14, 56, 43, 43, 45, 45] + const methodTab = `${methods.length}项能力` + const sheets = [ + { + name: '总览', widths: [26, 16, 16, 16, 16, 16, 17], prefix: [ + `Deva Desktop / Web · ${methodTab}验收清单`, commit, + `${repo} · 桌面 preload AST 与 parity manifest 已核对;证据固定于上述提交。`, totals, + `另列 ${manifest.values.length} 项平台/启动值,见「平台值」;单列 ${manifest.flows.length} 项跨功能流程。`, + ...(pr === undefined ? [] : [cell(`关联拉取请求:#${pr}(导出时指定)`, 'metaLink', `${base}/pull/${pr}`)]), + '部分覆盖:有明确范围和证据,仍属待完成;待实现:清单尚无验收范围记录。', + cell('查看验收清单源数据与完整字段', 'metaLink', evidence(manifestPath).href), + ], header: ['命名空间', '方法数', '订阅数', ...Object.values(labels)], + rows: [[cell('方法合计', 'total'), cell(methods.length, 'total'), cell(subs, 'total'), ...countCells(counts)], + ...manifest.groups.map(({ name, methods: rows }) => [name, rows.length, rows.filter(({ kind }) => kind === 'subscription').length, ...countCells(stats(rows))])], + }, + { + name: methodTab, widths: [33, 16, 16, 36, 17, 15, 46, ...webWidths, 52, 52], frozenColumns: 1, + prefix: [`${methodTab} · 桌面与 Web 对照`, commit, totals, + cell('查看桌面 preload(AST 清查来源)', 'metaLink', evidence(preloadPath).href)], + header: ['能力键', '命名空间', 'IPC 类型', 'IPC 通道', '订阅注记', '桌面入口类型', '桌面职责 / 用途', ...webHeader, '桌面宿主路径', '桌面界面路径'], + rows: manifest.groups.flatMap(({ name, host, methods: rows }) => rows.map(({ name: method, kind, channel, desktop, web }) => [ + `${name}.${method}`, name, kind, channel, kind === 'subscription' ? cell('订阅 · 含清理', 'subscription') : '', + desktopLabels[desktop.surface], desktop.use, ...webCells(web), evidence(desktop.host ?? host), evidence(desktop.entry), + ])), + }, + { + name: '跨功能流程', widths: [25, 37, 83, 56], prefix: [`跨功能流程 · ${manifest.flows.length} 项`, commit], + header: ['场景键', '关联能力键', '跨功能验收预期', '桌面参考实现'], + rows: manifest.flows.map(({ id, methods: keys, expectation, precedent }) => [id, keys.join('\n'), expectation, evidence(precedent)]), + }, + { + name: '平台值', widths: [18, 24, 15, 46, ...webWidths, 52, 52], frozenColumns: 1, + prefix: [`平台 / 启动值 · ${manifest.values.length} 项(单独计数)`, commit, '此表记录值表达式,独立于方法与订阅验收数。'], + header: ['值键', '桌面表达式', '桌面入口类型', '桌面职责 / 用途', ...webHeader, '桌面宿主路径', '桌面界面路径'], + rows: manifest.values.map(({ name, expression, desktop, web }) => [name, expression, desktopLabels[desktop.surface], desktop.use, + ...webCells(web), evidence(desktop.host), evidence(desktop.entry)]), + }, + ] + return { bytes: zipWorkbook(sheets), methodCount: methods.length, counts, subs } +} + +export function run(args, { stdout = console.log, stderr = console.error } = {}) { + if (args.length === 1 && args[0] === '--help') { stdout(usage); return 0 } + let options + try { options = parseOptions(args) } catch (error) { stderr(error.message); return 2 } + try { + const snapshot = openSnapshot(root) + const { bytes, methodCount } = buildWorkbook(loadParity(snapshot), { sha: snapshot.sha, ...options }) + snapshot.assertCurrent() + const { output, reused } = publishWorkbook(root, snapshot.sha, methodCount, bytes) + stdout(`${reused ? 'Verified existing' : 'Wrote'} ${output}\nPinned HEAD: ${snapshot.sha}`) + return 0 + } catch (error) { + stderr(`Parity workbook export failed: ${error.message}`) + return 1 + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + process.exitCode = run(process.argv.slice(2)) +} diff --git a/scripts/workbench/parity-workbook-guard.mjs b/scripts/workbench/parity-workbook-guard.mjs new file mode 100644 index 00000000..64e9756e --- /dev/null +++ b/scripts/workbench/parity-workbook-guard.mjs @@ -0,0 +1,168 @@ +import { execFileSync } from 'node:child_process' +import { createHash, randomUUID } from 'node:crypto' +import { + closeSync, constants, fstatSync, linkSync, lstatSync, mkdirSync, openSync, + readFileSync, realpathSync, unlinkSync, writeFileSync, +} from 'node:fs' +import { join, resolve } from 'node:path' + +const fullSha = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/ +export const validSha = (sha) => typeof sha === 'string' && fullSha.test(sha) +const plainDir = (stat) => stat?.isDirectory() && !stat.isSymbolicLink() +const sameFile = (a, b) => !!a && !!b && a.dev === b.dev && a.ino === b.ino +const singleFile = (stat) => stat?.isFile() && stat.nlink === 1n + +function noEntry(path) { + try { return lstatSync(path, { bigint: true }) } catch (error) { if (error.code !== 'ENOENT') throw error } +} + +function gitAt(root, args) { + // Use this checkout only, without replacement objects, external transports, or Git diagnostics that may contain remote details. + const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^GIT_/i.test(name))) + Object.assign(env, { + GIT_ALLOW_PROTOCOL: '', GIT_NO_LAZY_FETCH: '1', GIT_NO_REPLACE_OBJECTS: '1', GIT_OPTIONAL_LOCKS: '0', + GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null', + }) + try { + return execFileSync('git', ['-c', 'core.fsmonitor=false', ...args], { + cwd: root, env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 32 * 1024 * 1024, + }) + } catch { + throw new Error(`Git ${args[0]} failed in the exporter checkout`) + } +} + +function entries(raw, index) { + const map = new Map() + for (const line of raw.split('\0')) { + if (!line) continue + const tab = line.indexOf('\t') + const [mode, first, second] = line.slice(0, tab).split(' ') + if (index ? second === '0' : first === 'blob') map.set(line.slice(tab + 1), `${mode} ${index ? first : second}`) + } + return map +} + +export function snapshotFromEntries(root, sha, tree, index) { + if (!validSha(sha)) throw new Error('Expected an exact Git commit SHA') + const base = realpathSync(root) + const verified = new Map() + return { + sha, + verified, + read(file) { + if (verified.has(file)) return verified.get(file) + if (typeof file !== 'string' || /[\\:\x00-\x1f\x7f]/.test(file) || file.split('/').some((part) => !part || part === '.' || part === '..')) { + throw new Error(`Invalid repository path: ${JSON.stringify(file)}`) + } + const committed = tree.get(file) + if (!/^100(?:644|755) [0-9a-f]+$/.test(committed ?? '') || committed !== index.get(file)) { + throw new Error(`HEAD/index mismatch or missing exact-case tracked file: ${file}`) + } + const parts = file.split('/') + let path = base + for (const part of parts.slice(0, -1)) { + path = join(path, part) + if (!plainDir(noEntry(path))) throw new Error(`Expected a real worktree directory for: ${file}`) + } + path = join(path, parts.at(-1)) + if (!noEntry(path)?.isFile() || realpathSync(path) !== path) throw new Error(`Expected a real, exact-case worktree file: ${file}`) + const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)) + let bytes + try { + if (!fstatSync(fd).isFile()) throw new Error(`Expected a regular worktree file: ${file}`) + bytes = readFileSync(fd) + } finally { closeSync(fd) } + const blob = createHash(sha.length === 40 ? 'sha1' : 'sha256').update(`blob ${bytes.length}\0`).update(bytes).digest('hex') + if (blob !== committed.split(' ')[1]) throw new Error(`Worktree bytes differ from HEAD/index: ${file}`) + verified.set(file, bytes) + return bytes + }, + } +} + +export function openSnapshot(root) { + const base = realpathSync(root) + if (realpathSync(gitAt(base, ['rev-parse', '--show-toplevel']).replace(/\r?\n$/, '')) !== base) throw new Error('Expected exporter at the checkout root') + const head = () => gitAt(base, ['rev-parse', '--verify', 'HEAD']).trim() + const staged = () => entries(gitAt(base, ['ls-files', '--stage', '-z']), true) + const sha = head() + if (!validSha(sha)) throw new Error('Expected an exact Git commit SHA from HEAD') + const tree = entries(gitAt(base, ['ls-tree', '-r', '-z', sha]), false) + const index = staged() + const snapshot = snapshotFromEntries(base, sha, tree, index) + return Object.assign(snapshot, { + assertCurrent() { + if (head() !== sha) throw new Error('HEAD changed during workbook export') + const current = snapshotFromEntries(base, sha, tree, staged()) + for (const file of snapshot.verified.keys()) current.read(file) + if (head() !== sha) throw new Error('HEAD changed during workbook export') + }, + }) +} + +function outputDirectory(root, sha) { + const base = realpathSync(root) + const dirs = new Map([[base, noEntry(base)]]) + const intact = () => [...dirs].every(([dir, initial]) => { + const state = noEntry(dir) + return plainDir(state) && sameFile(initial, state) + }) + let next = base + for (const part of ['test-results', `parity-${sha.slice(0, 7)}`]) { + if (!intact()) throw new Error('Workbook output directory changed') + next = join(next, part) + if (!noEntry(next)) { + try { mkdirSync(next, { mode: 0o755 }) } catch (error) { if (error.code !== 'EEXIST') throw error } + } + const state = noEntry(next) + if (!plainDir(state) || realpathSync(next) !== next) throw new Error(`Unsafe workbook output directory: ${next}`) + dirs.set(next, state) + } + if (!intact()) throw new Error('Workbook output directory changed') + return { path: next, intact } +} + +function confirmExisting(output, bytes, initial, intact) { + if (!singleFile(initial) || initial.size !== BigInt(bytes.length)) throw new Error(`Workbook target already exists or is unsafe: ${output}`) + const fd = openSync(output, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0)) + try { + const current = fstatSync(fd, { bigint: true }) + if (intact() && singleFile(current) && sameFile(initial, current) && current.size === initial.size && + readFileSync(fd).equals(bytes)) { + const after = noEntry(output) + if (intact() && singleFile(after) && sameFile(current, after) && after.ctimeNs === current.ctimeNs) return + } + } finally { closeSync(fd) } + throw new Error(`Workbook target already exists with different bytes or changed: ${output}`) +} + +export function publishWorkbook(root, sha, methodCount, payload) { + if (!validSha(sha) || !Number.isSafeInteger(methodCount) || methodCount < 1) throw new Error('Invalid workbook output identity') + const dir = outputDirectory(resolve(root), sha) + const output = join(dir.path, `Deva-Web-${methodCount}项能力验收清单.xlsx`) + const bytes = Buffer.from(payload) + const existing = noEntry(output) + if (existing) { + confirmExisting(output, bytes, existing, dir.intact) + return { output, reused: true } + } + // Publish complete bytes without a replace operation; removing the staging link restores nlink=1. + const stage = join(dir.path, `.parity-workbook-${randomUUID()}.tmp`) + if (!dir.intact()) throw new Error('Workbook output directory changed') + const fd = openSync(stage, 'wx', 0o644) + const staged = fstatSync(fd, { bigint: true }) + let created = false + try { + writeFileSync(fd, bytes) + if (!dir.intact() || !sameFile(staged, noEntry(stage))) throw new Error('Workbook staging file or directory changed') + try { linkSync(stage, output); created = true } catch (error) { if (error.code !== 'EEXIST') throw error } + } finally { + closeSync(fd) + if (dir.intact() && sameFile(staged, noEntry(stage))) unlinkSync(stage) + } + const final = noEntry(output) + if (created && !sameFile(staged, final)) throw new Error('Published workbook target changed') + confirmExisting(output, bytes, final, dir.intact) + return { output, reused: !created } +} diff --git a/scripts/workbench/parity-workbook-ooxml.mjs b/scripts/workbench/parity-workbook-ooxml.mjs new file mode 100644 index 00000000..92fc1e83 --- /dev/null +++ b/scripts/workbench/parity-workbook-ooxml.mjs @@ -0,0 +1,98 @@ +import { createRequire } from 'node:module' + +const requireFromDesktop = createRequire(new URL('../../apps/desktop/package.json', import.meta.url)) +const mainNs = 'http://schemas.openxmlformats.org/spreadsheetml/2006/main' +const relNs = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' +const pkgNs = 'http://schemas.openxmlformats.org/package/2006' +const mime = 'application/vnd.openxmlformats-officedocument.spreadsheetml' +const xml = (body) => `${body}` +const escapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' } +const attr = (value) => String(value).replace(/[&<>"']/g, (character) => escapes[character]) +const text = (value) => attr(String(value) + .replace(/_x[\da-fA-F]{4}_/gi, (escape) => `_x005F_${escape.slice(1)}`) + .replace(/[\u0000-\u0008\u000b-\u001f\uD800-\uDFFF\uFFFE\uFFFF]/gu, (character) => + `_x${character.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0')}_`)) +const rels = (items) => xml(`${items.join('')}`) +const rel = (id, type, target, external = false) => `` +const override = (name, type) => `` + +const palette = { + body: ['172B42', 'FFFFFF'], alternate: ['172B42', 'F2F6FA'], header: ['FFFFFF', '254B69', 'bold'], + title: ['FFFFFF', '162F48', 'bold', 17], meta: ['324E65', 'EAF1F8'], link: ['14548C', 'FFFFFF', 'underline'], + metaLink: ['14548C', 'EAF1F8', 'underline'], total: ['162F48', 'E1ECF7', 'bold'], + implemented: ['0F5132', 'DDF3E8', 'bold'], partial: ['704700', 'FFF0C2', 'bold'], + pending: ['713247', 'F7E5EE', 'bold'], desktop: ['37465D', 'E8EDF3', 'bold'], subscription: ['1F4F7A', 'D9EDF9', 'bold'], +} +const styles = Object.keys(palette) + +function styleXml() { + const values = Object.values(palette) + const fonts = values.map(([foreground, , mark, size = 11]) => + `${mark === 'bold' ? '' : mark === 'underline' ? '' : ''}`) + const fills = values.map(([, bg]) => ``) + const xfs = values.map((_, i) => ``) + return xml(`${fonts.join('')}${fills.join('')}${xfs.join('')}`) +} + +export const cell = (value, style, href) => ({ value, style, href }) +const asCell = (value) => typeof value === 'object' && value !== null ? value : { value } +function col(index) { + let name = '' + for (let n = index + 1; n > 0; n = Math.floor((n - 1) / 26)) name = String.fromCharCode(65 + ((n - 1) % 26)) + name + return name +} + +function height(row, widths) { + const lines = row.map((item, i) => String(asCell(item).value ?? '').split('\n').reduce((sum, line) => { + const chars = [...line].reduce((size, character) => size + (character.codePointAt(0) > 255 ? 2 : 1), 0) + return sum + Math.max(1, Math.ceil(chars / Math.max(1, widths[i] - 3))) + }, 0)) + return Math.min(390, 8 + 16 * Math.max(1, ...lines)) +} + +function sheetXml({ widths, prefix, header, rows, frozenColumns = 0 }) { + const links = [] + const headerRow = prefix.length + 1 + const lastCol = col(widths.length - 1) + const render = (row, number, rowHeight, fallback) => `${row.map((item, i) => { + const { value, href, style } = asCell(item) + const ref = `${col(i)}${number}` + if (href) links.push({ ref, href }) + const s = styles.indexOf(style ?? (href ? 'link' : fallback)) + if (Number.isSafeInteger(value)) return `${value}` + return `${text(value ?? '')}` + }).join('')}` + const top = `${col(frozenColumns)}${headerRow + 1}` + const pane = frozenColumns ? 'bottomRight' : 'bottomLeft' + const view = `` + const cols = `${widths.map((w, i) => ``).join('')}` + const body = prefix.map((item, i) => render([item], i + 1, i === 0 ? 32 : 21, i === 0 ? 'title' : 'meta')).join('') + + render(header, headerRow, height(header, widths), 'header') + rows.map((row, i) => + render(row, headerRow + i + 1, height(row, widths), i % 2 ? 'alternate' : 'body')).join('') + const filter = `` + const merges = `${prefix.map((_, i) => ``).join('')}` + const hyperlinks = links.length ? `${links.map(({ ref }, i) => ``).join('')}` : '' + return { + data: xml(`${view}${cols}${body}${filter}${merges}${hyperlinks}`), + relationships: links.length ? rels(links.map(({ href }, i) => rel(`rId${i + 1}`, 'hyperlink', href, true))) : null, + } +} + +export function zipWorkbook(sheets) { + const { zipSync, strToU8 } = requireFromDesktop('fflate') + const path = (i) => `xl/worksheets/sheet${i + 1}.xml` + const files = { + '[Content_Types].xml': xml(`${override('xl/workbook.xml', 'sheet.main')}${override('xl/styles.xml', 'styles')}${sheets.map((_, i) => override(path(i), 'worksheet')).join('')}`), + '_rels/.rels': rels([rel('rId1', 'officeDocument', 'xl/workbook.xml')]), + 'xl/workbook.xml': xml(`${sheets.map(({ name }, i) => ``).join('')}`), + 'xl/_rels/workbook.xml.rels': rels([...sheets.map((_, i) => rel(`rId${i + 1}`, 'worksheet', `worksheets/sheet${i + 1}.xml`)), rel(`rId${sheets.length + 1}`, 'styles', 'styles.xml')]), + 'xl/styles.xml': styleXml(), + } + sheets.forEach((sheet, i) => { + const { data, relationships } = sheetXml(sheet) + files[path(i)] = data + if (relationships) files[`xl/worksheets/_rels/sheet${i + 1}.xml.rels`] = relationships + }) + // ZIP stores local DOS time; a fixed local calendar date is stable across time zones. + return zipSync(Object.fromEntries(Object.entries(files).map(([name, body]) => [name, strToU8(body)])), { level: 6, mtime: new Date(2000, 0, 1) }) +} diff --git a/scripts/workbench/parity-workbook.test.mjs b/scripts/workbench/parity-workbook.test.mjs new file mode 100644 index 00000000..bb7ed687 --- /dev/null +++ b/scripts/workbench/parity-workbook.test.mjs @@ -0,0 +1,233 @@ +import assert from 'node:assert/strict' +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { linkSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { createRequire } from 'node:module' +import { tmpdir } from 'node:os' +import { basename, dirname, join } from 'node:path' +import { test } from 'node:test' +import { promisify } from 'node:util' +import { manifestPath, root } from './check-parity.mjs' +import { buildWorkbook, defaultRepo, loadParity, parseOptions, run } from './export-parity-workbook.mjs' +import { publishWorkbook, snapshotFromEntries } from './parity-workbook-guard.mjs' + +const requireFromDesktop = createRequire(new URL('../../apps/desktop/package.json', import.meta.url)) +const { unzipSync, strFromU8 } = requireFromDesktop('fflate') +const concurrently = promisify(execFile) +const decode = (value) => value.replace(/&(amp|lt|gt|quot|apos);/g, (_, entity) => + ({ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" })[entity]) + +// Parse the generated XML subset (elements, attributes and the five built-in entities). +function parseXml(source) { + const doc = { children: [], text: '' } + const stack = [doc] + for (const token of source.match(/<[^>]+>|[^<]+/g)) { + if (token.startsWith(')$/.exec(token) + const attrs = Object.fromEntries([...attributes.matchAll(/([\w:]+)="([^"]*)"/g)].map(([, key, value]) => [key, decode(value)])) + const node = { name, attrs, children: [], text: '' } + stack.at(-1).children.push(node) + if (!token.endsWith('/>')) stack.push(node) + } else stack.at(-1).text += decode(token) + } + assert.equal(stack.length, 1) + assert.equal(doc.children.length, 1) + return doc.children[0] +} +const child = (node, name) => node.children.find((element) => element.name === name) +const content = (node) => node.text + node.children.map(content).join('') +const nextSha = (sha) => `${sha.slice(0, -1)}${sha.endsWith('a') ? 'b' : 'a'}` +const github = (repo, sha, file) => `https://github.com/${repo}/blob/${sha}/${file}` + +function unpack(bytes) { + const files = unzipSync(bytes) + const get = (name) => parseXml(strFromU8(files[name])) + const book = get('xl/workbook.xml') + const tabs = child(book, 'sheets').children.map(({ attrs }) => attrs.name) + const sheets = tabs.map((name, i) => { + const tree = get(`xl/worksheets/sheet${i + 1}.xml`) + const refs = get(`xl/worksheets/_rels/sheet${i + 1}.xml.rels`).children + const targets = new Map(refs.map(({ attrs }) => { + assert.equal(attrs.TargetMode, 'External') + assert.match(attrs.Type, /\/hyperlink$/) + return [attrs.Id, attrs.Target] + })) + const links = new Map(child(tree, 'hyperlinks').children.map(({ attrs }) => [attrs.ref, targets.get(attrs['r:id'])])) + assert.equal(links.size, refs.length) + const rows = child(tree, 'sheetData').children.map(({ children }) => children.map((c) => { + assert.ok(!child(c, 'f')) + return { value: content(c), type: c.attrs.t, link: links.get(c.attrs.r), style: c.attrs.s } + })) + const first = Number(child(child(child(tree, 'sheetViews'), 'sheetView'), 'pane').attrs.ySplit) + assert.match(child(tree, 'autoFilter').attrs.ref, new RegExp(`^A${first}:[A-Z]+${rows.length}$`)) + return { name, links, rows, data: rows.slice(first) } + }) + return { files, tabs, sheets } +} + +function actualParity() { + // Format tests can run while linked sources are being edited. These in-memory + // workbooks use a synthetic commit and are never published. The CLI checks actual Git blobs. + const base=realpathSync(root) + const manifest=loadParity({ read(file) { + const path=join(base,file) + assert.ok(path.startsWith(base+'/') && realpathSync(path)===path && lstatSync(path).isFile()) + return readFileSync(path) + } }) + return {manifest,sha:'0123456789abcdef0123456789abcdef01234567'} +} + +test('exact desktop AST methods and evidence, flows, values, and deterministic OOXML', () => { + const { manifest, sha } = actualParity() + const result = buildWorkbook(manifest, { sha }) + assert.deepEqual(result.bytes, buildWorkbook(manifest, { sha }).bytes) + assert.notDeepEqual(result.bytes, buildWorkbook(manifest, { sha: nextSha(sha) }).bytes) + const { files, tabs, sheets: [overview, methods, flows, values] } = unpack(result.bytes) + assert.equal(Object.keys(files).length, 13) + assert.ok(Object.keys(files).every((name) => !/macro|vba|externalLink/i.test(name))) + assert.deepEqual(tabs, ['总览', `${manifest.baseline.methods}项能力`, '跨功能流程', '平台值']) + assert.match(overview.rows[1][0].value, new RegExp(sha)) + assert.ok([...overview.links.values()].includes(github(defaultRepo, sha, manifestPath))) + assert.equal(overview.data.length, manifest.baseline.groups + 1) + assert.equal(methods.data.length, manifest.baseline.methods) + assert.equal(new Set(methods.data.map(([key]) => key.value)).size, manifest.baseline.methods) + assert.equal(methods.data.filter((row) => row[4].value === '订阅 · 含清理').length, manifest.baseline.subscriptions) + const expectedMethods = manifest.groups.flatMap((group) => group.methods.map((method) => ({ group, method }))) + let expectedEvidence = 1 // Methods header links to the exact AST input. + const dispositions = new Map([['已实现', 0], ['部分覆盖', 0], ['待实现', 0], ['仅桌面', 0]]) + for (const [i, { group, method }] of expectedMethods.entries()) { + const row = methods.data[i] + const { desktop, web } = method + assert.deepEqual(row.slice(0, 4).map(({ value }) => value), [`${group.name}.${method.name}`, group.name, method.kind, method.channel]) + assert.equal(row[6].value, desktop.use) + const label = web.status === 'implemented' ? '已实现' : web.status === 'desktop-only' ? '仅桌面' : web.partial ? '部分覆盖' : '待实现' + assert.equal(row[7].value, label) + dispositions.set(label, dispositions.get(label) + 1) + assert.equal(row[9].value, web.semantic) + if (web.partial) assert.deepEqual(row.slice(10, 12).map(({ value }) => value), [web.partial.scope, web.partial.remaining]) + const implementation = web.implementation ?? web.partial + for (const [j, file] of [implementation?.handler, implementation?.test, desktop.host ?? group.host, desktop.entry].entries()) { + assert.equal(row[12 + j].value, file ?? '') + assert.equal(row[12 + j].link, file ? github(defaultRepo, sha, file) : undefined) + if (file) expectedEvidence++ + } + } + assert.ok(expectedEvidence >= 344) + assert.equal(methods.links.size, expectedEvidence + 1) // One more non-blob link goes to the commit. + assert.deepEqual(overview.data[0].map(({ value }) => value), ['方法合计', String(manifest.baseline.methods), + String(manifest.baseline.subscriptions), ...[...dispositions.values()].map(String)]) + assert.ok(methods.data.find(([key]) => key.value === 'skills.list')?.[13].link) + assert.ok(methods.data.find(([key]) => key.value === 'skills.get')?.[12].link) + assert.ok(!methods.data.some(([key]) => key.value === 'platform')) + assert.deepEqual(flows.data.map((row) => row.map(({ value, link }) => [value, link])), manifest.flows.map(({ id, methods, expectation, precedent }) => + [[id, undefined], [methods.join('\n'), undefined], [expectation, undefined], [precedent ?? '', precedent ? github(defaultRepo, sha, precedent) : undefined]])) + assert.equal(values.data.length, manifest.baseline.values) + const platform = values.data.find(([key]) => key.value === 'platform') + assert.equal(platform[1].value, 'process.platform') + assert.ok(platform[10].link.startsWith(`https://github.com/${defaultRepo}/blob/${sha}/`)) +}) + +test('fork links preserve casing; string cells preserve formula-looking Unicode and XML characters', () => { + const { manifest, sha } = actualParity() + const fork = 'Case-Preserving/Repo_Fork.1' + const example = '=1+1 中文 😺 & < > " \' _x0041_ \u0001' + const method = manifest.groups[0].methods[0] + method.desktop.use = example + method.desktop.host = '目录/文件 #?&.ts' + const { sheets: [overview, methods] } = unpack(buildWorkbook(manifest, { sha, repo: fork, pr: 321 }).bytes) + assert.ok([...overview.links.values()].includes(`https://github.com/${fork}/pull/321`)) + assert.equal(methods.data[0][6].type, 'inlineStr') + assert.equal(methods.data[0][6].value, example.replace('_x0041_', '_x005F_x0041_').replace('\u0001', '_x0001_')) + assert.equal(methods.data[0][14].link, github(fork, sha, '%E7%9B%AE%E5%BD%95/%E6%96%87%E4%BB%B6%20%23%3F%26.ts')) + assert.deepEqual(parseOptions(['--repo', fork, '--pr', '321']), { repo: fork, pr: 321 }) + for (const repo of ['owner/repo\n', 'https://owner/repo', '../repo', 'owner/.', 'owner/repo.git', 'owner/repo?x', 'owner/repo/extra', 'foo--bar/repo', 'o%40x/r']) { + assert.throws(() => parseOptions(['--repo', repo]), /Invalid --repo/) + } + for (const pr of ['01', '0', '-1', '1.1', '1e3', '1\n', '9007199254740992']) assert.throws(() => parseOptions(['--pr', pr]), /Invalid --pr/) + assert.equal(run(['--repo', 'x/y', '--repo', 'z/y'], { stderr: () => {} }), 2) +}) + +const sha = 'abcdef1234567890abcdef1234567890abcdef12' +const payload = Buffer.from('original verified workbook bytes') +function scratch(t) { + const temp = realpathSync(tmpdir()) + const dir = mkdtempSync(join(temp, 'deva-parity-test-')) + const original=lstatSync(dir,{bigint:true}) + t.after(() => { + assert.equal(dirname(dir), temp) + assert.match(basename(dir), /^deva-parity-test-[a-z0-9]{6}$/i) + const current=lstatSync(dir,{bigint:true}) + assert.equal(realpathSync(dir),dir); assert.ok(current.isDirectory() && current.uid===BigInt(process.geteuid())) + assert.deepEqual([current.dev,current.ino],[original.dev,original.ino]) + rmSync(dir, { recursive: true }) + }) + return dir +} + +test('snapshot requires exact-case tracked, staged and actual raw bytes for every input', (t) => { + const dir = scratch(t) + const path = 'evidence/Entry.ts' + mkdirSync(join(dir, 'evidence')) + writeFileSync(join(dir, path), payload) + const blob = createHash('sha1').update(`blob ${payload.length}\0`).update(payload).digest('hex') + const tree = new Map([[path, `100644 ${blob}`]]) + assert.throws(() => snapshotFromEntries(dir, sha, tree, new Map()).read(path), /HEAD\/index mismatch/) + assert.throws(() => snapshotFromEntries(dir, sha, tree, new Map([[path, `100755 ${blob}`]])).read(path), /HEAD\/index mismatch/) + assert.throws(() => snapshotFromEntries(dir, sha, tree, tree).read('evidence/entry.ts'), /exact-case/) + assert.throws(() => snapshotFromEntries(dir, sha, tree, tree).read('../Entry.ts'), /Invalid repository path/) + assert.deepEqual(snapshotFromEntries(dir, sha, tree, tree).read(path), payload) + writeFileSync(join(dir, path), 'different worktree bytes') + assert.throws(() => snapshotFromEntries(dir, sha, tree, tree).read(path), /Worktree bytes differ/) + writeFileSync(join(dir, 'untrusted'), payload) + symlinkSync(join(dir, 'untrusted'), join(dir, 'evidence', 'Link.ts')) + const symlinkTree = new Map([['evidence/Link.ts', `100644 ${blob}`]]) + assert.throws(() => snapshotFromEntries(dir, sha, symlinkTree, symlinkTree).read('evidence/Link.ts'), /real, exact-case/) +}) + +test('publication is byte-idempotent and keeps unrelated files and links untouched', (t) => { + const dir = scratch(t) + const outputParent = join(dir, 'test-results', `parity-${sha.slice(0, 7)}`) + const output = join(outputParent, 'Deva-Web-186项能力验收清单.xlsx') + assert.deepEqual(publishWorkbook(dir, sha, 186, payload), { output, reused: false }) + assert.deepEqual(publishWorkbook(dir, sha, 186, payload), { output, reused: true }) + assert.throws(() => publishWorkbook(dir, sha, 186, Buffer.alloc(payload.length, 'X')), /exists/) + assert.deepEqual(readFileSync(output), payload) + assert.deepEqual(readdirSync(outputParent), [basename(output)]) + const unrelated = join(dir, 'unrelated') + writeFileSync(unrelated, payload) + symlinkSync(unrelated, join(outputParent, 'Deva-Web-187项能力验收清单.xlsx')) + linkSync(unrelated, join(outputParent, 'Deva-Web-188项能力验收清单.xlsx')) + const dangling = join(outputParent, 'Deva-Web-189项能力验收清单.xlsx') + symlinkSync(join(dir, 'nonexistent'), dangling) + for (const methodCount of [187, 188, 189]) assert.throws(() => publishWorkbook(dir, sha, methodCount, payload), /unsafe/) + assert.deepEqual(readFileSync(unrelated), payload) + assert.ok(lstatSync(dangling).isSymbolicLink()) + + const other = scratch(t) + symlinkSync(join(dir, 'test-results'), join(other, 'test-results'), 'dir') + assert.throws(() => publishWorkbook(other, sha, 186, payload), /Unsafe workbook output directory/) + const nested = scratch(t) + mkdirSync(join(nested, 'test-results')) + symlinkSync(outputParent, join(nested, 'test-results', `parity-${sha.slice(0, 7)}`), 'dir') + assert.throws(() => publishWorkbook(nested, sha, 186, payload), /Unsafe workbook output directory/) +}) + +test('competing writers preserve complete bytes and only reuse exact content', async (t) => { + const dir = scratch(t) + const entry = new URL('./parity-workbook-guard.mjs', import.meta.url).href + const script = `import { publishWorkbook } from ${JSON.stringify(entry)}; const [dir, sha, value] = process.argv.slice(1); console.log(JSON.stringify(publishWorkbook(dir, sha, 186, Buffer.from(value))));` + const launch = (value) => concurrently(process.execPath, ['--input-type=module', '-e', script, dir, sha, value]) + const candidates = ['candidate one', 'candidate two'] + const results = await Promise.allSettled(candidates.map(launch)) + const winner = results.findIndex(({ status }) => status === 'fulfilled') + assert.notEqual(winner, -1) + assert.equal(results.filter(({ status }) => status === 'fulfilled').length, 1) + const { output, reused } = JSON.parse(results[winner].value.stdout) + assert.equal(reused, false) + assert.equal(readFileSync(output, 'utf8'), candidates[winner]) + assert.deepEqual(publishWorkbook(dir, sha, 186, Buffer.from(candidates[winner])), { output, reused: true }) + assert.deepEqual(readdirSync(dirname(output)), [basename(output)]) +}) diff --git a/scripts/workbench/skill-library-ui.test.mjs b/scripts/workbench/skill-library-ui.test.mjs new file mode 100644 index 00000000..677e27e4 --- /dev/null +++ b/scripts/workbench/skill-library-ui.test.mjs @@ -0,0 +1,438 @@ +import assert from 'node:assert/strict' +import { readFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { setImmediate } from 'node:timers/promises' +import test from 'node:test' + +const require = createRequire(new URL('../../apps/desktop/package.json', import.meta.url)) +const ts = require('typescript') +const react = require('react') +const { createElement } = react +const { renderToStaticMarkup } = require('react-dom/server') +const src = new URL('../../apps/desktop/src/workbench/', import.meta.url) +const read = (name) => readFile(new URL(name, src), 'utf8') +async function load(name, dependencies = {}, extra = '') { + const js = ts.transpileModule(await read(name) + extra, { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX } + }).outputText + const mod = { exports: {} } + new Function('require', 'module', 'exports', 'window', js)( + (key) => Object.hasOwn(dependencies, key) ? dependencies[key] : require(key), mod, mod.exports, {}) + return mod.exports +} +const base = await load('transport.ts') +const transport = await load('skill-library-transport.ts', { './transport': base }) +const logic = await load('skill-library-controller.ts', { './skill-library-transport': transport }) +const labels = await load('skill-library-copy.ts') +const { createTransport, HttpFailure } = base +const { createSkillLibraryTransport, skillProblem } = transport +const { createSkillLibrary, draftRoles, invalidDraftRoles, roleNeedsReview } = logic + +const revision = (letter) => letter.repeat(64) +const documentId = 'editorial-guide' +const oldRole = 'legacy-role' +const baseSkill = { id: documentId, name: 'Editorial Guide', description: 'Plain text editing guide', source: 'custom', enabled: true, + roles: null, revision: revision('a'), canConfigure: true } +const builtin = { ...baseSkill, id: 'create-skill', name: 'create-skill', source: 'builtin', canConfigure: false } +const instructions = '\n# Raw\n [link](https://example.invalid/link) \n' +const detail = (s = baseSkill, text = instructions) => ({ ...s, detail: 'document', instructions: text, + trigger: '', license: '', compatibility: '', allowedTools: [], metadata: {} }) +const catalog = (item = baseSkill, rev = revision('b')) => ({ skills: [builtin, item], revision: rev }) +const withExecution = (value) => ({ ...value, execution: 'inactive' }) +const bootstrap = { protocol: 1, version: '1', platform: 'linux', config: {}, csrf: 'csrf-test', expiresAt: 1234, capabilities: { skillLibrary: true } } +const json = (value, status = 200) => new Response(JSON.stringify(value), { status }) +const signal = new AbortController().signal +const options = [{ id: 'general', name: 'General', enabled: true }, { id: '编校', name: 'Editor', enabled: false }] +const malformed = /Invalid skill library response/ +function defer() { + let resolve, reject + const promise = new Promise((yes, no) => { resolve = yes; reject = no }) + return { promise, resolve, reject } +} +async function until(check) { + for (let i = 0; i < 40; i++) { if (check()) return; await setImmediate() } + assert.ok(check(), 'state never settled') +} + +function queueTransport(steps) { + return createTransport(async (url, init) => { + const step = steps.shift() + assert.ok(step, `Unexpected request ${url}`) + const [method, path, body, result, status = 200] = step + assert.equal(url, `/api/v1${path}`) + assert.equal(init.method, method) + assert.deepEqual(init.body ? JSON.parse(init.body) : undefined, body) + assert.equal(init.credentials, 'same-origin') + assert.equal(init.mode, 'same-origin') + assert.equal(init.redirect, 'error') + assert.equal(init.cache, 'no-store') + assert.equal(init.headers.accept, 'application/json') + if (path !== '/bootstrap') assert.equal(init.signal, signal) + assert.equal(init.headers['x-deva-csrf'], method === 'GET' ? undefined : bootstrap.csrf) + assert.equal(init.referrerPolicy, method === 'GET' ? 'no-referrer' : 'same-origin') + return json(result, status) + }) +} + +test('literal bootstrap capability and request projections preserve the progressive read boundary', async () => { + const updated = { ...baseSkill, enabled: false, revision: revision('c') } + const steps = [ + ['GET', '/bootstrap', undefined, { ...bootstrap, capabilities: { skillLibrary: 'true', textChat: true } }], + ['GET', '/bootstrap', undefined, bootstrap], + ['GET', '/skills', undefined, withExecution(catalog())], + ['GET', `/skills/${documentId}`, undefined, withExecution({ skill: detail() })], + ['GET', '/skills/-/roles', undefined, { roles: options }], + ['PATCH', `/skills/${documentId}/preferences`, { revision: baseSkill.revision, enabled: false }, withExecution({ skill: updated })], + ['POST', '/skills/-/changes', { after: revision('b'), waitMs: 8000 }, { changed: true, revision: revision('d') }] + ] + const workbench = queueTransport(steps) + const disabled = (await workbench.inspect()).bootstrap + assert.deepEqual(disabled.capabilities, { textChat: true }) + assert.equal(createSkillLibraryTransport(workbench, disabled), undefined) + const active = (await workbench.inspect()).bootstrap + assert.deepEqual(active.capabilities, { skillLibrary: true }) + const api = createSkillLibraryTransport(workbench, active) + assert.deepEqual(steps.map(([method]) => method), ['GET', 'GET', 'GET', 'PATCH', 'POST'], 'constructing a client made a network request') + assert.deepEqual(await api.list(signal), catalog()) + assert.deepEqual(await api.detail(documentId, signal), detail()) + assert.deepEqual(await api.roles(signal), options) + assert.deepEqual(await api.patch(baseSkill, { enabled: false }, signal), updated) + assert.deepEqual(await api.changes(revision('b'), 8000, signal), { changed: true, revision: revision('d') }) + assert.deepEqual(steps, []) +}) + +test('strict wire and CAS reject unsafe routes, mixed edits, mismatched receipts and active execution', async () => { + const wire = [ + { ...catalog(), execution: 'active' }, + withExecution({ ...catalog(), skills: [baseSkill, baseSkill] }), + withExecution({ ...catalog(), skills: [{ ...builtin, canConfigure: true }] }), + withExecution({ ...catalog(), skills: [{ ...baseSkill, instructions }] }), + withExecution({ ...catalog(), revision: '1' }), + withExecution({ skill: { ...detail(), id: 'other' } }), + withExecution({ skill: { ...detail(), metadata: { 'key': 2 } } }), + { roles: [{ ...options[0], prompt: 'private' }] }, + { roles: [options[0], options[0]] }, + withExecution({ skill: { ...baseSkill, enabled: false } }), + withExecution({ skill: { ...baseSkill, enabled: false, revision: revision('d'), id: 'other' } }), + { revision: revision('b'), changed: true }, + withExecution({ skill: null }) + ] + let calls = 0 + const api = createSkillLibraryTransport(createTransport(async () => { calls++; return json(wire.shift()) }), bootstrap) + for (const id of ['../x', 'a..b', 'a.', 'x%2fy', 'x\n', 'x?y', 'CONSTRUCTOR']) await assert.rejects(api.detail(id, signal), malformed) + for (const target of [builtin, { ...baseSkill, canConfigure: false }, { ...baseSkill, revision: '0x1' }, { ...baseSkill, id: '/x' }]) + await assert.rejects(api.patch(target, { enabled: false }, signal), malformed) + for (const edit of [{}, { enabled: 'false' }, { roles: [undefined] }, { roles: Array(1) }, { roles: ['x', 'x'] }, { roles: [], enabled: false }, { revision: '0', enabled: false }]) + await assert.rejects(api.patch(baseSkill, edit, signal), malformed) + for (const ms of [-1, 1.2, 8001, '8000']) await assert.rejects(api.changes(revision('b'), ms, signal), malformed) + assert.equal(calls, 0) + for (let i = 0; i < 5; i++) await assert.rejects(api.list(signal), malformed) + for (let i = 0; i < 2; i++) await assert.rejects(api.detail(documentId, signal), malformed) + for (let i = 0; i < 2; i++) await assert.rejects(api.roles(signal), malformed) + for (let i = 0; i < 2; i++) await assert.rejects(api.patch(baseSkill, { enabled: false }, signal), malformed) + await assert.rejects(api.changes(revision('b'), 0, signal), malformed) + assert.equal(await api.detail(documentId, signal), null) + assert.deepEqual(wire, []) +}) + +function fixture(t, initial = baseSkill, overrides = {}) { + let current = initial, currentRevision = revision('b') + let active = 0, maximum = 0, expired = 0 + const changeRequests = [] + const calls = [] + const body = () => catalog(current, currentRevision) + const fake = { + list: async () => current ? body() : { skills: [builtin], revision: currentRevision }, + detail: async () => current ? detail(current) : null, + roles: async () => options, + patch: async (target, edit) => { + assert.equal(target.revision, current.revision) + current = { ...current, ...edit, revision: revision('e') }; currentRevision = revision('f') + return current + }, + changes(after, ms, signal) { + const pending = defer() + active++ + maximum = Math.max(maximum, active) + signal.addEventListener('abort', () => pending.reject(new Error('closed')), { once: true }) + changeRequests.push({ after, ms, signal, resolve: pending.resolve, reject: pending.reject }) + return pending.promise.finally(() => { active-- }) + }, ...overrides + } + const api = Object.fromEntries(Object.entries(fake).map(([name, call]) => [name, (...args) => { + calls.push([name, ...args]) + return call(...args) + }])) + const controller = createSkillLibrary(api, () => { expired++ }, [0, 0, 0]) + t.after(() => controller.dispose()) + return { controller, snap: controller.snapshot, calls, changeRequests, maximum: () => maximum, expired: () => expired, + modify(item, rev) { current = item; currentRevision = rev }, count(method) { return calls.filter(([name]) => name === method).length } } +} + +test('each explicit panel visit runs one live cursor; only the selected custom row and role chooser get details', async (t) => { + const f = fixture(t) + const { controller: c } = f + assert.deepEqual(f.calls, []) + c.start(); c.start() + await until(() => f.changeRequests.length === 1) + assert.deepEqual(f.calls.map(([name]) => name), ['list', 'changes']) + assert.equal(f.changeRequests[0].ms, 8000) + assert.equal(c.open(builtin.id), false) + assert.equal(c.openRoles(), false) + assert.equal(c.open(documentId), true) + await until(() => !!f.snap().selected?.document) + assert.equal(f.count('detail'), 1) + assert.equal(f.count('roles'), 0) + c.openRoles(); c.openRoles() + await until(() => !!f.snap().roles?.options) + assert.equal(f.count('roles'), 1) + c.back() + assert.equal(f.snap().selected, undefined) + assert.equal(f.snap().roles, undefined) + const changed = { ...baseSkill, name: 'Renamed', revision: revision('c') } + f.modify(changed, revision('d')) + f.changeRequests[0].resolve({ changed: true, revision: revision('d') }) + await until(() => f.snap().catalog?.revision === revision('d')) + assert.equal(f.count('detail'), 1, 'sync read opened a detail when the list was active') + await c.refresh() + assert.equal(f.maximum(), 1) + c.dispose() + assert.ok(f.changeRequests.every((r) => r.signal.aborted)) + await c.refresh() + assert.equal(f.count('list'), 3) +}) + +test('the switch stays on its saved value until the exact PATCH and readback; list toggles never read documents', async (t) => { + const patch = defer(), readback = defer() + let lists = 0 + const after = { ...baseSkill, enabled: false, revision: revision('c') } + const f = fixture(t, baseSkill, { + list: async () => ++lists === 1 ? catalog() : readback.promise, + patch: async (row, edit) => { assert.deepEqual(row, baseSkill); assert.deepEqual(edit, { enabled: false }); return patch.promise } + }) + const { controller: c } = f + c.start(); await until(() => !!f.snap().catalog) + c.toggle(builtin.id) + c.toggle(documentId); c.toggle(documentId) + assert.equal(f.count('patch'), 1) + assert.equal(f.snap().feedback.status, 'saving') + assert.equal(f.snap().catalog.skills[1].enabled, true) + patch.resolve(after) + await until(() => lists === 2) + assert.equal(f.snap().feedback.status, 'saving') + readback.resolve(catalog(after, revision('d'))) + await until(() => f.snap().feedback?.status === 'saved') + assert.equal(f.snap().catalog.skills[1].enabled, false) + assert.equal(f.count('detail'), 0) +}) + +test('409, 404, 403, 422 and lost receipts are distinct, and failures only trigger readback', async (t) => { + const failures = [[409, 'skill_conflict', 'stale'], [404, 'skill_not_found', 'missing'], [403, 'skill_read_only', 'readonly'], + [422, 'skill_restricted', 'restricted'], [409, 'skill_unknown_role', 'unknownRole'], [503, 'skill_storage_unconfirmed', 'unavailable']] + for (const [status, code, expected] of failures) { + const f = fixture(t, baseSkill, { patch: async () => { throw new HttpFailure(status, code) } }) + f.controller.start(); await until(() => !!f.snap().catalog) + f.controller.toggle(documentId) + await until(() => f.snap().feedback?.status === expected && f.count('list') === 2) + assert.equal(f.count('patch'), 1) + assert.equal(f.snap().catalog.skills[1].enabled, true) + assert.equal(f.snap().feedback.edit.enabled, false) + f.controller.dispose() + } + assert.equal(skillProblem(new HttpFailure(409, 'skill_builtin')), 'readonly') + assert.equal(skillProblem(new HttpFailure(409, 'skill_unsupported')), 'restricted') +}) + +test('external revisions recheck the selected detail but retain explicit role drafts pending review; unknown saved roles remain removable', async (t) => { + const historical = { ...baseSkill, roles: [oldRole] } + const f = fixture(t, historical) + const { controller: c } = f + c.start(); await until(() => f.changeRequests.length === 1) + c.open(documentId); await until(() => !!f.snap().selected?.document) + c.openRoles(); await until(() => !!f.snap().roles?.options) + assert.equal(f.snap().roles.draft.mode, 'selected') + assert.deepEqual(draftRoles(f.snap().roles.draft), [oldRole]) + c.pickRole('injected-id', true) + assert.deepEqual(draftRoles(f.snap().roles.draft), [oldRole]) + c.pickRole('编校', true) + assert.deepEqual(draftRoles(f.snap().roles.draft), [oldRole, '编校']) + assert.equal(invalidDraftRoles(f.snap().roles, historical), false) + const externallyChanged = { ...historical, enabled: false, revision: revision('c') } + f.modify(externallyChanged, revision('d')) + f.changeRequests[0].resolve({ changed: true, revision: revision('d') }) + await until(() => f.snap().selected?.document?.revision === revision('c')) + assert.equal(f.count('detail'), 2) + assert.equal(f.count('roles'), 1) + assert.deepEqual(draftRoles(f.snap().roles.draft), [oldRole, '编校']) + assert.equal(roleNeedsReview(f.snap().roles.draft, externallyChanged), true) + c.saveRoles(); assert.equal(f.count('patch'), 0) + await c.reviewRoles() + assert.equal(f.count('roles'), 2) + assert.equal(f.count('patch'), 0) + assert.equal(roleNeedsReview(f.snap().roles.draft, externallyChanged), false) + c.pickRole(oldRole, false) + assert.deepEqual(draftRoles(f.snap().roles.draft), ['编校']) + c.pickRole('编校', false) + assert.deepEqual(draftRoles(f.snap().roles.draft), []) + c.setRoleMode('all'); assert.equal(draftRoles(f.snap().roles.draft), null) + c.setRoleMode('none'); c.saveRoles() + await until(() => f.snap().feedback?.status === 'saved') + assert.equal(f.snap().roles, undefined) + assert.deepEqual(f.calls.find(([name]) => name === 'patch')[2], { roles: [] }) +}) + +test('role CAS 409 retains input and requires review; session expiration cancels the panel', async (t) => { + const f = fixture(t, baseSkill, { patch: async () => { throw new HttpFailure(409, 'skill_conflict') } }) + const { controller: c } = f + c.start(); await until(() => !!f.snap().catalog) + c.open(documentId); await until(() => !!f.snap().selected?.document) + c.openRoles(); await until(() => !!f.snap().roles?.options) + c.setRoleMode('none'); c.saveRoles() + await until(() => f.snap().feedback?.status === 'stale') + assert.deepEqual(draftRoles(f.snap().roles.draft), []) + assert.equal(f.snap().roles.draft.review, true) + c.saveRoles(); assert.equal(f.count('patch'), 1) + await c.reviewRoles() + assert.equal(f.snap().roles.draft.review, false) + assert.equal(f.count('patch'), 1) + const g = fixture(t, baseSkill, { changes: async () => { throw new HttpFailure(401) } }) + g.controller.start() + await until(() => g.expired() === 1) + assert.equal(g.controller.open(documentId), false) + assert.equal(g.count('detail'), 0) +}) + +test('a dropped watch freezes CAS and scrubs details, reconfirms the same cursor, and signs out on final 401', async (t) => { + const reconnect = defer() + let lists = 0, details = 0 + const f = fixture(t, baseSkill, { + list: async () => ++lists === 1 ? catalog() : reconnect.promise, + detail: async () => detail(baseSkill, ++details === 1 ? 'old preview' : 'reconfirmed preview') + }) + const { controller: c } = f + c.start(); await until(() => f.changeRequests.length === 1) + c.open(documentId); await until(() => !!f.snap().selected?.document) + c.openRoles(); await until(() => !!f.snap().roles?.options) + c.setRoleMode('none') + f.changeRequests[0].reject(new TypeError('watch disconnected')) + await until(() => f.snap().reconnecting && lists === 2) + assert.equal(f.snap().selected.document, undefined) + assert.equal(f.snap().roles.draft.review, true) + assert.deepEqual(draftRoles(f.snap().roles.draft), []) + c.saveRoles(); c.toggle(documentId) + assert.equal(f.count('patch'), 0) + reconnect.resolve(catalog()) + await until(() => f.changeRequests.length === 2) + assert.equal(details, 2, 'a matching cursor still needs selected detail confirmation') + assert.equal(f.snap().selected.document.instructions, 'reconfirmed preview') + assert.equal(f.snap().reconnecting, false) + assert.equal(f.snap().roles.draft.review, true) + assert.equal(f.count('roles'), 1, 'reconnecting is not a role selection') + assert.equal(f.count('patch'), 0) + assert.equal(f.maximum(), 1) + assert.equal(f.changeRequests[0].after, f.changeRequests[1].after) + f.changeRequests[1].reject(new HttpFailure(401)) + await until(() => f.expired() === 1) + assert.equal(f.snap().catalog, undefined) + assert.equal(f.snap().selected, undefined) + assert.equal(f.snap().roles, undefined) + assert.equal(f.changeRequests[1].signal.aborted, true) + assert.equal(f.count('patch'), 0) +}) + +test('recovery is bounded when watch keeps failing; permanent errors require explicit Refresh', async (t) => { + const repeated = fixture(t, baseSkill, { changes: async () => { throw new HttpFailure(429, 'skill_busy') } }) + repeated.controller.start() + await until(() => repeated.count('changes') === 4 && repeated.snap().reconnecting === false) + assert.equal(repeated.count('list'), 4) + assert.equal(repeated.snap().syncError, 'unavailable') + repeated.controller.toggle(documentId) + assert.equal(repeated.count('patch'), 0) + repeated.controller.dispose() + + const f = fixture(t) + const { controller: c } = f + c.start(); await until(() => f.changeRequests.length === 1) + c.open(documentId); await until(() => !!f.snap().selected?.document) + f.changeRequests[0].reject(new HttpFailure(403, 'skill_read_only')) + await until(() => f.snap().syncError === 'readonly') + assert.equal(f.snap().selected.document, undefined) + assert.equal(f.snap().reconnecting, false) + assert.equal(f.count('list'), 1) + c.toggle(documentId) + assert.equal(f.count('patch'), 0) + await c.refresh() + await until(() => f.changeRequests.length === 2) + assert.ok(f.snap().selected.document) + assert.equal(f.snap().syncError, undefined) + assert.equal(f.count('detail'), 2) +}) + +test('a completed stale detail and roster read cannot update another view or the reopened list', async (t) => { + const pendingDetail = defer(), pendingRoles = defer() + let detailReads = 0 + const newer = { ...baseSkill, name: 'New title', revision: revision('d') } + const f = fixture(t, baseSkill, { + detail: async () => ++detailReads === 1 ? pendingDetail.promise : detail(newer, 'new literal text'), + roles: async () => pendingRoles.promise + }) + const { controller: c } = f + c.start(); await until(() => !!f.snap().catalog) + c.open(documentId) + const oldDetailSignal = f.calls.find(([name]) => name === 'detail')[2] + f.modify(newer, revision('c')) + await c.refresh() + await until(() => f.snap().selected?.document?.instructions === 'new literal text') + assert.equal(oldDetailSignal.aborted, true) + pendingDetail.resolve(detail()) + await setImmediate() + assert.equal(f.snap().selected?.document?.instructions, 'new literal text') + c.openRoles() + const roleSignal = f.calls.find(([name]) => name === 'roles')[1] + c.back() + assert.equal(roleSignal.aborted, true) + pendingRoles.resolve(options) + await setImmediate() + assert.equal(f.snap().selected, undefined) + assert.equal(f.snap().roles, undefined) +}) + +test('the actual shared desktop extension row, Toggle, settings frame and literal detail are reused', async () => { + const i18n = { useI18n: () => ({ locale: 'en', t: (key) => ({ 'cf.builtin': 'Built-in', 'cf.kindSkill': 'Skill', 'extensions.skills': 'Skills', 'common.back': 'Back' })[key] ?? key }) } + const parts = await load('../renderer/src/redesign/SkillSettingsParts.tsx') + const shell = await load('../renderer/src/redesign/shell-common.tsx', { '../i18n/i18n': i18n, '../components/humation': {}, '../store/profile': {} }) + const frame = await load('../renderer/src/redesign/SettingsFrame.tsx', { '../i18n/i18n': i18n }) + const pane = await load('skill-library.tsx', { '../renderer/src/i18n/i18n': i18n, '../renderer/src/redesign/SkillSettingsParts': parts, + '../renderer/src/redesign/shell-common': shell, './skill-library-controller': logic, './skill-library-transport': transport, + './skill-library-copy': labels, './skill-library.css': {}, react: { ...react, useLayoutEffect: react.useEffect } }, '\nexport { OpenPanel }\n') + const markup = (state) => renderToStaticMarkup(createElement(frame.SettingsFrame, { navigation: 'Extensions', onClose() {} }, + createElement(pane.OpenPanel, { controller: { snapshot: () => state, subscribe: () => () => {}, back() {} } }))) + const list = markup({ catalog: catalog(), listing: false }) + assert.match(list, /role="dialog"/) + assert.match(list, /class="cf-rows"/) + assert.match(list, /data-skill-id="create-skill"[^>]*class="cf-setrow">
/) + assert.match(list, /Built-in · Read-only/) + assert.match(list, /data-testid="workbench-skill-open"[^>]*class="cf-setrow__open"/) + assert.equal([...list.matchAll(/data-testid="workbench-skill-toggle"/g)].length, 1) + assert.match(list, /class="cf-switch is-on" aria-pressed="true"/) + assert.doesNotMatch(list, /workbench-skill-instructions|workbench-skill-roles-save|example\.invalid/) + const view = markup({ catalog: catalog(), listing: false, selected: { item: baseSkill, document: detail(), loading: false } }) + assert.match(view, /class="provider-detail provider-detail--fill"/) + assert.match(view, /data-testid="workbench-skill-back"/) + assert.match(view, /]+data-testid="workbench-skill-instructions"[^>]*>[\s\S]+<img src=/) + assert.doesNotMatch(view, /<(?:img|script|a|iframe)\b|href="https:\/\//) + assert.match(view, /Web chat does not run skills or their tools/) + const native = await read('../renderer/src/redesign/SettingsPane.tsx') + assert.match(native, /\('models'\)/) + assert.match(settings, /chat\.bootstrap\.capabilities\?\.skillLibrary === true/) + assert.match(settings, /event\.nativeEvent\.isTrusted\) setSection\('skills'\)/) + assert.match(settings, //) + assert.match(settings, /lazy\(\(\) => import\('\.\/skill-library'\)\)/) + assert.match(settings, /lazy\(\(\) => import\('\.\/text-workbench'\)\)/) + assert.match(await read('first-use.tsx'), /await import\('\.\/desktop-settings'\)/) +})