From cbf27b772f6b3b2f1a7cb16f7d0723df6dd3ca7a Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Sun, 15 Nov 2026 21:28:02 +0900 Subject: [PATCH 01/10] feat: invoke a Bot's Skills from / in a Human DM Type / in a PersonaBot DM to pick a Host Skill or a Project Skill from the Bot's Memory Repository. The Host snapshots the Skill's text with the message and the Bot reads it as a block. The CLI gets skills-list and send --skill. Adds ADR-0341 and ADR-0342. Issue: #4232 Agent-Task: claude-code/local/0d4a6a9f-6296-49dd-b14c-6789efa657c3 Co-Authored-By: Claude Opus 5.5 --- .../verify-deepseekbot/features/README.md | 1 + .../features/skill-invocation.md | 32 ++ changes/4232-dm-skill-invocation.md | 11 + ...ject-skills-travel-with-their-directory.md | 20 ++ ...-snapshotted-text-that-addresses-no-one.md | 20 ++ docs/bot-cli.md | 2 + docs/bot-cli.zh.md | 4 + packages/client/src/client/actions.ts | 11 +- packages/client/src/client/bot-main.tsx | 49 ++- packages/client/src/client/bridge.ts | 85 +++++- .../client/src/client/channel-composer.tsx | 153 ++++++++-- .../src/client/channel-message-body.tsx | 35 ++- packages/client/src/client/channel-refs.ts | 31 +- .../src/client/composer-context-styles.ts | 6 + .../client/src/client/composer-draft-store.ts | 38 ++- packages/client/src/client/human-markdown.ts | 1 + packages/client/src/client/locale.ts | 6 + .../client/src/client/rich-mention-editor.ts | 54 +++- packages/client/src/client/skill-refs.ts | 92 ++++++ packages/client/src/client/store.ts | 1 + packages/client/test/bot-main.test.ts | 3 + packages/client/test/bot-sidebar.test.ts | 1 + .../channel-composer-dictation-guard.test.ts | 1 + .../test/channel-composer-lifecycle.test.ts | 1 + .../test/channel-composer-paste.test.ts | 1 + packages/client/test/channel-composer.test.ts | 1 + .../client/test/personabot-profile.test.ts | 1 + .../client/test/rich-mention-editor.test.ts | 14 +- .../client/test/session-stop-header.test.tsx | 1 + packages/client/test/skill-composer.test.ts | 193 ++++++++++++ packages/core/src/bots/cli-live.ts | 19 ++ packages/core/src/bots/cli-skills.ts | 81 +++++ packages/core/src/bridge/methods.ts | 93 ++++++ packages/core/src/bridge/rpc.ts | 14 +- packages/core/src/channels/channel.ts | 59 ++++ packages/core/src/channels/sqlite-store.ts | 11 + packages/core/src/plugin.ts | 10 + packages/core/src/runtime/bot-runtime.ts | 57 +++- packages/core/src/skills/catalog.ts | 136 +++++++++ packages/core/src/skills/entries.ts | 51 ++++ packages/core/src/team/member-methods.ts | 1 + packages/core/test/bridge-rpc.test.ts | 3 + packages/core/test/plugin.test.ts | 1 + packages/core/test/skill-invocation.test.ts | 289 ++++++++++++++++++ scripts/verification-inventory.json | 8 + 45 files changed, 1661 insertions(+), 41 deletions(-) create mode 100644 .agents/skills/verify-deepseekbot/features/skill-invocation.md create mode 100644 changes/4232-dm-skill-invocation.md create mode 100644 docs/adr/0341-project-skills-travel-with-their-directory.md create mode 100644 docs/adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md create mode 100644 packages/client/src/client/skill-refs.ts create mode 100644 packages/client/test/skill-composer.test.ts create mode 100644 packages/core/src/bots/cli-skills.ts create mode 100644 packages/core/src/skills/catalog.ts create mode 100644 packages/core/src/skills/entries.ts create mode 100644 packages/core/test/skill-invocation.test.ts diff --git a/.agents/skills/verify-deepseekbot/features/README.md b/.agents/skills/verify-deepseekbot/features/README.md index 811954e0fb..faedc73be2 100644 --- a/.agents/skills/verify-deepseekbot/features/README.md +++ b/.agents/skills/verify-deepseekbot/features/README.md @@ -67,6 +67,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 0000000000..68bf8c292d --- /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-0342](../../../../docs/adr/0342-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 0000000000..f24eb28efe --- /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/docs/adr/0341-project-skills-travel-with-their-directory.md b/docs/adr/0341-project-skills-travel-with-their-directory.md new file mode 100644 index 0000000000..53ac5d7396 --- /dev/null +++ b/docs/adr/0341-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, installing or importing a PersonaBot lists each incoming Project Skill in the existing install review (prompt-injection, exfiltration and script findings). Until a Human accepts that review, the Skills are not discoverable. 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. +- **Make imported Skills active immediately and amend ADR-0044** — rejected: a Skill can carry scripts and instructions that need the same review as any other installed bot content. diff --git a/docs/adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md b/docs/adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md new file mode 100644 index 0000000000..e25d5144b5 --- /dev/null +++ b/docs/adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md @@ -0,0 +1,20 @@ +--- +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. + +## 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 77cd981607..17aeda5036 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 diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index bd13be174e..a956393022 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` 变成 Skill Invocation:Host 把该 Skill 当前的文本随消息保存,Bot 以 `` 块读到它。Skill 不决定由谁回复;已不存在的 Skill 会以 `skill-unavailable` 拒绝。见 [ADR-0342](adr/0342-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 4b7f42a9ce..cfb6718268 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, @@ -1030,7 +1032,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; @@ -3312,6 +3316,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( @@ -3324,6 +3329,7 @@ export function createActions( grantRequestResolution, allBotMention, submissionId, + skillInvocations, ) { let snapshot = clientStore.getSnapshot(); const channel = snapshot.conversation.channel; @@ -3341,6 +3347,7 @@ export function createActions( !replyTo && !mentions?.length && !channelRefs?.length && + !skillInvocations?.length && !memorySwitchTarget && !grantRequestResolution ) { @@ -3427,6 +3434,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 8fbd8fb5fa..a4ffe7f8aa 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,15 @@ 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.map((item) => ({ + ...item, + start: item.start + leftTrim, + end: item.end + leftTrim, + })), + ); setUploadItems((current) => (current.length > 0 ? current : submittedUploads)); } } @@ -3606,6 +3647,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 +3715,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 +3825,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 +1096,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 +1113,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 82c0062320..e492965328 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 22aa5f6dc5..cbf88b4100 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 fecf3a1a9f..c97ab3897b 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 661ff3552d..62f36cd8b8 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 9d00518537..22e2c80e9b 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 6287727660..8d9c575e1e 100644 --- a/packages/client/src/client/locale.ts +++ b/packages/client/src/client/locale.ts @@ -4625,6 +4625,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', @@ -10604,6 +10607,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 c971ba75a1..d26c195855 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 0000000000..0bc508a67a --- /dev/null +++ b/packages/client/src/client/skill-refs.ts @@ -0,0 +1,92 @@ +import type { SkillCatalogEntry, SkillOwner } from '../../../core/src/skills/entries.js'; +import type { BotSummary } from './store.js'; + +/** A Skill chip in the composer: the `/name` token and whose Skill it is. */ +export interface SelectedSkill { + name: string; + owner: SkillOwner; + start: number; + end: number; +} + +export interface SkillQuery { + start: number; + end: number; + query: string; +} + +/** A `/` menu row: a catalog entry plus the owning PersonaBot, when it has one. */ +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; +} + +/** The `/query` the caret is typing, when it starts a line or follows whitespace. */ +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, + }; +} + +/** Keeps only chips whose `/name` text is still exactly where it was picked. */ +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 fad2281142..8fd6d395e3 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 4cb9e8ef8a..028944af69 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 adc9018386..3a40bb2618 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 de39b4b582..ffbf9c94a3 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 e6cc219b8c..f0da6ed5d1 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 3d98325da7..a140a3a6a4 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 6155fd3b2f..72191d4baf 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 558b933f69..eab3d0c95d 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 aba1c5f188..f3c1fbf904 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 c148663568..adedd67191 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 0000000000..46e46f3495 --- /dev/null +++ b/packages/client/test/skill-composer.test.ts @@ -0,0 +1,193 @@ +// @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(); + } + }); +}); diff --git a/packages/core/src/bots/cli-live.ts b/packages/core/src/bots/cli-live.ts index d0c3947287..b906a11aa7 100644 --- a/packages/core/src/bots/cli-live.ts +++ b/packages/core/src/bots/cli-live.ts @@ -156,6 +156,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, @@ -222,6 +230,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' }, @@ -365,6 +374,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', @@ -624,6 +634,7 @@ interface LiveValues ApprovalTemplateValues, ApprovalReviewerValues, VoiceValues { + skill?: string[]; as?: string; username?: string; 'display-name'?: string; @@ -1250,6 +1261,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)); @@ -1372,6 +1388,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') { @@ -1411,6 +1428,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' && @@ -1597,6 +1615,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 0000000000..c19e4d9a9d --- /dev/null +++ b/packages/core/src/bots/cli-skills.ts @@ -0,0 +1,81 @@ +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 ?? ''), + }; +} + +/** + * Turns `--skill /` values into Skill Invocation tokens for the + * first matching `/name` in the message body. Owner is `host` or `bot:`. + */ +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 match = new RegExp(`(^|\\s)/${name}(?=\\s|$)`, 'u').exec(body); + if (match === null) usage(`--skill ${raw} needs /${name} in the message body.`); + const start = match.index + match[1]!.length; + if (tokens.some((token) => token.start === start)) + usage(`/${name} is already picked by another --skill.`); + 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 d82073b875..abfe43150e 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,7 @@ import { type DataResetPreview, type DataResetResult, } from '../data-reset/reset.js'; +import type { SkillCatalog, SkillCatalogEntry } from '../skills/catalog.js'; import { isValidSlug } from '../bots/slug.js'; import { memoryMoveTarget, @@ -892,6 +896,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 +1269,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 +2082,7 @@ function historyPosition(cursor: string): ToolApprovalHistoryPosition | undefine } } const MAX_CHANNEL_SEND_ATTACHMENTS = 10; +const MAX_SKILL_INVOCATIONS = 5; function ownAttachments( message: ChannelMessage, @@ -6929,6 +6936,31 @@ 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 = ( + channel.type === 'group' + ? channel.members + : channel.botSlug === undefined + ? [] + : [channel.botSlug] + ).filter((slug) => { + const bot = deps.registry.get(slug); + return bot !== undefined && bot.paused !== true; + }); + 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'); @@ -7109,6 +7141,34 @@ 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'); + } const rawReplyTo = source['replyTo']; if (rawReplyTo !== undefined && (typeof rawReplyTo !== 'string' || rawReplyTo.length === 0)) { return invalidInput('replyTo must be a message id'); @@ -7271,6 +7331,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 @@ -7365,6 +7433,30 @@ function buildBridgeMethods( ) { return dmAdmissionFailure(channelId, channel.botSlug, 'archived-bot'); } + const skillInvocations: ChannelSkillInvocation[] = []; + for (const token of skillTokens) { + if ( + token.owner.kind === 'bot' && + !(channel.type === 'group' + ? channel.members.includes(token.owner.botSlug) + : channel.botSlug === token.owner.botSlug) + ) + return invalidInput(`Skill /${token.name} belongs to a PersonaBot outside this Channel`); + const resolved = await deps.skills?.resolve(token.name, token.owner); + 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 @@ -7392,6 +7484,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 feda37a878..49f90b4727 100644 --- a/packages/core/src/bridge/rpc.ts +++ b/packages/core/src/bridge/rpc.ts @@ -170,7 +170,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'; @@ -2178,6 +2184,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 })); } @@ -2198,9 +2207,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 }), @@ -3324,6 +3335,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 3d5b597bde..66fd6b6551 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,50 @@ export interface ChannelReference { end: number; } +/** + * A Skill Invocation: the `/name` token a Human picked from the `/` menu, with + * the Skill's text captured when the message was sent. It addresses no one. + */ +export interface ChannelSkillInvocation { + name: string; + owner: SkillOwner; + start: number; + end: number; + path?: string; + content: string; +} + +/** What a Client sends for a Skill Invocation; the Host adds the text snapshot. */ +export type ChannelSkillInvocationToken = Pick< + ChannelSkillInvocation, + 'name' | 'owner' | 'start' | 'end' +>; + +const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u; + +/** Checks a Skill Invocation's name, owner and `/name` position inside `body`. */ +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 +553,7 @@ export interface ChannelMessage { mentions?: ChannelMention[]; humanMentions?: { humanId: string; label: string; start: number; end: number }[]; channelRefs?: ChannelReference[]; + skillInvocations?: ChannelSkillInvocation[]; channelRevision?: number; @@ -1088,6 +1134,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 61a5d6f377..44981fa3ca 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 08d9d364b5..943f244797 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -244,6 +244,7 @@ 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 { DeveloperModeSkillGate } from './logs/skill.js'; import { openLogDatabase, type LogDatabase } from './logs/log-db.js'; import type { ChannelStore } from './channels/store.js'; @@ -3217,8 +3218,13 @@ 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), + }); const bridgeDeps: BridgeMethodsDeps = { team, + skills: skillCatalog, hostVersion: () => release.version(), callText: createCallTextHarvest({ calls: () => voiceCalls, attachments: core.attachments }), voiceProviders: core.voiceProviders, @@ -3792,6 +3798,10 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { }, }); developerModeTarget.gate = gate; + skillsCtx.effect( + () => skillCatalog.attach((skillsCtx as unknown as { skills: SkillRegistryPort }).skills), + '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 04b43c225d..02748cc610 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,43 @@ export interface DirectBotToolCall { const DIRECT_TOOL_CALL_LIMIT = 50; +/** + * Wraps each picked `/name` token as `[/name]`. DSH loads a Skill again for any + * bare `/name` in user input; the snapshot below is the one the Human sent. + */ +export function markSkillTokens( + text: string, + invocations: readonly ChannelSkillInvocation[] | undefined, +): string { + let marked = text; + for (const name of new Set((invocations ?? []).map((skill) => skill.name))) + marked = marked.replace( + new RegExp(`(^|\\s)/${name}(?=\\s|$)`, 'gu'), + (_match, lead: string) => `${lead}[/${name}]`, + ); + return marked; +} + +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, @@ -4183,10 +4221,18 @@ 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, + markSkillTokens(body, message.skillInvocations), + ) + + 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 +4243,17 @@ class BotRuntimeImplementation implements BotRuntime { (message.mentions?.length ?? 0) > 0 ? message.body : body; - const text = sessionMentionText(mentionBody, message?.mentions ?? []); + const text = markSkillTokens( + sessionMentionText(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/skills/catalog.ts b/packages/core/src/skills/catalog.ts new file mode 100644 index 0000000000..74c86f64ec --- /dev/null +++ b/packages/core/src/skills/catalog.ts @@ -0,0 +1,136 @@ +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'; + +/** The subset of DSH's `ctx.skills` registry the catalog reads. */ +export interface SkillRegistryPort { + list(options?: { cwd?: string }): Promise; + get(name: string, options?: { cwd?: string }): 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; + +const PROJECT_SOURCES = new Set(['project-agents', 'project-dsh']); + +function inside(root: string, path: string | undefined): boolean { + if (path === undefined) return false; + const rel = relative(resolve(root), resolve(path)); + return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel); +} + +/** + * Lists and resolves the Skills a Human can invoke in a conversation: Host + * Skills plus the Project Skills of each PersonaBot's Memory Repository. + * DSH discovery stays the authority; this module only labels owners and + * keeps a Bot's same-named Skill from hiding the Host one in the menu. + */ +export class SkillCatalog { + #registry: SkillRegistryPort | undefined; + readonly #memoryDirFor: (botSlug: string) => string | undefined; + + constructor(options: { memoryDirFor(botSlug: string): string | undefined }) { + this.#memoryDirFor = options.memoryDirFor; + } + + get available(): boolean { + return this.#registry !== undefined; + } + + attach(registry: SkillRegistryPort): () => void { + this.#registry = registry; + return () => { + if (this.#registry === registry) this.#registry = undefined; + }; + } + + async list(botSlugs: readonly string[]): Promise { + const registry = this.#registry; + if (registry === undefined) return []; + const entries: SkillCatalogEntry[] = []; + for (const botSlug of new Set(botSlugs)) { + const root = this.#memoryDirFor(botSlug); + if (root === undefined) continue; + for (const skill of await registry.list({ 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 }), + }); + } + for (const skill of await registry.list()) + if (skill.invocation.userInvocable && !PROJECT_SOURCES.has(skill.source)) + entries.push({ + name: skill.name, + description: skill.description, + owner: { kind: 'host' }, + ...(skill.path === undefined ? {} : { path: skill.path }), + }); + return entries; + } + + /** Reads the current text of one Skill so a message can keep a snapshot of it. */ + async resolve(name: string, owner: SkillOwner): Promise { + const registry = this.#registry; + if (registry === undefined) return undefined; + if (owner.kind === 'host') { + const skill = await registry.get(name); + if (skill === undefined || !skill.invocation.userInvocable) return undefined; + if (PROJECT_SOURCES.has(skill.source)) return undefined; + return { + name, + owner, + content: skill.content.slice(0, MAX_SKILL_INVOCATION_CONTENT), + ...(skill.path === undefined ? {} : { path: skill.path }), + }; + } + const root = this.#memoryDirFor(owner.botSlug); + if (root === undefined) return undefined; + const skill = await registry.get(name, { 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.slice(0, MAX_SKILL_INVOCATION_CONTENT), + ...(skill.path === undefined ? {} : { path: skill.path }), + }; + } +} diff --git a/packages/core/src/skills/entries.ts b/packages/core/src/skills/entries.ts new file mode 100644 index 0000000000..78f9a366ca --- /dev/null +++ b/packages/core/src/skills/entries.ts @@ -0,0 +1,51 @@ +import { isValidSlug } from '../bots/slug.js'; + +/** Who a Skill belongs to: the Host (user level) or one PersonaBot's Memory Repository. */ +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; +} + +/** + * Orders catalog entries for a `/` query: name prefix, then name subsequence, + * then description substring. Ties keep catalog order. + */ +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 7db1f3ff9e..bc13f0733b 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/bridge-rpc.test.ts b/packages/core/test/bridge-rpc.test.ts index 7ef13da8a3..fe998fa76f 100644 --- a/packages/core/test/bridge-rpc.test.ts +++ b/packages/core/test/bridge-rpc.test.ts @@ -871,6 +871,7 @@ describe('bridge typert service', () => { 'messageSearch', 'channelUnreadCounts', 'channelAllBotPreview', + 'channelSkillCatalog', 'channelSend', 'channelSendStatus', 'channelGenuiView', @@ -1239,7 +1240,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 af2dd9a748..7f85969dcb 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 0000000000..8f6ad30a94 --- /dev/null +++ b/packages/core/test/skill-invocation.test.ts @@ -0,0 +1,289 @@ +import { join } from 'node:path'; + +import { describe, expect, it } from 'vitest'; + +import { skillInvocationTokens } from '../src/bots/cli-skills.js'; +import { createBridgeMethods } from '../src/bridge/methods.js'; +import { OWNER_HUMAN_CONTEXT } from '../src/humans/context.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, + rankSkillEntries, + type SkillRegistryDefinition, + type SkillRegistryPort, +} from '../src/skills/catalog.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 }, + }; +} + +/** A DSH-shaped registry: project roots win over Host rows of the same name. */ +function registry( + host: SkillRegistryDefinition[], + project: Map, +) { + const view = (cwd?: string) => { + 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); + }, + async get(name, options) { + return view(options?.cwd).find((item) => item.name === name); + }, + }; + return port; +} + +describe('SkillCatalog', () => { + 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({ + 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' })).toMatchObject({ + content: 'Body of pdf', + path: '/home/.agents/skills/pdf/SKILL.md', + }); + expect(await catalog.resolve('pdf', { kind: 'bot', botSlug: 'ada' })).toMatchObject({ + path: join(memory, '.agents/skills/pdf/SKILL.md'), + }); + expect(await catalog.resolve('outside', { kind: 'bot', botSlug: 'ada' })).toBeUndefined(); + expect(await catalog.resolve('review', { kind: 'host' })).toBeUndefined(); + expect(await catalog.resolve('hidden', { kind: 'host' })).toBeUndefined(); + }); + + 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('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({ + 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({ + 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(skillInvocationPrompt(invocations)).toContain( + '\nDo PDF things.\n', + ); + expect(skillInvocationPrompt([])).toBe(''); + }); +}); + +describe('deepseekbot send --skill', () => { + 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 65cea6ccb2..934f674f87 100644 --- a/scripts/verification-inventory.json +++ b/scripts/verification-inventory.json @@ -736,6 +736,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", From a741544c5345a5a34cb541fae0d2beed56c75ab9 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Sun, 15 Nov 2026 22:02:42 +0900 Subject: [PATCH 02/10] fix(skills): compare Memory paths after resolving symlinks Issue: #4232 Agent-Task: claude-code/local/0d4a6a9f-6296-49dd-b14c-6789efa657c3 Co-Authored-By: Claude Opus 5.5 --- packages/core/src/skills/catalog.ts | 11 ++++++++++- packages/core/test/skill-invocation.test.ts | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/packages/core/src/skills/catalog.ts b/packages/core/src/skills/catalog.ts index 74c86f64ec..faa1c32e78 100644 --- a/packages/core/src/skills/catalog.ts +++ b/packages/core/src/skills/catalog.ts @@ -1,3 +1,4 @@ +import { realpathSync } from 'node:fs'; import { isAbsolute, relative, resolve } from 'node:path'; import type { SkillCatalogEntry, SkillOwner } from './entries.js'; @@ -39,9 +40,17 @@ export const MAX_SKILL_INVOCATION_CONTENT = 64_000; 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(resolve(root), resolve(path)); + const rel = relative(real(root), real(path)); return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel); } diff --git a/packages/core/test/skill-invocation.test.ts b/packages/core/test/skill-invocation.test.ts index 8f6ad30a94..9edb5a5a2a 100644 --- a/packages/core/test/skill-invocation.test.ts +++ b/packages/core/test/skill-invocation.test.ts @@ -1,3 +1,4 @@ +import { mkdirSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; @@ -108,6 +109,21 @@ describe('SkillCatalog', () => { expect(await catalog.resolve('hidden', { kind: 'host' })).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({ 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' }, From f5ce5d6bbc86b2ccf487ba0638385d75f97ae5e9 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Sun, 15 Nov 2026 22:33:57 +0900 Subject: [PATCH 03/10] fix(skills): use the Orchestrator agent-preset scope Issue: #4232 Agent-Task: codex/local/01a1df4e-2d7e-7673-9123-d46d99e296da Co-Authored-By: Claude Opus 5.5 --- packages/core/src/bridge/methods.ts | 12 +- packages/core/src/plugin.ts | 10 + packages/core/src/skills/agent-view.ts | 30 +++ packages/core/src/skills/catalog.ts | 148 ++++++++----- packages/core/test/skill-invocation.test.ts | 218 +++++++++++++++++++- 5 files changed, 355 insertions(+), 63 deletions(-) create mode 100644 packages/core/src/skills/agent-view.ts diff --git a/packages/core/src/bridge/methods.ts b/packages/core/src/bridge/methods.ts index abfe43150e..d925c08c0d 100644 --- a/packages/core/src/bridge/methods.ts +++ b/packages/core/src/bridge/methods.ts @@ -7434,6 +7434,13 @@ function buildBridgeMethods( return dmAdmissionFailure(channelId, channel.botSlug, 'archived-bot'); } const skillInvocations: ChannelSkillInvocation[] = []; + const skillViewer = + skillTokens.length === 0 + ? undefined + : (channel.type === 'group' ? channel.members : [channel.botSlug]).find((slug) => { + const bot = slug === undefined ? undefined : deps.registry.get(slug); + return bot !== undefined && bot.paused !== true; + }); for (const token of skillTokens) { if ( token.owner.kind === 'bot' && @@ -7442,7 +7449,10 @@ function buildBridgeMethods( : channel.botSlug === token.owner.botSlug) ) return invalidInput(`Skill /${token.name} belongs to a PersonaBot outside this Channel`); - const resolved = await deps.skills?.resolve(token.name, token.owner); + const resolved = + skillViewer === undefined + ? undefined + : await deps.skills?.resolve(token.name, token.owner, skillViewer); if (resolved === undefined) return { ok: false, diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 94ff83938c..d0c95dd73e 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -246,6 +246,7 @@ 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 { DeveloperModeSkillGate } from './logs/skill.js'; import { openLogDatabase, type LogDatabase } from './logs/log-db.js'; import type { ChannelStore } from './channels/store.js'; @@ -3249,6 +3250,15 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { 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: () => ctx.get('agentPresets') as SkillAgentPresetsPort | undefined, + }), }); const bridgeDeps: BridgeMethodsDeps = { team, diff --git a/packages/core/src/skills/agent-view.ts b/packages/core/src/skills/agent-view.ts new file mode 100644 index 0000000000..242b7f10d1 --- /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 index faa1c32e78..9276331aeb 100644 --- a/packages/core/src/skills/catalog.ts +++ b/packages/core/src/skills/catalog.ts @@ -13,10 +13,23 @@ export { /** The subset of DSH's `ctx.skills` registry the catalog reads. */ export interface SkillRegistryPort { - list(options?: { cwd?: string }): Promise; - get(name: string, options?: { cwd?: string }): Promise; + 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; @@ -63,9 +76,14 @@ function inside(root: string, path: string | undefined): boolean { export class SkillCatalog { #registry: SkillRegistryPort | undefined; readonly #memoryDirFor: (botSlug: string) => string | undefined; + readonly #viewFor: SkillViewPort | undefined; - constructor(options: { memoryDirFor(botSlug: string): string | undefined }) { + constructor(options: { + memoryDirFor(botSlug: string): string | undefined; + viewFor?: SkillViewPort; + }) { this.#memoryDirFor = options.memoryDirFor; + this.#viewFor = options.viewFor; } get available(): boolean { @@ -79,67 +97,93 @@ export class SkillCatalog { }; } + 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; - for (const skill of await registry.list({ 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 }), - }); + 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; + }); } - for (const skill of await registry.list()) - if (skill.invocation.userInvocable && !PROJECT_SOURCES.has(skill.source)) - entries.push({ - name: skill.name, - description: skill.description, - owner: { kind: 'host' }, - ...(skill.path === undefined ? {} : { path: skill.path }), - }); - return entries; + return [...entries, ...hostEntries]; } /** Reads the current text of one Skill so a message can keep a snapshot of it. */ - async resolve(name: string, owner: SkillOwner): Promise { + async resolve( + name: string, + owner: SkillOwner, + viewerBotSlug: string, + ): Promise { const registry = this.#registry; if (registry === undefined) return undefined; - if (owner.kind === 'host') { - const skill = await registry.get(name); - if (skill === undefined || !skill.invocation.userInvocable) return undefined; - if (PROJECT_SOURCES.has(skill.source)) return undefined; - return { - name, - owner, - content: skill.content.slice(0, MAX_SKILL_INVOCATION_CONTENT), - ...(skill.path === undefined ? {} : { path: skill.path }), - }; - } - const root = this.#memoryDirFor(owner.botSlug); - if (root === undefined) return undefined; - const skill = await registry.get(name, { 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.slice(0, MAX_SKILL_INVOCATION_CONTENT), - ...(skill.path === undefined ? {} : { path: skill.path }), - }; + return 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.slice(0, MAX_SKILL_INVOCATION_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.slice(0, MAX_SKILL_INVOCATION_CONTENT), + ...(skill.path === undefined ? {} : { path: skill.path }), + }; + }, + ); } } diff --git a/packages/core/test/skill-invocation.test.ts b/packages/core/test/skill-invocation.test.ts index 9edb5a5a2a..31faaf2d2f 100644 --- a/packages/core/test/skill-invocation.test.ts +++ b/packages/core/test/skill-invocation.test.ts @@ -1,7 +1,7 @@ import { mkdirSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { skillInvocationTokens } from '../src/bots/cli-skills.js'; import { createBridgeMethods } from '../src/bridge/methods.js'; @@ -14,7 +14,9 @@ import { 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 { @@ -50,26 +52,178 @@ function registry( host: SkillRegistryDefinition[], project: Map, ) { - const view = (cwd?: string) => { + 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); + return view(options?.cwd, options?.scope); }, async get(name, options) { - return view(options?.cwd).find((item) => item.name === name); + 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('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([]); @@ -97,16 +251,18 @@ describe('SkillCatalog', () => { ['review', { kind: 'bot', botSlug: 'ada' }], ['pdf', { kind: 'host' }], ]); - expect(await catalog.resolve('pdf', { kind: 'host' })).toMatchObject({ + 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' })).toMatchObject({ + 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' })).toBeUndefined(); - expect(await catalog.resolve('review', { kind: 'host' })).toBeUndefined(); - expect(await catalog.resolve('hidden', { kind: 'host' })).toBeUndefined(); + 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 () => { @@ -117,7 +273,10 @@ describe('SkillCatalog', () => { 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({ memoryDirFor: () => link }); + 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' }, @@ -141,6 +300,43 @@ describe('SkillCatalog', () => { }); describe('Skill Invocation in a Human DM', () => { + 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, + }); + catalog.attach(registry([skill('host', 'user-agents', '/host/SKILL.md')], new Map())); + 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')!; + 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[] = []; @@ -162,6 +358,7 @@ describe('Skill Invocation in a Human DM', () => { ], ]); const catalog = new SkillCatalog({ + viewFor: liveView, memoryDirFor: (slug) => core.registry.memoryDirFor(slug), }); catalog.attach(registry([skill('pdf', 'user-agents', '/home/pdf/SKILL.md')], project)); @@ -236,6 +433,7 @@ describe('Skill Invocation in a Human DM', () => { 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())); From be4baefccd2b1936f2ecef991c2c429f8fb99037 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Sun, 15 Nov 2026 23:59:21 +0900 Subject: [PATCH 04/10] chore(skills): meet source policy, ADR numbering and Host cast checks Drop comments, renumber the Skill ADRs to 0344 and 0345, read the skills and agentPresets services through the Host compatibility module, and add the missing English CLI paragraph. Issue: #4232 Agent-Task: claude-code/local/0d4a6a9f-6296-49dd-b14c-6789efa657c3 Co-Authored-By: Claude Opus 5.5 --- .../features/skill-invocation.md | 2 +- ...ect-skills-travel-with-their-directory.md} | 0 ...snapshotted-text-that-addresses-no-one.md} | 0 docs/bot-cli.md | 2 ++ docs/bot-cli.zh.md | 2 +- .../client/src/client/channel-composer.tsx | 1 - packages/client/src/client/skill-refs.ts | 4 ---- packages/core/src/bots/cli-skills.ts | 4 ---- packages/core/src/channels/channel.ts | 6 ------ packages/core/src/plugin.ts | 17 +++++++++++----- packages/core/src/runtime/bot-runtime.ts | 8 -------- .../core/src/runtime/native-agent-compat.ts | 20 +++++++++++++++++++ packages/core/src/skills/catalog.ts | 8 -------- packages/core/src/skills/entries.ts | 5 ----- packages/core/test/skill-invocation.test.ts | 1 - 15 files changed, 36 insertions(+), 44 deletions(-) rename docs/adr/{0341-project-skills-travel-with-their-directory.md => 0344-project-skills-travel-with-their-directory.md} (100%) rename docs/adr/{0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md => 0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md} (100%) diff --git a/.agents/skills/verify-deepseekbot/features/skill-invocation.md b/.agents/skills/verify-deepseekbot/features/skill-invocation.md index 68bf8c292d..7058418fe3 100644 --- a/.agents/skills/verify-deepseekbot/features/skill-invocation.md +++ b/.agents/skills/verify-deepseekbot/features/skill-invocation.md @@ -1,6 +1,6 @@ # 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-0342](../../../../docs/adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)). +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-0345](../../../../docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)). ## Sub-features diff --git a/docs/adr/0341-project-skills-travel-with-their-directory.md b/docs/adr/0344-project-skills-travel-with-their-directory.md similarity index 100% rename from docs/adr/0341-project-skills-travel-with-their-directory.md rename to docs/adr/0344-project-skills-travel-with-their-directory.md diff --git a/docs/adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md b/docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md similarity index 100% rename from docs/adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md rename to docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md diff --git a/docs/bot-cli.md b/docs/bot-cli.md index 17aeda5036..f6d6575357 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -238,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 `/name` in the body into a Skill Invocation: 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`. See [ADR-0345](adr/0345-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 a956393022..ad21850ff9 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -233,7 +233,7 @@ 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` 变成 Skill Invocation:Host 把该 Skill 当前的文本随消息保存,Bot 以 `` 块读到它。Skill 不决定由谁回复;已不存在的 Skill 会以 `skill-unavailable` 拒绝。见 [ADR-0342](adr/0342-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)。 +`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` 变成 Skill Invocation:Host 把该 Skill 当前的文本随消息保存,Bot 以 `` 块读到它。Skill 不决定由谁回复;已不存在的 Skill 会以 `skill-unavailable` 拒绝。见 [ADR-0345](adr/0345-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` 类型列出它。其他卡片会拒绝这个选项。 diff --git a/packages/client/src/client/channel-composer.tsx b/packages/client/src/client/channel-composer.tsx index 85ce643849..0d7e7e1813 100644 --- a/packages/client/src/client/channel-composer.tsx +++ b/packages/client/src/client/channel-composer.tsx @@ -121,7 +121,6 @@ export interface ChannelComposerProps { skills?: readonly SelectedSkill[] | undefined; reply?: { id: string; author: string; body: string } | undefined; t?: BotHarnessTranslate | undefined; - /** Omitted `skills` means the caller did not track Skill chips; the owner rebases them. */ onChange( value: string, mentions?: SelectedMention[], diff --git a/packages/client/src/client/skill-refs.ts b/packages/client/src/client/skill-refs.ts index 0bc508a67a..8548124e75 100644 --- a/packages/client/src/client/skill-refs.ts +++ b/packages/client/src/client/skill-refs.ts @@ -1,7 +1,6 @@ import type { SkillCatalogEntry, SkillOwner } from '../../../core/src/skills/entries.js'; import type { BotSummary } from './store.js'; -/** A Skill chip in the composer: the `/name` token and whose Skill it is. */ export interface SelectedSkill { name: string; owner: SkillOwner; @@ -15,7 +14,6 @@ export interface SkillQuery { query: string; } -/** A `/` menu row: a catalog entry plus the owning PersonaBot, when it has one. */ export type ComposerSkillOption = SkillCatalogEntry & { bot?: BotSummary | undefined }; export function sameSkillOwner(left: SkillOwner, right: SkillOwner): boolean { @@ -24,7 +22,6 @@ export function sameSkillOwner(left: SkillOwner, right: SkillOwner): boolean { : right.kind === 'bot' && left.botSlug === right.botSlug; } -/** The `/query` the caret is typing, when it starts a line or follows whitespace. */ export function activeSkillQuery( value: string, caret: number, @@ -86,7 +83,6 @@ export function selectSkill( }; } -/** Keeps only chips whose `/name` text is still exactly where it was picked. */ 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/core/src/bots/cli-skills.ts b/packages/core/src/bots/cli-skills.ts index c19e4d9a9d..51cb1ff558 100644 --- a/packages/core/src/bots/cli-skills.ts +++ b/packages/core/src/bots/cli-skills.ts @@ -55,10 +55,6 @@ export async function runSkillCommand( }; } -/** - * Turns `--skill /` values into Skill Invocation tokens for the - * first matching `/name` in the message body. Owner is `host` or `bot:`. - */ export function skillInvocationTokens( body: string, values: readonly string[] | undefined, diff --git a/packages/core/src/channels/channel.ts b/packages/core/src/channels/channel.ts index 66fd6b6551..06e6b1ef95 100644 --- a/packages/core/src/channels/channel.ts +++ b/packages/core/src/channels/channel.ts @@ -288,10 +288,6 @@ export interface ChannelReference { end: number; } -/** - * A Skill Invocation: the `/name` token a Human picked from the `/` menu, with - * the Skill's text captured when the message was sent. It addresses no one. - */ export interface ChannelSkillInvocation { name: string; owner: SkillOwner; @@ -301,7 +297,6 @@ export interface ChannelSkillInvocation { content: string; } -/** What a Client sends for a Skill Invocation; the Host adds the text snapshot. */ export type ChannelSkillInvocationToken = Pick< ChannelSkillInvocation, 'name' | 'owner' | 'start' | 'end' @@ -309,7 +304,6 @@ export type ChannelSkillInvocationToken = Pick< const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u; -/** Checks a Skill Invocation's name, owner and `/name` position inside `body`. */ export function isSkillInvocationToken( item: unknown, body: string, diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index d0c95dd73e..7271d5134f 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -247,6 +247,11 @@ import { createChannelLiveHub, CHANNEL_STREAM_PATH, type ChannelLiveHub } from ' 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'; @@ -3257,7 +3262,7 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { }, presetFor: (slug) => core.registry.get(slug)?.preset ?? config.agentPreset ?? DEFAULT_AGENT_PRESET, - agentPresets: () => ctx.get('agentPresets') as SkillAgentPresetsPort | undefined, + agentPresets: () => hostAgentPresets>(ctx), }), }); const bridgeDeps: BridgeMethodsDeps = { @@ -3836,10 +3841,12 @@ export function apply(ctx: Context, config: BotHarnessConfig): void { }, }); developerModeTarget.gate = gate; - skillsCtx.effect( - () => skillCatalog.attach((skillsCtx as unknown as { skills: SkillRegistryPort }).skills), - 'botharness: skill catalog', - ); + 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 02748cc610..0f098b0811 100644 --- a/packages/core/src/runtime/bot-runtime.ts +++ b/packages/core/src/runtime/bot-runtime.ts @@ -730,10 +730,6 @@ export interface DirectBotToolCall { const DIRECT_TOOL_CALL_LIMIT = 50; -/** - * Wraps each picked `/name` token as `[/name]`. DSH loads a Skill again for any - * bare `/name` in user input; the snapshot below is the one the Human sent. - */ export function markSkillTokens( text: string, invocations: readonly ChannelSkillInvocation[] | undefined, @@ -751,10 +747,6 @@ function xmlAttribute(value: string): string { return value.replace(/&/gu, '&').replace(/"/gu, '"').replace(/ 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/catalog.ts b/packages/core/src/skills/catalog.ts index 9276331aeb..a8447a5c16 100644 --- a/packages/core/src/skills/catalog.ts +++ b/packages/core/src/skills/catalog.ts @@ -11,7 +11,6 @@ export { type SkillOwner, } from './entries.js'; -/** The subset of DSH's `ctx.skills` registry the catalog reads. */ export interface SkillRegistryPort { list(options?: { cwd?: string; scope?: object }): Promise; get( @@ -67,12 +66,6 @@ function inside(root: string, path: string | undefined): boolean { return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel); } -/** - * Lists and resolves the Skills a Human can invoke in a conversation: Host - * Skills plus the Project Skills of each PersonaBot's Memory Repository. - * DSH discovery stays the authority; this module only labels owners and - * keeps a Bot's same-named Skill from hiding the Host one in the menu. - */ export class SkillCatalog { #registry: SkillRegistryPort | undefined; readonly #memoryDirFor: (botSlug: string) => string | undefined; @@ -144,7 +137,6 @@ export class SkillCatalog { return [...entries, ...hostEntries]; } - /** Reads the current text of one Skill so a message can keep a snapshot of it. */ async resolve( name: string, owner: SkillOwner, diff --git a/packages/core/src/skills/entries.ts b/packages/core/src/skills/entries.ts index 78f9a366ca..e47290fb67 100644 --- a/packages/core/src/skills/entries.ts +++ b/packages/core/src/skills/entries.ts @@ -1,6 +1,5 @@ import { isValidSlug } from '../bots/slug.js'; -/** Who a Skill belongs to: the Host (user level) or one PersonaBot's Memory Repository. */ export type SkillOwner = { kind: 'host' } | { kind: 'bot'; botSlug: string }; export interface SkillCatalogEntry { @@ -21,10 +20,6 @@ export function parseSkillOwnerKey(value: string): SkillOwner | undefined { return isValidSlug(botSlug) ? { kind: 'bot', botSlug } : undefined; } -/** - * Orders catalog entries for a `/` query: name prefix, then name subsequence, - * then description substring. Ties keep catalog order. - */ export function rankSkillEntries( entries: readonly T[], rawQuery: string, diff --git a/packages/core/test/skill-invocation.test.ts b/packages/core/test/skill-invocation.test.ts index 31faaf2d2f..c39d5b69c7 100644 --- a/packages/core/test/skill-invocation.test.ts +++ b/packages/core/test/skill-invocation.test.ts @@ -47,7 +47,6 @@ function skill( }; } -/** A DSH-shaped registry: project roots win over Host rows of the same name. */ function registry( host: SkillRegistryDefinition[], project: Map, From d519bf1e63e90b6e0491c59936a623131625232e Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 16 Nov 2026 04:48:28 +0900 Subject: [PATCH 05/10] fix(skills): keep restored Skill offsets and chips out of command parsing Restore a failed send's Skill chips at the trimmed body's offsets, ignore a command range that overlaps a selected Skill chip, and note the staged delivery scope in ADR-0345. Issue: #4232 Agent-Task: claude-code/local/b7955cb7-65c2-4b41-bafd-b18256e4a38b Co-Authored-By: Claude Opus 5.5 --- ...-snapshotted-text-that-addresses-no-one.md | 2 + packages/client/src/client/bot-main.tsx | 10 +--- .../client/src/client/channel-composer.tsx | 8 +++- packages/client/test/skill-composer.test.ts | 47 +++++++++++++++++++ 4 files changed, 57 insertions(+), 10 deletions(-) diff --git a/docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md b/docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md index e25d5144b5..78ece613b5 100644 --- a/docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md +++ b/docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md @@ -13,6 +13,8 @@ The Host resolves the Skill when the message is sent and stores a snapshot in a 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. diff --git a/packages/client/src/client/bot-main.tsx b/packages/client/src/client/bot-main.tsx index a4ffe7f8aa..7478474f24 100644 --- a/packages/client/src/client/bot-main.tsx +++ b/packages/client/src/client/bot-main.tsx @@ -2803,15 +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.map((item) => ({ - ...item, - start: item.start + leftTrim, - end: item.end + leftTrim, - })), - ); + setSkillTokens((current) => (current.length > 0 ? current : submittedSkills)); setUploadItems((current) => (current.length > 0 ? current : submittedUploads)); } } diff --git a/packages/client/src/client/channel-composer.tsx b/packages/client/src/client/channel-composer.tsx index 0d7e7e1813..2ba38333d5 100644 --- a/packages/client/src/client/channel-composer.tsx +++ b/packages/client/src/client/channel-composer.tsx @@ -829,7 +829,13 @@ export function ChannelComposer({ onChange(next.value, next.mentions, next.channelRefs, next.skills); const caret = richSelectionOffsets(editor)?.end ?? next.value.length; slashTarget.current = context?.target; - setSlashQuery(context === undefined ? undefined : composerSlashQuery(next.value, caret)); + const command = context === undefined ? undefined : composerSlashQuery(next.value, caret); + setSlashQuery( + command !== undefined && + next.skills.some((skill) => skill.start < command.end && skill.end > command.start) + ? undefined + : command, + ); setSkillQuery( skillOptions.length === 0 ? undefined : activeSkillQuery(next.value, caret, next.skills), ); diff --git a/packages/client/test/skill-composer.test.ts b/packages/client/test/skill-composer.test.ts index 46e46f3495..a87639dd0a 100644 --- a/packages/client/test/skill-composer.test.ts +++ b/packages/client/test/skill-composer.test.ts @@ -190,4 +190,51 @@ describe('composer / menu', () => { 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', 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(); + } + }); }); From b7c592b345e063f2adce24234b8e101d99b80e41 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 16 Nov 2026 05:14:35 +0900 Subject: [PATCH 06/10] docs(skills): imported Project Skills activate without a separate review Human decision on #4238: Project Skills in a Memory Repository arrive with the rest of the PersonaBot's Memory and need no Skill-only review. Issue: #4232 Agent-Task: claude-code/local/b7955cb7-65c2-4b41-bafd-b18256e4a38b Co-Authored-By: Claude Opus 5.5 --- docs/adr/0344-project-skills-travel-with-their-directory.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/adr/0344-project-skills-travel-with-their-directory.md b/docs/adr/0344-project-skills-travel-with-their-directory.md index 53ac5d7396..0ee2850805 100644 --- a/docs/adr/0344-project-skills-travel-with-their-directory.md +++ b/docs/adr/0344-project-skills-travel-with-their-directory.md @@ -9,7 +9,7 @@ A PersonaBot's Skills are the **Project Skills** of its Memory Repository: `SKIL 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, installing or importing a PersonaBot lists each incoming Project Skill in the existing install review (prompt-injection, exfiltration and script findings). Until a Human accepts that review, the Skills are not discoverable. 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. +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 @@ -17,4 +17,4 @@ Because Project Skills are ordinary text files in the Memory Repository, they tr - **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. -- **Make imported Skills active immediately and amend ADR-0044** — rejected: a Skill can carry scripts and instructions that need the same review as any other installed bot content. +- **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. From 8d9216dde5105f4499ab8a1ee43e75879bab0a62 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 16 Nov 2026 05:19:37 +0900 Subject: [PATCH 07/10] fix(skills): preserve selected invocations and refuse oversized skills Issue: #4232 Agent-Task: codex/local/01a1e0bf-b3b5-7c23-9f65-bbc04bc24987 --- changes/4232-skill-invocation-review-fixes.md | 11 ++ docs/bot-cli.md | 2 +- docs/bot-cli.zh.md | 2 +- packages/core/src/bots/cli-skills.ts | 15 +- packages/core/src/bridge/methods.ts | 22 ++- packages/core/src/runtime/bot-runtime.ts | 44 +++-- packages/core/src/skills/catalog.ts | 20 +- packages/core/test/bot-live-cli.test.ts | 42 +++++ packages/core/test/skill-invocation.test.ts | 171 ++++++++++++++++++ 9 files changed, 300 insertions(+), 29 deletions(-) create mode 100644 changes/4232-skill-invocation-review-fixes.md diff --git a/changes/4232-skill-invocation-review-fixes.md b/changes/4232-skill-invocation-review-fixes.md new file mode 100644 index 0000000000..be54311821 --- /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, and oversized Skill sends being silently truncated ([#4232](https://github.com/BotHarness/BotHarness/issues/4232)). + +## zh + +- 修复 CLI 重复选择同名 Skill、Bot 提示词中已选 Skill 与提及的渲染,以及超长 Skill 发送时被静默截断的问题([#4232](https://github.com/BotHarness/BotHarness/issues/4232))。 diff --git a/docs/bot-cli.md b/docs/bot-cli.md index f6d6575357..1b7a74549b 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -238,7 +238,7 @@ 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 `/name` in the body into a Skill Invocation: 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`. See [ADR-0345](adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md). +`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-0345](adr/0345-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. diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index ad21850ff9..112eaa4c99 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -233,7 +233,7 @@ 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` 变成 Skill Invocation:Host 把该 Skill 当前的文本随消息保存,Bot 以 `` 块读到它。Skill 不决定由谁回复;已不存在的 Skill 会以 `skill-unavailable` 拒绝。见 [ADR-0345](adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)。 +`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-0345](adr/0345-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` 类型列出它。其他卡片会拒绝这个选项。 diff --git a/packages/core/src/bots/cli-skills.ts b/packages/core/src/bots/cli-skills.ts index 51cb1ff558..0fc2847aa2 100644 --- a/packages/core/src/bots/cli-skills.ts +++ b/packages/core/src/bots/cli-skills.ts @@ -66,11 +66,16 @@ export function skillInvocationTokens( 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 match = new RegExp(`(^|\\s)/${name}(?=\\s|$)`, 'u').exec(body); - if (match === null) usage(`--skill ${raw} needs /${name} in the message body.`); - const start = match.index + match[1]!.length; - if (tokens.some((token) => token.start === start)) - usage(`/${name} is already picked by another --skill.`); + 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 d925c08c0d..90a40dd4d4 100644 --- a/packages/core/src/bridge/methods.ts +++ b/packages/core/src/bridge/methods.ts @@ -338,7 +338,12 @@ import { type DataResetPreview, type DataResetResult, } from '../data-reset/reset.js'; -import type { SkillCatalog, SkillCatalogEntry } from '../skills/catalog.js'; +import { + SkillContentTooLargeError, + type SkillCatalog, + type SkillCatalogEntry, + type ResolvedSkill, +} from '../skills/catalog.js'; import { isValidSlug } from '../bots/slug.js'; import { memoryMoveTarget, @@ -7449,10 +7454,17 @@ function buildBridgeMethods( : channel.botSlug === token.owner.botSlug) ) return invalidInput(`Skill /${token.name} belongs to a PersonaBot outside this Channel`); - const resolved = - skillViewer === undefined - ? undefined - : await deps.skills?.resolve(token.name, token.owner, skillViewer); + let resolved: ResolvedSkill | undefined; + try { + resolved = + skillViewer === undefined + ? 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, diff --git a/packages/core/src/runtime/bot-runtime.ts b/packages/core/src/runtime/bot-runtime.ts index 0f098b0811..a82bb0ce99 100644 --- a/packages/core/src/runtime/bot-runtime.ts +++ b/packages/core/src/runtime/bot-runtime.ts @@ -735,14 +735,29 @@ export function markSkillTokens( invocations: readonly ChannelSkillInvocation[] | undefined, ): string { let marked = text; - for (const name of new Set((invocations ?? []).map((skill) => skill.name))) - marked = marked.replace( - new RegExp(`(^|\\s)/${name}(?=\\s|$)`, 'gu'), - (_match, lead: string) => `${lead}[/${name}]`, - ); + 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(/ 0 ? message.body : body; - const text = markSkillTokens( - sessionMentionText(mentionBody, message?.mentions ?? []), + const text = sessionSkillText( + mentionBody, + message?.mentions ?? [], message?.author.kind === 'human' ? message.skillInvocations : undefined, ); if (channel?.type === 'group') diff --git a/packages/core/src/skills/catalog.ts b/packages/core/src/skills/catalog.ts index a8447a5c16..3c5be76aca 100644 --- a/packages/core/src/skills/catalog.ts +++ b/packages/core/src/skills/catalog.ts @@ -50,6 +50,17 @@ export interface ResolvedSkill { 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 { @@ -144,7 +155,7 @@ export class SkillCatalog { ): Promise { const registry = this.#registry; if (registry === undefined) return undefined; - return this.#withView( + const resolved = await this.#withView( owner.kind === 'bot' ? owner.botSlug : viewerBotSlug, registry, async (registry, options) => { @@ -155,7 +166,7 @@ export class SkillCatalog { return { name, owner, - content: skill.content.slice(0, MAX_SKILL_INVOCATION_CONTENT), + content: skill.content, ...(skill.path === undefined ? {} : { path: skill.path }), }; } @@ -172,10 +183,13 @@ export class SkillCatalog { return { name, owner, - content: skill.content.slice(0, MAX_SKILL_INVOCATION_CONTENT), + 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/test/bot-live-cli.test.ts b/packages/core/test/bot-live-cli.test.ts index cb5dd56c5c..4c10effb90 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/skill-invocation.test.ts b/packages/core/test/skill-invocation.test.ts index c39d5b69c7..6e1081b123 100644 --- a/packages/core/test/skill-invocation.test.ts +++ b/packages/core/test/skill-invocation.test.ts @@ -11,6 +11,7 @@ import type { BotAgentAdapter, OrchestratorAgentRun } from '../src/runtime/bot-r import { markSkillTokens, skillInvocationPrompt } from '../src/runtime/bot-runtime.js'; import { SkillCatalog, + MAX_SKILL_INVOCATION_CONTENT, rankSkillEntries, type SkillRegistryDefinition, type SkillRegistryPort, @@ -76,6 +77,28 @@ const liveView: SkillViewPort = async (_slug, registry) => ({ }); 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( @@ -299,6 +322,131 @@ describe('SkillCatalog', () => { }); 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-viewer-'), @@ -483,6 +631,14 @@ describe('Skill Invocation text', () => { 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', ); @@ -491,6 +647,21 @@ describe('Skill Invocation text', () => { }); 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 }, From e5e36a2d83b2a853319e535ca4b3231334be5a06 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 16 Nov 2026 05:59:47 +0900 Subject: [PATCH 08/10] test(skills): type the shortcut choice id Issue: #4232 Agent-Task: claude-code/local/b7955cb7-65c2-4b41-bafd-b18256e4a38b Co-Authored-By: Claude Opus 5.5 --- packages/client/test/skill-composer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/test/skill-composer.test.ts b/packages/client/test/skill-composer.test.ts index a87639dd0a..4ba7ae5042 100644 --- a/packages/client/test/skill-composer.test.ts +++ b/packages/client/test/skill-composer.test.ts @@ -211,7 +211,7 @@ describe('composer / menu', () => { id: 'model', label: 'Model', run: () => undefined, - choices: () => [{ id: 'model', label: 'fast', run }], + choices: () => [{ id: 'model' as const, label: 'fast', run }], }, ], }, From e90efa9ec265d5c3ef187c5ff4f844eeace50877 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 16 Nov 2026 06:00:10 +0900 Subject: [PATCH 09/10] docs(skills): renumber the Skill ADRs to 0345 and 0346 after main took 0344 Issue: #4232 Agent-Task: claude-code/local/b7955cb7-65c2-4b41-bafd-b18256e4a38b Co-Authored-By: Claude Opus 5.5 --- .agents/skills/verify-deepseekbot/features/skill-invocation.md | 2 +- ...ry.md => 0345-project-skills-travel-with-their-directory.md} | 0 ...ill-invocation-is-snapshotted-text-that-addresses-no-one.md} | 0 docs/bot-cli.md | 2 +- docs/bot-cli.zh.md | 2 +- 5 files changed, 3 insertions(+), 3 deletions(-) rename docs/adr/{0344-project-skills-travel-with-their-directory.md => 0345-project-skills-travel-with-their-directory.md} (100%) rename docs/adr/{0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md => 0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md} (100%) diff --git a/.agents/skills/verify-deepseekbot/features/skill-invocation.md b/.agents/skills/verify-deepseekbot/features/skill-invocation.md index 7058418fe3..83f191dd51 100644 --- a/.agents/skills/verify-deepseekbot/features/skill-invocation.md +++ b/.agents/skills/verify-deepseekbot/features/skill-invocation.md @@ -1,6 +1,6 @@ # 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-0345](../../../../docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)). +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 diff --git a/docs/adr/0344-project-skills-travel-with-their-directory.md b/docs/adr/0345-project-skills-travel-with-their-directory.md similarity index 100% rename from docs/adr/0344-project-skills-travel-with-their-directory.md rename to docs/adr/0345-project-skills-travel-with-their-directory.md diff --git a/docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md b/docs/adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md similarity index 100% rename from docs/adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md rename to docs/adr/0346-skill-invocation-is-snapshotted-text-that-addresses-no-one.md diff --git a/docs/bot-cli.md b/docs/bot-cli.md index 21654060e8..c549cb0cb0 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -238,7 +238,7 @@ 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-0345](adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md). +`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. diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index d5e898c34b..8f2b782f99 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -233,7 +233,7 @@ 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-0345](adr/0345-skill-invocation-is-snapshotted-text-that-addresses-no-one.md)。 +`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` 类型列出它。其他卡片会拒绝这个选项。 From d0d376f3688d8a183e746b106c596bc931d77919 Mon Sep 17 00:00:00 2001 From: DoodleBear Date: Mon, 16 Nov 2026 07:38:42 +0900 Subject: [PATCH 10/10] fix(skills): enforce readable owners and shift expanded tokens Issue: #4232 Agent-Task: codex/local/01a1e114-73bc-76d1-9b25-d052767849d7 --- changes/4232-skill-invocation-review-fixes.md | 4 +- packages/core/src/bridge/methods.ts | 61 +++--- packages/core/test/skill-invocation.test.ts | 202 +++++++++++++++++- 3 files changed, 235 insertions(+), 32 deletions(-) diff --git a/changes/4232-skill-invocation-review-fixes.md b/changes/4232-skill-invocation-review-fixes.md index be54311821..3e1cfe3603 100644 --- a/changes/4232-skill-invocation-review-fixes.md +++ b/changes/4232-skill-invocation-review-fixes.md @@ -4,8 +4,8 @@ section: Fixed ## en -- Fixed repeated Skill selection in the CLI, selected Skill and mention rendering in Bot prompts, and oversized Skill sends being silently truncated ([#4232](https://github.com/BotHarness/BotHarness/issues/4232)). +- 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 发送时被静默截断的问题([#4232](https://github.com/BotHarness/BotHarness/issues/4232))。 +- 修复 CLI 重复选择同名 Skill、Bot 提示词中已选 Skill 与提及的渲染,超长 Skill 发送时被静默截断、群聊接受无权读取或已归档 Bot 的 Skill,以及所有 Bot 提及展开后的 Skill 位置错误([#4232](https://github.com/BotHarness/BotHarness/issues/4232))。 diff --git a/packages/core/src/bridge/methods.ts b/packages/core/src/bridge/methods.ts index af8a42413c..858d60df50 100644 --- a/packages/core/src/bridge/methods.ts +++ b/packages/core/src/bridge/methods.ts @@ -2166,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 && @@ -6956,16 +6966,7 @@ function buildBridgeMethods( const channel = deps.channels.get(channelId); if (channel === undefined) return unknownChannel(channelId); if (deps.skills === undefined) return { ok: true, value: { skills: [] } }; - const bots = ( - 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 bots = channelSkillBots(channel); try { return { ok: true, value: { skills: await deps.skills.list(bots) } }; } catch (error) { @@ -7107,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); } @@ -7183,6 +7181,24 @@ function buildBridgeMethods( ) 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'); @@ -7448,25 +7464,14 @@ function buildBridgeMethods( return dmAdmissionFailure(channelId, channel.botSlug, 'archived-bot'); } const skillInvocations: ChannelSkillInvocation[] = []; - const skillViewer = - skillTokens.length === 0 - ? undefined - : (channel.type === 'group' ? channel.members : [channel.botSlug]).find((slug) => { - const bot = slug === undefined ? undefined : deps.registry.get(slug); - return bot !== undefined && bot.paused !== true; - }); + const skillBots = skillTokens.length === 0 ? [] : channelSkillBots(channel); + const skillViewer = skillBots[0]; for (const token of skillTokens) { - if ( - token.owner.kind === 'bot' && - !(channel.type === 'group' - ? channel.members.includes(token.owner.botSlug) - : channel.botSlug === token.owner.botSlug) - ) - return invalidInput(`Skill /${token.name} belongs to a PersonaBot outside this Channel`); let resolved: ResolvedSkill | undefined; try { resolved = - skillViewer === undefined + skillViewer === undefined || + (token.owner.kind === 'bot' && !skillBots.includes(token.owner.botSlug)) ? undefined : await deps.skills?.resolve(token.name, token.owner, skillViewer); } catch (error) { diff --git a/packages/core/test/skill-invocation.test.ts b/packages/core/test/skill-invocation.test.ts index 6e1081b123..bf537b1b9f 100644 --- a/packages/core/test/skill-invocation.test.ts +++ b/packages/core/test/skill-invocation.test.ts @@ -5,7 +5,8 @@ import { describe, expect, it, vi } from 'vitest'; import { skillInvocationTokens } from '../src/bots/cli-skills.js'; import { createBridgeMethods } from '../src/bridge/methods.js'; -import { OWNER_HUMAN_CONTEXT } from '../src/humans/context.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'; @@ -447,6 +448,178 @@ describe('Skill Invocation in a Human DM', () => { }, ); + it('shifts Skill snapshots after expanding All Bots and preserves earlier tokens', async () => { + 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-'), @@ -461,13 +634,38 @@ describe('Skill Invocation in a Human DM', () => { memoryDirFor: (slug) => core.registry.memoryDirFor(slug), viewFor, }); - catalog.attach(registry([skill('host', 'user-agents', '/host/SKILL.md')], new Map())); + 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({