diff --git a/.agents/skills/verify-deepseekbot/features/README.md b/.agents/skills/verify-deepseekbot/features/README.md index 9c9993497..31b43f6ad 100644 --- a/.agents/skills/verify-deepseekbot/features/README.md +++ b/.agents/skills/verify-deepseekbot/features/README.md @@ -70,6 +70,7 @@ One file per user-facing feature. Each file has four sections: `Sub-features`, ` | Historical Overview: idle PersonaBot (retired by #2026) | no | `scripts/e2e-activity-idle.mjs` | [activity-center-idle.md](activity-center-idle.md) | | Temporary Workspace Grant authorization, read and revocation | no | `scripts/e2e-workspace-grant.mjs` | [workspace-grant.md](workspace-grant.md) | | Default Bot Browser open, observe, stop and Access refusal | no | `scripts/e2e-browser-lifecycle.mjs` | [browser-lifecycle.md](browser-lifecycle.md) | +| Skill Invocation from `/` in a Bot DM | yes for the reply | `verify-app` Bot DM and `skills-list` / `send --skill` | [skill-invocation.md](skill-invocation.md) | | Composer footer customization and optional reply speed | yes for a speed sample | none (Web interaction path) | [composer-footer.md](composer-footer.md) | | Disposable Memory history, restore and stale-head refusal | no | `scripts/e2e-memory-restore.mjs` | [memory-restore.md](memory-restore.md) | | Version-bound Memory images, Markdown previews and CLI export | no | `scripts/e2e-memory-images.mjs`, `scripts/e2e-memory-markdown.mjs`, `scripts/e2e-memory-formats.mjs` | [memory-images.md](memory-images.md) | diff --git a/.agents/skills/verify-deepseekbot/features/skill-invocation.md b/.agents/skills/verify-deepseekbot/features/skill-invocation.md new file mode 100644 index 000000000..83f191dd5 --- /dev/null +++ b/.agents/skills/verify-deepseekbot/features/skill-invocation.md @@ -0,0 +1,32 @@ +# Skill Invocation in a Bot DM + +A Human types `/` in a PersonaBot DM, picks a Skill, and sends it. The Host stores the Skill's text with the message and the Bot reads it as a `` block ([ADR-0346](../../../../docs/adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)). + +## Sub-features + +- `menu` lists composer commands first, then Skills: Host Skills and the Project Skills under the Bot's Memory Repository `.agents/skills` or `.dsh/skills`. Each row shows its owner (Bot avatar or Skill icon), `/name` and a one-line description. +- `rank` orders Skills by name prefix, then name subsequence, then description text. +- `chip` inserts the picked Skill as one token; Backspace removes it whole; the draft keeps it across reloads. +- `snapshot` stores `{name, owner, path, content}` with the message; editing or deleting the `SKILL.md` later does not change the sent message. +- `deliver` gives the Bot the message with `[/name]` and the `` block, so DSH does not load the Skill a second time. +- `cli` `deepseekbot skills-list --bot [--query]` and `send --body "/name …" --skill /`. + +## How to get to it (user POV) + +- Enter Bot mode, open a Bot DM, type `/` and a few letters in the composer, choose a Skill with the arrow keys and Enter (or click it), write the rest of the message, press Enter. + +## Driving it with verify-app + +Preconditions: `launch` reported a model credential and `doctor` passes. + +1. **Seed a Project Skill.** Get the Bot's Memory Repository from `rpc botharness/list` and the Host profile layout, then write `/.agents/skills/qa-echo/SKILL.md` with frontmatter `name: qa-echo`, `description: Reply with a fixed QA word` and a body such as `Reply with exactly SKILL_QA_7731 and nothing else.` +2. **Menu.** `shot skill-menu --bot-mode --fill "Message =/qa"` and read `skill-menu.aria.txt`: a `/qa-echo · ` menu item appears after any matching command. +3. **Send.** `shot skill-send --bot-mode --fill "Message =/qa" --press Enter --press Enter --wait-text SKILL_QA_7731`. The first Enter picks the Skill, the second sends. +4. **Canonical state.** `rpc botharness/channelTimeline '{"channelId":""}'`: the Human entry has `skillInvocations[0]` with `owner {kind: bot}`, the `path` of the seeded file and its body; the Bot entry replies `SKILL_QA_7731`. +5. **CLI.** `deepseekbot skills-list --bot --query qa` lists `qa-echo`; `deepseekbot send --body "/qa-echo" --skill bot:/qa-echo` returns a committed reply. + +## Gotchas + +- The `/` menu reads the catalog when the DM opens. A Skill written while the DM is open appears after reopening the DM until S3 (live refresh) lands. +- DSH discovers `/.agents/skills` because the Orchestrator's cwd is the Memory Repository; a Skill placed in `.botharness/` is not found. +- Recalling an older message with ArrowUp, or restoring a failed send, keeps `/name` as plain text without the chip. diff --git a/changes/4232-dm-skill-invocation.md b/changes/4232-dm-skill-invocation.md new file mode 100644 index 000000000..f24eb28ef --- /dev/null +++ b/changes/4232-dm-skill-invocation.md @@ -0,0 +1,11 @@ +--- +section: Added +--- + +## en + +- Type `/` in a PersonaBot DM to pick a Skill: commands come first, then Host Skills and the Skills in the Bot's Memory Repository `.agents/skills`, each with its owner and a one-line description. The picked Skill becomes a chip, its text is saved with the message, and the Bot reads that text with your message; `deepseekbot skills-list` and `send --skill` do the same from the CLI ([#4232](https://github.com/BotHarness/DeepSeekBot/issues/4232)). + +## zh + +- 在 PersonaBot 私聊中输入 `/` 即可选择 Skill:先列命令,再列 Host Skill 和该 Bot Memory Repository `.agents/skills` 下的 Skill,每行显示归属和单行描述。选中的 Skill 显示为 chip,其文本随消息保存,Bot 会连同你的消息一起读到;CLI 中可用 `deepseekbot skills-list` 和 `send --skill` 完成同样的操作([#4232](https://github.com/BotHarness/DeepSeekBot/issues/4232))。 diff --git a/changes/4232-skill-invocation-review-fixes.md b/changes/4232-skill-invocation-review-fixes.md new file mode 100644 index 000000000..3e1cfe360 --- /dev/null +++ b/changes/4232-skill-invocation-review-fixes.md @@ -0,0 +1,11 @@ +--- +section: Fixed +--- + +## en + +- Fixed repeated Skill selection in the CLI, selected Skill and mention rendering in Bot prompts, oversized Skill sends being silently truncated, private or archived Bot Skills being accepted in Group sends, and Skill offsets after All Bots expansion ([#4232](https://github.com/BotHarness/BotHarness/issues/4232)). + +## zh + +- 修复 CLI 重复选择同名 Skill、Bot 提示词中已选 Skill 与提及的渲染,超长 Skill 发送时被静默截断、群聊接受无权读取或已归档 Bot 的 Skill,以及所有 Bot 提及展开后的 Skill 位置错误([#4232](https://github.com/BotHarness/BotHarness/issues/4232))。 diff --git a/docs/adr/0345-project-skills-travel-with-their-directory.md b/docs/adr/0345-project-skills-travel-with-their-directory.md new file mode 100644 index 000000000..0ee285080 --- /dev/null +++ b/docs/adr/0345-project-skills-travel-with-their-directory.md @@ -0,0 +1,20 @@ +--- +Status: Proposed +Date: 2026-11-15 +--- + +# Project Skills travel with their directory + +A PersonaBot's Skills are the **Project Skills** of its Memory Repository: `SKILL.md` folders under `/.agents/skills/`. They are not a separate kind of Skill and have no store of their own. The Orchestrator Session's cwd is already the Memory Repository, so DSH's file-skill discovery finds them, and in that PersonaBot's own Sessions they override a **Host Skill** of the same name, without BotHarness registration code. A folder covered by a Workspace Grant contributes Project Skills the same way. BotHarness scans only the granted root itself (`.agents/skills` and `.dsh/skills`) and does not walk up to an enclosing Git root, so visibility never exceeds the Grant. + +Installing a Skill is a file write. A PersonaBot decides where a Skill belongs. If it is the bot's own capability, it goes in the Memory Repository, which the bot may write freely. If it is a project convention, it goes in a Workspace folder, under the existing write authority. Memory's Git history is the record of these writes, so no separate activity entry is created. A Human removes a Project Skill by deleting its files; there is no disabled state. + +Because Project Skills are ordinary text files in the Memory Repository, they travel with every existing way of sharing a PersonaBot: the Memory Git repository, a Bot Zip and a Profile Backup. This differs from ADR-0044. That ADR rejects embedding or auto-installing Skills as **Host** runtime dependencies. A Project Skill is part of the PersonaBot's own content, not a Host dependency. On a target Host, the Project Skills arrive with the rest of the PersonaBot's Memory and are discoverable as soon as the PersonaBot is installed or imported. They get no separate Skill review: they carry the same trust as the Memory content they live in. The marketplace detail page and the PersonaBot profile show a Skills section listing the Memory Repository's Project Skills. Workspace Skills belong to the project and are not listed there. + +## Considered Options + +- **A `.botharness/skills/` folder with a BotHarness skill provider** — rejected: DSH does not scan it. BotHarness would need a per-bot provider, but DSH registrations are scoped only to an agent preset. It would also diverge from the `.agents/skills` layout that Humans and cross-agent tooling already use. +- **A separate "Bot Skill" concept** — rejected: it has the same mechanism as any Project Skill. A second name would suggest storage or rules that do not exist. +- **Walk up to the enclosing Git root like DSH** — rejected for BotHarness listings: a Grant on a monorepo subfolder would expose Skills outside the granted folder. +- **Export only Desired Dependency References and leave the Skill files behind** — rejected: Skills are a defining part of what a PersonaBot can do, and they are plain text that already lives in its Memory. +- **Hold imported Skills in a pending folder until a Human reviews them** — rejected: the rest of the Memory Repository, which also shapes the PersonaBot's behavior, is not held back. A Skill-only gate would add a second copy of each Skill, a move on acceptance, and conflicts with the Memory Git repository shared between Hosts, without closing a gap the Memory itself leaves open. diff --git a/docs/adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md b/docs/adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md new file mode 100644 index 000000000..78ece613b --- /dev/null +++ b/docs/adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md @@ -0,0 +1,22 @@ +--- +Status: Proposed +Date: 2026-11-15 +--- + +# Skill Invocation is snapshotted text that addresses no one + +Typing `/` in a Channel or DM composer lists commands first, then Skills. The Skills come from the Host Skills plus the Project Skills of every PersonaBot in the conversation: each bot's Memory Repository and its Workspace Grants. A DM counts only that one PersonaBot. Each row shows its owner (a PersonaBot avatar, a folder for a Workspace, or a Host mark), its name and a one-line description. Picking a row inserts a chip, as `@` does. + +A **Skill Invocation** addresses no one. It inserts the Skill's text into the message. Which PersonaBot reads and acts on the message follows its mentions and normal routing, never the Skill's owner. Picking Alice's Skill and mentioning Bob gives Bob that text. Ownership affects only automatic discovery: a bot's model catalog contains Host Skills and its own Memory Repository's Project Skills, and nothing else. + +The Host resolves the Skill when the message is sent and stores a snapshot in a typed `ChannelMessage` part: the name, the owner (`host`, `bot:` or `workspace:`), the `SKILL.md` path and the content. Every recipient therefore gets identical text, even one whose Sessions cannot discover that Skill. History stays reproducible after the Skill changes or is deleted. Bot Inbox delivery renders the snapshot as a `` block carrying its owner and path. A recipient without read authority for that path receives the text but not the files: ADR-0067's path guard still applies. External IM mirrors fall back to the plain text `/name`. + +When a command and a Skill share a name, the command keeps the bare name. + +Delivery is staged under #4231. The first slice covers Human DMs with Host Skills and the PersonaBot's Memory Repository Skills, so `SkillOwner` has only the `host` and `bot` kinds. Group Channels and Workspace Grant Skills, with the `workspace:` owner, arrive in later slices. + +## Considered Options + +- **A Skill Invocation implicitly mentions the Skill's owner** — rejected: it adds hidden rules ("whose Skill is it?") to what Humans already understand as inserted text plus explicit mentions. +- **Expand at delivery time, per recipient** — rejected: recipients could see different text, history would not reproduce, and a recipient that cannot discover the Skill would fail. +- **Plain `/name` text expanded by DSH's user-message scanner** — rejected: Channel messages reach bots as Bot Inbox text, not DSH user messages. The scanner also matches `/word` anywhere and cannot say which owner's Skill was meant. diff --git a/docs/bot-cli.md b/docs/bot-cli.md index c55de0409..c549cb0cb 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -214,6 +214,8 @@ From a built checkout, `node scripts/cli-smoke.mjs --preset [--zip ./shared deepseekbot send --body "Reply with QA_OK" --timeout 60 deepseekbot send --body-stdin --message-id human- deepseekbot send --body "Yes, this one" --reply-to +deepseekbot skills-list --bot [--query ] +deepseekbot send --body "/summarize-pr #42" --skill bot:/summarize-pr deepseekbot send-status --message-id deepseekbot channel-messages --host http://127.0.0.1:31917 --limit 20 deepseekbot tool-approval-status --message-id @@ -236,6 +238,8 @@ deepseekbot folder-browse [] [--offset ] deepseekbot grant-create --workspace ``` +`skills-list` returns the Skills the `/` menu offers in that conversation, ranked like the menu by `--query` (name prefix, then name subsequence, then description): Host Skills (`owner.kind` `host`) and the Project Skills under each PersonaBot's Memory Repository `.agents/skills` or `.dsh/skills` (`owner.kind` `bot`), as that Bot's Orchestrator sees them. Pass `--channel ` instead of `--bot` for any Channel. `send --skill /` (owner `host` or `bot:`, repeatable) turns the first unused `/name` token in the body into a Skill Invocation for each flag, in flag order (the token must start and end at whitespace or a body boundary; the send is refused if no unused occurrence remains): the Host stores the Skill's text as it is now with the message and the Bot reads it as a `` block. The Skill does not choose who replies; a Skill that is gone refuses with `skill-unavailable`, and Skill text longer than 64,000 characters refuses with `skill-too-large` instead of being truncated. See [ADR-0346](adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md). + `tool-approval-status` returns `status` and, while the card is still `pending`, its `expiresAt`, the time the Web card counts down to. `--outcome allowed-always-kind` is the `secret_cli` card's "Always allow this kind": it allows this call and saves a rule for the same program, account and environment variable names, which `tool-approval-rules` lists with kind `secret-cli`; any other card refuses it. `user-question-answer` accepts the same offered selections as the Web card. A durable timed diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index 5416e034d..8f2b782f9 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -216,6 +216,8 @@ Prompt Preset 用于编辑 System Prompt 和每轮模板里的行为文字;围 deepseekbot send --body "回复 QA_OK" --timeout 60 deepseekbot send --body-stdin --message-id human- deepseekbot send --body "就这条" --reply-to <消息-id> +deepseekbot skills-list --bot [--query <文本>] +deepseekbot send --body "/summarize-pr #42" --skill bot:/summarize-pr deepseekbot send-status --message-id <回执中的消息-id> deepseekbot channel-messages --host http://127.0.0.1:31917 --limit 20 deepseekbot tool-approval-status --message-id <卡片-id> @@ -231,6 +233,8 @@ deepseekbot folder-browse [<文件夹路径>] [--offset ] deepseekbot grant-create --workspace ``` +`skills-list` 返回该对话 `/` 菜单提供的 Skill,并按 `--query` 以与菜单相同的规则排序(名称前缀、名称子序列、描述):包括 Host Skill(`owner.kind` 为 `host`),以及各 PersonaBot Memory Repository 下 `.agents/skills` 或 `.dsh/skills` 中的 Project Skill(`owner.kind` 为 `bot`)。任意 Channel 可用 `--channel ` 代替 `--bot`。`send --skill /`(owner 为 `host` 或 `bot:`,可重复)按参数顺序,为每个参数把正文中第一个尚未选中的 `/name` token 变成 Skill Invocation(token 两端必须为空白或正文边界;没有未用匹配时拒绝发送):Host 把该 Skill 当前的文本随消息保存,Bot 以 `` 块读到它。Skill 不决定由谁回复;已不存在的 Skill 会以 `skill-unavailable` 拒绝;Skill 文本超过 64,000 个字符时会以 `skill-too-large` 拒绝,不会截断。见 [ADR-0346](adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)。 + `tool-approval-status` 返回 `status`;卡片仍为 `pending` 时还返回 `expiresAt`,即网页卡片倒计时的截止时间。`--outcome allowed-always-kind` 对应 `secret_cli` 卡片上的“总是允许此类”:批准这一次,并为同一程序、账号和环境变量名保存一条规则;`tool-approval-rules` 会以 `secret-cli` 类型列出它。其他卡片会拒绝这个选项。 `user-question-answer` 接受与网页卡片相同的已提供选项。持久化限时提问可在 Host 重启后回答, diff --git a/packages/client/src/client/actions.ts b/packages/client/src/client/actions.ts index ee13b614d..4c7f65a67 100644 --- a/packages/client/src/client/actions.ts +++ b/packages/client/src/client/actions.ts @@ -87,9 +87,11 @@ import type { import type { ShareDraftView } from '../../../core/src/marketplace/share-draft.js'; import type { MarketplaceLanguage } from '../../../core/src/marketplace/language.js'; import type { InstallReviewResult } from '../../../core/src/marketplace/install-review.js'; -import { loadAllBotPreview } from './bridge.js'; +import { loadAllBotPreview, loadChannelSkillCatalog } from './bridge.js'; import { loadComposerIdentity, validateComposerDraft } from './bridge.js'; import type { AllBotPreview, AllBotMention } from '../../../core/src/channels/all-bot-mention.js'; +import type { ChannelSkillInvocationToken } from '../../../core/src/channels/channel.js'; +import type { SkillCatalogEntry } from '../../../core/src/skills/entries.js'; import type { ChannelBridgeInput, @@ -1031,7 +1033,9 @@ export interface BridgeActions { grantRequestResolution?: ChannelMessage['grantRequestResolution'], allBotMention?: AllBotMention, submissionId?: string, + skillInvocations?: ChannelSkillInvocationToken[], ): Promise; + skillCatalog?(channelId: string): Promise; submissions: { subscribe(listener: () => void): () => void; snapshot(channelId: string): SubmissionSnapshot | undefined; @@ -3313,6 +3317,7 @@ export function createActions( await loadSessionsFor(slug, selection); }, allBotPreview: (channelId) => loadAllBotPreview(call, channelId), + skillCatalog: (channelId) => loadChannelSkillCatalog(call, channelId), validateComposerDraft: (channelId, attachments, replyTo) => validateComposerDraft(call, channelId, attachments, replyTo), async send( @@ -3325,6 +3330,7 @@ export function createActions( grantRequestResolution, allBotMention, submissionId, + skillInvocations, ) { let snapshot = clientStore.getSnapshot(); const channel = snapshot.conversation.channel; @@ -3342,6 +3348,7 @@ export function createActions( !replyTo && !mentions?.length && !channelRefs?.length && + !skillInvocations?.length && !memorySwitchTarget && !grantRequestResolution ) { @@ -3428,6 +3435,8 @@ export function createActions( grantRequestResolution, undefined, allBotMention, + undefined, + skillInvocations, ); remainingFailures(channel.id, [message]); settleSubmission(channel.id, localId, 'sent'); diff --git a/packages/client/src/client/bot-main.tsx b/packages/client/src/client/bot-main.tsx index 8fbd8fb5f..7478474f2 100644 --- a/packages/client/src/client/bot-main.tsx +++ b/packages/client/src/client/bot-main.tsx @@ -113,6 +113,8 @@ import { import { insertAttachmentReferences, removeAttachmentReferences } from './attachment-refs.js'; import { appendMention, quoteMention, rebaseMentions } from './mentions.js'; import { AtSignIcon } from './at-sign-icon.js'; +import { liveSkills, type ComposerSkillOption } from './skill-refs.js'; +import type { SkillCatalogEntry } from '../../../core/src/skills/entries.js'; import { rebaseChannelRefs } from './channel-refs.js'; import { channelHumanName, humanLabel } from './actor-names.js'; import { ChannelHeaderMenu, type ChannelMenuTrigger } from './human-channel-name.js'; @@ -1377,6 +1379,8 @@ function ConversationView({ 'channelRefs', [], ); + const [skillTokens, setSkillTokens] = useConversationDraft(draftScope, 'skills', []); + const [skillCatalog, setSkillCatalog] = useScopedState(scopeKey); const [selectedMemoryView, setSelectedMemoryView] = useScopedState< { channelId: string } & ( | { kind: 'commit'; sha: string } @@ -1903,6 +1907,27 @@ function ConversationView({ cancelled = true; }; }, [scopeKey, channelId, previewRoster]); + const skillCatalogMount = useMountedResource(() => { + let cancelled = false; + setSkillCatalog(undefined); + if (channel?.type === 'dm' && channel.botSlug !== undefined && actions.skillCatalog) + void actions + .skillCatalog(channel.id) + .then((skills) => { + if (!cancelled) setSkillCatalog(skills); + }) + .catch(() => undefined); + return () => { + cancelled = true; + }; + }, [scopeKey, channelId]); + const skillOptions: ComposerSkillOption[] = (skillCatalog ?? []).map((entry) => ({ + ...entry, + bot: + entry.owner.kind === 'bot' + ? state.bots.find((bot) => entry.owner.kind === 'bot' && bot.slug === entry.owner.botSlug) + : undefined, + })); const [searchTop, setSearchTop] = useScopedState(scopeKey, undefined); const searchAvailable = useScopedRef(scopeKey, false); const searchReturnFocus = useScopedRef(scopeKey, null); @@ -2674,6 +2699,12 @@ function ConversationView({ ? [adjusted] : []; }); + const submittedSkills = liveSkills(draft, skillTokens).flatMap((token) => { + const adjusted = { ...token, start: token.start - leftTrim, end: token.end - leftTrim }; + return adjusted.start >= 0 && body.slice(adjusted.start, adjusted.end) === '/' + token.name + ? [adjusted] + : []; + }); const submittedMentions = mentionTokens.flatMap((token) => { const adjusted = { ...token, start: token.start - leftTrim, end: token.end - leftTrim }; return adjusted.start >= 0 && body.slice(adjusted.start, adjusted.end) === '@' + token.label @@ -2743,7 +2774,7 @@ function ConversationView({ ); recall.current = undefined; setRecallNotice(undefined); - recovery.update({ text: '', mentions: [], channelRefs: [], uploads: [] }); + recovery.update({ text: '', mentions: [], channelRefs: [], skills: [], uploads: [] }); try { const sent = await actions.send( body, @@ -2755,6 +2786,7 @@ function ConversationView({ undefined, allBotMention, attempt?.id, + submittedSkills.map(({ name, owner, start, end }) => ({ name, owner, start, end })), ); if (sent) { setAllBotNotice(undefined); @@ -2771,6 +2803,7 @@ function ConversationView({ setDraft((current) => current || body); setMentionTokens((current) => (current.length > 0 ? current : submittedMentions)); setChannelRefTokens((current) => (current.length > 0 ? current : submittedRefs)); + setSkillTokens((current) => (current.length > 0 ? current : submittedSkills)); setUploadItems((current) => (current.length > 0 ? current : submittedUploads)); } } @@ -3606,6 +3639,8 @@ function ConversationView({ value={draft} mentions={mentionTokens} channelRefs={channelRefTokens} + skills={skillTokens} + skillOptions={skillOptions} channelCandidates={ channel?.type === 'dm' && channel.botSlug !== undefined ? state.channels.filter((candidate) => candidate.type === 'group') @@ -3672,11 +3707,12 @@ function ConversationView({ } } t={t} - onChange={(value, mentions, channelRefs) => { + onChange={(value, mentions, channelRefs, skills) => { recovery.update({ text: value, mentions: mentions ?? [], channelRefs: channelRefs ?? [], + ...(skills === undefined ? {} : { skills }), }); setRestoreBlocked(false); }} @@ -3781,6 +3817,7 @@ function ConversationView({ return (
) : null} - {shortcutOptions.length === 0 ? null : ( + {menuLength === 0 ? null : (
{ - if (index === shortcutIndex % shortcutOptions.length) + if (index === shortcutIndex % menuLength) node?.scrollIntoView?.({ block: 'nearest' }); }} type="button" @@ -1029,7 +1101,7 @@ export function ChannelComposer({ ? shortcut.label : `${shortcut.label} · ${shortcut.reason}` } - data-active={index === shortcutIndex % shortcutOptions.length ? 'true' : undefined} + data-active={index === shortcutIndex % menuLength ? 'true' : undefined} data-selected={shortcut.selected ? 'true' : undefined} onMouseDown={(event) => event.preventDefault()} onClick={() => chooseShortcut(shortcut)} @@ -1046,6 +1118,56 @@ export function ChannelComposer({ ) : null} ))} + {skillMatches.length === 0 ? null : ( +
+ {t('composer.skills')} +
+ )} + {skillMatches.map((option, offset) => { + const index = shortcutOptions.length + offset; + const owner = + option.owner.kind === 'host' + ? t('composer.skillHost') + : (option.bot?.displayName ?? option.owner.botSlug); + return ( + + ); + })}
)} {mentionQuery !== undefined && candidates.length > 0 ? ( diff --git a/packages/client/src/client/channel-message-body.tsx b/packages/client/src/client/channel-message-body.tsx index 82c006232..e49296532 100644 --- a/packages/client/src/client/channel-message-body.tsx +++ b/packages/client/src/client/channel-message-body.tsx @@ -790,6 +790,30 @@ export function ChannelMessageBody({ ); }; + const renderSkill = ( + skill: NonNullable[number], + key: number, + ) => { + const owner = + skill.owner.kind === 'host' + ? t('composer.skillHost') + : (store + .getSnapshot() + .bots.find((bot) => skill.owner.kind === 'bot' && bot.slug === skill.owner.botSlug) + ?.displayName ?? skill.owner.botSlug); + const preview = + skill.content.length > 1500 ? `${skill.content.slice(0, 1500)}…` : skill.content; + return ( + + /{skill.name} + + ); + }; const voice = message.voice; const { voice: voiceAttachment, @@ -874,8 +898,17 @@ export function ChannelMessageBody({ message.mentions ?? [], message.channelRefs ?? [], message.humanMentions ?? [], + message.skillInvocations ?? [], ).map((run, index) => - run.mention !== undefined ? ( + run.skill !== undefined ? ( + renderSkill( + message.skillInvocations?.find((skill) => skill.start === run.skill.start) ?? { + ...run.skill, + content: '', + }, + index, + ) + ) : run.mention !== undefined ? ( renderMention(run.mention, index) ) : run.humanMention !== undefined ? ( renderMention(run.humanMention, index) diff --git a/packages/client/src/client/channel-refs.ts b/packages/client/src/client/channel-refs.ts index 22aa5f6dc..cbf88b410 100644 --- a/packages/client/src/client/channel-refs.ts +++ b/packages/client/src/client/channel-refs.ts @@ -1,5 +1,6 @@ import type { SelectedMention } from './mentions.js'; import type { ChannelMessage } from './store.js'; +import type { SelectedSkill } from './skill-refs.js'; export interface SelectedChannelRef { channelId: string; @@ -99,14 +100,28 @@ export function deleteSelectedChannelRef( } export type ReferenceRun = - | { text: string; mention?: never; channelRef?: never; humanMention?: never } - | { text: string; mention: M; channelRef?: never; humanMention?: never } - | { text: string; mention?: never; channelRef: SelectedChannelRef; humanMention?: never } + | { text: string; mention?: never; channelRef?: never; humanMention?: never; skill?: never } + | { text: string; mention: M; channelRef?: never; humanMention?: never; skill?: never } + | { + text: string; + mention?: never; + channelRef: SelectedChannelRef; + humanMention?: never; + skill?: never; + } | { text: string; mention?: never; channelRef?: never; humanMention: NonNullable[number]; + skill?: never; + } + | { + text: string; + mention?: never; + channelRef?: never; + humanMention?: never; + skill: SelectedSkill; }; export function referenceRuns( @@ -114,6 +129,7 @@ export function referenceRuns( mentions: readonly M[], refs: readonly SelectedChannelRef[], humanMentions: readonly NonNullable[number][] = [], + skills: readonly SelectedSkill[] = [], ): ReferenceRun[] { const tokens = [ ...mentions.map((mention) => ({ start: mention.start, end: mention.end, mention })), @@ -123,18 +139,23 @@ export function referenceRuns( end: humanMention.end, humanMention, })), + ...skills.map((skill) => ({ start: skill.start, end: skill.end, skill })), ].sort((a, b) => a.start - b.start); const runs: ReferenceRun[] = []; let cursor = 0; for (const token of tokens) { if (token.start < cursor) continue; - if ('mention' in token) { + if ('skill' in token) { + if (value.slice(token.start, token.end) !== '/' + token.skill.name) continue; + } else if ('mention' in token) { if (value.slice(token.start, token.end) !== '@' + token.mention.label) continue; } else if ('humanMention' in token) { if (value.slice(token.start, token.end) !== '@' + token.humanMention.label) continue; } else if (value.slice(token.start, token.end) !== '#' + token.channelRef.label) continue; if (token.start > cursor) runs.push({ text: value.slice(cursor, token.start) }); - if ('mention' in token) + if ('skill' in token) + runs.push({ text: value.slice(token.start, token.end), skill: token.skill }); + else if ('mention' in token) runs.push({ text: value.slice(token.start, token.end), mention: token.mention }); else if ('humanMention' in token) runs.push({ text: value.slice(token.start, token.end), humanMention: token.humanMention }); diff --git a/packages/client/src/client/composer-context-styles.ts b/packages/client/src/client/composer-context-styles.ts index fecf3a1a9..c97ab3897 100644 --- a/packages/client/src/client/composer-context-styles.ts +++ b/packages/client/src/client/composer-context-styles.ts @@ -14,6 +14,12 @@ export const COMPOSER_CONTEXT_CSS = ` .bh-composer-shortcuts small {color:var(--dsw-alias-label-secondary);} .bh-composer-shortcut-label {display:flex;align-items:center;gap:${space.x3};} .bh-composer-shortcut-label svg {flex-shrink:0;} +.bh-composer-menu-section {padding:${space.x2} ${space.x3} 0;font-size:${text.metaSize};color:var(--dsw-alias-label-secondary);} +.bh-composer-shortcuts button.bh-composer-skill-option {justify-content:flex-start;} +.bh-composer-skill-owner {display:inline-flex;flex-shrink:0;align-items:center;justify-content:center;width:20px;height:20px;color:var(--dsw-alias-label-secondary);} +.bh-composer-skill-copy {display:flex;flex:1;align-items:baseline;gap:${space.x3};min-width:0;} +.bh-composer-skill-copy strong {flex-shrink:0;font-weight:${text.strong};} +.bh-composer-skill-copy small {flex:1;min-width:0;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;} .bh-composer-usage-popover {position:fixed;z-index:1000;max-height:min(70vh,480px);overflow:auto;box-sizing:border-box;padding:${space.x5};border:${border.hairline} solid ${color.border};border-radius:${radius.md};background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);box-shadow:0 8px 32px color-mix(in srgb,var(--dsw-alias-label-primary) 15%,transparent);font-size:${text.bodySize};line-height:1.5;} .bh-composer-usage-head,.bh-composer-usage-total,.bh-composer-usage-row {display:flex;gap:${space.x3};align-items:center;justify-content:space-between;} .bh-composer-usage-head {margin-bottom:${space.x4};} diff --git a/packages/client/src/client/composer-draft-store.ts b/packages/client/src/client/composer-draft-store.ts index 661ff3552..62f36cd8b 100644 --- a/packages/client/src/client/composer-draft-store.ts +++ b/packages/client/src/client/composer-draft-store.ts @@ -2,12 +2,15 @@ import type { ChannelComposerUpload } from './channel-composer.js'; import type { ChannelMessage } from './store.js'; import type { SelectedMention } from './mentions.js'; import type { SelectedChannelRef } from './channel-refs.js'; +import { rebaseSkills, type SelectedSkill } from './skill-refs.js'; +import { parseSkillOwnerKey, skillOwnerKey } from '../../../core/src/skills/entries.js'; import { isChannelAttachmentRef } from '../../../core/src/attachments/ref.js'; export interface ComposerDraft { text: string; mentions: SelectedMention[]; channelRefs: SelectedChannelRef[]; + skills: SelectedSkill[]; reply: ChannelMessage | undefined; uploads: ChannelComposerUpload[]; } @@ -34,7 +37,7 @@ const MAX_BYTES = 1_048_576; const MAX_VERSIONS = 100; export function emptyComposerDraft(): ComposerDraft { - return { text: '', mentions: [], channelRefs: [], reply: undefined, uploads: [] }; + return { text: '', mentions: [], channelRefs: [], skills: [], reply: undefined, uploads: [] }; } function record(value: unknown): Record { @@ -86,6 +89,21 @@ function parseVersion(raw: string): Version { start: number(token['start']), end: number(token['end']), })); + const skills = (saved['skills'] === undefined ? [] : tokens(saved['skills'], '/')).flatMap( + (token): SelectedSkill[] => { + const owner = parseSkillOwnerKey(string(token['owner'])); + return owner === undefined + ? [] + : [ + { + name: string(token['label']), + owner, + start: number(token['start']), + end: number(token['end']), + }, + ]; + }, + ); let reply: ChannelMessage | undefined; if (saved['reply'] !== null) { const target = record(saved['reply']); @@ -113,7 +131,7 @@ function parseVersion(raw: string): Version { writer: string(source['writer']), sequence: number(source['sequence']), seen, - draft: { text, mentions, channelRefs, reply, uploads }, + draft: { text, mentions, channelRefs, skills, reply, uploads }, notice: source['reselectAllBots'] === true || mentions.length !== (saved['mentions'] as unknown[]).length, @@ -136,6 +154,14 @@ function serialize(version: Version): string { channelRefs: draft.channelRefs.filter( (token) => draft.text.slice(token.start, token.end) === '#' + token.label, ), + skills: draft.skills + .filter((token) => draft.text.slice(token.start, token.end) === '/' + token.name) + .map((token) => ({ + label: token.name, + owner: skillOwnerKey(token.owner), + start: token.start, + end: token.end, + })), reply: draft.reply === undefined ? null : { id: draft.reply.id }, uploads: draft.uploads.map((upload) => ({ id: upload.id, @@ -293,7 +319,13 @@ export class ComposerDraftStore { writer: this.writer, sequence: Math.max(own?.sequence ?? 0, seen[this.writer] ?? 0) + 1, seen, - draft: { ...snapshot.draft, ...patch }, + draft: { + ...snapshot.draft, + ...patch, + ...(patch.text === undefined || patch.skills !== undefined + ? {} + : { skills: rebaseSkills(snapshot.draft.text, patch.text, snapshot.draft.skills ?? []) }), + }, }; let error = snapshot.error; if (error !== 'corrupt' && (snapshot.versions.length < MAX_VERSIONS || resolve)) { diff --git a/packages/client/src/client/human-markdown.ts b/packages/client/src/client/human-markdown.ts index 9d0051853..22e2c80e9 100644 --- a/packages/client/src/client/human-markdown.ts +++ b/packages/client/src/client/human-markdown.ts @@ -41,6 +41,7 @@ export function preserveHumanLineBreaks(text: string): string { export function rendersHumanMarkdown(message: ChannelMessage): boolean { if (message.author.kind !== 'human' || message.format !== undefined) return false; if ((message.channelRefs?.length ?? 0) > 0) return false; + if ((message.skillInvocations?.length ?? 0) > 0) return false; if (/\]\(attachment:/u.test(message.body)) return false; const mentions = [...(message.mentions ?? []), ...(message.humanMentions ?? [])].sort( (left, right) => left.start - right.start, diff --git a/packages/client/src/client/locale.ts b/packages/client/src/client/locale.ts index 75674a593..f28c3d331 100644 --- a/packages/client/src/client/locale.ts +++ b/packages/client/src/client/locale.ts @@ -4645,6 +4645,9 @@ export const zh = { 'avatar.label': '{name}:{activity}', 'composer.allBots': '所有 Bot', 'composer.allBotsScope': '仅当前群内的活跃 Bot', + 'composer.skills': 'Skills', + 'composer.skillHost': '本机', + 'composer.skillUnavailable': 'Skill /{name} 已不可用,请重新选择', 'composer.allBotsCount': '{count} 个 Bot', 'composer.allBotsChanged': '接收 Bot 已变化,请确认更新的人数后再次发送。', 'composer.selectedMentions': '已选中的 Bot', @@ -10644,6 +10647,9 @@ My relationship with you, established lore and topics to avoid: [fill in]. 'avatar.label': '{name}: {activity}', 'composer.allBots': 'All Bots', 'composer.allBotsScope': 'Active Bots in this Group only', + 'composer.skills': 'Skills', + 'composer.skillHost': 'Host', + 'composer.skillUnavailable': 'Skill /{name} is no longer available. Pick it again.', 'composer.allBotsCount': '{count} Bots', 'composer.allBotsChanged': 'Recipients changed. Review the updated count and send again.', 'composer.selectedMentions': 'Selected Bots', diff --git a/packages/client/src/client/rich-mention-editor.ts b/packages/client/src/client/rich-mention-editor.ts index c971ba75a..d26c19585 100644 --- a/packages/client/src/client/rich-mention-editor.ts +++ b/packages/client/src/client/rich-mention-editor.ts @@ -4,6 +4,8 @@ import { referenceRuns, type SelectedChannelRef } from './channel-refs.js'; import type { BotSummary } from './store.js'; import { botNameSource, paintBotName } from './bot-primary-color.js'; import { attachmentReferenceRuns, type ComposerAttachmentReference } from './attachment-refs.js'; +import type { SelectedSkill } from './skill-refs.js'; +import { parseSkillOwnerKey, skillOwnerKey } from '../../../core/src/skills/entries.js'; export interface MentionAvatarMount { target: HTMLElement; @@ -17,6 +19,7 @@ export interface RichMentionDraft { value: string; mentions: SelectedMention[]; channelRefs: SelectedChannelRef[]; + skills: SelectedSkill[]; } function token( @@ -25,10 +28,17 @@ function token( | { kind: 'all-bots'; preview: AllBotPreview; label: string } | { kind: 'bot'; botSlug: string; label: string } | { kind: 'channel'; channelId: string; label: string } + | { kind: 'skill'; skill: Pick; label: string } | undefined { if (!(node instanceof HTMLElement)) return undefined; const label = node.dataset.mentionLabel; if (label === undefined) return undefined; + if (node.dataset.skillOwner !== undefined) { + const owner = parseSkillOwnerKey(node.dataset.skillOwner); + return owner === undefined + ? undefined + : { kind: 'skill', skill: { name: label, owner }, label }; + } if (node.dataset.allBotPreview !== undefined) { try { return { @@ -87,12 +97,42 @@ export function renderRichMentionDraft( bots: readonly BotSummary[], refs: readonly SelectedChannelRef[] = [], attachments: readonly ComposerAttachmentReference[] = [], + skills: readonly SelectedSkill[] = [], ): MentionAvatarMount[] { const document = editor.ownerDocument; const nodes: Node[] = []; const mounts: MentionAvatarMount[] = []; const named: Array<[HTMLElement, string | undefined]> = []; - for (const run of referenceRuns(value, mentions, refs)) { + for (const run of referenceRuns(value, mentions, refs, [], skills)) { + if (run.skill !== undefined) { + const skill = run.skill; + const badge = document.createElement('span'); + badge.className = + 'bh-inline-mention bh-inline-mention-sent bh-composer-inline-mention bh-inline-skill'; + badge.contentEditable = 'false'; + badge.dataset.skillOwner = skillOwnerKey(skill.owner); + badge.dataset.mentionLabel = skill.name; + const label = document.createElement('span'); + label.textContent = '/' + skill.name; + if (skill.owner.kind === 'bot') { + const botSlug = skill.owner.botSlug; + const bot = bots.find((candidate) => candidate.slug === botSlug); + const avatar = document.createElement('span'); + avatar.className = 'bh-inline-mention-avatar'; + avatar.setAttribute('aria-hidden', 'true'); + badge.append(avatar, label); + mounts.push({ + target: avatar, + botSlug, + name: bot?.displayName ?? botSlug, + src: bot?.avatar, + appearance: bot?.appearance, + avatarSeed: bot?.avatarSeed, + }); + } else badge.append(label); + nodes.push(badge); + continue; + } if (run.mention === undefined && run.channelRef === undefined) { for (const part of attachmentReferenceRuns(run.text, attachments)) { if (part.attachment === undefined) { @@ -181,12 +221,19 @@ export function readRichMentionDraft(editor: HTMLElement): RichMentionDraft { let value = ''; const mentions: SelectedMention[] = []; const channelRefs: SelectedChannelRef[] = []; + const skills: SelectedSkill[] = []; const append = (node: Node): void => { if (node instanceof HTMLElement && node.dataset.attachmentText !== undefined) { value += node.dataset.attachmentText; return; } const mention = token(node); + if (mention?.kind === 'skill') { + const start = value.length; + value += '/' + mention.label; + skills.push({ ...mention.skill, start, end: value.length }); + return; + } if (mention !== undefined) { const start = value.length; value += (mention.kind === 'channel' ? '#' : '@') + mention.label; @@ -220,7 +267,7 @@ export function readRichMentionDraft(editor: HTMLElement): RichMentionDraft { for (const child of node.childNodes) append(child); }; for (const child of editor.childNodes) append(child); - return { value, mentions, channelRefs }; + return { value, mentions, channelRefs, skills }; } export function sameRichMentionDraft( @@ -228,9 +275,12 @@ export function sameRichMentionDraft( value: string, mentions: readonly SelectedMention[], refs: readonly SelectedChannelRef[], + skills: readonly SelectedSkill[] = [], ): boolean { return ( left.value === value && + JSON.stringify(left.skills) === + JSON.stringify(skills.map(({ name, owner, start, end }) => ({ name, owner, start, end }))) && left.mentions.length === mentions.length && left.mentions.every( (item, index) => diff --git a/packages/client/src/client/skill-refs.ts b/packages/client/src/client/skill-refs.ts new file mode 100644 index 000000000..8548124e7 --- /dev/null +++ b/packages/client/src/client/skill-refs.ts @@ -0,0 +1,88 @@ +import type { SkillCatalogEntry, SkillOwner } from '../../../core/src/skills/entries.js'; +import type { BotSummary } from './store.js'; + +export interface SelectedSkill { + name: string; + owner: SkillOwner; + start: number; + end: number; +} + +export interface SkillQuery { + start: number; + end: number; + query: string; +} + +export type ComposerSkillOption = SkillCatalogEntry & { bot?: BotSummary | undefined }; + +export function sameSkillOwner(left: SkillOwner, right: SkillOwner): boolean { + return left.kind === 'host' + ? right.kind === 'host' + : right.kind === 'bot' && left.botSlug === right.botSlug; +} + +export function activeSkillQuery( + value: string, + caret: number, + skills: readonly SelectedSkill[], +): SkillQuery | undefined { + const match = /(^|\s)\/([a-z0-9-]{0,64})$/u.exec(value.slice(0, caret)); + if (match === null) return undefined; + const start = caret - match[2]!.length - 1; + if (skills.some((item) => item.start === start)) return undefined; + return { start, end: caret, query: match[2]! }; +} + +export function rebaseSkills( + before: string, + after: string, + skills: readonly SelectedSkill[], +): SelectedSkill[] { + let prefix = 0; + while (prefix < before.length && prefix < after.length && before[prefix] === after[prefix]) + prefix += 1; + let suffix = 0; + while ( + suffix < before.length - prefix && + suffix < after.length - prefix && + before[before.length - suffix - 1] === after[after.length - suffix - 1] + ) + suffix += 1; + const oldEnd = before.length - suffix; + const delta = after.length - before.length; + return skills + .flatMap((item) => { + if (item.end <= prefix) return [item]; + if (item.start >= oldEnd) + return [{ ...item, start: item.start + delta, end: item.end + delta }]; + return []; + }) + .filter((item) => after.slice(item.start, item.end) === '/' + item.name); +} + +export function selectSkill( + value: string, + skills: readonly SelectedSkill[], + query: SkillQuery, + option: Pick, +): { value: string; skills: SelectedSkill[]; caret: number } { + const token = '/' + option.name; + const trailing = value[query.end] === ' ' ? '' : ' '; + const next = value.slice(0, query.start) + token + trailing + value.slice(query.end); + const selected: SelectedSkill = { + name: option.name, + owner: option.owner, + start: query.start, + end: query.start + token.length, + }; + return { + value: next, + skills: [...rebaseSkills(value, next, skills), selected].sort((a, b) => a.start - b.start), + caret: selected.end + trailing.length, + }; +} + +export function liveSkills(value: string, skills: readonly SelectedSkill[]): SelectedSkill[] { + return skills.filter((item) => value.slice(item.start, item.end) === '/' + item.name); +} diff --git a/packages/client/src/client/store.ts b/packages/client/src/client/store.ts index fad228114..8fd6d395e 100644 --- a/packages/client/src/client/store.ts +++ b/packages/client/src/client/store.ts @@ -225,6 +225,7 @@ export interface ChannelMessage { mentions?: { botSlug: string; label: string; start: number; end: number }[]; humanMentions?: { humanId: string; label: string; start: number; end: number }[]; channelRefs?: { channelId: string; label: string; start: number; end: number }[]; + skillInvocations?: import('../../../core/src/channels/channel.js').ChannelSkillInvocation[]; humanReceipts?: { humanId: string; displayName: string; diff --git a/packages/client/test/bot-main.test.ts b/packages/client/test/bot-main.test.ts index 4cb9e8ef8..028944af6 100644 --- a/packages/client/test/bot-main.test.ts +++ b/packages/client/test/bot-main.test.ts @@ -124,6 +124,7 @@ it('keeps settled message groups mounted without rerendering their author cards modelCatalog: async () => ({ models: [] }), listWorkspaceGrants: async () => [], botSourcePolicies: async () => [], + skillCatalog: async () => [], allBotPreview: async () => ({ recipients: [], excluded: [] }), listWorkspaceOptions: async () => [], markRead: async () => undefined, @@ -331,6 +332,7 @@ describe('Bot main Sessions pane', () => { createElement(BotMain, { actions: { ...inertSubmissionActions, + skillCatalog: async () => [], allBotPreview: async () => undefined, } as unknown as BridgeActions, channelSidebar: createChannelSidebarRegistry(), @@ -1969,6 +1971,7 @@ describe('B2 chat bubbles', () => { modelPlanState: async () => ({}), listWorkspaceGrants: async () => [], botSourcePolicies: async () => [], + skillCatalog: async () => [], allBotPreview: async () => ({ recipients: [], excluded: [] }), listWorkspaceOptions: async () => [], markRead: async () => undefined, diff --git a/packages/client/test/bot-sidebar.test.ts b/packages/client/test/bot-sidebar.test.ts index 24771113a..79288cc7a 100644 --- a/packages/client/test/bot-sidebar.test.ts +++ b/packages/client/test/bot-sidebar.test.ts @@ -220,6 +220,7 @@ function stubActions(): BridgeActions { deletionRetry: vi.fn(), deletionFolderApplications: vi.fn(), deletionFolderOpen: vi.fn(), + skillCatalog: vi.fn(async () => []), allBotPreview: vi.fn(async () => { throw new Error('unexpected All Bots preview'); }), diff --git a/packages/client/test/channel-composer-dictation-guard.test.ts b/packages/client/test/channel-composer-dictation-guard.test.ts index de39b4b58..ffbf9c94a 100644 --- a/packages/client/test/channel-composer-dictation-guard.test.ts +++ b/packages/client/test/channel-composer-dictation-guard.test.ts @@ -17,6 +17,7 @@ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ IconMicrophoneOutlineRegular: () => null, IconPaperclipOutlineRegular: () => null, IconSendOutlineRegular: () => null, + IconSkillOutlineRegular: () => null, })); import { ChannelComposer } from '../src/client/channel-composer.js'; diff --git a/packages/client/test/channel-composer-lifecycle.test.ts b/packages/client/test/channel-composer-lifecycle.test.ts index e6cc219b8..f0da6ed5d 100644 --- a/packages/client/test/channel-composer-lifecycle.test.ts +++ b/packages/client/test/channel-composer-lifecycle.test.ts @@ -22,6 +22,7 @@ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ IconCloseOutlineRegular: () => null, IconPaperclipOutlineRegular: () => null, IconSendOutlineRegular: () => null, + IconSkillOutlineRegular: () => null, ImageLightbox: () => null, })); diff --git a/packages/client/test/channel-composer-paste.test.ts b/packages/client/test/channel-composer-paste.test.ts index 3d98325da..a140a3a6a 100644 --- a/packages/client/test/channel-composer-paste.test.ts +++ b/packages/client/test/channel-composer-paste.test.ts @@ -19,6 +19,7 @@ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ IconCloseOutlineRegular: () => null, IconPaperclipOutlineRegular: () => null, IconSendOutlineRegular: () => null, + IconSkillOutlineRegular: () => null, ImageLightbox: ({ src, alt, diff --git a/packages/client/test/channel-composer.test.ts b/packages/client/test/channel-composer.test.ts index 6155fd3b2..72191d4ba 100644 --- a/packages/client/test/channel-composer.test.ts +++ b/packages/client/test/channel-composer.test.ts @@ -25,6 +25,7 @@ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ Tooltip: ({ children }: { children: ReactNode }) => children, IconPaperclipOutlineRegular: () => null, IconSendOutlineRegular: () => null, + IconSkillOutlineRegular: () => null, ImageLightbox: () => null, fileSizeText: (size: number) => `${size} B`, })); diff --git a/packages/client/test/personabot-profile.test.ts b/packages/client/test/personabot-profile.test.ts index 558b933f6..eab3d0c95 100644 --- a/packages/client/test/personabot-profile.test.ts +++ b/packages/client/test/personabot-profile.test.ts @@ -476,6 +476,7 @@ describe('PersonaBot Profile surface', () => { root.render( createElement(BotMain, { actions: { + skillCatalog: async () => [], allBotPreview: vi.fn(async () => ({ revision: '0'.repeat(64), recipients: [] })), channelAssignments: vi.fn(async () => []), groupProfileActivity: vi.fn(() => new Promise(() => {})), diff --git a/packages/client/test/rich-mention-editor.test.ts b/packages/client/test/rich-mention-editor.test.ts index aba1c5f18..f3c1fbf90 100644 --- a/packages/client/test/rich-mention-editor.test.ts +++ b/packages/client/test/rich-mention-editor.test.ts @@ -18,6 +18,7 @@ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ IconCloseOutlineRegular: () => null, IconPaperclipOutlineRegular: () => null, IconSendOutlineRegular: () => null, + IconSkillOutlineRegular: () => null, ImageLightbox: () => null, })); @@ -82,7 +83,7 @@ describe('rich mention editor', () => { const chip = editor.querySelector('[data-attachment-id="report"]')!; expect(chip.contentEditable).toBe('false'); expect(chip.textContent).toBe('1report.txt5 B'); - expect(readRichMentionDraft(editor)).toEqual({ value, mentions, channelRefs: [] }); + expect(readRichMentionDraft(editor)).toEqual({ value, mentions, channelRefs: [], skills: [] }); setRichSelection(editor, 9 + text.length); expect(richSelectionOffsets(editor)).toEqual({ start: 9 + text.length, end: 9 + text.length }); insertRichPlainText(editor, ' next'); @@ -127,6 +128,7 @@ describe('rich mention editor', () => { value: '@All Bots check', mentions: [{ kind: 'all-bots', preview, label: 'All Bots', start: 0, end: 9 }], channelRefs: [], + skills: [], }); expect( deleteSelectedMention( @@ -333,7 +335,7 @@ describe('rich mention editor', () => { const mounts = renderRichMentionDraft(editor, value, mentions, []); expect(editor.textContent).toBe('Ada hi Bea'); expect(mounts.map((item) => item.botSlug)).toEqual(['ada', 'bea']); - expect(readRichMentionDraft(editor)).toEqual({ value, mentions, channelRefs: [] }); + expect(readRichMentionDraft(editor)).toEqual({ value, mentions, channelRefs: [], skills: [] }); setRichSelection(editor, 4); expect(richSelectionOffsets(editor)).toEqual({ start: 4, end: 4 }); @@ -342,6 +344,7 @@ describe('rich mention editor', () => { value: '@Ada there hi @Bea', mentions: [mentions[0], { botSlug: 'bea', label: 'Bea', start: 14, end: 18 }], channelRefs: [], + skills: [], }); editor.remove(); }); @@ -373,7 +376,12 @@ describe('rich mention editor', () => { expect(editor.querySelector('[data-channel-id="group-planning"]')?.textContent).toBe( '#Planning', ); - expect(readRichMentionDraft(editor)).toEqual({ value, mentions, channelRefs: refs }); + expect(readRichMentionDraft(editor)).toEqual({ + value, + mentions, + channelRefs: refs, + skills: [], + }); expect(referenceRuns(value, mentions, refs).map((run) => run.text)).toEqual([ '@Ada', ' please use ', diff --git a/packages/client/test/session-stop-header.test.tsx b/packages/client/test/session-stop-header.test.tsx index c14866356..adedd6719 100644 --- a/packages/client/test/session-stop-header.test.tsx +++ b/packages/client/test/session-stop-header.test.tsx @@ -28,6 +28,7 @@ vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ Tooltip: ({ children }: { children: ReactNode }) => children, IconPaperclipOutlineRegular: () => null, IconSendOutlineRegular: () => null, + IconSkillOutlineRegular: () => null, IconStopFillRegular: () => null, ImageLightbox: () => null, Tag: ({ children }: { children: ReactNode }) => createElement('span', null, children), diff --git a/packages/client/test/skill-composer.test.ts b/packages/client/test/skill-composer.test.ts new file mode 100644 index 000000000..4ba7ae504 --- /dev/null +++ b/packages/client/test/skill-composer.test.ts @@ -0,0 +1,240 @@ +// @vitest-environment jsdom +import { act, createElement, type ButtonHTMLAttributes, type PropsWithChildren } from 'react'; +import { createRoot } from 'react-dom/client'; +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('@deepseek-ai/dsh-client-ui-primitives', () => ({ + IconAgentPresetOutlineRegular: () => null, + IconCodeOutlineRegular: () => null, + IconBranchOutlineRegular: () => null, + IconCheckOutlineRegular: () => null, + Button: ({ + children, + icon: _icon, + ...props + }: PropsWithChildren & { icon?: unknown }>) => + createElement('button', props, children), + FileTypeIcon: () => null, + fileSizeText: (size: number) => `${size} B`, + IconCloseOutlineRegular: () => null, + IconPaperclipOutlineRegular: () => null, + IconSendOutlineRegular: () => null, + IconSkillOutlineRegular: () => null, + ImageLightbox: () => null, +})); + +import { ChannelComposer } from '../src/client/channel-composer.js'; +import { ComposerDraftStore } from '../src/client/composer-draft-store.js'; +import { + readRichMentionDraft, + renderRichMentionDraft, + setRichSelection, +} from '../src/client/rich-mention-editor.js'; +import { + activeSkillQuery, + rebaseSkills, + selectSkill, + type ComposerSkillOption, + type SelectedSkill, +} from '../src/client/skill-refs.js'; + +const ada = { + slug: 'ada', + displayName: 'Ada', + roles: [], + aggregateState: 'idle' as const, + workspaces: [], + createdAt: '2026-11-15T00:00:00.000Z', +}; + +function storage() { + const values = new Map(); + return { + get length() { + return values.size; + }, + key: (index: number) => [...values.keys()][index] ?? null, + getItem: (key: string) => values.get(key) ?? null, + setItem: (key: string, value: string) => void values.set(key, value), + removeItem: (key: string) => void values.delete(key), + }; +} + +describe('Skill tokens', () => { + it('finds a /query after whitespace and picks a Skill as one token', () => { + expect(activeSkillQuery('hi /su', 6, [])).toEqual({ start: 3, end: 6, query: 'su' }); + expect(activeSkillQuery('a/su', 4, [])).toBeUndefined(); + expect(activeSkillQuery('/su now', 7, [])).toBeUndefined(); + const picked = selectSkill( + 'hi /su', + [], + { start: 3, end: 6, query: 'su' }, + { + name: 'summarize-pr', + owner: { kind: 'bot', botSlug: 'ada' }, + }, + ); + expect(picked.value).toBe('hi /summarize-pr '); + expect(picked.skills).toEqual([ + { name: 'summarize-pr', owner: { kind: 'bot', botSlug: 'ada' }, start: 3, end: 16 }, + ]); + expect(rebaseSkills(picked.value, 'oh ' + picked.value, picked.skills)[0]?.start).toBe(6); + expect(rebaseSkills(picked.value, 'hi /summarize', picked.skills)).toEqual([]); + }); + + it('renders Bot and Host Skill chips and reads their owners back', () => { + const editor = document.createElement('div'); + document.body.append(editor); + const value = '/pdf and /review'; + const skills: SelectedSkill[] = [ + { name: 'pdf', owner: { kind: 'host' }, start: 0, end: 4 }, + { name: 'review', owner: { kind: 'bot', botSlug: 'ada' }, start: 9, end: 16 }, + ]; + const mounts = renderRichMentionDraft(editor, value, [], [ada], [], [], skills); + expect(mounts.map((mount) => mount.botSlug)).toEqual(['ada']); + expect( + [...editor.querySelectorAll('.bh-inline-skill')].map( + (chip) => chip.dataset['skillOwner'], + ), + ).toEqual(['host', 'bot:ada']); + expect(readRichMentionDraft(editor)).toMatchObject({ value, skills }); + editor.remove(); + }); + + it('keeps Skill chips in a saved draft and rebases them when only text changes', () => { + const local = storage(); + const first = new ComposerDraftStore(local, 'first'); + first.update('channel', { + text: '/pdf now', + skills: [{ name: 'pdf', owner: { kind: 'host' }, start: 0, end: 4 }], + }); + first.update('channel', { text: 'go /pdf now' }); + expect(first.read('channel').draft.skills).toEqual([ + { name: 'pdf', owner: { kind: 'host' }, start: 3, end: 7 }, + ]); + const second = new ComposerDraftStore(local, 'second'); + expect(second.read('channel').draft.skills).toEqual([ + { name: 'pdf', owner: { kind: 'host' }, start: 3, end: 7 }, + ]); + }); +}); + +describe('composer / menu', () => { + it('lists commands before ranked Skills and inserts the picked Skill as a chip', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + const options: ComposerSkillOption[] = [ + { name: 'pdf', description: 'Read PDFs', owner: { kind: 'host' } }, + { + name: 'summarize-pr', + description: 'Summarize a pull request in three bullets and nothing else at all', + owner: { kind: 'bot', botSlug: 'ada' }, + bot: ada, + }, + ]; + const changes: Array<{ value: string; skills: SelectedSkill[] | undefined }> = []; + const show = (value: string, skills: SelectedSkill[] = []) => + act(async () => { + root.render( + createElement(ChannelComposer, { + value, + skills, + skillOptions: options, + context: { + target: 'dm', + content: null, + shortcuts: [{ id: 'sessions', label: 'Sessions', run: () => undefined }], + }, + placeholder: 'Message', + sending: false, + onChange: (next: string, _m: unknown, _c: unknown, skills?: SelectedSkill[]) => + changes.push({ value: next, skills }), + onSubmit: () => undefined, + }), + ); + }); + try { + await show('/s'); + const input = container.querySelector('.bh-composer-rich-input')!; + setRichSelection(input, 2); + await act(async () => { + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + const rows = [...container.querySelectorAll('.bh-composer-shortcuts button')]; + expect(rows.map((row) => row.getAttribute('aria-label'))).toEqual([ + 'Sessions', + '/summarize-pr · Ada', + '/pdf · 本机', + ]); + expect(container.querySelector('.bh-composer-menu-section')).not.toBeNull(); + await act(async () => { + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })); + }); + await act(async () => { + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + }); + expect(changes.at(-1)).toEqual({ + value: '/summarize-pr ', + skills: [ + { name: 'summarize-pr', owner: { kind: 'bot', botSlug: 'ada' }, start: 0, end: 13 }, + ], + }); + await show('/summarize-pr ', changes.at(-1)!.skills); + expect(container.querySelector('.bh-inline-skill')?.dataset['skillOwner']).toBe( + 'bot:ada', + ); + } finally { + await act(async () => root.unmount()); + container.remove(); + } + }); + it('keeps a selected Skill chip out of command argument parsing', async () => { + Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); + const container = document.createElement('div'); + document.body.append(container); + const root = createRoot(container); + const run = vi.fn(); + try { + await act(async () => { + root.render( + createElement(ChannelComposer, { + value: '/model fast', + skills: [{ name: 'model', owner: { kind: 'host' }, start: 0, end: 6 }], + skillOptions: [{ name: 'model', description: 'Pick a model', owner: { kind: 'host' } }], + context: { + target: 'dm', + content: null, + shortcuts: [ + { + id: 'model', + label: 'Model', + run: () => undefined, + choices: () => [{ id: 'model' as const, label: 'fast', run }], + }, + ], + }, + placeholder: 'Message', + sending: false, + onChange: () => undefined, + onSubmit: () => undefined, + }), + ); + }); + const input = container.querySelector('.bh-composer-rich-input')!; + setRichSelection(input, '/model fast'.length); + await act(async () => { + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + expect(container.querySelectorAll('.bh-composer-shortcuts button')).toHaveLength(0); + await act(async () => { + input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); + }); + expect(run).not.toHaveBeenCalled(); + } finally { + await act(async () => root.unmount()); + container.remove(); + } + }); +}); diff --git a/packages/core/src/bots/cli-live.ts b/packages/core/src/bots/cli-live.ts index 277d06cce..9576e9bab 100644 --- a/packages/core/src/bots/cli-live.ts +++ b/packages/core/src/bots/cli-live.ts @@ -157,6 +157,14 @@ import { type VoiceValues, } from './cli-voice.js'; import { CALL_COMMANDS, CALL_OPTIONS, isCallCommand, runCallCommand } from './cli-call.js'; +import { + SKILL_COMMANDS, + SKILL_OPTIONS, + isSkillCommand, + runSkillCommand, + skillInvocationTokens, + type SkillValues, +} from './cli-skills.js'; import { VOICE_CALL_PATH, type VoiceCallResult } from '../voice/call-contract.js'; import { isStorageCommand, @@ -223,6 +231,7 @@ export const LIVE_OPTIONS = { ...CALL_OPTIONS, ...CALL_TIMELINE_OPTIONS, ...STORAGE_OPTIONS, + ...SKILL_OPTIONS, host: { type: 'string' }, 'token-file': { type: 'string' }, 'image-source': { type: 'string' }, @@ -367,6 +376,7 @@ export const LIVE_COMMANDS = [ ...CALL_TIMELINE_COMMANDS, ...IDLE_COMPACTION_COMMANDS, ...STORAGE_COMMANDS, + ...SKILL_COMMANDS, { command: 'send', description: 'send a Human DM and collect its committed Bot reply from a live Host', @@ -630,6 +640,7 @@ interface LiveValues ApprovalTemplateValues, ApprovalReviewerValues, VoiceValues { + skill?: string[]; as?: string; username?: string; 'display-name'?: string; @@ -1256,6 +1267,11 @@ export async function runLiveCli( const signal = AbortSignal.timeout(timeoutMs(values.timeout)); return (await connectLiveHost(values, io, signal)).rpc; }); + if (isSkillCommand(command)) + return runSkillCommand(command, rest, values as SkillValues, async () => { + const signal = AbortSignal.timeout(timeoutMs(values.timeout)); + return (await connectLiveHost(values, io, signal)).rpc; + }); if (isStorageCommand(command)) return runStorageCommand(command, rest, values as StorageValues, io, async () => { const signal = AbortSignal.timeout(timeoutMs(values.timeout)); @@ -1378,6 +1394,7 @@ export async function runLiveCli( ) usage('--message-id is required.'); let body: string | undefined; + let skillTokens: ReturnType = []; let answer: unknown; let confidential: Record | undefined; if (command === 'ask-secret-submit') { @@ -1417,6 +1434,7 @@ export async function runLiveCli( usage('--message-id must be human- followed by a UUID.'); if (values['reply-to'] !== undefined && !values['reply-to'].trim()) usage('--reply-to needs a message id.'); + skillTokens = skillInvocationTokens(body, values.skill); } if ( command === 'tool-approval-decide' && @@ -1603,6 +1621,7 @@ export async function runLiveCli( body, messageId: receipt.messageId, ...(values['reply-to'] === undefined ? {} : { replyTo: values['reply-to'].trim() }), + ...(skillTokens.length === 0 ? {} : { skillInvocations: skillTokens }), }); while (Date.now() < deadline) { const status = await rpc<{ state: string; replies: unknown[] }>( diff --git a/packages/core/src/bots/cli-skills.ts b/packages/core/src/bots/cli-skills.ts new file mode 100644 index 000000000..0fc2847aa --- /dev/null +++ b/packages/core/src/bots/cli-skills.ts @@ -0,0 +1,82 @@ +import { dmChannelId, type ChannelSkillInvocationToken } from '../channels/channel.js'; +import { parseSkillOwnerKey, rankSkillEntries, type SkillCatalogEntry } from '../skills/entries.js'; +import { CliLiveError } from './cli-live-error.js'; + +type Rpc = (method: string, payload: Record) => Promise; + +export const SKILL_OPTIONS = { + skill: { type: 'string', multiple: true }, +} as const; + +export interface SkillValues { + bot?: string; + channel?: string; + query?: string; +} + +export const SKILL_COMMANDS = [ + { + command: 'skills-list', + description: + 'list the Skills the / menu offers in a conversation (--bot for its DM, or --channel ): Host Skills plus each PersonaBot Memory Repository Project Skill, ranked by --query like the menu', + }, +] as const; + +type Command = (typeof SKILL_COMMANDS)[number]['command']; + +export function isSkillCommand(command: string): command is Command { + return SKILL_COMMANDS.some((entry) => entry.command === command); +} + +function usage(message: string): never { + throw new CliLiveError('usage', message); +} + +export async function runSkillCommand( + _command: Command, + rest: string[], + values: SkillValues, + connect: () => Promise, +): Promise { + if (rest.length !== 0) + usage('skills-list takes no positional arguments; use --bot or --channel.'); + const bot = values.bot?.trim(); + const channel = values.channel?.trim(); + if ((bot ? 1 : 0) + (channel ? 1 : 0) !== 1) + usage('skills-list requires exactly one of --bot or --channel.'); + const rpc = await connect(); + const channelId = channel || dmChannelId(bot!); + const result = (await rpc('channelSkillCatalog', { channelId })) as { + skills: SkillCatalogEntry[]; + }; + return { + channelId, + skills: rankSkillEntries(result.skills, values.query ?? ''), + }; +} + +export function skillInvocationTokens( + body: string, + values: readonly string[] | undefined, +): ChannelSkillInvocationToken[] { + const tokens: ChannelSkillInvocationToken[] = []; + for (const raw of values ?? []) { + const split = raw.lastIndexOf('/'); + const owner = split <= 0 ? undefined : parseSkillOwnerKey(raw.slice(0, split)); + const name = raw.slice(split + 1); + if (owner === undefined || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(name)) + usage('--skill takes /, where owner is host or bot:.'); + const matches = body.matchAll(new RegExp(`(^|\\s)/${name}(?=\\s|$)`, 'gu')); + let start: number | undefined; + for (const match of matches) { + const offset = match.index + match[1]!.length; + if (tokens.some((token) => token.start === offset)) continue; + start = offset; + break; + } + if (start === undefined) + usage(`--skill ${raw} needs /${name} in the message body at an unused occurrence.`); + tokens.push({ name, owner, start, end: start + name.length + 1 }); + } + return tokens.sort((a, b) => a.start - b.start); +} diff --git a/packages/core/src/bridge/methods.ts b/packages/core/src/bridge/methods.ts index 49fb6ce8b..858d60df5 100644 --- a/packages/core/src/bridge/methods.ts +++ b/packages/core/src/bridge/methods.ts @@ -256,6 +256,7 @@ import { isChannelCallVisual, isChannelVoiceCallMessage, isValidChannelId, + isSkillInvocationToken, isGroupAvatar, isReactionEmoji, type LocalHumanIdentity, @@ -264,6 +265,8 @@ import { type ChannelReaction, type ChannelRecord, type ChannelReference, + type ChannelSkillInvocation, + type ChannelSkillInvocationToken, } from '../channels/channel.js'; import { botAvatarUrl } from '../bots/avatar-http.js'; import { botBannerSummary, type BotBannerSummary } from '../bots/banner-http.js'; @@ -335,6 +338,12 @@ import { type DataResetPreview, type DataResetResult, } from '../data-reset/reset.js'; +import { + SkillContentTooLargeError, + type SkillCatalog, + type SkillCatalogEntry, + type ResolvedSkill, +} from '../skills/catalog.js'; import { isValidSlug } from '../bots/slug.js'; import { memoryMoveTarget, @@ -892,6 +901,7 @@ export interface BridgeMethods extends TeamBridgeMethods { messageSearch(payload: unknown): BridgeResult; channelMessages(payload: unknown): BridgeResult<{ messages: ChannelMessage[]; revision: number }>; channelAllBotPreview(payload: unknown): BridgeResult; + channelSkillCatalog(payload: unknown): Promise>; channelSend(payload: unknown): Promise>; channelSendStatus(payload: unknown): BridgeResult; channelGenuiView(payload: unknown): BridgeResult; @@ -1264,6 +1274,7 @@ export interface BridgeMethodsDeps { team?: TeamService; voiceProviders?: VoiceProviders; callText?: (input: CallTextInput) => Promise; + skills?: SkillCatalog; voiceLog?: (phase: string, fields: Record) => void; botContext?(slug: string): Promise; botSystemPrompt?(slug: string): Promise; @@ -2076,6 +2087,7 @@ function historyPosition(cursor: string): ToolApprovalHistoryPosition | undefine } } const MAX_CHANNEL_SEND_ATTACHMENTS = 10; +const MAX_SKILL_INVOCATIONS = 5; function ownAttachments( message: ChannelMessage, @@ -2154,6 +2166,16 @@ function buildBridgeMethods( ): BridgeMethods { const isHostOwner = () => deps.team?.isOwner(human) ?? human.humanId === OWNER_HUMAN_CONTEXT.humanId; + const channelSkillBots = (channel: ChannelRecord): string[] => + (channel.type === 'group' + ? channel.members + : channel.botSlug === undefined + ? [] + : [channel.botSlug] + ).filter((slug) => { + const bot = deps.registry.get(slug); + return bot !== undefined && bot.paused !== true; + }); const requireOwnedBot = (slug: string): void => { if ( deps.team && @@ -6938,6 +6960,22 @@ function buildBridgeMethods( return invalidInput(String(error)); } }, + async channelSkillCatalog(payload) { + const channelId = asNonBlank(asObject(payload), 'channelId'); + if (channelId === undefined) return invalidInput('channelId is required'); + const channel = deps.channels.get(channelId); + if (channel === undefined) return unknownChannel(channelId); + if (deps.skills === undefined) return { ok: true, value: { skills: [] } }; + const bots = channelSkillBots(channel); + try { + return { ok: true, value: { skills: await deps.skills.list(bots) } }; + } catch (error) { + return { + ok: false, + error: { code: 'skills-unavailable', message: (error as Error).message }, + }; + } + }, channelAllBotPreview(payload) { const channelId = asNonBlank(asObject(payload), 'channelId'); if (channelId === undefined) return invalidInput('channelId is required'); @@ -7070,9 +7108,6 @@ function buildBridgeMethods( if (rawAllBotMention !== undefined) { try { allBotMention = parseAllBotMention(rawAllBotMention, body); - const expanded = expandAllBotMention(body, mentions, allBotMention); - body = expanded.body; - mentions.splice(0, mentions.length, ...expanded.mentions); } catch (error) { return invalidInput((error as Error).message); } @@ -7118,6 +7153,52 @@ function buildBridgeMethods( ) return invalidInput('overlapping selected tokens'); } + const rawSkills = source['skillInvocations']; + if (rawSkills !== undefined && !Array.isArray(rawSkills)) + return invalidInput('skillInvocations must be selected /Skill tokens'); + const skillTokens: ChannelSkillInvocationToken[] = []; + if (Array.isArray(rawSkills)) { + if (rawSkills.length > MAX_SKILL_INVOCATIONS) return invalidInput('too many Skills'); + for (const item of rawSkills) { + if (!isSkillInvocationToken(item, body)) return invalidInput('invalid Skill token'); + const owner = + item.owner.kind === 'host' + ? ({ kind: 'host' } as const) + : ({ kind: 'bot', botSlug: item.owner.botSlug } as const); + skillTokens.push({ name: item.name, owner, start: item.start, end: item.end }); + } + skillTokens.sort((a, b) => a.start - b.start); + if ( + skillTokens.some((item, index) => index > 0 && item.start < skillTokens[index - 1]!.end) + ) + return invalidInput('overlapping Skill tokens'); + if ( + skillTokens.some((skill) => + [...mentions, ...channelRefs].some( + (token) => skill.start < token.end && token.start < skill.end, + ), + ) + ) + return invalidInput('overlapping selected tokens'); + } + if (allBotMention !== undefined) { + try { + const expanded = expandAllBotMention(body, mentions, allBotMention); + const delta = expanded.body.length - body.length; + for (const token of [...channelRefs, ...skillTokens]) { + if (token.start < allBotMention.end && allBotMention.start < token.end) + return invalidInput('overlapping selected tokens'); + if (token.start >= allBotMention.end) { + token.start += delta; + token.end += delta; + } + } + body = expanded.body; + mentions.splice(0, mentions.length, ...expanded.mentions); + } catch (error) { + return invalidInput((error as Error).message); + } + } const rawReplyTo = source['replyTo']; if (rawReplyTo !== undefined && (typeof rawReplyTo !== 'string' || rawReplyTo.length === 0)) { return invalidInput('replyTo must be a message id'); @@ -7280,6 +7361,14 @@ function buildBridgeMethods( JSON.stringify(attachmentIntent(attachments ?? [])) && JSON.stringify(existing.mentions ?? []) === JSON.stringify(mentions) && JSON.stringify(existing.channelRefs ?? []) === JSON.stringify(channelRefs) && + JSON.stringify( + (existing.skillInvocations ?? []).map(({ name, owner, start, end }) => ({ + name, + owner, + start, + end, + })), + ) === JSON.stringify(skillTokens) && JSON.stringify(existing.grantRequestResolution) === JSON.stringify(grantRequestResolution); return same @@ -7374,6 +7463,36 @@ function buildBridgeMethods( ) { return dmAdmissionFailure(channelId, channel.botSlug, 'archived-bot'); } + const skillInvocations: ChannelSkillInvocation[] = []; + const skillBots = skillTokens.length === 0 ? [] : channelSkillBots(channel); + const skillViewer = skillBots[0]; + for (const token of skillTokens) { + let resolved: ResolvedSkill | undefined; + try { + resolved = + skillViewer === undefined || + (token.owner.kind === 'bot' && !skillBots.includes(token.owner.botSlug)) + ? undefined + : await deps.skills?.resolve(token.name, token.owner, skillViewer); + } catch (error) { + if (error instanceof SkillContentTooLargeError) + return { ok: false, error: { code: error.code, message: error.message } }; + throw error; + } + if (resolved === undefined) + return { + ok: false, + error: { + code: 'skill-unavailable', + message: `Skill /${token.name} is no longer available`, + }, + }; + skillInvocations.push({ + ...token, + content: resolved.content, + ...(resolved.path === undefined ? {} : { path: resolved.path }), + }); + } const id = requestedMessageId ?? randomUUID(); const harvest = voiceCall === undefined && channel.type === 'dm' && channel.botSlug !== undefined @@ -7401,6 +7520,7 @@ function buildBridgeMethods( ...(sent.length === 0 ? {} : { attachments: sent }), ...(mentions.length === 0 ? {} : { mentions }), ...(channelRefs.length === 0 ? {} : { channelRefs }), + ...(skillInvocations.length === 0 ? {} : { skillInvocations }), ...(replyTo === undefined ? {} : { replyTo }), ...(grantRequestResolution === undefined ? {} : { grantRequestResolution }), ...(assignmentReply === undefined ? {} : { assignmentReply }), diff --git a/packages/core/src/bridge/rpc.ts b/packages/core/src/bridge/rpc.ts index 70225463d..78818d65c 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -175,7 +175,13 @@ import type { } from './methods.js'; import type { ChannelActivityToday } from '../channels/activity-today.js'; import type { GroupProfileActivity } from '../channels/profile-activity.js'; -import type { ChannelMessage, ChannelReaction, ChannelRecord } from '../channels/channel.js'; +import type { + ChannelMessage, + ChannelReaction, + ChannelRecord, + ChannelSkillInvocationToken, +} from '../channels/channel.js'; +import type { SkillCatalogEntry } from '../skills/catalog.js'; import type { ChannelSendStatus, HumanMessageSearchPage } from '../channels/store.js'; import type { ChannelAttachmentRef } from '../attachments/ref.js'; import type { ChannelReadPosition } from '../channels/store.js'; @@ -2183,6 +2189,9 @@ export class BotharnessBridgeService extends TypertRemoteService { return unwrap(this.methods.messageSearch({ text, cursor, limit })); } + async channelSkillCatalog(channelId: string): Promise<{ skills: SkillCatalogEntry[] }> { + return unwrap(await this.methods.channelSkillCatalog({ channelId })); + } channelAllBotPreview(channelId: string): AllBotPreview { return unwrap(this.methods.channelAllBotPreview({ channelId })); } @@ -2203,9 +2212,11 @@ export class BotharnessBridgeService extends TypertRemoteService { assignmentReply?: ChannelMessage['assignmentReply'], allBotMention?: AllBotMention, genuiReply?: GenuiMessageReply, + skillInvocations?: ChannelSkillInvocationToken[], ): Promise<{ message: ChannelMessage }> { return unwrap( await this.methods.channelSend({ + ...(skillInvocations === undefined ? {} : { skillInvocations }), channelId, body, ...(allBotMention === undefined ? {} : { allBotMention }), @@ -3329,6 +3340,7 @@ markRemoteMethods(BotharnessBridgeService.prototype, [ 'messageSearch', 'channelUnreadCounts', 'channelAllBotPreview', + 'channelSkillCatalog', 'channelSend', 'channelSendStatus', 'channelGenuiView', diff --git a/packages/core/src/channels/channel.ts b/packages/core/src/channels/channel.ts index 3d5b597bd..06e6b1ef9 100644 --- a/packages/core/src/channels/channel.ts +++ b/packages/core/src/channels/channel.ts @@ -1,4 +1,5 @@ import type { ApprovalCard } from '../team/approval-contract.js'; +import type { SkillOwner } from '../skills/entries.js'; import type { ChannelMessageAuthor } from './message-author.js'; import type { ChannelReplyPreview } from './reply-preview.js'; import { isChannelMessageVoice, type ChannelMessageVoice } from './voice.js'; @@ -287,6 +288,44 @@ export interface ChannelReference { end: number; } +export interface ChannelSkillInvocation { + name: string; + owner: SkillOwner; + start: number; + end: number; + path?: string; + content: string; +} + +export type ChannelSkillInvocationToken = Pick< + ChannelSkillInvocation, + 'name' | 'owner' | 'start' | 'end' +>; + +const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u; + +export function isSkillInvocationToken( + item: unknown, + body: string, +): item is ChannelSkillInvocationToken { + if (typeof item !== 'object' || item === null) return false; + const { name, owner, start, end } = item as Record; + if (typeof name !== 'string' || name.length > 64 || !SKILL_NAME.test(name)) return false; + if (typeof owner !== 'object' || owner === null) return false; + const { kind, botSlug } = owner as Record; + if (kind !== 'host' && !(kind === 'bot' && typeof botSlug === 'string' && isValidSlug(botSlug))) + return false; + return ( + typeof start === 'number' && + typeof end === 'number' && + Number.isSafeInteger(start) && + Number.isSafeInteger(end) && + start >= 0 && + end > start && + body.slice(start, end) === '/' + name + ); +} + export const LOCAL_HUMAN_ID = 'local-human'; export interface LocalHumanIdentity { @@ -508,6 +547,7 @@ export interface ChannelMessage { mentions?: ChannelMention[]; humanMentions?: { humanId: string; label: string; start: number; end: number }[]; channelRefs?: ChannelReference[]; + skillInvocations?: ChannelSkillInvocation[]; channelRevision?: number; @@ -1088,6 +1128,19 @@ export function isChannelMessage(value: unknown): value is ChannelMessage { )) ) return false; + const skillInvocations = message['skillInvocations']; + if ( + skillInvocations !== undefined && + (!Array.isArray(skillInvocations) || + (message['author'] as ChannelMessageAuthor)?.kind !== 'human' || + skillInvocations.some( + (item) => + !isSkillInvocationToken(item, message['body'] as string) || + typeof (item as { content?: unknown }).content !== 'string' || + !['string', 'undefined'].includes(typeof (item as { path?: unknown }).path), + )) + ) + return false; const questionRequest = message['userQuestionRequest']; if (questionRequest !== undefined) { if ( diff --git a/packages/core/src/channels/sqlite-store.ts b/packages/core/src/channels/sqlite-store.ts index 61a5d6f37..44981fa3c 100644 --- a/packages/core/src/channels/sqlite-store.ts +++ b/packages/core/src/channels/sqlite-store.ts @@ -238,6 +238,15 @@ function noticeOrigin( : {}; } +function skillInvocationIntent(message: ChannelMessage) { + return (message.skillInvocations ?? []).map(({ name, owner, start, end }) => ({ + name, + owner, + start, + end, + })); +} + function sameIntent(left: ChannelMessage, right: ChannelMessage): boolean { const author = (message: ChannelMessage) => message.author.kind === 'human' @@ -253,6 +262,7 @@ function sameIntent(left: ChannelMessage, right: ChannelMessage): boolean { mentions: left.mentions ?? [], humanMentions: left.humanMentions ?? [], channelRefs: left.channelRefs ?? [], + skillInvocations: skillInvocationIntent(left), botDmAction: left.botDmAction, botCausation: left.botCausation, grantRequestResolution: left.grantRequestResolution, @@ -270,6 +280,7 @@ function sameIntent(left: ChannelMessage, right: ChannelMessage): boolean { mentions: right.mentions ?? [], humanMentions: right.humanMentions ?? [], channelRefs: right.channelRefs ?? [], + skillInvocations: skillInvocationIntent(right), botDmAction: right.botDmAction, botCausation: right.botCausation, grantRequestResolution: right.grantRequestResolution, diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 474ced63a..baa21f08b 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -247,6 +247,13 @@ import { createMediaVersions, type MediaVersions } from './attachments/media-ver import { loadImageProcessor } from './attachments/thumbnails.js'; import { createChannelLiveHub, CHANNEL_STREAM_PATH, type ChannelLiveHub } from './channels/live.js'; import type { ChannelDraftEvent } from './channels/draft.js'; +import { SkillCatalog, type SkillRegistryPort } from './skills/catalog.js'; +import { createSkillViewPort, type SkillAgentPresetsPort } from './skills/agent-view.js'; +import { + degradeHostCapability, + hostAgentPresets, + hostSkillRegistry, +} from './runtime/native-agent-compat.js'; import { DeveloperModeSkillGate } from './logs/skill.js'; import { openLogDatabase, type LogDatabase } from './logs/log-db.js'; import type { ChannelStore } from './channels/store.js'; @@ -3264,8 +3271,22 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { drafts: shareDrafts, log: (event) => ctx.logger.info(JSON.stringify(event)), }); + const skillCatalog = new SkillCatalog({ + memoryDirFor: (slug) => + core.registry.get(slug) === undefined ? undefined : core.registry.memoryDirFor(slug), + viewFor: createSkillViewPort({ + agentFor: (slug) => { + const sessionId = core.runtime.currentOrchestratorSessionId?.(slug); + return sessionId == null ? undefined : liveAgent(sessionId); + }, + presetFor: (slug) => + core.registry.get(slug)?.preset ?? config.agentPreset ?? DEFAULT_AGENT_PRESET, + agentPresets: () => hostAgentPresets>(ctx), + }), + }); const bridgeDeps: BridgeMethodsDeps = { team, + skills: skillCatalog, hostVersion: () => release.version(), callText: createCallTextHarvest({ calls: () => voiceCalls, attachments: core.attachments }), voiceProviders: core.voiceProviders, @@ -3839,6 +3860,12 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { }, }); developerModeTarget.gate = gate; + skillsCtx.effect(() => { + const registry = hostSkillRegistry(skillsCtx); + return registry === undefined + ? degradeHostCapability(skillsCtx, 'skills.list') + : skillCatalog.attach(registry); + }, 'botharness: skill catalog'); skillsCtx.effect( () => skills.register({ diff --git a/packages/core/src/runtime/bot-runtime.ts b/packages/core/src/runtime/bot-runtime.ts index 04b43c225..a82bb0ce9 100644 --- a/packages/core/src/runtime/bot-runtime.ts +++ b/packages/core/src/runtime/bot-runtime.ts @@ -116,6 +116,7 @@ import { type ChannelMessagePerf, type ChannelReaction, type ChannelRecord, + type ChannelSkillInvocation, type SessionFailureProgress, } from '../channels/channel.js'; import type { ChannelVoiceCallRecord } from '../channels/voice-call-record.js'; @@ -729,6 +730,50 @@ export interface DirectBotToolCall { const DIRECT_TOOL_CALL_LIMIT = 50; +export function markSkillTokens( + text: string, + invocations: readonly ChannelSkillInvocation[] | undefined, +): string { + let marked = text; + for (const skill of [...(invocations ?? [])].sort((a, b) => b.start - a.start)) { + if (text.slice(skill.start, skill.end) !== '/' + skill.name) continue; + marked = marked.slice(0, skill.start) + `[/${skill.name}]` + marked.slice(skill.end); + } + return marked; +} + +function sessionSkillText( + body: string, + mentions: readonly ChannelMention[], + invocations: readonly ChannelSkillInvocation[] | undefined, +): string { + const text = sessionMentionText(body, mentions); + const mentionStarts = mentions + .filter((mention) => body.slice(mention.start, mention.end) === '@' + mention.label) + .map((mention) => mention.start); + const rebased = invocations?.map((skill) => { + const offset = mentionStarts.filter((start) => start < skill.start).length; + return { ...skill, start: skill.start + offset, end: skill.end + offset }; + }); + return markSkillTokens(text, rebased); +} + +function xmlAttribute(value: string): string { + return value.replace(/&/gu, '&').replace(/"/gu, '"').replace(/ { + const owner = skill.owner.kind === 'host' ? 'host' : `bot:${skill.owner.botSlug}`; + const path = skill.path === undefined ? '' : ` path="${xmlAttribute(skill.path)}"`; + return `\n${skill.content}\n`; + }); + return `\n\n[The Human invoked ${invocations.length === 1 ? 'this Skill' : 'these Skills'} with /. Each block is the Skill text as it was when the message was sent; follow it for this message. owner names whose Skill it is, not who should act.]\n${blocks.join('\n')}`; +} + export class DirectBotToolError extends Error { constructor( readonly code: string, @@ -4146,7 +4191,12 @@ class BotRuntimeImplementation implements BotRuntime { #groupMentionPrompt(botSlug: string, channelId: string, messageId: string, body: string): string { const message = this.#channels.message(channelId, messageId); const sender = message?.author.kind === 'bot' ? `PersonaBot ${message.author.slug}` : 'Human'; - return `[Bot Inbox: direct Group mention from ${sender}]\nChannel: ${channelId}\nMessage ID: ${messageId}\nMessage: ${sessionMentionText(body, message?.mentions ?? [])}\n${this.#promptText(botSlug)('group-mention-hint')}`; + const text = sessionSkillText( + body, + message?.mentions ?? [], + message?.author.kind === 'human' ? message.skillInvocations : undefined, + ); + return `[Bot Inbox: direct Group mention from ${sender}]\nChannel: ${channelId}\nMessage ID: ${messageId}\nMessage: ${text}\n${this.#promptText(botSlug)('group-mention-hint')}`; } #inboundChannelMessage( @@ -4183,10 +4233,13 @@ class BotRuntimeImplementation implements BotRuntime { this.#channels.message(channelId, target.recordMessageId)?.toolAutoApproval?.input ?? ''; return `[Bot Inbox: Human allowed an auto-rejected call once]\nChannel: ${channelId}\nMessage ID: ${messageId}\nTool: ${target.toolName}\nSession: ${target.sessionId}\nInput:\n${input}\nThe Approval Reviewer rejected this call earlier, and the Human allowed it once anyway. You may retry it in that Session with exactly this input, every argument unchanged; that one retry runs without review. Later calls are still reviewed under your Approval Template. If the call came from an Assignment Session, relay this with send_assignment_request.`; } + const skills = + message?.author.kind === 'human' ? skillInvocationPrompt(message.skillInvocations) : ''; if (channel?.type === 'group' && message?.mentions?.length) return ( `Source Event ID: ${sourceEventId}\n` + - this.#groupMentionPrompt(botSlug, channelId, messageId, body) + this.#groupMentionPrompt(botSlug, channelId, messageId, body) + + skills ); if (channel?.type === 'group' && message?.grantRequestResolution !== undefined) return `[Bot Inbox: Human answered your Workspace Grant request]\nChannel: ${channelId}\nMessage ID: ${messageId}\nMessage: ${body}\nContinue the task you requested access for; if you speak in this Group Channel, use bot_send_message with the trusted source_event_id.`; @@ -4197,14 +4250,18 @@ class BotRuntimeImplementation implements BotRuntime { (message.mentions?.length ?? 0) > 0 ? message.body : body; - const text = sessionMentionText(mentionBody, message?.mentions ?? []); + const text = sessionSkillText( + mentionBody, + message?.mentions ?? [], + message?.author.kind === 'human' ? message.skillInvocations : undefined, + ); if (channel?.type === 'group') - return `[Group]\nSource Event ID: ${sourceEventId}\nChannel: ${channelId}\nMessage ID: ${messageId}\n${text}`; + return `[Group]\nSource Event ID: ${sourceEventId}\nChannel: ${channelId}\nMessage ID: ${messageId}\n${text}${skills}`; if (channel?.type !== 'dm' || channel.botSlug === undefined || message?.author.kind !== 'human') return text; const selected = [...new Set((message.mentions ?? []).map((mention) => mention.botSlug))]; const parts = [ - `[Human DM]\nSource Event ID: ${sourceEventId}\nChannel: ${channelId}\nMessage ID: ${messageId}\n${text}`, + `[Human DM]\nSource Event ID: ${sourceEventId}\nChannel: ${channelId}\nMessage ID: ${messageId}\n${text}${skills}`, ]; if (message.genuiReplyContext !== undefined) parts.push(message.genuiReplyContext); if (message.voiceCall !== undefined) { diff --git a/packages/core/src/runtime/native-agent-compat.ts b/packages/core/src/runtime/native-agent-compat.ts index a8273cbbe..65e5afa88 100644 --- a/packages/core/src/runtime/native-agent-compat.ts +++ b/packages/core/src/runtime/native-agent-compat.ts @@ -87,6 +87,26 @@ export function degradeHostCapability( return () => undefined; } +export function hostSkillRegistry(ctx: Context): Registry | undefined { + const skills: unknown = Reflect.get(ctx, 'skills'); + return typeof skills === 'object' && + skills !== null && + typeof Reflect.get(skills, 'list') === 'function' && + typeof Reflect.get(skills, 'get') === 'function' + ? (skills as Registry) + : undefined; +} + +export function hostAgentPresets(ctx: Context): Presets | undefined { + const presets: unknown = Reflect.get(ctx, 'get')?.call(ctx, 'agentPresets'); + return typeof presets === 'object' && + presets !== null && + typeof Reflect.get(presets, 'serviceFor') === 'function' && + typeof Reflect.get(presets, 'acquireScope') === 'function' + ? (presets as Presets) + : undefined; +} + export function requireHostCapability(capability: string, cause?: unknown): never { throw new HostIncompatibleError(capability, installedDshVersion(), cause); } diff --git a/packages/core/src/skills/agent-view.ts b/packages/core/src/skills/agent-view.ts new file mode 100644 index 000000000..242b7f10d --- /dev/null +++ b/packages/core/src/skills/agent-view.ts @@ -0,0 +1,30 @@ +import type { SkillRegistryPort, SkillViewPort } from './catalog.js'; + +export interface SkillAgentPresetsPort { + serviceFor(agent: AgentScope, name: 'skills'): SkillRegistryPort | undefined; + acquireScope(id?: string): Promise<{ key: object } & AsyncDisposable>; +} + +export function createSkillViewPort(options: { + agentFor(botSlug: string): AgentScope | undefined; + presetFor(botSlug: string): string; + agentPresets(): SkillAgentPresetsPort | undefined; +}): SkillViewPort { + return async (slug, registry) => { + const presets = options.agentPresets(); + if (presets === undefined) return { registry, async [Symbol.asyncDispose]() {} }; + const agent = options.agentFor(slug); + if (agent !== undefined) + return { + registry: presets.serviceFor(agent, 'skills') ?? registry, + scope: agent, + async [Symbol.asyncDispose]() {}, + }; + const lease = await presets.acquireScope(options.presetFor(slug)); + return { + registry, + scope: lease.key, + [Symbol.asyncDispose]: () => lease[Symbol.asyncDispose](), + }; + }; +} diff --git a/packages/core/src/skills/catalog.ts b/packages/core/src/skills/catalog.ts new file mode 100644 index 000000000..3c5be76ac --- /dev/null +++ b/packages/core/src/skills/catalog.ts @@ -0,0 +1,195 @@ +import { realpathSync } from 'node:fs'; +import { isAbsolute, relative, resolve } from 'node:path'; + +import type { SkillCatalogEntry, SkillOwner } from './entries.js'; + +export { + parseSkillOwnerKey, + rankSkillEntries, + skillOwnerKey, + type SkillCatalogEntry, + type SkillOwner, +} from './entries.js'; + +export interface SkillRegistryPort { + list(options?: { cwd?: string; scope?: object }): Promise; + get( + name: string, + options?: { cwd?: string; scope?: object }, + ): Promise; +} + +export interface SkillRegistryView extends AsyncDisposable { + readonly registry: SkillRegistryPort; + readonly scope?: object; +} + +export type SkillViewPort = ( + botSlug: string, + registry: SkillRegistryPort, +) => Promise; + +export interface SkillRegistrySummary { + readonly name: string; + readonly description: string; + readonly source: string; + readonly path?: string; + readonly invocation: { readonly userInvocable: boolean }; +} + +export interface SkillRegistryDefinition extends SkillRegistrySummary { + readonly content: string; +} + +export interface ResolvedSkill { + name: string; + owner: SkillOwner; + path?: string; + content: string; +} + +export const MAX_SKILL_INVOCATION_CONTENT = 64_000; + +export class SkillContentTooLargeError extends Error { + readonly code = 'skill-too-large'; + + constructor(name: string) { + super( + `Skill /${name} exceeds the ${MAX_SKILL_INVOCATION_CONTENT}-character invocation limit. Shorten the Skill and try again.`, + ); + this.name = 'SkillContentTooLargeError'; + } +} + +const PROJECT_SOURCES = new Set(['project-agents', 'project-dsh']); + +function real(path: string): string { + try { + return realpathSync(path); + } catch { + return resolve(path); + } +} + +function inside(root: string, path: string | undefined): boolean { + if (path === undefined) return false; + const rel = relative(real(root), real(path)); + return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel); +} + +export class SkillCatalog { + #registry: SkillRegistryPort | undefined; + readonly #memoryDirFor: (botSlug: string) => string | undefined; + readonly #viewFor: SkillViewPort | undefined; + + constructor(options: { + memoryDirFor(botSlug: string): string | undefined; + viewFor?: SkillViewPort; + }) { + this.#memoryDirFor = options.memoryDirFor; + this.#viewFor = options.viewFor; + } + + get available(): boolean { + return this.#registry !== undefined; + } + + attach(registry: SkillRegistryPort): () => void { + this.#registry = registry; + return () => { + if (this.#registry === registry) this.#registry = undefined; + }; + } + + async #withView( + botSlug: string, + registry: SkillRegistryPort, + read: (registry: SkillRegistryPort, options: { scope?: object }) => Promise, + ): Promise { + if (this.#viewFor === undefined) return read(registry, {}); + await using view = await this.#viewFor(botSlug, registry); + return await read(view.registry, view.scope === undefined ? {} : { scope: view.scope }); + } + + async list(botSlugs: readonly string[]): Promise { + const registry = this.#registry; + if (registry === undefined) return []; + const entries: SkillCatalogEntry[] = []; + const hostEntries: SkillCatalogEntry[] = []; + let hostListed = false; + for (const botSlug of new Set(botSlugs)) { + const root = this.#memoryDirFor(botSlug); + if (root === undefined) continue; + await this.#withView(botSlug, registry, async (registry, options) => { + for (const skill of await registry.list({ ...options, cwd: root })) + if ( + skill.invocation.userInvocable && + PROJECT_SOURCES.has(skill.source) && + inside(root, skill.path) + ) + entries.push({ + name: skill.name, + description: skill.description, + owner: { kind: 'bot', botSlug }, + ...(skill.path === undefined ? {} : { path: skill.path }), + }); + if (hostListed) return; + for (const skill of await registry.list(options)) + if (skill.invocation.userInvocable && !PROJECT_SOURCES.has(skill.source)) + hostEntries.push({ + name: skill.name, + description: skill.description, + owner: { kind: 'host' }, + ...(skill.path === undefined ? {} : { path: skill.path }), + }); + hostListed = true; + }); + } + return [...entries, ...hostEntries]; + } + + async resolve( + name: string, + owner: SkillOwner, + viewerBotSlug: string, + ): Promise { + const registry = this.#registry; + if (registry === undefined) return undefined; + const resolved = await this.#withView( + owner.kind === 'bot' ? owner.botSlug : viewerBotSlug, + registry, + async (registry, options) => { + if (owner.kind === 'host') { + const skill = await registry.get(name, options); + if (skill === undefined || !skill.invocation.userInvocable) return undefined; + if (PROJECT_SOURCES.has(skill.source)) return undefined; + return { + name, + owner, + content: skill.content, + ...(skill.path === undefined ? {} : { path: skill.path }), + }; + } + const root = this.#memoryDirFor(owner.botSlug); + if (root === undefined) return undefined; + const skill = await registry.get(name, { ...options, cwd: root }); + if ( + skill === undefined || + !skill.invocation.userInvocable || + !PROJECT_SOURCES.has(skill.source) || + !inside(root, skill.path) + ) + return undefined; + return { + name, + owner, + content: skill.content, + ...(skill.path === undefined ? {} : { path: skill.path }), + }; + }, + ); + if (resolved !== undefined && resolved.content.length > MAX_SKILL_INVOCATION_CONTENT) + throw new SkillContentTooLargeError(name); + return resolved; + } +} diff --git a/packages/core/src/skills/entries.ts b/packages/core/src/skills/entries.ts new file mode 100644 index 000000000..e47290fb6 --- /dev/null +++ b/packages/core/src/skills/entries.ts @@ -0,0 +1,46 @@ +import { isValidSlug } from '../bots/slug.js'; + +export type SkillOwner = { kind: 'host' } | { kind: 'bot'; botSlug: string }; + +export interface SkillCatalogEntry { + name: string; + description: string; + owner: SkillOwner; + path?: string; +} + +export function skillOwnerKey(owner: SkillOwner): string { + return owner.kind === 'host' ? 'host' : `bot:${owner.botSlug}`; +} + +export function parseSkillOwnerKey(value: string): SkillOwner | undefined { + if (value === 'host') return { kind: 'host' }; + if (!value.startsWith('bot:')) return undefined; + const botSlug = value.slice(4); + return isValidSlug(botSlug) ? { kind: 'bot', botSlug } : undefined; +} + +export function rankSkillEntries( + entries: readonly T[], + rawQuery: string, +): T[] { + const query = rawQuery.trim().toLowerCase(); + if (query.length === 0) return [...entries]; + const subsequence = (text: string): boolean => { + let index = 0; + for (const char of text) if (char === query[index]) index += 1; + return index === query.length; + }; + const tier = (entry: T): number => { + const name = entry.name.toLowerCase(); + if (name.startsWith(query)) return 0; + if (subsequence(name)) return 1; + if (entry.description.toLowerCase().includes(query)) return 2; + return 3; + }; + return entries + .map((entry, index) => ({ entry, index, tier: tier(entry) })) + .filter((item) => item.tier < 3) + .sort((a, b) => a.tier - b.tier || a.index - b.index) + .map((item) => item.entry); +} diff --git a/packages/core/src/team/member-methods.ts b/packages/core/src/team/member-methods.ts index 7db1f3ff9..bc13f0733 100644 --- a/packages/core/src/team/member-methods.ts +++ b/packages/core/src/team/member-methods.ts @@ -109,6 +109,7 @@ export const MEMBER_CHANNEL_METHODS = [ 'channelHumanAdd', 'channelGroupInvite', 'channelAllBotPreview', + 'channelSkillCatalog', 'composerValidate', 'channelGet', 'channelSendStatus', diff --git a/packages/core/test/bot-live-cli.test.ts b/packages/core/test/bot-live-cli.test.ts index cb5dd56c5..4c10effb9 100644 --- a/packages/core/test/bot-live-cli.test.ts +++ b/packages/core/test/bot-live-cli.test.ts @@ -79,6 +79,48 @@ async function invoke(argv: string[], url?: string, stdin = '', token = 'private } describe('live CLI over the authenticated DSH carrier', () => { + it('sends repeated Skill names with distinct owners and spans', async () => { + const live = await host((method) => ({ + ok: true, + value: + method === 'get' + ? { bot: { displayName: 'Ada' } } + : method === 'channelSend' + ? { message: { id: 'human-33333333-3333-4333-8333-333333333333' } } + : { state: 'handled', replies: [{ id: 'reply', body: 'ok' }] }, + })); + const sent = await invoke( + ['send', 'ada', '--body', '/pdf /pdf', '--skill', 'host/pdf', '--skill', 'bot:ada/pdf'], + live.url, + ); + expect(sent.code).toBe(0); + expect(live.calls.find((call) => call.method === 'channelSend')?.args).toMatchObject({ + body: '/pdf /pdf', + skillInvocations: [ + { name: 'pdf', owner: { kind: 'host' }, start: 0, end: 4 }, + { name: 'pdf', owner: { kind: 'bot', botSlug: 'ada' }, start: 5, end: 9 }, + ], + }); + }); + + it('surfaces the Host oversized Skill refusal without retrying the send', async () => { + const error = { + code: 'skill-too-large', + message: + 'Skill /pdf exceeds the 64000-character invocation limit. Shorten the Skill and try again.', + }; + const live = await host((method) => + method === 'channelSend' + ? { ok: false, error } + : { ok: true, value: { bot: { displayName: 'Ada' } } }, + ); + const sent = await invoke(['send', 'ada', '--body', '/pdf', '--skill', 'host/pdf'], live.url); + expect(sent.code).not.toBe(0); + expect(sent.json.error).toMatchObject(error); + expect(live.calls.filter((call) => call.method === 'channelSend')).toHaveLength(1); + expect(live.calls.some((call) => call.method === 'channelSendStatus')).toBe(false); + }); + it('uses existing commands for v2 document state and continuation without expanding CLI input limits', async () => { const live = await host(() => ({ ok: true, value: { version: 0, state: {} } })); const state = { version: 1, values: { selected: 'alpha', count: 2, expanded: true } }; diff --git a/packages/core/test/bridge-rpc.test.ts b/packages/core/test/bridge-rpc.test.ts index 537582065..2433bc144 100644 --- a/packages/core/test/bridge-rpc.test.ts +++ b/packages/core/test/bridge-rpc.test.ts @@ -872,6 +872,7 @@ describe('bridge typert service', () => { 'messageSearch', 'channelUnreadCounts', 'channelAllBotPreview', + 'channelSkillCatalog', 'channelSend', 'channelSendStatus', 'channelGenuiView', @@ -1240,7 +1241,9 @@ describe('bridge typert service', () => { 'assignmentReply', 'allBotMention', 'genuiReply', + 'skillInvocations', ]); + expect(parameterNames(service.channelSkillCatalog)).toEqual(['channelId']); expect(parameterNames(service.botAttention)).toEqual(['slug', 'limit', 'cursor', 'state']); expect(parameterNames(service.humanAssignmentContext)).toEqual([ 'slug', diff --git a/packages/core/test/plugin.test.ts b/packages/core/test/plugin.test.ts index af2dd9a74..7f85969dc 100644 --- a/packages/core/test/plugin.test.ts +++ b/packages/core/test/plugin.test.ts @@ -964,6 +964,7 @@ describe('plugin entry', () => { 'messageSearch', 'channelUnreadCounts', 'channelAllBotPreview', + 'channelSkillCatalog', 'channelSend', 'channelSendStatus', 'channelGenuiView', diff --git a/packages/core/test/skill-invocation.test.ts b/packages/core/test/skill-invocation.test.ts new file mode 100644 index 000000000..bf537b1b9 --- /dev/null +++ b/packages/core/test/skill-invocation.test.ts @@ -0,0 +1,871 @@ +import { mkdirSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import { describe, expect, it, vi } from 'vitest'; + +import { skillInvocationTokens } from '../src/bots/cli-skills.js'; +import { createBridgeMethods } from '../src/bridge/methods.js'; +import { humanContext, OWNER_HUMAN_CONTEXT } from '../src/humans/context.js'; +import { attachOperationalModule } from '../src/database/owner.js'; +import { createCore } from '../src/plugin.js'; +import type { BotAgentAdapter, OrchestratorAgentRun } from '../src/runtime/bot-runtime.js'; +import { markSkillTokens, skillInvocationPrompt } from '../src/runtime/bot-runtime.js'; +import { + SkillCatalog, + MAX_SKILL_INVOCATION_CONTENT, + rankSkillEntries, + type SkillRegistryDefinition, + type SkillRegistryPort, + type SkillViewPort, +} from '../src/skills/catalog.js'; +import { createSkillViewPort } from '../src/skills/agent-view.js'; +import { createTempRoot } from './helpers.js'; + +function adapter(onRun: (run: OrchestratorAgentRun) => Promise): BotAgentAdapter { + return { + runOrchestrator: onRun, + async runAssignment() {}, + requestAssignment() { + throw new Error('No Assignment expected'); + }, + async close() {}, + }; +} + +function skill( + name: string, + source: string, + path: string, + content = `Body of ${name}`, + userInvocable = true, +): SkillRegistryDefinition { + return { + name, + description: `${name} description`, + source, + path, + content, + invocation: { userInvocable }, + }; +} + +function registry( + host: SkillRegistryDefinition[], + project: Map, +) { + const view = (cwd?: string, scope?: object) => { + if (scope === undefined) return host.filter((item) => item.source === 'runtime'); + const local = cwd === undefined ? [] : (project.get(cwd) ?? []); + const names = new Set(local.map((item) => item.name)); + return [...local, ...host.filter((item) => !names.has(item.name))]; + }; + const port: SkillRegistryPort = { + async list(options) { + return view(options?.cwd, options?.scope); + }, + async get(name, options) { + return view(options?.cwd, options?.scope).find((item) => item.name === name); + }, + }; + return port; +} + +const liveAgent = { session: { id: 'ada-orchestrator' } }; +const liveView: SkillViewPort = async (_slug, registry) => ({ + registry, + scope: liveAgent, + async [Symbol.asyncDispose]() {}, +}); + +describe('SkillCatalog', () => { + it.each(['host', 'bot'] as const)( + 'rejects oversized %s Skills without truncating', + async (kind) => { + const memory = '/profiles/ada/memory'; + const definition = skill( + 'pdf', + kind === 'host' ? 'user-agents' : 'project-agents', + join(memory, '.agents/skills/pdf/SKILL.md'), + 'x'.repeat(MAX_SKILL_INVOCATION_CONTENT), + ); + const catalog = new SkillCatalog({ memoryDirFor: () => memory, viewFor: liveView }); + const definitions = [definition]; + catalog.attach( + registry(kind === 'host' ? definitions : [], new Map([[memory, definitions]])), + ); + const owner = kind === 'host' ? { kind } : { kind, botSlug: 'ada' }; + expect((await catalog.resolve('pdf', owner, 'ada'))?.content).toBe(definition.content); + definitions[0] = { ...definition, content: definition.content + 'x' }; + await expect(catalog.resolve('pdf', owner, 'ada')).rejects.toThrow(/Skill \/pdf.*64000/u); + }, + ); + + it('uses the live Orchestrator scope and its isolated registry for both lookups', async () => { + const memory = '/profiles/ada/memory'; + const scoped = registry( + [skill('host', 'custom', '/host/SKILL.md')], + new Map([ + [memory, [skill('qa', 'project-agents', join(memory, '.agents/skills/qa/SKILL.md'))]], + ]), + ); + const list = vi.spyOn(scoped, 'list'); + const get = vi.spyOn(scoped, 'get'); + const acquireScope = vi.fn(); + const serviceFor = vi.fn(() => scoped); + const viewFor = vi.fn( + createSkillViewPort({ + agentFor: () => liveAgent, + presetFor: () => 'bot-preset', + agentPresets: () => ({ serviceFor, acquireScope }), + }), + ); + const catalog = new SkillCatalog({ memoryDirFor: () => memory, viewFor }); + catalog.attach(registry([], new Map())); + expect((await catalog.list(['ada', 'ada'])).map((row) => row.name)).toEqual(['qa', 'host']); + expect(list.mock.calls).toEqual([[{ cwd: memory, scope: liveAgent }], [{ scope: liveAgent }]]); + expect(viewFor).toHaveBeenCalledTimes(1); + expect(serviceFor).toHaveBeenCalledWith(liveAgent, 'skills'); + expect(acquireScope).not.toHaveBeenCalled(); + await catalog.resolve('qa', { kind: 'bot', botSlug: 'ada' }, 'bob'); + await catalog.resolve('host', { kind: 'host' }, 'bob'); + expect(viewFor.mock.calls.map(([slug]) => slug)).toEqual(['ada', 'ada', 'bob']); + expect(get.mock.calls).toEqual([ + ['qa', { cwd: memory, scope: liveAgent }], + ['host', { scope: liveAgent }], + ]); + }); + + it('releases a standing scope after list and resolve, including failed lookups', async () => { + const scope = {}; + let active = 0; + const release = vi.fn(async () => { + active--; + }); + const port: SkillRegistryPort = { + async list(options) { + expect(active).toBe(1); + expect(options?.scope).toBe(scope); + return [skill('host', 'user-agents', '/host/SKILL.md')]; + }, + async get(name, options) { + expect(active).toBe(1); + expect(options?.scope).toBe(scope); + if (name === 'host') return skill('host', 'user-agents', '/host/SKILL.md'); + throw new Error('lookup failed'); + }, + }; + const acquireScope = vi.fn(async (_id?: string) => { + active++; + return { key: scope, [Symbol.asyncDispose]: release }; + }); + const catalog = new SkillCatalog({ + memoryDirFor: () => '/memory', + viewFor: createSkillViewPort({ + agentFor: () => undefined, + presetFor: () => 'bot-preset', + agentPresets: () => ({ serviceFor: vi.fn(), acquireScope }), + }), + }); + catalog.attach(port); + await catalog.list(['ada']); + expect(active).toBe(0); + expect(await catalog.resolve('host', { kind: 'host' }, 'ada')).toMatchObject({ name: 'host' }); + expect(active).toBe(0); + await expect(catalog.resolve('broken', { kind: 'host' }, 'ada')).rejects.toThrow( + 'lookup failed', + ); + expect(active).toBe(0); + vi.spyOn(port, 'list').mockRejectedValueOnce(new Error('list failed')); + await expect(catalog.list(['ada'])).rejects.toThrow('list failed'); + expect(active).toBe(0); + expect(release).toHaveBeenCalledTimes(4); + expect(acquireScope.mock.calls).toEqual([ + ['bot-preset'], + ['bot-preset'], + ['bot-preset'], + ['bot-preset'], + ]); + }); + + it('keeps the live scope when its preset uses the Host registry', async () => { + const catalog = new SkillCatalog({ + memoryDirFor: () => '/memory', + viewFor: createSkillViewPort({ + agentFor: () => liveAgent, + presetFor: () => 'default', + agentPresets: () => ({ serviceFor: () => undefined, acquireScope: vi.fn() }), + }), + }); + catalog.attach(registry([skill('host', 'user-dsh', '/host/SKILL.md')], new Map())); + expect(await catalog.resolve('host', { kind: 'host' }, 'ada')).toMatchObject({ name: 'host' }); + }); + + it('keeps the plain global registry fallback when agent presets are absent', async () => { + const catalog = new SkillCatalog({ + memoryDirFor: () => '/memory', + viewFor: createSkillViewPort({ + agentFor: () => liveAgent, + presetFor: () => 'default', + agentPresets: () => undefined, + }), + }); + catalog.attach( + registry( + [ + skill('runtime', 'runtime', '/runtime/SKILL.md'), + skill('filesystem', 'user-agents', '/host/SKILL.md'), + ], + new Map(), + ), + ); + expect((await catalog.list(['ada'])).map((row) => row.name)).toEqual(['runtime']); + expect(await catalog.resolve('runtime', { kind: 'host' }, 'ada')).toMatchObject({ + name: 'runtime', + }); + expect(await catalog.resolve('filesystem', { kind: 'host' }, 'ada')).toBeUndefined(); + expect(await catalog.list([])).toEqual([]); + }); + + it('lists Host Skills only from the first eligible Bot view', async () => { + const viewFor = vi.fn(async (slug) => ({ + registry: registry([skill(`host-${slug}`, 'bundled', '/host/SKILL.md')], new Map()), + scope: {}, + async [Symbol.asyncDispose]() {}, + })); + const catalog = new SkillCatalog({ + memoryDirFor: (slug) => (slug === 'ghost' ? undefined : `/memory/${slug}`), + viewFor, + }); + catalog.attach(registry([], new Map())); + expect((await catalog.list(['ghost', 'ada', 'bob', 'ada'])).map((row) => row.name)).toEqual([ + 'host-ada', + ]); + expect(viewFor.mock.calls.map(([slug]) => slug)).toEqual(['ada', 'bob']); + }); + + it('lists Host Skills and each Bot Memory Skill, keeping same-named Host Skills visible', async () => { + const memory = '/profiles/ada/memory'; + const catalog = new SkillCatalog({ + viewFor: liveView, + memoryDirFor: (slug) => (slug === 'ada' ? memory : undefined), + }); + expect(await catalog.list(['ada'])).toEqual([]); + catalog.attach( + registry( + [ + skill('pdf', 'user-agents', '/home/.agents/skills/pdf/SKILL.md'), + skill('hidden', 'user-dsh', '/home/.dsh/skills/hidden/SKILL.md', 'x', false), + ], + new Map([ + [ + memory, + [ + skill('pdf', 'project-agents', join(memory, '.agents/skills/pdf/SKILL.md')), + skill('review', 'project-dsh', join(memory, '.dsh/skills/review/SKILL.md')), + skill('outside', 'project-agents', '/elsewhere/.agents/skills/outside/SKILL.md'), + ], + ], + ]), + ), + ); + const entries = await catalog.list(['ada', 'ghost']); + expect(entries.map((entry) => [entry.name, entry.owner])).toEqual([ + ['pdf', { kind: 'bot', botSlug: 'ada' }], + ['review', { kind: 'bot', botSlug: 'ada' }], + ['pdf', { kind: 'host' }], + ]); + expect(await catalog.resolve('pdf', { kind: 'host' }, 'ada')).toMatchObject({ + content: 'Body of pdf', + path: '/home/.agents/skills/pdf/SKILL.md', + }); + expect(await catalog.resolve('pdf', { kind: 'bot', botSlug: 'ada' }, 'bob')).toMatchObject({ + path: join(memory, '.agents/skills/pdf/SKILL.md'), + }); + expect( + await catalog.resolve('outside', { kind: 'bot', botSlug: 'ada' }, 'bob'), + ).toBeUndefined(); + expect(await catalog.resolve('review', { kind: 'host' }, 'ada')).toBeUndefined(); + expect(await catalog.resolve('hidden', { kind: 'host' }, 'ada')).toBeUndefined(); + }); + + it('matches a Memory Repository reached through a symlink against DSH real paths', async () => { + const root = createTempRoot('botharness-skill-symlink-'); + const real = join(root, 'real-memory'); + const link = join(root, 'linked-memory'); + mkdirSync(join(real, '.agents/skills/qa'), { recursive: true }); + writeFileSync(join(real, '.agents/skills/qa/SKILL.md'), 'x'); + symlinkSync(real, link); + const skillPath = join(realpathSync(real), '.agents/skills/qa/SKILL.md'); + const catalog = new SkillCatalog({ + viewFor: liveView, + memoryDirFor: () => link, + }); + catalog.attach(registry([], new Map([[link, [skill('qa', 'project-agents', skillPath)]]]))); + expect((await catalog.list(['ada'])).map((entry) => entry.owner)).toEqual([ + { kind: 'bot', botSlug: 'ada' }, + ]); + }); + + it('ranks name prefix, then name subsequence, then description', () => { + const entries = [ + { name: 'zeta', description: 'about pr reviews' }, + { name: 'make-pr', description: '' }, + { name: 'pr-summary', description: '' }, + { name: 'other', description: '' }, + ]; + expect(rankSkillEntries(entries, 'pr').map((entry) => entry.name)).toEqual([ + 'pr-summary', + 'make-pr', + 'zeta', + ]); + expect(rankSkillEntries(entries, '')).toHaveLength(4); + }); +}); + +describe('Skill Invocation in a Human DM', () => { + it.each(['host', 'bot'] as const)( + 'refuses an oversized %s Skill before storing or delivering a message', + async (kind) => { + const runs = vi.fn(async (_run: OrchestratorAgentRun) => {}); + const core = createCore({ + dshHome: createTempRoot('botharness-skill-too-large-'), + agents: adapter(runs), + }); + try { + core.registry.create({ slug: 'ada', displayName: 'Ada' }); + const memory = core.registry.memoryDirFor('ada')!; + const definition = skill( + 'pdf', + kind === 'host' ? 'user-agents' : 'project-agents', + join(memory, '.agents/skills/pdf/SKILL.md'), + 'x'.repeat(MAX_SKILL_INVOCATION_CONTENT + 1), + ); + const catalog = new SkillCatalog({ memoryDirFor: () => memory, viewFor: liveView }); + catalog.attach( + registry(kind === 'host' ? [definition] : [], new Map([[memory, [definition]]])), + ); + const dm = core.channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, 'ada', 'Ada')!; + const before = core.channels.readMessages(dm.id); + const methods = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...core, skills: catalog }); + expect( + await methods.channelSend({ + channelId: dm.id, + body: '/pdf', + skillInvocations: [ + { + name: 'pdf', + owner: kind === 'host' ? { kind } : { kind, botSlug: 'ada' }, + start: 0, + end: 4, + }, + ], + }), + ).toMatchObject({ + ok: false, + error: { code: 'skill-too-large', message: expect.stringMatching(/Skill \/pdf.*64000/u) }, + }); + await core.runtime.whenIdle(); + expect(core.channels.readMessages(dm.id)).toEqual(before); + expect(runs).not.toHaveBeenCalled(); + } finally { + await core.runtime.close(); + core.operationalDatabase.close(); + } + }, + ); + + it.each(['dm', 'group'] as const)( + 'keeps selected Skill spans and defangs mentions in a %s prompt', + async (type) => { + const runs: string[] = []; + const core = createCore({ + dshHome: createTempRoot('botharness-skill-mention-spans-'), + agents: adapter(async (run) => { + runs.push(run.message); + }), + }); + try { + core.registry.create({ slug: 'ada', displayName: 'Ada' }); + core.registry.create({ slug: 'bob', displayName: 'Bob' }); + const catalog = new SkillCatalog({ + memoryDirFor: (slug) => core.registry.memoryDirFor(slug), + viewFor: liveView, + }); + catalog.attach(registry([skill('pdf', 'user-agents', '/host/pdf/SKILL.md')], new Map())); + const channel = + type === 'dm' + ? core.channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, 'ada', 'Ada')! + : core.channels.createGroup(OWNER_HUMAN_CONTEXT, { + name: 'Team', + members: ['ada', 'bob'], + }); + const methods = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...core, skills: catalog }); + const cases: [string, string][] = [ + ['/pdf, next @Bob and /pdf', '[/pdf], next \u2060@Bob and /pdf'], + ['@Bob /pdf, next /pdf', '\u2060@Bob [/pdf], next /pdf'], + ['/pdf @Bob /pdf, next /pdf', '[/pdf] \u2060@Bob [/pdf], next /pdf'], + ]; + for (const [body, expected] of cases) { + const mentionStart = body.indexOf('@Bob'); + const starts = [body.indexOf('/pdf')]; + if (body.startsWith('/pdf @')) starts.push(body.indexOf('/pdf', 4)); + const sent = await methods.channelSend({ + channelId: channel.id, + body, + mentions: [ + { botSlug: 'bob', label: 'Bob', start: mentionStart, end: mentionStart + 4 }, + ], + skillInvocations: starts.map((start) => ({ + name: 'pdf', + owner: { kind: 'host' }, + start, + end: start + 4, + })), + }); + expect(sent.ok).toBe(true); + if (!sent.ok) throw new Error(sent.error.message); + if (type === 'group') core.runtime.admitGroupMessage(channel.id, sent.value.message.id); + else + core.runtime.admitDmMessage(OWNER_HUMAN_CONTEXT, { + channelId: channel.id, + messageId: sent.value.message.id, + body, + }); + await core.runtime.whenIdle(); + const delivered = runs.filter((run) => + run.includes(`Message ID: ${sent.value.message.id}`), + ); + expect(delivered.length).toBeGreaterThan(0); + for (const prompt of delivered) { + expect(prompt).toContain(expected); + expect(prompt).toContain(' { + const core = createCore({ + dshHome: createTempRoot('botharness-skill-all-bots-'), + agents: adapter(async () => {}), + }); + try { + core.registry.create({ slug: 'ada', displayName: 'Ada' }); + core.registry.create({ slug: 'bob', displayName: 'Bob Builder' }); + const catalog = new SkillCatalog({ + memoryDirFor: (slug) => core.registry.memoryDirFor(slug), + viewFor: liveView, + }); + catalog.attach(registry([skill('pdf', 'user-agents', '/host/pdf/SKILL.md')], new Map())); + const group = core.channels.createGroup(OWNER_HUMAN_CONTEXT, { + name: 'Skills', + members: ['ada', 'bob'], + }); + const methods = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...core, skills: catalog }); + const preview = core.channels.previewAllBotMention(group.id); + for (const body of ['@All Bots /pdf', '/pdf @All Bots /pdf']) { + const start = body.indexOf('@All Bots'); + const tokens = [...body.matchAll(/\/pdf/gu)].map((match) => ({ + name: 'pdf', + owner: { kind: 'host' }, + start: match.index, + end: match.index + 4, + })); + const sent = await methods.channelSend({ + channelId: group.id, + body, + allBotMention: { start, end: start + 9, label: 'All Bots', preview }, + skillInvocations: tokens, + }); + expect(sent.ok).toBe(true); + if (!sent.ok) throw new Error(sent.error.message); + const stored = core.channels.message(group.id, sent.value.message.id)!; + expect(stored.body).toBe(body.replace('@All Bots', '@Ada @Bob Builder')); + expect(stored.skillInvocations).toHaveLength(tokens.length); + for (const token of stored.skillInvocations ?? []) { + expect(stored.body.slice(token.start, token.end)).toBe('/pdf'); + expect(token).toMatchObject({ content: 'Body of pdf', path: '/host/pdf/SKILL.md' }); + } + if (body.startsWith('/pdf')) expect(stored.skillInvocations?.[0]?.start).toBe(0); + } + } finally { + await core.runtime.close(); + core.operationalDatabase.close(); + } + }); + + it('keeps Group Skill catalog and sends within each Human readable active Bots', async () => { + const alice = humanContext('alice'); + const bob = humanContext('bob'); + const core = createCore({ + dshHome: createTempRoot('botharness-skill-team-'), + agents: adapter(async () => {}), + }); + try { + const database = attachOperationalModule(core.operationalDatabase, 'team'); + database.transaction((db) => { + for (const human of [alice, bob]) { + db.prepare("INSERT INTO humans VALUES (?, ?, 'active', ?)").run( + human.humanId, + human.humanId, + new Date().toISOString(), + ); + db.prepare("INSERT INTO human_roles VALUES (?, 'member')").run(human.humanId); + } + db.prepare('UPDATE team_settings SET enabled = 1').run(); + }); + for (const human of [OWNER_HUMAN_CONTEXT, alice, bob]) { + core.team.spaces.ensureAccount(human.humanId); + core.registry.create({ + slug: human === OWNER_HUMAN_CONTEXT ? 'owner-bot' : human.humanId + '-bot', + displayName: human.humanId, + ownerHumanId: human.humanId, + }); + } + const viewFor = vi.fn(liveView); + const catalog = new SkillCatalog({ + memoryDirFor: (slug) => core.registry.memoryDirFor(slug), + viewFor, + }); + catalog.attach( + registry( + [skill('host', 'user-agents', '/host/SKILL.md')], + new Map( + ['alice-bot', 'bob-bot', 'owner-bot'].map((slug) => { + const memory = core.registry.memoryDirFor(slug)!; + return [ + memory, + [skill('pdf', 'project-agents', join(memory, '.agents/skills/pdf/SKILL.md'))], + ]; + }), + ), + ), + ); + const group = core.channels.createGroup(OWNER_HUMAN_CONTEXT, { + name: 'Shared Skills', + members: ['alice-bot', 'owner-bot', 'bob-bot'], + }); + core.team.channelAccess.visibilitySet(OWNER_HUMAN_CONTEXT, group.id, { kind: 'public' }); + for (const human of [alice, bob]) core.team.channelAccess.join(human, group.id); + const methods = (human: typeof alice) => + createBridgeMethods(human, { ...core, skills: catalog }); + const send = (human: typeof alice, botSlug: string) => + methods(human).channelSend({ + channelId: group.id, + body: '/pdf', + skillInvocations: [{ name: 'pdf', owner: { kind: 'bot', botSlug }, start: 0, end: 4 }], + }); + for (const [human, slug] of [ + [OWNER_HUMAN_CONTEXT, 'owner-bot'], + [alice, 'alice-bot'], + [bob, 'bob-bot'], + ] as const) { + expect(await methods(human).channelSkillCatalog({ channelId: group.id })).toMatchObject({ + ok: true, + value: { + skills: [ + { name: 'pdf', owner: { kind: 'bot', botSlug: slug } }, + { name: 'host', owner: { kind: 'host' } }, + ], + }, + }); + expect(await send(human, slug)).toMatchObject({ + ok: true, + value: { message: { skillInvocations: [{ content: 'Body of pdf' }] } }, + }); + } + const before = core.channels.readMessages(group.id); + viewFor.mockClear(); + const hidden = await send(bob, 'alice-bot'); + expect(hidden).toEqual({ + ok: false, + error: { code: 'skill-unavailable', message: 'Skill /pdf is no longer available' }, + }); + expect(await send(bob, 'missing-bot')).toEqual(hidden); + expect(await send(OWNER_HUMAN_CONTEXT, 'alice-bot')).toEqual(hidden); + expect(viewFor).not.toHaveBeenCalled(); + expect(core.channels.readMessages(group.id)).toEqual(before); + expect( + await methods(bob).channelSend({ + channelId: group.id, + body: '/host', + skillInvocations: [{ name: 'host', owner: { kind: 'host' }, start: 0, end: 5 }], + }), + ).toMatchObject({ ok: true }); + expect(viewFor.mock.calls.map(([slug]) => slug)).toEqual(['bob-bot']); + core.registry.setPaused('alice-bot', true); + viewFor.mockClear(); + expect(await methods(alice).channelSkillCatalog({ channelId: group.id })).toEqual({ + ok: true, + value: { skills: [] }, + }); + const pausedBefore = core.channels.readMessages(group.id); + expect(await send(alice, 'alice-bot')).toEqual(hidden); + expect( + await methods(alice).channelSend({ + channelId: group.id, + body: '/host', + skillInvocations: [{ name: 'host', owner: { kind: 'host' }, start: 0, end: 5 }], + }), + ).toMatchObject({ ok: false, error: { code: 'skill-unavailable' } }); + expect(viewFor).not.toHaveBeenCalled(); + expect(core.channels.readMessages(group.id)).toEqual(pausedBefore); + } finally { + await core.runtime.close(); + core.operationalDatabase.close(); + } + }); + + it('uses the DM Bot and first eligible Group Bot when resolving Host Skills', async () => { + const core = createCore({ + dshHome: createTempRoot('botharness-skill-viewer-'), + agents: adapter(async () => {}), + }); + try { + core.registry.create({ slug: 'ada', displayName: 'Ada' }); + core.registry.create({ slug: 'bob', displayName: 'Bob' }); + core.registry.setPaused('ada', true); + const viewFor = vi.fn(liveView); + const catalog = new SkillCatalog({ + memoryDirFor: (slug) => core.registry.memoryDirFor(slug), + viewFor, + }); + const memory = core.registry.memoryDirFor('ada')!; + catalog.attach( + registry( + [skill('host', 'user-agents', '/host/SKILL.md')], + new Map([ + [memory, [skill('pdf', 'project-agents', join(memory, '.agents/skills/pdf/SKILL.md'))]], + ]), + ), + ); + const methods = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...core, skills: catalog }); + const group = core.channels.createGroup(OWNER_HUMAN_CONTEXT, { + name: 'Team', + members: ['ada', 'bob'], + }); + const dm = core.channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, 'bob', 'Bob')!; + expect(await methods.channelSkillCatalog({ channelId: group.id })).toMatchObject({ + ok: true, + value: { skills: [{ name: 'host', owner: { kind: 'host' } }] }, + }); + viewFor.mockClear(); + const before = core.channels.readMessages(group.id); + expect( + await methods.channelSend({ + channelId: group.id, + body: '/pdf', + skillInvocations: [ + { name: 'pdf', owner: { kind: 'bot', botSlug: 'ada' }, start: 0, end: 4 }, + ], + }), + ).toMatchObject({ ok: false, error: { code: 'skill-unavailable' } }); + expect(core.channels.readMessages(group.id)).toEqual(before); + expect(viewFor).not.toHaveBeenCalled(); + for (const channelId of [group.id, dm.id]) { + expect( + await methods.channelSend({ + channelId, + body: '/host', + skillInvocations: [{ name: 'host', owner: { kind: 'host' }, start: 0, end: 5 }], + }), + ).toMatchObject({ ok: true }); + } + expect(viewFor.mock.calls.map(([slug]) => slug)).toEqual(['bob', 'bob']); + } finally { + await core.runtime.close(); + core.operationalDatabase.close(); + } + }); + + it('snapshots the picked Skill and delivers it without a bare /name', async () => { + const home = createTempRoot('botharness-skill-invocation-'); + const runs: string[] = []; + const core = createCore({ + dshHome: home, + agents: adapter(async (run) => { + runs.push(run.message); + }), + }); + try { + core.registry.create({ slug: 'ada', displayName: 'Ada' }); + core.registry.create({ slug: 'bob', displayName: 'Bob' }); + const memory = core.registry.memoryDirFor('ada')!; + const skillPath = join(memory, '.agents/skills/summarize-pr/SKILL.md'); + const project = new Map([ + [ + memory, + [skill('summarize-pr', 'project-agents', skillPath, 'Summarize the PR in 3 bullets.')], + ], + ]); + const catalog = new SkillCatalog({ + viewFor: liveView, + memoryDirFor: (slug) => core.registry.memoryDirFor(slug), + }); + catalog.attach(registry([skill('pdf', 'user-agents', '/home/pdf/SKILL.md')], project)); + const dm = core.channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, 'ada', 'Ada')!; + const methods = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...core, skills: catalog }); + + expect(await methods.channelSkillCatalog({ channelId: dm.id })).toMatchObject({ + ok: true, + value: { + skills: [ + { name: 'summarize-pr', owner: { kind: 'bot', botSlug: 'ada' }, path: skillPath }, + { name: 'pdf', owner: { kind: 'host' } }, + ], + }, + }); + + const body = 'please /summarize-pr #42'; + const start = body.indexOf('/'); + const sent = await methods.channelSend({ + channelId: dm.id, + body, + skillInvocations: [ + { + name: 'summarize-pr', + owner: { kind: 'bot', botSlug: 'ada' }, + start, + end: start + '/summarize-pr'.length, + }, + ], + }); + expect(sent.ok).toBe(true); + const message = sent.ok ? sent.value.message : undefined; + expect(message?.skillInvocations).toEqual([ + { + name: 'summarize-pr', + owner: { kind: 'bot', botSlug: 'ada' }, + start, + end: start + 13, + path: skillPath, + content: 'Summarize the PR in 3 bullets.', + }, + ]); + + project.set(memory, []); + expect(core.channels.message(dm.id, message!.id)?.skillInvocations?.[0]?.content).toBe( + 'Summarize the PR in 3 bullets.', + ); + + if (runs.length === 0) + core.runtime.admitDmMessage(OWNER_HUMAN_CONTEXT, { + channelId: dm.id, + messageId: message!.id, + body, + }); + await core.runtime.whenIdle(); + const delivered = runs.find((run) => run.includes('\nSummarize the PR in 3 bullets.\n`, + ); + expect(delivered).not.toMatch(/(^|\s)\/summarize-pr(?=\s|$)/mu); + } finally { + await core.runtime.close(); + core.operationalDatabase.close(); + } + }); + + it('refuses tokens that do not match the body, other Bots and Skills that are gone', async () => { + const home = createTempRoot('botharness-skill-invocation-refuse-'); + const core = createCore({ dshHome: home, agents: adapter(async () => {}) }); + try { + core.registry.create({ slug: 'ada', displayName: 'Ada' }); + core.registry.create({ slug: 'bob', displayName: 'Bob' }); + const catalog = new SkillCatalog({ + viewFor: liveView, + memoryDirFor: (slug) => core.registry.memoryDirFor(slug), + }); + catalog.attach(registry([skill('pdf', 'user-agents', '/home/pdf/SKILL.md')], new Map())); + const dm = core.channels.getOrCreateDm(OWNER_HUMAN_CONTEXT, 'ada', 'Ada')!; + const methods = createBridgeMethods(OWNER_HUMAN_CONTEXT, { ...core, skills: catalog }); + const send = (body: string, token: Record) => + methods.channelSend({ channelId: dm.id, body, skillInvocations: [token] }); + + expect( + await send('/pdf', { name: 'pdf', owner: { kind: 'host' }, start: 0, end: 3 }), + ).toMatchObject({ ok: false, error: { code: 'invalid-input' } }); + expect( + await send('/pdf now', { + name: 'pdf', + owner: { kind: 'bot', botSlug: 'bob' }, + start: 0, + end: 4, + }), + ).toMatchObject({ ok: false }); + expect( + await send('/gone now', { name: 'gone', owner: { kind: 'host' }, start: 0, end: 5 }), + ).toMatchObject({ ok: false, error: { code: 'skill-unavailable' } }); + expect( + await send('/pdf now', { name: 'pdf', owner: { kind: 'host' }, start: 0, end: 4 }), + ).toMatchObject({ + ok: true, + value: { message: { skillInvocations: [{ name: 'pdf', content: 'Body of pdf' }] } }, + }); + } finally { + await core.runtime.close(); + core.operationalDatabase.close(); + } + }); +}); + +describe('Skill Invocation text', () => { + it('marks only picked tokens and escapes the path attribute', () => { + const invocations = [ + { + name: 'pdf', + owner: { kind: 'host' } as const, + start: 0, + end: 4, + path: '/a"b/SKILL.md', + content: 'Do PDF things.', + }, + ]; + expect(markSkillTokens('/pdf and /pdf-two and x/pdf', invocations)).toBe( + '[/pdf] and /pdf-two and x/pdf', + ); + expect(markSkillTokens('/pdf, next', invocations)).toBe('[/pdf], next'); + expect(markSkillTokens('/pdf and /pdf', invocations)).toBe('[/pdf] and /pdf'); + expect(markSkillTokens('/pdf and /pdf', [{ ...invocations[0]!, start: 9, end: 13 }])).toBe( + '/pdf and [/pdf]', + ); + expect( + markSkillTokens('/pdf /pdf', [{ ...invocations[0]!, start: 5, end: 9 }, invocations[0]!]), + ).toBe('[/pdf] [/pdf]'); + expect(skillInvocationPrompt(invocations)).toContain( + '\nDo PDF things.\n', + ); + expect(skillInvocationPrompt([])).toBe(''); + }); +}); + +describe('deepseekbot send --skill', () => { + it('assigns repeated names to unused occurrences in flag order', () => { + expect(skillInvocationTokens('/pdf /pdf', ['host/pdf', 'bot:ada/pdf'])).toEqual([ + { name: 'pdf', owner: { kind: 'host' }, start: 0, end: 4 }, + { name: 'pdf', owner: { kind: 'bot', botSlug: 'ada' }, start: 5, end: 9 }, + ]); + expect(skillInvocationTokens('x/pdf /pdf-two /pdf /pdf', ['bot:ada/pdf', 'host/pdf'])).toEqual([ + { name: 'pdf', owner: { kind: 'bot', botSlug: 'ada' }, start: 15, end: 19 }, + { name: 'pdf', owner: { kind: 'host' }, start: 20, end: 24 }, + ]); + expect(() => skillInvocationTokens('/pdf', ['host/pdf', 'bot:ada/pdf'])).toThrow(); + expect(() => + skillInvocationTokens('/pdf /pdf', ['host/pdf', 'bot:ada/pdf', 'host/pdf']), + ).toThrow(); + }); + + it('maps owner/name to the first matching /name token', () => { + expect(skillInvocationTokens('run /pdf then /review', ['bot:ada/review', 'host/pdf'])).toEqual([ + { name: 'pdf', owner: { kind: 'host' }, start: 4, end: 8 }, + { name: 'review', owner: { kind: 'bot', botSlug: 'ada' }, start: 14, end: 21 }, + ]); + expect(() => skillInvocationTokens('no token', ['host/pdf'])).toThrow(/needs \/pdf/u); + expect(() => skillInvocationTokens('/pdf', ['pdf'])).toThrow(/\//u); + }); +}); diff --git a/scripts/verification-inventory.json b/scripts/verification-inventory.json index f66fec7f9..02b84a368 100644 --- a/scripts/verification-inventory.json +++ b/scripts/verification-inventory.json @@ -760,6 +760,14 @@ "task": 1958, "gap": null }, + { + "id": "desktop.composer.skill-invocation", + "label": "Pick a Skill from / in a Bot DM and deliver its text snapshot", + "source": "packages/client/src/client/channel-composer.tsx", + "guide": ".agents/skills/verify-deepseekbot/features/skill-invocation.md", + "task": 4232, + "gap": null + }, { "id": "native.settings.handoff", "label": "Open native Models from Bot mode and restore navigation after Settings closes",