Merge remote-tracking branch 'origin/master' into feature/shared-cli-config-foundation
# Conflicts: # packages/host/apiproxy/README.i18n.yaml
This commit is contained in:
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/ui-skill/README.md
|
||||
README.md: 4838be893c1d5422cc707cb0d7542a056be41fa7
|
||||
README.zh.md: ed582128246a62297f555f8abe09f427cb9d256a
|
||||
README.md: 2cb382f53466c07b977eef4d5a1ef2804c13abea
|
||||
README.zh.md: 2fc30da5e4c895027ab9dea78e9e3f86890cafc1
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Skill reference source, browser half: registers the `/`-trigger `skill` source into `ctx.slash`. Candidates come from the `skill.list` RPC addressed by the per-call `ClientSessionContext` projection's `{sessionId}` — every session is agent-backed and the host resolves `cwd` from the session header. Catalogs cache per session with a single-flight fetch; the scope-birth `warm` hook prewarms the session's entry and `connection/reset` clears everything. Results filter by `startsWith(query)`; picking a candidate lands the literal `/name ` text through the slash pipeline (decision 21 plain-text reference), and the source `codec` owns the reference's two projections: `clipboardText` → `/name`, `serialize` → the model form `<skill>name</skill>` invoked at submit time. The RPC rides the plugin's root-context connection captured at registration — the source never reads services off a per-call argument. The source implements no `matchSpace`/`matchEnter` hooks — skill references never enter command adjudication and ride ordinary prompts into the default sink.
|
||||
Skill reference source, browser half: registers the `/`-trigger `skill` source into `ctx.slash`. Candidates come from the `skill.list` RPC addressed by the per-call `ClientSessionContext` projection's `{sessionId}` — every session is agent-backed and the host resolves `cwd` from the session header. The host returns the intersection of model-invocable and user-invocable skills because this browser path lets a user insert a model reference rather than loading the body directly. Catalogs cache per session with a single-flight fetch; the scope-birth `warm` hook prewarms the session's entry and `connection/reset` clears everything. Results filter by `startsWith(query)`; picking a candidate lands the literal `/name ` text through the slash pipeline (decision 21 plain-text reference), and the source `codec` owns the reference's two projections: `clipboardText` → `/name`, `serialize` → the model form `<skill>name</skill>` invoked at submit time. The RPC rides the plugin's root-context connection captured at registration — the source never reads services off a per-call argument. The source implements no `matchSpace`/`matchEnter` hooks — skill references never enter command adjudication and ride ordinary prompts into the default sink.
|
||||
|
||||
A failed `skill.list` throws from `candidates`, which the slash shell logs and folds into a silent menu-group drop — the menu shows only pending/ready states.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
skill(技能)引用 source 的浏览器端:把 `/` 触发的 `skill` source 注册进 `ctx.slash`。候选来自 `skill.list` RPC,以每次调用的 `ClientSessionContext` 投影中的 `{sessionId}` 寻址——每个会话始终由 agent(智能体)支撑,host 从会话 header 解析 `cwd`。目录按会话缓存,拉取走 single-flight;scope 创建时的 `warm` 钩子预热该会话的缓存项,`connection/reset` 清空全部缓存。结果按 `startsWith(query)` 过滤;pick 一个候选会把字面文本 `/name ` 经 slash 管线落进草稿(决策 21 的纯文本引用),source 的 `codec` 拥有该引用的两种投影:`clipboardText` → `/name`,`serialize` → 提交时生成的模型形式 `<skill>name</skill>`。RPC 使用插件注册时捕获的根上下文连接——source 绝不从每次调用的参数上读取服务。source 不实现 `matchSpace`/`matchEnter` 钩子——skill 引用永不进入命令裁决,随普通提示词落入 default sink。
|
||||
skill(技能)引用 source 的浏览器端:把 `/` 触发的 `skill` source 注册进 `ctx.slash`。候选来自 `skill.list` RPC,以每次调用的 `ClientSessionContext` 投影中的 `{sessionId}` 寻址——每个会话始终由 agent(智能体)支撑,host 从会话 header 解析 `cwd`。宿主返回模型可调用与用户可调用 skill 的交集,因为该浏览器路径让用户插入模型引用,而不是直接加载正文。目录按会话缓存,拉取走 single-flight;scope 创建时的 `warm` 钩子预热该会话的缓存项,`connection/reset` 清空全部缓存。结果按 `startsWith(query)` 过滤;pick 一个候选会把字面文本 `/name ` 经 slash 管线落进草稿(决策 21 的纯文本引用),source 的 `codec` 拥有该引用的两种投影:`clipboardText` → `/name`,`serialize` → 提交时生成的模型形式 `<skill>name</skill>`。RPC 使用插件注册时捕获的根上下文连接——source 绝不从每次调用的参数上读取服务。source 不实现 `matchSpace`/`matchEnter` 钩子——skill 引用永不进入命令裁决,随普通提示词落入 default sink。
|
||||
|
||||
`skill.list` 失败时 `candidates` 抛出异常,slash 壳层记录日志并折叠为静默的菜单组丢弃——菜单只显示 pending/ready 状态。
|
||||
|
||||
|
||||
@@ -758,15 +758,15 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
},
|
||||
{
|
||||
signature: 'register(skill: SkillRegistration): () => void',
|
||||
jsDoc: '/**\n * Register a borrowed readonly runtime skill. Project entries outrank runtime entries, which\n * outrank user entries. Same-name runtime entries are first-wins; a duplicate logs a warning and\n * receives a no-op disposer so it cannot remove the winner.\n * @param skill - the complete skill definition to expose for discovery.\n * @returns the exact Cordis effect disposer, preserving composite teardown order and invalidating caches.\n */',
|
||||
jsDoc: '/**\n * Register a borrowed readonly runtime skill. Project entries outrank runtime entries, which\n * outrank user entries. Same-name runtime entries are first-wins; a duplicate logs a warning and\n * receives a no-op disposer so it cannot remove the winner.\n * @param skill - the skill definition input; omitted invocation and provider fields receive defaults.\n * @returns the exact Cordis effect disposer, preserving composite teardown order and invalidating caches.\n */',
|
||||
},
|
||||
{
|
||||
signature: 'async list(options: SkillLookupOptions = {}): Promise<SkillSummary[]>',
|
||||
jsDoc: '/**\n * List model-invocable skill summaries for a workspace. Lookup options and\n * provider candidates are readonly same-process values borrowed throughout\n * discovery.\n * @param options - lookup options; `cwd` selects project roots and `signal` cancels discovery.\n * @returns sorted summaries, excluding skills disabled for model invocation.\n */',
|
||||
jsDoc: '/**\n * List invocation-neutral skill summaries for a workspace. Consumers apply\n * model or user invocation policy at their operational boundary. Lookup\n * options and provider candidates are readonly same-process values borrowed\n * throughout discovery.\n * @param options - lookup options; `cwd` selects project roots and `signal` cancels discovery.\n * @returns all sorted winning summaries.\n */',
|
||||
},
|
||||
{
|
||||
signature: 'async snapshot(options: SkillLookupOptions = {}): Promise<SkillCatalogSnapshot>',
|
||||
jsDoc: '/**\n * Observe the current model-invocable catalog and whether discovery completed within a stable revision.\n * Incomplete observations are never cached, allowing consumers to retain last-good state and\n * retry on their next request boundary.\n * @param options - lookup options; `cwd` selects project roots and `signal` cancels discovery.\n * @returns sorted summaries plus discovery-completeness state.\n */',
|
||||
jsDoc: '/**\n * Observe the current invocation-neutral catalog and whether discovery completed within a stable revision.\n * Incomplete observations are never cached, allowing consumers to retain last-good state and\n * retry on their next request boundary.\n * @param options - lookup options; `cwd` selects project roots and `signal` cancels discovery.\n * @returns sorted summaries plus discovery-completeness state.\n */',
|
||||
},
|
||||
{
|
||||
signature: 'async get(name: string, options: SkillLookupOptions = {}): Promise<SkillDefinition | undefined>',
|
||||
@@ -2358,6 +2358,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'SkillDefinition',
|
||||
declaration: 'export interface SkillDefinition extends SkillSummary {\n readonly content: string;\n readonly path?: string;\n readonly metadata?: Readonly<Record<string, unknown>>;\n}',
|
||||
},
|
||||
{
|
||||
name: 'SkillInvocationPolicy',
|
||||
declaration: 'export interface SkillInvocationPolicy {\n readonly modelInvocable: boolean;\n readonly userInvocable: boolean;\n}',
|
||||
},
|
||||
{
|
||||
name: 'SkillLookupOptions',
|
||||
declaration: 'export interface SkillLookupOptions {\n readonly cwd?: string | undefined;\n readonly signal?: AbortSignal | undefined;\n}',
|
||||
@@ -2376,7 +2380,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'SkillRegistration',
|
||||
declaration: 'export type SkillRegistration = Omit<SkillDefinition, \'provider\'> & {\n readonly provider?: string;\n};',
|
||||
declaration: 'export type SkillRegistration = Omit<SkillDefinition, \'invocation\' | \'provider\'> & {\n readonly invocation?: SkillInvocationPolicy;\n readonly provider?: string;\n};',
|
||||
},
|
||||
{
|
||||
name: 'SkillResourceBase',
|
||||
@@ -2388,7 +2392,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'SkillSummary',
|
||||
declaration: 'export interface SkillSummary {\n readonly name: string;\n readonly description: string;\n readonly whenToUse?: string;\n readonly disableModelInvocation?: boolean;\n readonly source: SkillSource;\n readonly provider: string;\n readonly resourceBase?: SkillResourceBase;\n}',
|
||||
declaration: 'export interface SkillSummary {\n readonly name: string;\n readonly description: string;\n readonly whenToUse?: string;\n readonly invocation: SkillInvocationPolicy;\n readonly source: SkillSource;\n readonly provider: string;\n readonly resourceBase?: SkillResourceBase;\n}',
|
||||
},
|
||||
{
|
||||
name: 'SpillLocator',
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md
|
||||
README.md: f7528836743c7acd07d200f80147fdd49c364da9
|
||||
README.zh.md: 3aae2c4cbd2053aa6aa6261f1b78898233505eff
|
||||
README.md: 863f2ed58ad0490d5591ea77621088353e0fb39d
|
||||
README.zh.md: 1f343084533f83abe3f1948e0785ce94f3838978
|
||||
|
||||
@@ -22,7 +22,7 @@ Directory picking delegates to the composed `ctx.directoryPicker` backend ([the
|
||||
|
||||
`host.openPath` opens a filesystem path with the operating system's default application (`open` on macOS, `Invoke-Item` on Windows, `xdg-open` on Linux). The opener is injectable for tests. The browser carrier applies the same loopback, same-origin restriction as `host.pickDirectory`.
|
||||
|
||||
The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `command.execute` runs a slash-command line host-side with pure admission semantics: the response reports whether the line resolved to a handler plus the minted lifecycle `commandId` when it did (correlating the acknowledgment with the flow node), while the outcome rides the durably logged `command/run`/`command/done` lifecycle pair broadcast on the mux stream; the carrier's request signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing.
|
||||
The `command.*` and `skill.*` domains expose the host command registry and skill catalog to clients. Every method addresses one session's agent by `sessionId` (a served session always has an Agent; `command.*` resumes cold sessions through the same path as `session.*`, while `skill.list` resolves the project root from the session header without touching the Agent registry). `skill.list` serves the browser's user-selected model-reference path, so it returns only skills that are both model-invocable and user-invocable; this domain has no direct skill-loading RPC. `command.execute` runs a slash-command line host-side with pure admission semantics: the response reports whether the line resolved to a handler plus the minted lifecycle `commandId` when it did (correlating the acknowledgment with the flow node), while the outcome rides the durably logged `command/run`/`command/done` lifecycle pair broadcast on the mux stream; the carrier's request signal cancels the running handler. `host/commands-changed` is the catalog invalidation frame: clients refetch `command.list` instead of diffing.
|
||||
|
||||
## Carrier layer (`/client` + root)
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr
|
||||
|
||||
`host.openPath` 会用操作系统的默认应用打开一个文件系统路径(macOS 为 `open`,Windows 为 `Invoke-Item`,Linux 为 `xdg-open`)。打开器可在测试中注入。浏览器载体对其施加与 `host.pickDirectory` 相同的回环、同源限制。
|
||||
|
||||
`command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载;载体的请求信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。
|
||||
`command.*` 与 `skill.*` 领域向客户端暴露宿主命令注册表和技能目录。每个方法都通过 `sessionId` 寻址一个会话的 Agent(被服务的会话必有 Agent;`command.*` 经由与 `session.*` 相同的路径恢复冷会话,而 `skill.list` 从会话头解析项目根目录,不触碰 Agent 注册表)。`skill.list` 服务于浏览器中由用户选择的模型引用路径,因此仅返回模型和用户均可调用的 skill;该领域没有直接加载 skill 的 RPC。`command.execute` 在宿主侧运行一条斜杠命令行,语义为纯准入:响应报告该行是否解析到处理器,并在解析到时回带铸造的生命周期 `commandId`(将本次确认与流节点关联);结局经由持久落账并在 mux 流广播的 `command/run`/`command/done` 生命周期事件对承载;载体的请求信号可取消正在运行的处理器。`host/commands-changed` 是目录失效帧:客户端重新拉取 `command.list` 而不是做差分。
|
||||
|
||||
## 载体层(`/client` + 根路径)
|
||||
|
||||
|
||||
@@ -1457,7 +1457,8 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
|
||||
return err(request, { code: 'internal', message: 'skill registry is absent: this deployment does not mount @deepseek-ai/dsh-skill in its composition (cordis.yml or explicit assembly)', details: {} })
|
||||
}
|
||||
try {
|
||||
const skills = await skillRegistry.list({ cwd })
|
||||
const skills = (await skillRegistry.list({ cwd }))
|
||||
.filter(skill => skill.invocation.modelInvocable && skill.invocation.userInvocable)
|
||||
return ok(request, {
|
||||
skills: skills.map(skill => ({
|
||||
name: skill.name,
|
||||
|
||||
@@ -20,6 +20,6 @@ export interface SkillEntry {
|
||||
|
||||
/** Skill-domain unary methods (the map key skill.* of RpcMethodMap). */
|
||||
export interface SkillsApi {
|
||||
/** Lists model-invocable skills for the addressed session's project root. */
|
||||
/** Lists skills usable by the browser's user-selected model-reference path. */
|
||||
list(request: RpcRequest<{ sessionId: SessionId }>): Promise<RpcResponse<{ skills: readonly SkillEntry[] }>>
|
||||
}
|
||||
|
||||
@@ -184,10 +184,28 @@ describe('skill.list', () => {
|
||||
name: 'probe',
|
||||
list: (options) => {
|
||||
seenCwds.push(options.cwd)
|
||||
return Promise.resolve([{
|
||||
name: 'commit-helper', description: 'Git commits', whenToUse: 'when committing',
|
||||
source: 'custom', provider: 'probe', rank: 0, locator: null,
|
||||
}])
|
||||
return Promise.resolve([
|
||||
{
|
||||
name: 'commit-helper', description: 'Git commits', whenToUse: 'when committing',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'custom', provider: 'probe', rank: 0, locator: null,
|
||||
},
|
||||
{
|
||||
name: 'user-only', description: 'User-only',
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
source: 'custom', provider: 'probe', rank: 0, locator: null,
|
||||
},
|
||||
{
|
||||
name: 'model-only', description: 'Model-only',
|
||||
invocation: { modelInvocable: true, userInvocable: false },
|
||||
source: 'custom', provider: 'probe', rank: 0, locator: null,
|
||||
},
|
||||
{
|
||||
name: 'trusted-only', description: 'Trusted-only',
|
||||
invocation: { modelInvocable: false, userInvocable: false },
|
||||
source: 'custom', provider: 'probe', rank: 0, locator: null,
|
||||
},
|
||||
])
|
||||
},
|
||||
get: () => Promise.resolve(undefined),
|
||||
}))
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/skill/skill-local/README.md
|
||||
README.md: d4b6253c6667f4786d53ad6c291f9e96f82546c3
|
||||
README.zh.md: 0c02080fce49c13c4a128676c39b793f3054fdb8
|
||||
README.md: 2077cf852fe90f7a0fec4e9bda1e9ff68fc56453
|
||||
README.zh.md: ba1c71f1bc1916daad82d872ae6658bb203133c9
|
||||
|
||||
@@ -50,7 +50,9 @@ The first-party filesystem `write` and `edit` tools also synchronously invalidat
|
||||
|
||||
## Skill Format
|
||||
|
||||
Skills can be single-level directory bundles (`<name>/SKILL.md`) or flat Markdown files (`<name>.md`). Nested `**/SKILL.md` discovery is intentionally not part of v1. Frontmatter is parsed as YAML with the `yaml` package; it requires `name` and `description`, while `whenToUse`, `disableModelInvocation`, and `metadata` are optional. Names must be kebab-case.
|
||||
Skills can be single-level directory bundles (`<name>/SKILL.md`) or flat Markdown files (`<name>.md`). Nested `**/SKILL.md` discovery is intentionally not part of v1. Frontmatter is parsed as an open YAML object with the `yaml` package; this provider currently interprets required `name` and `description`, plus optional `whenToUse`, `metadata`, `disable-model-invocation`, and `user-invocable`. Names must be kebab-case.
|
||||
|
||||
The two invocation fields accept YAML booleans and the case-insensitive forms `true`/`false`, `yes`/`no`, `on`/`off`, and `1`/`0`. `disable-model-invocation: true` excludes the skill from model-facing catalogs and loaders; `user-invocable: false` excludes it from human-facing commands. Each omitted field defaults to permitting its surface, and the provider always emits both positive internal policy values, including when both keys are absent. A rejected camel-case spelling or a non-boolean invocation value drops the entire skill from discovery with a warning instead of discarding only that field or falling back to a permissive default. Invocation policy fails closed because ignoring invalid data could expose a skill on a disabled surface; wrong-typed optional `whenToUse` and `metadata` values are omitted because neither currently grants invocation.
|
||||
|
||||
The catalog and body have separate lifecycles. Discovery parses frontmatter to produce the summary. Every `skill(name)` load rereads and reparses the current file, so body edits need no hash, revision, cache invalidation, or proactive model notification. A frontmatter rename between discovery and loading rejects the stale name and invalidates the provider; the next catalog observation publishes the new name.
|
||||
|
||||
|
||||
@@ -50,7 +50,9 @@
|
||||
|
||||
## Skill 格式
|
||||
|
||||
Skill 可以是单层目录 bundle(`<name>/SKILL.md`),也可以是平铺 Markdown 文件(`<name>.md`)。v1 刻意不支持发现嵌套的 `**/SKILL.md`。Frontmatter 使用 `yaml` 包解析为 YAML;它要求 `name` 和 `description`,而 `whenToUse`、`disableModelInvocation` 和 `metadata` 可选。名称必须使用 kebab-case。
|
||||
Skill 可以是单层目录 bundle(`<name>/SKILL.md`),也可以是平铺 Markdown 文件(`<name>.md`)。v1 刻意不支持发现嵌套的 `**/SKILL.md`。Frontmatter 使用 `yaml` 包解析为开放的 YAML 对象;该提供方目前解析必填的 `name` 和 `description`,以及可选的 `whenToUse`、`metadata`、`disable-model-invocation` 和 `user-invocable`。名称必须使用 kebab-case。
|
||||
|
||||
这两个调用字段接受 YAML 布尔值,以及不区分大小写的 `true`/`false`、`yes`/`no`、`on`/`off` 和 `1`/`0`。`disable-model-invocation: true` 会从面向模型的目录和 loader 中排除该 skill;`user-invocable: false` 会从面向用户的命令中排除该 skill。每个省略的字段都默认为允许对应接口调用;提供方始终输出两个正向内部策略值,即使两个键都不存在也不例外。若使用驼峰拼写或提供非布尔调用值,系统会记录警告并从发现结果中排除整个 skill,而不是只丢弃该字段或回退到宽松的默认值。调用策略校验遵循失败时默认拒绝原则,因为忽略无效数据可能会在已禁用的接口上暴露 skill;类型错误的可选 `whenToUse` 和 `metadata` 值则会被省略,因为这两个字段目前都不授予调用权限。
|
||||
|
||||
目录与正文具有独立的生命周期。发现阶段解析 frontmatter 以生成概述。每次 `skill(name)` 加载都会重新读取并解析当前文件,因此正文编辑不需要 hash、修订号、缓存失效或主动通知模型。若在发现与加载之间重命名 frontmatter,系统会拒绝陈旧名称并使提供方失效;下一次目录观察会发布新名称。
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
isSkillName,
|
||||
type SkillCandidate,
|
||||
type SkillDefinition,
|
||||
type SkillInvocationPolicy,
|
||||
type SkillLookupOptions,
|
||||
type SkillProvider,
|
||||
type SkillProviderControl,
|
||||
@@ -100,7 +101,7 @@ interface ParsedSkill {
|
||||
name: string
|
||||
description: string
|
||||
whenToUse?: string
|
||||
disableModelInvocation?: boolean
|
||||
invocation: SkillInvocationPolicy
|
||||
metadata?: Record<string, unknown>
|
||||
content: string
|
||||
}
|
||||
@@ -197,7 +198,7 @@ export class LocalSkillProvider implements SkillProvider {
|
||||
name: parsed.name,
|
||||
description: parsed.description,
|
||||
...parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {},
|
||||
...parsed.disableModelInvocation !== undefined ? { disableModelInvocation: parsed.disableModelInvocation } : {},
|
||||
invocation: parsed.invocation,
|
||||
source: candidate.source,
|
||||
provider: this.name,
|
||||
resourceBase: { kind: 'directory', path: locator.directory },
|
||||
@@ -709,7 +710,7 @@ async function discoverRoot(root: SkillRoot, ctx: Context): Promise<SkillCandida
|
||||
name: parsed.name,
|
||||
description: parsed.description,
|
||||
...parsed.whenToUse !== undefined ? { whenToUse: parsed.whenToUse } : {},
|
||||
...parsed.disableModelInvocation !== undefined ? { disableModelInvocation: parsed.disableModelInvocation } : {},
|
||||
invocation: parsed.invocation,
|
||||
provider: 'local',
|
||||
source: root.source,
|
||||
rank: root.rank,
|
||||
@@ -793,11 +794,18 @@ async function parseSkillFile(path: string, ctx: Context, signal?: AbortSignal,
|
||||
ctx.logger.warn(`skill file ${path} ignored: invalid skill name "${name}"`)
|
||||
return undefined
|
||||
}
|
||||
let invocation
|
||||
try {
|
||||
invocation = parseInvocationPolicy(parsed.data)
|
||||
} catch (error) {
|
||||
ctx.logger.warn(`skill file ${path} ignored: invalid invocation frontmatter: ${errorMessage(error)}`)
|
||||
return undefined
|
||||
}
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
...optionalString(parsed.data, 'whenToUse'),
|
||||
...optionalBoolean(parsed.data, 'disableModelInvocation'),
|
||||
invocation,
|
||||
...optionalMetadata(parsed.data),
|
||||
content: parsed.body.trim(),
|
||||
}
|
||||
@@ -958,9 +966,43 @@ function optionalString(data: Record<string, unknown>, key: string): { [K in typ
|
||||
return typeof value === 'string' && value.length > 0 ? { [key]: value } : {}
|
||||
}
|
||||
|
||||
function optionalBoolean(data: Record<string, unknown>, key: string): { [K in typeof key]?: boolean } {
|
||||
function parseInvocationPolicy(data: Record<string, unknown>): SkillInvocationPolicy {
|
||||
rejectLegacyInvocationKey(data, 'disableModelInvocation', 'disable-model-invocation')
|
||||
rejectLegacyInvocationKey(data, 'modelInvocable', 'disable-model-invocation')
|
||||
rejectLegacyInvocationKey(data, 'userInvocable', 'user-invocable')
|
||||
const disableModelInvocation = frontmatterBoolean(data, 'disable-model-invocation')
|
||||
const userInvocable = frontmatterBoolean(data, 'user-invocable')
|
||||
return {
|
||||
modelInvocable: disableModelInvocation !== true,
|
||||
userInvocable: userInvocable !== false,
|
||||
}
|
||||
}
|
||||
|
||||
function rejectLegacyInvocationKey(data: Record<string, unknown>, legacy: string, canonical: string): void {
|
||||
if (Object.hasOwn(data, legacy)) {
|
||||
throw new Error(`frontmatter field "${legacy}" is unsupported; use "${canonical}"`)
|
||||
}
|
||||
}
|
||||
|
||||
function frontmatterBoolean(data: Record<string, unknown>, key: string): boolean | undefined {
|
||||
if (!Object.hasOwn(data, key)) return undefined
|
||||
const value = data[key]
|
||||
return typeof value === 'boolean' ? { [key]: value } : {}
|
||||
if (typeof value === 'boolean') return value
|
||||
if (value === 1 || value === '1') return true
|
||||
if (value === 0 || value === '0') return false
|
||||
if (typeof value === 'string') {
|
||||
switch (value.toLowerCase()) {
|
||||
case 'true':
|
||||
case 'yes':
|
||||
case 'on':
|
||||
return true
|
||||
case 'false':
|
||||
case 'no':
|
||||
case 'off':
|
||||
return false
|
||||
}
|
||||
}
|
||||
throw new TypeError(`frontmatter field "${key}" must be a boolean`)
|
||||
}
|
||||
|
||||
function optionalMetadata(data: Record<string, unknown>): { metadata?: Record<string, unknown> } {
|
||||
|
||||
@@ -221,7 +221,7 @@ describe('LocalSkillProvider', () => {
|
||||
expect((await ctx.skills.get('runtime-name', { cwd: project }))?.description).toBe('Runtime wins')
|
||||
})
|
||||
|
||||
it('parses flat skills and filters invalid or model-disabled skills from listing', async () => {
|
||||
it('parses flat skills and filters invalid skills from the invocation-neutral listing', async () => {
|
||||
const home = await tempDir('skill-flat')
|
||||
const root = join(home, '.dsh/skills')
|
||||
await writeFlatSkill(root, 'flat-skill', 'flat description', 'Flat instructions.')
|
||||
@@ -230,7 +230,8 @@ describe('LocalSkillProvider', () => {
|
||||
'name: rich-skill',
|
||||
'description: rich description',
|
||||
'whenToUse: For richer local parsing',
|
||||
'disableModelInvocation: false',
|
||||
'disable-model-invocation: off',
|
||||
'user-invocable: YES',
|
||||
'metadata:',
|
||||
' owner: tests',
|
||||
'---',
|
||||
@@ -246,8 +247,10 @@ describe('LocalSkillProvider', () => {
|
||||
await writeFile(join(root, 'no-trailing-body.md'), '---\nname: no-trailing-body\ndescription: No trailing body\n---')
|
||||
await writeFile(join(root, 'notes.txt'), 'ignored')
|
||||
await mkdir(join(root, 'not-a-skill'), { recursive: true })
|
||||
await writeSkill(root, 'hidden-skill', 'hidden description', 'Hidden.')
|
||||
await writeFile(join(root, 'hidden-skill/SKILL.md'), '---\nname: hidden-skill\ndescription: hidden description\ndisableModelInvocation: true\n---\n\nHidden.\n')
|
||||
await writeSkill(root, 'user-only-skill', 'user-only description', 'User-only.')
|
||||
await writeFile(join(root, 'user-only-skill/SKILL.md'), '---\nname: user-only-skill\ndescription: user-only description\ndisable-model-invocation: true\n---\n\nUser-only.\n')
|
||||
await writeSkill(root, 'model-only-skill', 'model-only description', 'Model-only.')
|
||||
await writeFile(join(root, 'model-only-skill/SKILL.md'), '---\nname: model-only-skill\ndescription: model-only description\nuser-invocable: false\n---\n\nModel-only.\n')
|
||||
|
||||
const ctx = await setupLocal(home)
|
||||
const listedBeforeDelete = await ctx.skills.list()
|
||||
@@ -255,17 +258,99 @@ describe('LocalSkillProvider', () => {
|
||||
if (flatSummary === undefined) throw new Error('expected flat-skill')
|
||||
await rm(join(root, 'flat-skill.md'))
|
||||
|
||||
expect(listedBeforeDelete.map(skill => skill.name)).toEqual(['flat-skill', 'no-trailing-body', 'rich-skill'])
|
||||
expect(listedBeforeDelete.map(skill => skill.name)).toEqual([
|
||||
'flat-skill',
|
||||
'model-only-skill',
|
||||
'no-trailing-body',
|
||||
'rich-skill',
|
||||
'user-only-skill',
|
||||
])
|
||||
expect(flatSummary.invocation).toEqual({ modelInvocable: true, userInvocable: true })
|
||||
expect(await ctx.skills.get('flat-skill')).toBeUndefined()
|
||||
expect((await ctx.skills.get('hidden-skill'))?.content).toContain('Hidden.')
|
||||
expect(await ctx.skills.get('no-trailing-body')).toMatchObject({
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
})
|
||||
expect(await ctx.skills.get('user-only-skill')).toMatchObject({
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
content: 'User-only.',
|
||||
})
|
||||
expect(await ctx.skills.get('model-only-skill')).toMatchObject({
|
||||
invocation: { modelInvocable: true, userInvocable: false },
|
||||
content: 'Model-only.',
|
||||
})
|
||||
expect(await ctx.skills.get('rich-skill')).toMatchObject({
|
||||
whenToUse: 'For richer local parsing',
|
||||
disableModelInvocation: false,
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
metadata: { owner: 'tests' },
|
||||
})
|
||||
expect(await ctx.skills.get('Bad_Name')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('accepts the documented boolean spellings for invocation frontmatter', async () => {
|
||||
const home = await tempDir('skill-invocation-booleans')
|
||||
const root = join(home, '.dsh/skills')
|
||||
await mkdir(root, { recursive: true })
|
||||
const truthy = ['true', 'TRUE', '"true"', 'yes', 'ON', '1', '"1"']
|
||||
const falsy = ['false', 'FALSE', '"false"', 'no', 'OFF', '0', '"0"']
|
||||
for (const [index, value] of truthy.entries()) {
|
||||
await writeFile(join(root, `truthy-${index}.md`), [
|
||||
'---',
|
||||
`name: truthy-${index}`,
|
||||
`description: Truthy ${index}`,
|
||||
`disable-model-invocation: ${value}`,
|
||||
'---',
|
||||
'',
|
||||
'Truthy.',
|
||||
].join('\n'))
|
||||
}
|
||||
for (const [index, value] of falsy.entries()) {
|
||||
await writeFile(join(root, `falsy-${index}.md`), [
|
||||
'---',
|
||||
`name: falsy-${index}`,
|
||||
`description: Falsy ${index}`,
|
||||
`user-invocable: ${value}`,
|
||||
'---',
|
||||
'',
|
||||
'Falsy.',
|
||||
].join('\n'))
|
||||
}
|
||||
|
||||
const ctx = await setupLocal(home)
|
||||
|
||||
for (const [index] of truthy.entries()) {
|
||||
expect((await ctx.skills.get(`truthy-${index}`))?.invocation).toEqual({
|
||||
modelInvocable: false,
|
||||
userInvocable: true,
|
||||
})
|
||||
}
|
||||
for (const [index] of falsy.entries()) {
|
||||
expect((await ctx.skills.get(`falsy-${index}`))?.invocation).toEqual({
|
||||
modelInvocable: true,
|
||||
userInvocable: false,
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects legacy and invalid invocation frontmatter without hiding valid siblings', async () => {
|
||||
const home = await tempDir('skill-invalid-invocation')
|
||||
const root = join(home, '.dsh/skills')
|
||||
await writeSkill(root, 'good-skill', 'Good skill')
|
||||
const invalid = [
|
||||
['legacy-model', 'disableModelInvocation: true'],
|
||||
['legacy-positive-model', 'modelInvocable: false'],
|
||||
['legacy-user', 'userInvocable: false'],
|
||||
['bad-string', 'disable-model-invocation: maybe'],
|
||||
['bad-value', 'user-invocable: null'],
|
||||
] as const
|
||||
for (const [name, field] of invalid) {
|
||||
await writeFile(join(root, `${name}.md`), `---\nname: ${name}\ndescription: ${name}\n${field}\n---\n\nBad.\n`)
|
||||
}
|
||||
|
||||
const ctx = await setupLocal(home)
|
||||
|
||||
expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['good-skill'])
|
||||
})
|
||||
|
||||
it('supports CRLF frontmatter and ignores delimiter-looking text inside YAML values', async () => {
|
||||
const home = await tempDir('skill-frontmatter-crlf')
|
||||
const root = join(home, '.dsh/skills')
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/skill/skill/README.md
|
||||
README.md: 65ff110999ea416648f3d676eb813dd4ceb194f8
|
||||
README.zh.md: 79e77d2a2846489125ba0ecaafc138172ba2fd86
|
||||
README.md: f538ae668ccff291be86348627d5547150f460df
|
||||
README.zh.md: 8a44f684ea4d9519a0af7866d272a8e7834aeda6
|
||||
|
||||
@@ -11,10 +11,10 @@ This package owns the `ctx.skills` interface. It does not know whether skills co
|
||||
### Public API
|
||||
|
||||
- `ctx.skills.registerProvider(create): () => void` Calls a synchronous provider factory with `{ signal, invalidate }`, then registers its readonly result by unique `provider.name`. Duplicate names throw, `runtime` is reserved, and failed registration aborts the signal. The exact Cordis disposer unregisters the provider, aborts the signal, and preserves ordered composite teardown.
|
||||
- `ctx.skills.snapshot({ cwd?, signal? })` Returns `{ skills, complete }`. `complete` is false when any provider rejects or explicitly reports incomplete discovery, or when a second catalog revision races the bounded retry; candidates supplied by that observation remain in this result, which is never cached.
|
||||
- `ctx.skills.list({ cwd?, signal? })` Borrows the readonly lookup options, then returns model-invocable summaries for the current workspace, merged across providers and sorted by name.
|
||||
- `ctx.skills.get(name, { cwd?, signal? })` Uses the same readonly options and winning candidate for discovery and loading, rechecks cancellation after discovery or a cache hit, races provider loading against the signal, validates the loaded definition, then returns it, including disabled-for-model skills.
|
||||
- `ctx.skills.register(skill): () => void` Registers a readonly runtime embedded skill, adding `provider: "runtime"` when omitted. Same-name runtime registrations are first-wins: a duplicate logs a warning and gets a no-op disposer. Successful registrations return the exact Cordis disposer for ordered composite teardown.
|
||||
- `ctx.skills.snapshot({ cwd?, signal? })` Returns the invocation-neutral `{ skills, complete }` observation. `complete` is false when any provider rejects or explicitly reports incomplete discovery, or when a second catalog revision races the bounded retry; candidates supplied by that observation remain in this result, which is never cached.
|
||||
- `ctx.skills.list({ cwd?, signal? })` Borrows the readonly lookup options, then returns every winning summary for the current workspace, merged across providers and sorted by name. Consumers apply `isModelInvocable(skill)` or `isUserInvocable(skill)` at their own boundary.
|
||||
- `ctx.skills.get(name, { cwd?, signal? })` Uses the same readonly options and winning candidate for discovery and loading, rechecks cancellation after discovery or a cache hit, races provider loading against the signal, validates the loaded definition, then returns it regardless of invocation policy.
|
||||
- `ctx.skills.register(skill): () => void` Registers a readonly runtime embedded skill, adding the all-invocable policy and `provider: "runtime"` when omitted. Same-name runtime registrations are first-wins: a duplicate logs a warning and gets a no-op disposer. Successful registrations return the exact Cordis disposer for ordered composite teardown.
|
||||
|
||||
### Events
|
||||
|
||||
@@ -26,6 +26,19 @@ This package owns the `ctx.skills` interface. It does not know whether skills co
|
||||
|---|---|---|
|
||||
| `collectCacheMaxEntries` | `128` | Maximum completed cwd/provider catalogs kept in memory. |
|
||||
|
||||
### Invocation policy
|
||||
|
||||
`SkillSummary.invocation` is a required typed policy object whose positive booleans `modelInvocable` and `userInvocable` describe the two surfaces independently. Providers return this resolved shape on every candidate and definition; only the `SkillRegistration` input may omit it, in which case `register()` supplies `{ modelInvocable: true, userInvocable: true }`. The registry keeps all four combinations so one discovery result can serve model-facing tools, human-facing commands, and trusted internal callers without conflating their catalogs.
|
||||
|
||||
| Policy | Model | User |
|
||||
|---|---|---|
|
||||
| `{ modelInvocable: true, userInvocable: true }` | included | included |
|
||||
| `{ modelInvocable: true, userInvocable: false }` | included | excluded |
|
||||
| `{ modelInvocable: false, userInvocable: true }` | excluded | included |
|
||||
| `{ modelInvocable: false, userInvocable: false }` | excluded | excluded |
|
||||
|
||||
`isModelInvocable(skill)` and `isUserInvocable(skill)` read the matching positive field directly. `ctx.skills.get()` remains the trusted, policy-neutral loading primitive, so every user- or model-facing consumer must enforce the predicate that matches its surface before exposing or loading a skill.
|
||||
|
||||
## Provider Contract
|
||||
|
||||
A provider factory runs synchronously and receives one registration-scoped control. `control.signal` aborts when registration fails or is disposed; `control.invalidate()` clears completed catalogs only while that exact registration remains active, so late callbacks cannot affect a replacement with the same name. Immutable providers may ignore the control. Remote setup, authentication, and discovery belong in the provider's awaited `list(options)` call. An array return is shorthand for complete discovery; a provider that collected usable candidates but could not establish an authoritative observation returns `{ candidates, complete: false }`. Provider objects, lookup options, candidates, and definitions are borrowed readonly rather than cloned or rebound. Providers should honor `options.signal`; the registry also stops awaiting uncooperative discovery or loading after cancellation.
|
||||
@@ -38,7 +51,7 @@ Definitions remain progressively loaded. `get()` asks the winning provider for t
|
||||
|
||||
## Runtime Skills
|
||||
|
||||
`ctx.skills.register(...)` is a convenience for embedded runtime skills. Runtime skills use rank `250`: project providers can override them, while they override the shipped local provider's custom and user roots. Runtime definitions and nested resource metadata are borrowed readonly; the service only materializes the top-level definition needed to supply the default `provider`. Registration is first-wins within runtime contributions, so a duplicate contribution cannot remove the active one through its disposer.
|
||||
`ctx.skills.register(...)` is a convenience for embedded runtime skills. Runtime skills use rank `250`: project providers can override them, while they override the shipped local provider's custom and user roots. Runtime definitions and nested resource metadata are borrowed readonly; the service materializes one top-level definition to supply omitted invocation and provider defaults. Registration is first-wins within runtime contributions, so a duplicate contribution cannot remove the active one through its disposer.
|
||||
|
||||
## Consumer boundary
|
||||
|
||||
|
||||
@@ -11,10 +11,10 @@
|
||||
### 公开 API
|
||||
|
||||
- `ctx.skills.registerProvider(create): () => void` 调用同步提供方工厂并向其传入 `{ signal, invalidate }`,随后使用唯一 `provider.name` 注册其只读结果。重复提供方名称会抛错,`runtime` 为保留名称;注册失败会中止信号。精确的 Cordis disposer 会注销提供方、中止信号,并保持有序组合拆卸。
|
||||
- `ctx.skills.snapshot({ cwd?, signal? })` 返回 `{ skills, complete }`。任一提供方调用被拒绝或显式报告发现不完整,或有界重试期间又发生目录修订时,`complete` 为 false;该次观测提供的候选项仍保留在此结果中,但该结果绝不缓存。
|
||||
- `ctx.skills.list({ cwd?, signal? })` 借用只读查找选项,然后返回当前工作区中模型可调用的摘要;这些摘要跨提供方合并,并按名称排序。
|
||||
- `ctx.skills.get(name, { cwd?, signal? })` 在发现和加载中使用同一组只读选项和胜出候选项;在发现或缓存命中后重新检查取消,让提供方加载与信号竞速,验证已加载定义,然后将其返回,包括已对模型禁用的 skill。
|
||||
- `ctx.skills.register(skill): () => void` 注册只读运行时嵌入式 skill,省略时添加 `provider: "runtime"`。同名运行时注册使用先到先得:重复项会记录警告,并获得无操作 disposer。成功注册会返回精确的 Cordis disposer,以供有序组合拆卸。
|
||||
- `ctx.skills.snapshot({ cwd?, signal? })` 返回与调用策略无关的 `{ skills, complete }` 观测。任一提供方调用被拒绝或显式报告发现不完整,或有界重试期间又发生目录修订时,`complete` 为 false;该次观测提供的候选项仍保留在此结果中,但该结果绝不缓存。
|
||||
- `ctx.skills.list({ cwd?, signal? })` 借用只读查找选项,然后返回当前工作区中的全部胜出摘要;这些摘要跨提供方合并,并按名称排序。消费方在自身边界调用 `isModelInvocable(skill)` 或 `isUserInvocable(skill)`。
|
||||
- `ctx.skills.get(name, { cwd?, signal? })` 在发现和加载中使用同一组只读选项和胜出候选项;在发现或缓存命中后重新检查取消,让提供方加载与信号竞速,验证已加载定义,然后无论调用策略如何都将其返回。
|
||||
- `ctx.skills.register(skill): () => void` 注册只读运行时嵌入式 skill,省略时添加允许模型和用户调用的策略以及 `provider: "runtime"`。同名运行时注册使用先到先得:重复项会记录警告,并获得无操作 disposer。成功注册会返回精确的 Cordis disposer,以供有序组合拆卸。
|
||||
|
||||
### 事件
|
||||
|
||||
@@ -26,6 +26,19 @@
|
||||
|---|---|---|
|
||||
| `collectCacheMaxEntries` | `128` | 内存中保留的最大已完成 cwd/提供方目录数。 |
|
||||
|
||||
### 调用策略
|
||||
|
||||
`SkillSummary.invocation` 是一个必填的类型化策略对象,其正向布尔字段 `modelInvocable` 和 `userInvocable` 分别描述两个接口。提供方会在每个候选项和定义中返回这一已解析形状;只有 `SkillRegistration` 输入可以省略它,此时 `register()` 会补入 `{ modelInvocable: true, userInvocable: true }`。注册表保留全部四种组合,使一次发现结果可以同时服务面向模型的工具、面向用户的命令和受信内部调用方,而不会混淆各自的目录。
|
||||
|
||||
| 策略 | 模型 | 用户 |
|
||||
|---|---|---|
|
||||
| `{ modelInvocable: true, userInvocable: true }` | 包含 | 包含 |
|
||||
| `{ modelInvocable: true, userInvocable: false }` | 包含 | 排除 |
|
||||
| `{ modelInvocable: false, userInvocable: true }` | 排除 | 包含 |
|
||||
| `{ modelInvocable: false, userInvocable: false }` | 排除 | 排除 |
|
||||
|
||||
`isModelInvocable(skill)` 和 `isUserInvocable(skill)` 分别直接读取对应的正向字段。`ctx.skills.get()` 仍是受信且与策略无关的加载原语,因此每个面向用户或模型的消费方都必须先执行与自身接口匹配的判定,再暴露或加载 skill。
|
||||
|
||||
## 提供方契约
|
||||
|
||||
提供方工厂同步运行,并接收一项注册作用域内的控制能力。注册失败或释放时,`control.signal` 会中止;仅当该精确注册仍处于活动状态时,`control.invalidate()` 才会清除已完成目录,因此延迟回调无法影响同名替代项。不可变提供方可以忽略该控制能力。远程设置、身份验证和发现由提供方可等待的 `list(options)` 调用执行。返回数组是完整发现的简写形式;若提供方已收集到可用候选项,却无法建立权威观测,则返回 `{ candidates, complete: false }`。提供方对象、查找选项、候选项和定义都以只读方式借用,而不是克隆或重新绑定。提供方应遵守 `options.signal`;取消后,注册表也会停止等待不协作的发现或加载。
|
||||
@@ -38,7 +51,7 @@
|
||||
|
||||
## 运行时 skill
|
||||
|
||||
`ctx.skills.register(...)` 是嵌入式运行时 skill 的便利接口。运行时 skill 使用 rank `250`:项目提供方可覆盖它们,它们则覆盖已发布本地提供方的自定义根目录和用户根目录。运行时定义和嵌套资源元数据均以只读方式借用;服务只物化提供默认 `provider` 所需的顶层定义。运行时贡献内的注册使用先到先得,因此重复贡献无法通过其 disposer 移除当前生效的贡献。
|
||||
`ctx.skills.register(...)` 是嵌入式运行时 skill 的便利接口。运行时 skill 使用 rank `250`:项目提供方可覆盖它们,它们则覆盖已发布本地提供方的自定义根目录和用户根目录。运行时定义和嵌套资源元数据均以只读方式借用;服务只物化补入默认调用策略和 `provider` 所需的顶层定义。运行时贡献内的注册使用先到先得,因此重复贡献无法通过其 disposer 移除当前生效的贡献。
|
||||
|
||||
## 消费方边界
|
||||
|
||||
|
||||
@@ -37,16 +37,24 @@ export type SkillResourceBase =
|
||||
| { readonly kind: 'url'; readonly url: string }
|
||||
| { readonly kind: 'opaque'; readonly description: string }
|
||||
|
||||
/** Model-visible skill metadata returned by `ctx.skills.list()` and rendered into request guidance. */
|
||||
/** Invocation controls shared by skill discovery consumers. */
|
||||
export interface SkillInvocationPolicy {
|
||||
/** Whether model-facing catalogs and loaders include this skill. */
|
||||
readonly modelInvocable: boolean
|
||||
/** Whether human-facing command catalogs and loaders include this skill. */
|
||||
readonly userInvocable: boolean
|
||||
}
|
||||
|
||||
/** Invocation-neutral skill metadata returned by `ctx.skills.list()`. */
|
||||
export interface SkillSummary {
|
||||
/** Kebab-case identifier used with the `skill` tool. */
|
||||
/** Kebab-case identifier used to address the skill. */
|
||||
readonly name: string
|
||||
/** Short routing description shown to the model. */
|
||||
/** Short routing description shown by discovery consumers. */
|
||||
readonly description: string
|
||||
/** Optional extra routing guidance shown to the model. */
|
||||
/** Optional extra routing guidance. */
|
||||
readonly whenToUse?: string
|
||||
/** Whether the skill is hidden from model listings while remaining loadable by trusted callers. */
|
||||
readonly disableModelInvocation?: boolean
|
||||
/** Resolved model and user invocation controls. */
|
||||
readonly invocation: SkillInvocationPolicy
|
||||
/** Discovery source that produced this winning skill. */
|
||||
readonly source: SkillSource
|
||||
/** Provider that owns this skill body. */
|
||||
@@ -78,7 +86,12 @@ export interface SkillDefinition extends SkillSummary {
|
||||
}
|
||||
|
||||
/** Runtime skill contribution accepted by `ctx.skills.register()`. */
|
||||
export type SkillRegistration = Omit<SkillDefinition, 'provider'> & { readonly provider?: string }
|
||||
export type SkillRegistration = Omit<SkillDefinition, 'invocation' | 'provider'> & {
|
||||
/** Invocation controls; omission permits both model and user surfaces. */
|
||||
readonly invocation?: SkillInvocationPolicy
|
||||
/** Provider label; omission uses the registry-owned runtime provider. */
|
||||
readonly provider?: string
|
||||
}
|
||||
|
||||
/** Caller context used for cwd-sensitive and abortable provider work. */
|
||||
export interface SkillLookupOptions {
|
||||
@@ -88,9 +101,27 @@ export interface SkillLookupOptions {
|
||||
readonly signal?: AbortSignal | undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether a skill may be advertised to and loaded by a model.
|
||||
* @param skill - skill metadata carrying resolved invocation controls.
|
||||
* @returns whether the policy permits model invocation.
|
||||
*/
|
||||
export function isModelInvocable(skill: Pick<SkillSummary, 'invocation'>): boolean {
|
||||
return skill.invocation.modelInvocable
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether a skill may be advertised to and loaded by a human-facing command.
|
||||
* @param skill - skill metadata carrying resolved invocation controls.
|
||||
* @returns whether the policy permits user invocation.
|
||||
*/
|
||||
export function isUserInvocable(skill: Pick<SkillSummary, 'invocation'>): boolean {
|
||||
return skill.invocation.userInvocable
|
||||
}
|
||||
|
||||
/** One catalog observation plus whether discovery completed within a stable catalog revision. */
|
||||
export interface SkillCatalogSnapshot {
|
||||
/** Sorted model-invocable summaries collected in this observation. */
|
||||
/** Sorted invocation-neutral summaries collected in this observation. */
|
||||
readonly skills: SkillSummary[]
|
||||
/** Whether every registered provider completed without a concurrent catalog revision. */
|
||||
readonly complete: boolean
|
||||
@@ -172,7 +203,7 @@ interface CollectResult {
|
||||
|
||||
/**
|
||||
* Registry of skill providers. It merges provider catalogs with stable
|
||||
* first-wins duplicate handling, exposes sorted model-visible summaries, and
|
||||
* first-wins duplicate handling, exposes sorted invocation-neutral summaries, and
|
||||
* loads full skill bodies on demand.
|
||||
*/
|
||||
export class SkillService extends Service {
|
||||
@@ -182,7 +213,7 @@ export class SkillService extends Service {
|
||||
|
||||
private readonly collectCacheMaxEntries: number
|
||||
private readonly providers = new Map<string, { provider: SkillProvider; order: number }>()
|
||||
private readonly runtime = new Map<string, SkillRegistration>()
|
||||
private readonly runtime = new Map<string, SkillDefinition>()
|
||||
private readonly collectCache = new Map<string, IndexedCandidate[]>()
|
||||
private providerRevision = 0
|
||||
private nextProviderOrder = 0
|
||||
@@ -248,7 +279,7 @@ export class SkillService extends Service {
|
||||
* Register a borrowed readonly runtime skill. Project entries outrank runtime entries, which
|
||||
* outrank user entries. Same-name runtime entries are first-wins; a duplicate logs a warning and
|
||||
* receives a no-op disposer so it cannot remove the winner.
|
||||
* @param skill - the complete skill definition to expose for discovery.
|
||||
* @param skill - the skill definition input; omitted invocation and provider fields receive defaults.
|
||||
* @returns the exact Cordis effect disposer, preserving composite teardown order and invalidating caches.
|
||||
*/
|
||||
register(skill: SkillRegistration): () => void {
|
||||
@@ -258,15 +289,20 @@ export class SkillService extends Service {
|
||||
this.ctx.logger.warn(`runtime skill "${skill.name}" ignored because it is already registered`)
|
||||
return () => {}
|
||||
}
|
||||
const definition: SkillDefinition = {
|
||||
...skill,
|
||||
invocation: skill.invocation ?? { modelInvocable: true, userInvocable: true },
|
||||
provider: skill.provider ?? RUNTIME_PROVIDER,
|
||||
}
|
||||
const runtime = this.runtime
|
||||
const updateRevision = (): void => { this.runtimeRevision += 1 }
|
||||
const invalidateCache = (): void => { this.invalidateCache() }
|
||||
const dispose = this.ctx.effect(function* () {
|
||||
runtime.set(skill.name, skill)
|
||||
runtime.set(definition.name, definition)
|
||||
updateRevision()
|
||||
invalidateCache()
|
||||
yield () => {
|
||||
runtime.delete(skill.name)
|
||||
runtime.delete(definition.name)
|
||||
updateRevision()
|
||||
invalidateCache()
|
||||
}
|
||||
@@ -276,18 +312,19 @@ export class SkillService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* List model-invocable skill summaries for a workspace. Lookup options and
|
||||
* provider candidates are readonly same-process values borrowed throughout
|
||||
* discovery.
|
||||
* List invocation-neutral skill summaries for a workspace. Consumers apply
|
||||
* model or user invocation policy at their operational boundary. Lookup
|
||||
* options and provider candidates are readonly same-process values borrowed
|
||||
* throughout discovery.
|
||||
* @param options - lookup options; `cwd` selects project roots and `signal` cancels discovery.
|
||||
* @returns sorted summaries, excluding skills disabled for model invocation.
|
||||
* @returns all sorted winning summaries.
|
||||
*/
|
||||
async list(options: SkillLookupOptions = {}): Promise<SkillSummary[]> {
|
||||
return (await this.snapshot(options)).skills
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe the current model-invocable catalog and whether discovery completed within a stable revision.
|
||||
* Observe the current invocation-neutral catalog and whether discovery completed within a stable revision.
|
||||
* Incomplete observations are never cached, allowing consumers to retain last-good state and
|
||||
* retry on their next request boundary.
|
||||
* @param options - lookup options; `cwd` selects project roots and `signal` cancels discovery.
|
||||
@@ -298,7 +335,6 @@ export class SkillService extends Service {
|
||||
return {
|
||||
skills: collected.entries
|
||||
.map(entry => entry.candidate)
|
||||
.filter(skill => skill.disableModelInvocation !== true)
|
||||
.map(toSummary)
|
||||
.sort(compareSkillSummary),
|
||||
complete: collected.cacheable,
|
||||
@@ -466,19 +502,18 @@ const RUNTIME_SKILL_PROVIDER: SkillProvider = {
|
||||
return Promise.resolve([])
|
||||
},
|
||||
get(candidate) {
|
||||
const skill = candidate.locator as SkillRegistration
|
||||
return Promise.resolve({ ...skill, provider: skill.provider ?? RUNTIME_PROVIDER })
|
||||
return Promise.resolve(candidate.locator as SkillDefinition)
|
||||
},
|
||||
}
|
||||
|
||||
function runtimeCandidate(skill: SkillRegistration): SkillCandidate {
|
||||
function runtimeCandidate(skill: SkillDefinition): SkillCandidate {
|
||||
return {
|
||||
name: skill.name,
|
||||
description: skill.description,
|
||||
...skill.whenToUse !== undefined ? { whenToUse: skill.whenToUse } : {},
|
||||
...skill.disableModelInvocation !== undefined ? { disableModelInvocation: skill.disableModelInvocation } : {},
|
||||
invocation: skill.invocation,
|
||||
source: skill.source,
|
||||
provider: skill.provider ?? RUNTIME_PROVIDER,
|
||||
provider: skill.provider,
|
||||
...skill.resourceBase !== undefined ? { resourceBase: skill.resourceBase } : {},
|
||||
rank: RUNTIME_RANK,
|
||||
locator: skill,
|
||||
@@ -500,9 +535,7 @@ function validateCandidate(candidate: SkillCandidate, providerName: string): voi
|
||||
if (candidate.description.length === 0) {
|
||||
throw new Error(`skill provider "${providerName}" returned skill "${candidate.name}" without a description`)
|
||||
}
|
||||
if (candidate.disableModelInvocation !== undefined && typeof candidate.disableModelInvocation !== 'boolean') {
|
||||
throw new TypeError(`skill provider "${providerName}" returned skill "${candidate.name}" with a non-boolean disableModelInvocation`)
|
||||
}
|
||||
validateInvocation(candidate.invocation, `skill provider "${providerName}" returned skill "${candidate.name}"`)
|
||||
if (candidate.whenToUse !== undefined && typeof candidate.whenToUse !== 'string') {
|
||||
throw new TypeError(`skill provider "${providerName}" returned skill "${candidate.name}" with a non-string whenToUse`)
|
||||
}
|
||||
@@ -526,6 +559,7 @@ function validateCandidate(candidate: SkillCandidate, providerName: string): voi
|
||||
function validateRuntimeSkill(skill: SkillRegistration): void {
|
||||
if (!SKILL_NAME.test(skill.name)) throw new Error(`invalid skill name "${skill.name}"`)
|
||||
if (skill.description.length === 0) throw new Error(`skill "${skill.name}" requires a description`)
|
||||
validateInvocation(skill.invocation, `runtime skill "${skill.name}"`)
|
||||
}
|
||||
|
||||
/** Validate a definition loaded from a provider-controlled parser or remote source. */
|
||||
@@ -533,7 +567,7 @@ function validateDefinition(skill: SkillDefinition): void {
|
||||
const name = skill.name
|
||||
const description = skill.description
|
||||
const whenToUse = skill.whenToUse
|
||||
const disableModelInvocation = skill.disableModelInvocation
|
||||
const invocation = skill.invocation
|
||||
const source = skill.source
|
||||
const provider = skill.provider
|
||||
const content = skill.content
|
||||
@@ -542,9 +576,7 @@ function validateDefinition(skill: SkillDefinition): void {
|
||||
if (!SKILL_NAME.test(name)) throw new Error(`loaded skill has invalid name "${name}"`)
|
||||
if (typeof description !== 'string') throw new TypeError(`loaded skill "${name}" description must be a string`)
|
||||
if (description.length === 0) throw new Error(`loaded skill "${name}" requires a description`)
|
||||
if (disableModelInvocation !== undefined && typeof disableModelInvocation !== 'boolean') {
|
||||
throw new TypeError(`loaded skill "${name}" disableModelInvocation must be a boolean`)
|
||||
}
|
||||
validateInvocation(invocation, `loaded skill "${name}"`)
|
||||
if (whenToUse !== undefined && typeof whenToUse !== 'string') throw new TypeError(`loaded skill "${name}" whenToUse must be a string`)
|
||||
if (typeof source !== 'string') throw new TypeError(`loaded skill "${name}" source must be a string`)
|
||||
if (typeof provider !== 'string') throw new TypeError(`loaded skill "${name}" provider must be a string`)
|
||||
@@ -553,18 +585,32 @@ function validateDefinition(skill: SkillDefinition): void {
|
||||
}
|
||||
|
||||
function toSummary(skill: SkillDefinition | SkillCandidate): SkillSummary {
|
||||
const { name, description, whenToUse, disableModelInvocation, source, provider, resourceBase } = skill
|
||||
const { name, description, whenToUse, invocation, source, provider, resourceBase } = skill
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
...whenToUse !== undefined ? { whenToUse } : {},
|
||||
...disableModelInvocation !== undefined ? { disableModelInvocation } : {},
|
||||
invocation,
|
||||
source,
|
||||
provider,
|
||||
...resourceBase !== undefined ? { resourceBase } : {},
|
||||
}
|
||||
}
|
||||
|
||||
function validateInvocation(invocation: unknown, subject: string): void {
|
||||
if (invocation === undefined) return
|
||||
if (typeof invocation !== 'object' || invocation === null || Array.isArray(invocation)) {
|
||||
throw new TypeError(`${subject} with a non-object invocation policy`)
|
||||
}
|
||||
const policy = invocation as Record<string, unknown>
|
||||
if (typeof policy.modelInvocable !== 'boolean') {
|
||||
throw new TypeError(`${subject} with a non-boolean invocation.modelInvocable`)
|
||||
}
|
||||
if (typeof policy.userInvocable !== 'boolean') {
|
||||
throw new TypeError(`${subject} with a non-boolean invocation.userInvocable`)
|
||||
}
|
||||
}
|
||||
|
||||
function compareSkillSummary(left: SkillSummary, right: SkillSummary): number {
|
||||
return compareCodePoints(left.name, right.name)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,21 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import SkillService, { type SkillCandidate, type SkillDefinition, type SkillLookupOptions, type SkillProvider, type SkillProviderObservation } from '@deepseek-ai/dsh-skill'
|
||||
import SkillService, {
|
||||
isModelInvocable,
|
||||
isUserInvocable,
|
||||
type SkillCandidate,
|
||||
type SkillDefinition,
|
||||
type SkillInvocationPolicy,
|
||||
type SkillLookupOptions,
|
||||
type SkillProvider,
|
||||
type SkillProviderObservation,
|
||||
} from '@deepseek-ai/dsh-skill'
|
||||
|
||||
function memorySkill(name: string, description: string, rank: number, body = `${name} body.`): SkillCandidate {
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'memory',
|
||||
source: 'memory',
|
||||
rank,
|
||||
@@ -53,6 +63,7 @@ describe('SkillService registry', () => {
|
||||
return [{
|
||||
name: 'shadowed',
|
||||
description: 'Higher priority',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'override',
|
||||
source: 'override',
|
||||
rank: 5,
|
||||
@@ -78,6 +89,7 @@ describe('SkillService registry', () => {
|
||||
return [{
|
||||
name: 'same-rank-skill',
|
||||
description: 'Same rank',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'same-rank',
|
||||
source: 'same-rank',
|
||||
rank: 10,
|
||||
@@ -139,6 +151,34 @@ describe('SkillService registry', () => {
|
||||
expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['same-rank-skill', 'shadowed'])
|
||||
})
|
||||
|
||||
it('returns an invocation-neutral catalog and resolves model and user policy independently', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SkillService)
|
||||
const registrations = [
|
||||
{ name: 'both', invocation: undefined },
|
||||
{ name: 'model-only', invocation: { modelInvocable: true, userInvocable: false } },
|
||||
{ name: 'user-only', invocation: { modelInvocable: false, userInvocable: true } },
|
||||
{ name: 'trusted-only', invocation: { modelInvocable: false, userInvocable: false } },
|
||||
] as const
|
||||
for (const registration of registrations) {
|
||||
ctx.skills.register({
|
||||
name: registration.name,
|
||||
description: registration.name,
|
||||
source: 'runtime',
|
||||
...registration.invocation === undefined ? {} : { invocation: registration.invocation },
|
||||
content: `${registration.name} body.`,
|
||||
})
|
||||
}
|
||||
|
||||
const listed = await ctx.skills.list()
|
||||
expect(listed.map(skill => skill.name)).toEqual(['both', 'model-only', 'trusted-only', 'user-only'])
|
||||
expect(listed.find(skill => skill.name === 'both')?.invocation).toEqual({ modelInvocable: true, userInvocable: true })
|
||||
expect(listed.filter(isModelInvocable).map(skill => skill.name)).toEqual(['both', 'model-only'])
|
||||
expect(listed.filter(isUserInvocable).map(skill => skill.name)).toEqual(['both', 'user-only'])
|
||||
expect(await ctx.skills.get('trusted-only')).toMatchObject({ content: 'trusted-only body.' })
|
||||
expect((await ctx.skills.get('both'))?.invocation).toEqual({ modelInvocable: true, userInvocable: true })
|
||||
})
|
||||
|
||||
it('validates parsed candidate fields', async () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SkillService)
|
||||
@@ -149,7 +189,7 @@ describe('SkillService registry', () => {
|
||||
...memorySkill('bad-candidate', 'placeholder', 1),
|
||||
provider: 'bad-candidate',
|
||||
description: badDescription as unknown as string,
|
||||
disableModelInvocation: 'false' as unknown as boolean,
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
}]),
|
||||
get: () => Promise.resolve(undefined),
|
||||
})
|
||||
@@ -162,11 +202,11 @@ describe('SkillService registry', () => {
|
||||
list: () => Promise.resolve([{
|
||||
...memorySkill('bad-boolean', 'Bad boolean', 1),
|
||||
provider: 'bad-boolean',
|
||||
disableModelInvocation: 'false' as unknown as boolean,
|
||||
invocation: { modelInvocable: 'false' as unknown as boolean, userInvocable: true },
|
||||
}]),
|
||||
get: () => Promise.resolve(undefined),
|
||||
})
|
||||
await expect(badBoolean.skills.list()).rejects.toThrow('non-boolean disableModelInvocation')
|
||||
await expect(badBoolean.skills.list()).rejects.toThrow('non-boolean invocation.modelInvocable')
|
||||
})
|
||||
|
||||
it('rejects malformed provider results and every malformed candidate scalar', async () => {
|
||||
@@ -198,7 +238,7 @@ describe('SkillService registry', () => {
|
||||
name: `candidate-${index}`,
|
||||
description: 'Candidate',
|
||||
whenToUse: 'Use this candidate.',
|
||||
disableModelInvocation: false,
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: providerName,
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
@@ -225,6 +265,7 @@ describe('SkillService registry', () => {
|
||||
const candidate: SkillCandidate = {
|
||||
name: 'skill-a',
|
||||
description: 'Skill A',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'contextual',
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
@@ -259,6 +300,7 @@ describe('SkillService registry', () => {
|
||||
return [{
|
||||
name: 'cached-skill',
|
||||
description: 'Cached skill',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'cached',
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
@@ -296,6 +338,7 @@ describe('SkillService registry', () => {
|
||||
resolve({
|
||||
name: 'held-skill',
|
||||
description: 'Held skill',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'held',
|
||||
source: 'test',
|
||||
content: 'Held body.',
|
||||
@@ -308,6 +351,7 @@ describe('SkillService registry', () => {
|
||||
return [{
|
||||
name: 'held-skill',
|
||||
description: 'Held skill',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'held',
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
@@ -355,11 +399,12 @@ describe('SkillService registry', () => {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SkillService)
|
||||
const locator = { id: 'provider-owned' }
|
||||
const invocation = { modelInvocable: true, userInvocable: true }
|
||||
const candidate: SkillCandidate = {
|
||||
name: 'stable-skill',
|
||||
description: 'Stable description',
|
||||
whenToUse: 'When stability matters.',
|
||||
disableModelInvocation: false,
|
||||
invocation,
|
||||
provider: 'detached',
|
||||
source: 'test',
|
||||
resourceBase: { kind: 'opaque', description: 'candidate resources' },
|
||||
@@ -372,7 +417,7 @@ describe('SkillService registry', () => {
|
||||
name: 'stable-skill',
|
||||
description: 'Stable description',
|
||||
whenToUse: 'When stability matters.',
|
||||
disableModelInvocation: false,
|
||||
invocation,
|
||||
provider: 'detached',
|
||||
source: 'test',
|
||||
resourceBase: { kind: 'opaque', description: 'definition resources' },
|
||||
@@ -401,6 +446,7 @@ describe('SkillService registry', () => {
|
||||
resourceBase: { kind: 'opaque', description: 'candidate resources' },
|
||||
})])
|
||||
expect(listed[0]?.resourceBase).toBe(candidate.resourceBase)
|
||||
expect(listed[0]?.invocation).toBe(invocation)
|
||||
expect(listCalls).toBe(1)
|
||||
|
||||
const loaded = await ctx.skills.get('stable-skill')
|
||||
@@ -414,11 +460,12 @@ describe('SkillService registry', () => {
|
||||
await ctx.plugin(SkillService)
|
||||
const resourceBase = { kind: 'opaque' as const, description: 'runtime resources' }
|
||||
const metadata = { owner: 'runtime' }
|
||||
const invocation = { modelInvocable: true, userInvocable: true }
|
||||
const registration = {
|
||||
name: 'runtime-skill',
|
||||
description: 'Runtime',
|
||||
whenToUse: 'When runtime data is needed.',
|
||||
disableModelInvocation: false,
|
||||
invocation,
|
||||
source: 'runtime',
|
||||
resourceBase,
|
||||
metadata,
|
||||
@@ -434,6 +481,7 @@ describe('SkillService registry', () => {
|
||||
const listed = await ctx.skills.list()
|
||||
const loaded = await ctx.skills.get('runtime-skill')
|
||||
expect(listed[0]?.resourceBase).toBe(resourceBase)
|
||||
expect(listed[0]?.invocation).toBe(invocation)
|
||||
expect(loaded?.resourceBase).toBe(resourceBase)
|
||||
expect(loaded?.metadata).toBe(metadata)
|
||||
expect(loaded?.provider).toBe('runtime')
|
||||
@@ -445,7 +493,23 @@ describe('SkillService registry', () => {
|
||||
{ patch: { name: 'Bad_Name' }, expected: 'loaded skill has invalid name' },
|
||||
{ patch: { description: { value: 'description' } as unknown as string }, expected: 'description must be a string' },
|
||||
{ patch: { description: '' }, expected: 'requires a description' },
|
||||
{ patch: { disableModelInvocation: 'false' as unknown as boolean }, expected: 'disableModelInvocation must be a boolean' },
|
||||
{ patch: { invocation: null as never }, expected: 'non-object invocation policy' },
|
||||
{
|
||||
patch: { invocation: { modelInvocable: 'false' as unknown as boolean, userInvocable: true } },
|
||||
expected: 'invocation.modelInvocable',
|
||||
},
|
||||
{
|
||||
patch: { invocation: { modelInvocable: true, userInvocable: 'true' as unknown as boolean } },
|
||||
expected: 'invocation.userInvocable',
|
||||
},
|
||||
{
|
||||
patch: { invocation: { userInvocable: true } as unknown as SkillInvocationPolicy },
|
||||
expected: 'invocation.modelInvocable',
|
||||
},
|
||||
{
|
||||
patch: { invocation: { modelInvocable: true } as unknown as SkillInvocationPolicy },
|
||||
expected: 'invocation.userInvocable',
|
||||
},
|
||||
{ patch: { whenToUse: 1 as unknown as string }, expected: 'whenToUse must be a string' },
|
||||
{ patch: { source: { value: 'source' } as unknown as string }, expected: 'source must be a string' },
|
||||
{ patch: { provider: { value: 'provider' } as unknown as string }, expected: 'provider must be a string' },
|
||||
@@ -462,6 +526,7 @@ describe('SkillService registry', () => {
|
||||
list: () => Promise.resolve([{
|
||||
name: skillName,
|
||||
description: 'Candidate',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: providerName,
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
@@ -471,7 +536,7 @@ describe('SkillService registry', () => {
|
||||
name: skillName,
|
||||
description: 'Definition',
|
||||
whenToUse: 'Use this definition.',
|
||||
disableModelInvocation: false,
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: providerName,
|
||||
source: 'test',
|
||||
content: 'Definition body.',
|
||||
@@ -771,6 +836,7 @@ describe('SkillService registry', () => {
|
||||
skills: [{
|
||||
name: 'bounded-skill',
|
||||
description: 'Attempt 2',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'self-invalidating',
|
||||
source: 'memory',
|
||||
}],
|
||||
@@ -793,6 +859,7 @@ describe('SkillService registry', () => {
|
||||
return [{
|
||||
name: 'old-name',
|
||||
description: 'Old name',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'renamed',
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
@@ -928,6 +995,13 @@ describe('SkillService registry', () => {
|
||||
await ctx.plugin(SkillService)
|
||||
expect(() => ctx.skills.register({ name: 'Bad_Name', description: 'Bad', source: 'runtime', content: 'bad' })).toThrow('invalid skill name')
|
||||
expect(() => ctx.skills.register({ name: 'no-description', description: '', source: 'runtime', content: 'bad' })).toThrow('requires a description')
|
||||
expect(() => ctx.skills.register({
|
||||
name: 'bad-invocation',
|
||||
description: 'Bad invocation',
|
||||
source: 'runtime',
|
||||
invocation: [] as never,
|
||||
content: 'bad',
|
||||
})).toThrow('non-object invocation policy')
|
||||
expect(await ctx.skills.get('missing-skill')).toBeUndefined()
|
||||
expect(await ctx.skills.get('Bad_Name')).toBeUndefined()
|
||||
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/skill/tool-skill/README.md
|
||||
README.md: 53f1494b8d0a348910ff7fb3965ae1798fc3b3b8
|
||||
README.zh.md: f30d47fa1f774c449069278d17e8c6c5c3d1a43d
|
||||
README.md: d8e00bc839358f58cd83bfa9b28eed09dd407bce
|
||||
README.zh.md: 6c0df1d6e38c99ce64cadeb668bbf0ad7b3029e3
|
||||
|
||||
@@ -26,7 +26,7 @@ Execution uses the calling agent's `session.header.cwd` so workspace-sensitive p
|
||||
|
||||
Resource guidance resolves only paths or URLs explicitly referenced by the instructions against `resourceBase`; scripts, references, and assets load on demand, and the result does not enumerate a skill directory. Local providers may supply a directory, while remote or embedded providers may supply a URL or opaque loading guidance.
|
||||
|
||||
An unresolved name reports that the skill is unknown or no longer available. Invalid names and `disableModelInvocation: true` skills produce distinct error results.
|
||||
An unresolved name reports that the skill is unknown or no longer available. Invalid names and skills whose `invocation.modelInvocable` is `false` produce distinct error results. `invocation.userInvocable` does not restrict this model-facing surface.
|
||||
|
||||
Tool execution does not call `agent.inject()`. Its freshly loaded result is already recorded as the tool result and becomes available to the next model step without duplicating the body as synthetic context. Only the catalog projection injects replacement summaries.
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
资源指引只会根据 `resourceBase` 解析指令显式引用的路径或 URL;脚本、参考资料和资源文件按需加载,结果不会列举 skill 目录。本地提供方可以提供目录,而远程或嵌入式提供方可以提供 URL 或不透明加载指引。
|
||||
|
||||
无法解析的名称会报告 skill 未知或已不可用。无效名称和 `disableModelInvocation: true` skill 产生不同的错误结果。
|
||||
无法解析的名称会报告 skill 未知或已不可用。无效名称和 `invocation.modelInvocable` 为 `false` 的 skill 会产生不同的错误结果。`invocation.userInvocable` 不限制这个面向模型的接口。
|
||||
|
||||
工具执行不调用 `agent.inject()`。新加载的结果已作为工具结果记录,并在下一个模型步骤可用,无需将正文重复为合成上下文。只有目录投影会注入替换摘要。
|
||||
|
||||
|
||||
@@ -9,9 +9,14 @@ import type { Context } from 'cordis'
|
||||
import z from 'schemastery'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import { defineTool } from '@deepseek-ai/dsh-tools'
|
||||
import { createUserMessage, assertNever } from '@deepseek-ai/dsh-llm'
|
||||
import { assertNever, createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import type { UserMessage } from '@deepseek-ai/dsh-session'
|
||||
import { isSkillName, type SkillDefinition, type SkillSummary } from '@deepseek-ai/dsh-skill'
|
||||
import {
|
||||
isModelInvocable,
|
||||
isSkillName,
|
||||
type SkillDefinition,
|
||||
type SkillSummary,
|
||||
} from '@deepseek-ai/dsh-skill'
|
||||
|
||||
export const name = 'tool-skill'
|
||||
export const inject = ['agents', 'tools', 'skills']
|
||||
@@ -92,11 +97,19 @@ export function apply(ctx: Context, config: Config = {}): void {
|
||||
if (!isSkillName(args.name)) {
|
||||
throw new Error(`invalid skill name "${args.name}"`)
|
||||
}
|
||||
const skill = await ctx.skills.get(args.name, { cwd: exec.agent?.session.header.cwd, signal: exec.signal })
|
||||
const lookup = { cwd: exec.agent?.session.header.cwd, signal: exec.signal }
|
||||
const summary = (await ctx.skills.list(lookup)).find(skill => skill.name === args.name)
|
||||
if (!summary) {
|
||||
throw new Error(`skill "${args.name}" is unknown or no longer available`)
|
||||
}
|
||||
if (!isModelInvocable(summary)) {
|
||||
throw new Error(`skill "${args.name}" is not available for model invocation`)
|
||||
}
|
||||
const skill = await ctx.skills.get(args.name, lookup)
|
||||
if (!skill) {
|
||||
throw new Error(`skill "${args.name}" is unknown or no longer available`)
|
||||
}
|
||||
if (skill.disableModelInvocation === true) {
|
||||
if (!isModelInvocable(skill)) {
|
||||
throw new Error(`skill "${args.name}" is not available for model invocation`)
|
||||
}
|
||||
return {
|
||||
@@ -128,13 +141,14 @@ export function apply(ctx: Context, config: Config = {}): void {
|
||||
: { skills: [], complete: true }
|
||||
signal.throwIfAborted()
|
||||
if (!snapshot.complete) return
|
||||
const digest = catalogDigest(snapshot.skills, catalogDescriptionMaxLength)
|
||||
const skills = snapshot.skills.filter(isModelInvocable)
|
||||
const digest = catalogDigest(skills, catalogDescriptionMaxLength)
|
||||
const history = catalogHistory(agent)
|
||||
if (history.visibleDigest === digest) return
|
||||
if (!history.published && snapshot.skills.length === 0) return
|
||||
if (!history.published && skills.length === 0) return
|
||||
const catalog = history.published
|
||||
? renderCatalogUpdate(snapshot.skills, catalogDescriptionMaxLength)
|
||||
: renderCatalogMessage(snapshot.skills, catalogDescriptionMaxLength)
|
||||
? renderCatalogUpdate(skills, catalogDescriptionMaxLength)
|
||||
: renderCatalogMessage(skills, catalogDescriptionMaxLength)
|
||||
agent.inject(catalog)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -187,6 +187,20 @@ describe('dsh-tool-skill', () => {
|
||||
provider: 'runtime',
|
||||
content: 'A body.',
|
||||
})
|
||||
ctx.skills.register({
|
||||
name: 'model-only-skill',
|
||||
description: 'Model-only skill.',
|
||||
invocation: { modelInvocable: true, userInvocable: false },
|
||||
source: 'runtime',
|
||||
content: 'Model-only body.',
|
||||
})
|
||||
ctx.skills.register({
|
||||
name: 'user-only-skill',
|
||||
description: 'User-only skill.',
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
source: 'runtime',
|
||||
content: 'User-only body.',
|
||||
})
|
||||
ctx.on('agent/step', (agent) => {
|
||||
agent.inject(createUserMessage({ content: [{ type: 'text', text: 'later contribution' }], source: { kind: 'plugin', plugin: 'later-contribution' } }))
|
||||
})
|
||||
@@ -206,6 +220,7 @@ describe('dsh-tool-skill', () => {
|
||||
'',
|
||||
'<available_skills>',
|
||||
'- `a-skill`: Use {{placeholder}} <safely> & carefully.',
|
||||
'- `model-only-skill`: Model-only skill.',
|
||||
'- `z-skill`: Long description Long description Long descript...',
|
||||
'</available_skills>',
|
||||
'',
|
||||
@@ -226,14 +241,24 @@ describe('dsh-tool-skill', () => {
|
||||
expect(rendered).not.toContain('secret-source')
|
||||
expect(rendered).not.toContain('/secret/path')
|
||||
expect(rendered).not.toContain('Secret body')
|
||||
expect(rendered).not.toContain('user-only-skill')
|
||||
expect(renderPrompt(await ctx.systemPrompt.assemble({ agent: agentForCwd('/workspace') }))).not.toContain('<available_skills>')
|
||||
})
|
||||
|
||||
it('does not inject a catalog when no skills are available', async () => {
|
||||
it('does not inject a catalog when no model-invocable skills are available', async () => {
|
||||
const home = await tempDir('tool-empty-catalog')
|
||||
const ctx = await setup(home)
|
||||
ctx.skills.register({
|
||||
name: 'user-only-skill',
|
||||
description: 'User-only skill',
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
source: 'runtime',
|
||||
content: 'User-only body.',
|
||||
})
|
||||
|
||||
expect(await composePrefix(ctx, '/workspace')).toEqual([])
|
||||
const agent = agentForCwd('/workspace')
|
||||
expect(await composePrefixForAgent(ctx, agent)).toEqual([])
|
||||
expect(await composePrefixForAgent(ctx, agent)).toEqual([])
|
||||
})
|
||||
|
||||
it('omits an incomplete initial catalog and retries on a later request boundary', async () => {
|
||||
@@ -603,18 +628,94 @@ describe('dsh-tool-skill', () => {
|
||||
it('returns isError for unknown, invalid, and model-disabled skills', async () => {
|
||||
const home = await tempDir('tool-errors')
|
||||
await writeSkill(join(home, '.dsh/skills'), 'hidden-skill', 'Hidden skill', 'Hidden instructions.')
|
||||
await writeFile(join(home, '.dsh/skills/hidden-skill/SKILL.md'), '---\nname: hidden-skill\ndescription: Hidden skill\ndisableModelInvocation: true\n---\n\nHidden instructions.\n')
|
||||
await writeFile(join(home, '.dsh/skills/hidden-skill/SKILL.md'), '---\nname: hidden-skill\ndescription: Hidden skill\ndisable-model-invocation: true\n---\n\nHidden instructions.\n')
|
||||
const ctx = await setup(home)
|
||||
ctx.skills.register({
|
||||
name: 'model-only-skill',
|
||||
description: 'Model-only skill',
|
||||
invocation: { modelInvocable: true, userInvocable: false },
|
||||
source: 'runtime',
|
||||
content: 'Model-only instructions.',
|
||||
})
|
||||
|
||||
const unknown = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c1'), name: 'skill', arguments: { name: 'missing' } })
|
||||
const invalid = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c2'), name: 'skill', arguments: { name: 'Bad_Name' } })
|
||||
const disabled = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c3'), name: 'skill', arguments: { name: 'hidden-skill' } })
|
||||
const modelOnly = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c4'), name: 'skill', arguments: { name: 'model-only-skill' } })
|
||||
|
||||
expect(unknown.isError).toBe(true)
|
||||
expect(invalid.isError).toBe(true)
|
||||
expect(disabled.isError).toBe(true)
|
||||
expect(modelOnly.isError).toBe(false)
|
||||
const unknownBlock = unknown.content[0]
|
||||
if (unknownBlock?.type !== 'text') throw new Error('expected text tool result')
|
||||
expect(unknownBlock.text).toContain('skill "missing" is unknown or no longer available')
|
||||
})
|
||||
|
||||
it('checks model policy before provider loading and rechecks the loaded definition', async () => {
|
||||
const home = await tempDir('tool-policy-before-load')
|
||||
const ctx = await setup(home)
|
||||
const getCalls: string[] = []
|
||||
ctx.skills.registerProvider(() => ({
|
||||
name: 'policy-probe',
|
||||
async list() {
|
||||
return [
|
||||
{
|
||||
name: 'denied-skill',
|
||||
description: 'Denied skill',
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
provider: 'policy-probe',
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
locator: 'denied-skill',
|
||||
},
|
||||
{
|
||||
name: 'policy-race-skill',
|
||||
description: 'Policy race skill',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'policy-probe',
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
locator: 'policy-race-skill',
|
||||
},
|
||||
{
|
||||
name: 'vanishing-skill',
|
||||
description: 'Vanishing skill',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
provider: 'policy-probe',
|
||||
source: 'test',
|
||||
rank: 1,
|
||||
locator: 'vanishing-skill',
|
||||
},
|
||||
]
|
||||
},
|
||||
async get(candidate) {
|
||||
getCalls.push(candidate.name)
|
||||
if (candidate.name === 'vanishing-skill') return undefined
|
||||
return {
|
||||
...candidate,
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
content: 'Instructions must not be disclosed.',
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
const denied = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c6'), name: 'skill', arguments: { name: 'denied-skill' } })
|
||||
const raced = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c7'), name: 'skill', arguments: { name: 'policy-race-skill' } })
|
||||
const vanished = await ctx.tools.execute({ signal: testToolSignal, callId: CallId('c8'), name: 'skill', arguments: { name: 'vanishing-skill' } })
|
||||
|
||||
expect(denied.isError).toBe(true)
|
||||
expect(raced.isError).toBe(true)
|
||||
expect(vanished.isError).toBe(true)
|
||||
expect(getCalls).toEqual(['policy-race-skill', 'vanishing-skill'])
|
||||
for (const result of [denied, raced]) {
|
||||
const block = result.content[0]
|
||||
if (block?.type !== 'text') throw new Error('expected text tool result')
|
||||
expect(block.text).toContain('is not available for model invocation')
|
||||
expect(block.text).not.toContain('Instructions must not be disclosed.')
|
||||
}
|
||||
const vanishedBlock = vanished.content[0]
|
||||
if (vanishedBlock?.type !== 'text') throw new Error('expected text tool result')
|
||||
expect(vanishedBlock.text).toContain('skill "vanishing-skill" is unknown or no longer available')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/ui/tui/README.md
|
||||
README.md: 1a46e7d0557939df77ca27cc4bd09842c9db72ac
|
||||
README.zh.md: 45353bdc52446d6864f4e365eb4329201432a33b
|
||||
README.md: 88c4501d87b7f24de1f5cc0d67f4c0e03ec49aa4
|
||||
README.zh.md: f03120e5a7820e2bcb572ab31b535211cf859c82
|
||||
|
||||
@@ -26,7 +26,7 @@ While the agent is running, ordinary editor submissions call `agent.steer()`; ot
|
||||
|
||||
`/model` opens the advisory `ctx.llm` catalog as a keyboard selector: a filter box above the list narrows rows by a case-insensitive substring over each row's `provider/model` label, model name, and description, keeping the highlighted row selected when it survives the filter; Up/Down moves, Shift+Tab cycles the focused model's adapter-advertised reasoning efforts in display order, Enter selects the model and effort, and Escape clears a non-empty filter before a second Escape closes it. When an adapter does not advertise a default effort, the cycle also includes `provider default`, which clears an explicit selection; models without selectable effort metadata ignore Shift+Tab. The selector renders the exact advertised effort list—including `off` when present—and does not synthesize, clamp, or transfer an effort between models. `/model <model>` still selects an unambiguous model id directly, while `/model <provider>/<model>` selects an exact target and uses its adapter default when one exists. The configured target or latest logged request header initializes the selector, and an unlisted current model remains visible because catalogs are advisory. Selection is local to this TUI session. Prompt assembly snapshots the target for one step, replaces `{{provider}}` and `{{model}}`, and applies the same provider/model/reasoning-effort target through `agent/request`; a switch during assembly therefore starts with a later step. The request header durably records targets that reach the model, while an unused selection remains process-local.
|
||||
|
||||
`/reload` (EXPERIMENTAL, dev-only) re-reads every file-backed loader config tree and applies the diff to the running app — the HMR watcher's config path, invoked manually; it needs the cordis Loader in the context and degrades to a warning without one, runs only while the agent is idle, and refuses re-entry while a reload is in flight. Module-source hot reload remains watcher-owned. When a `skills` service is mounted, `/skill:<name> [instructions]` loads that skill's instructions into the conversation as a user turn; autocomplete lists the model-invocable skills, and any skill (including a model-disabled one) is loadable by its exact name.
|
||||
`/reload` (EXPERIMENTAL, dev-only) re-reads every file-backed loader config tree and applies the diff to the running app — the HMR watcher's config path, invoked manually; it needs the cordis Loader in the context and degrades to a warning without one, runs only while the agent is idle, and refuses re-entry while a reload is in flight. Module-source hot reload remains watcher-owned. When a `skills` service is mounted, `/skill:<name> [instructions]` loads that skill's instructions into the conversation as a user turn; autocomplete lists user-invocable skills, and exact invocation rejects a skill whose user policy disables it.
|
||||
|
||||
The footer sums the session's reported usage as `↑<uncached input> ↓<output>`, followed by `cache <rate>%` once any input has been billed — the share of billed prompt tokens (uncached input plus cache reads and writes) served from the provider cache, rounded to a percent. It also compares token-meter pressure with `ctx.llm.resolveModelInfo()` context for the current route (omitting the context share when the adapter has no capacity metadata) and shows the current model and tool-card mode; the right side clips first when the footer is narrow.
|
||||
|
||||
@@ -139,7 +139,7 @@ Changing provider or model enters that target's cache domain; no cache reuse acr
|
||||
|
||||
#### What the model sees
|
||||
|
||||
A `/skill:<name> [instructions]` submission loads the named skill and delivers one text block: a `<skill name="…">` element wrapping the skill's instructions — preceded, when the provider exposes a resource base, by a line locating the skill's relative resources — followed by any trailing instructions the user typed. Delivery follows the same followup-while-idle / steer-while-running rule as ordinary input. The command, not the model, chooses the skill; model-disabled skills are omitted from autocomplete but stay loadable by exact name. Autocomplete retains its last complete skill snapshot and refetches after `skills/change`; an incomplete observation preserves the prior menu, a complete empty observation clears it, and a catalog arriving while a slash-name draft is open immediately re-queries that draft.
|
||||
A `/skill:<name> [instructions]` submission loads the named skill and delivers one text block: a `<skill name="…">` element wrapping the skill's instructions — preceded, when the provider exposes a resource base, by a line locating the skill's relative resources — followed by any trailing instructions the user typed. Delivery follows the same followup-while-idle / steer-while-running rule as ordinary input. The command, not the model, chooses the skill: autocomplete and exact invocation apply `invocation.userInvocable`, while `invocation.modelInvocable` does not restrict this surface. User-disabled skills are omitted from autocomplete and rejected before exact-name loading; the loaded definition is rechecked for a policy race. Autocomplete retains its last complete skill snapshot and refetches after `skills/change`; an incomplete observation preserves the prior menu, a complete empty observation clears it, and a catalog arriving while a slash-name draft is open immediately re-queries that draft. The skill service is an optional peer; this policy check uses its type contract without introducing a runtime package dependency.
|
||||
|
||||
#### Token effect
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ Agent 运行时,普通编辑器提交会调用 `agent.steer()`;其他时候
|
||||
|
||||
`/model` 将建议性的 `ctx.llm` catalog 打开为键盘选择器:列表上方设有一个过滤框,按对每行 `provider/model` 标签、模型名称和描述的大小写不敏感子串匹配来缩小行集,并在高亮行仍通过过滤时保持其选中状态;Up/Down 移动,Shift+Tab 按显示顺序循环切换适配器为焦点模型公布的推理强度,Enter 选择模型和推理强度,Escape 会先清除非空过滤内容,再次按下才关闭选择器。适配器未公布默认推理强度时,循环还会包含 `provider default`,该项会清除显式选择;没有可选推理强度元数据的模型会忽略 Shift+Tab。选择器会原样呈现公布的推理强度列表(包括存在时的 `off`),不会合成、自动调整或在模型之间转移推理强度。`/model <model>` 仍可直接选择无歧义的模型 id,`/model <provider>/<model>` 则选择精确目标,并在存在时使用其适配器默认值。已配置目标或最新记录的请求 header 会初始化选择器;由于 catalog 仅提供建议,未列出的当前模型仍会显示。选择仅对本 TUI 会话有效。提示词组装会为一个步骤建立目标快照,替换 `{{provider}}` 和 `{{model}}`,并通过 `agent/request` 应用同一个提供方/模型/推理强度目标;因此组装期间的切换会从后续步骤开始生效。请求 header 会持久记录真正到达模型的目标,未使用的选择则只存在于进程本地。
|
||||
|
||||
`/reload`(实验性,仅开发环境)会重新读取所有基于文件的 loader 配置树,并把 diff 应用到运行中 app:它手动调用 HMR(热模块替换)watcher 的配置路径;上下文中必须有 cordis Loader,否则退化为警告。它只在 agent 空闲时运行,并拒绝 reload 进行期间的再次进入。模块源代码热重载仍由 watcher 持有。挂载 `skills` 服务后,`/skill:<name> [instructions]` 会把该 skill 的指令作为一个 user 轮次加载到会话中;自动补全列出模型可调用的 skill,任何 skill(包括模型禁用的 skill)都可通过精确名称加载。
|
||||
`/reload`(实验性,仅开发环境)会重新读取所有基于文件的 loader 配置树,并把 diff 应用到运行中 app:它手动调用 HMR(热模块替换)watcher 的配置路径;上下文中必须有 cordis Loader,否则退化为警告。它只在 agent 空闲时运行,并拒绝 reload 进行期间的再次进入。模块源代码热重载仍由 watcher 持有。挂载 `skills` 服务后,`/skill:<name> [instructions]` 会把该 skill 的指令作为一个 user 轮次加载到会话中;自动补全列出用户可调用的 skill,按精确名称调用时也会拒绝用户策略禁用的 skill。
|
||||
|
||||
Footer 将会话报告的用量汇总为 `↑<uncached input> ↓<output>`;任何输入计费后,后面会显示 `cache <rate>%`,表示提供方缓存服务的已计费提示词 token 占比(未缓存输入加缓存读写),并四舍五入为百分比。它还会将 token-meter 压力与 `ctx.llm.resolveModelInfo()` 为当前路由返回的上下文容量进行比较(适配器没有容量元数据时省略上下文占比),并显示当前模型和工具卡片模式;footer 过窄时,右侧会优先裁剪。
|
||||
|
||||
@@ -139,7 +139,7 @@ Paths prefixed with @ are files explicitly referenced by the user. Use the read
|
||||
|
||||
#### 模型看到的内容
|
||||
|
||||
提交 `/skill:<name> [instructions]` 会加载具名 skill,并交付一个文本块:用 `<skill name="…">` 元素包装 skill 指令;提供方公开资源基准时,会先添加一行定位 skill 相对资源;最后附上用户输入的尾随指令。交付遵循普通输入同样的空闲时 followup、运行时 steer 规则。选择 skill 的是命令而非模型;模型禁用的 skill 不出现在自动补全中,但仍可按精确名称加载。自动补全会保留最后一份完整 skill 快照,并在 `skills/change` 后重新获取。观测不完整时保留先前菜单,完整的空观测会将其清空;如果目录在斜杠命令名称草稿打开期间到达,则会立即根据该草稿重新查询。
|
||||
提交 `/skill:<name> [instructions]` 会加载具名 skill,并交付一个文本块:用 `<skill name="…">` 元素包装 skill 指令;提供方公开资源基准时,会先添加一行定位 skill 相对资源;最后附上用户输入的尾随指令。交付遵循普通输入同样的空闲时 followup、运行时 steer 规则。选择 skill 的是命令而非模型:自动补全和按精确名称调用都应用 `invocation.userInvocable`,`invocation.modelInvocable` 不限制这个接口。用户禁用的 skill 不出现在自动补全中,按精确名称调用时也会在加载前被拒绝;为防止策略竞态,加载后的定义还会再次接受检查。自动补全会保留最后一份完整 skill 快照,并在 `skills/change` 后重新获取。观测不完整时保留先前菜单,完整的空观测会将其清空;如果目录在斜杠命令名称草稿打开期间到达,则会立即根据该草稿重新查询。skill 服务是可选 peer;这项策略检查仅使用其类型契约,不引入运行时包依赖。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
|
||||
@@ -1047,11 +1047,10 @@ export function createTuiChat(
|
||||
requestRender()
|
||||
}
|
||||
|
||||
// Skill listing is async while `createTuiChat` is synchronous, so the
|
||||
// TUI retains the last complete catalog for synchronous editor completion
|
||||
// and refreshes it after registry invalidation. Disabled-for-model skills are
|
||||
// absent from snapshots, so they never appear as completions; a user can
|
||||
// still invoke one by typing its exact name.
|
||||
// Skill listing is async while `createTuiChat` is synchronous, so the TUI
|
||||
// retains the last complete invocation-neutral catalog for synchronous
|
||||
// editor completion, filters it for user invocation, and refreshes it after
|
||||
// registry invalidation.
|
||||
let skillCommands: SlashCommand[] = []
|
||||
let skillCommandScan = 0
|
||||
const refreshCommandAutocomplete = (): void => {
|
||||
@@ -1092,12 +1091,13 @@ export function createTuiChat(
|
||||
service.snapshot({ cwd, signal: skillAbort.signal }).then(
|
||||
(snapshot) => {
|
||||
if (disposed || scan !== skillCommandScan || !snapshot.complete) return
|
||||
const invocable = snapshot.skills.filter(skill => skill.invocation.userInvocable)
|
||||
// The argument-hint slot shows in the menu but is never inserted on
|
||||
// selection, so it carries the skill's scope instead of an
|
||||
// instructions placeholder. `SkillSource` is open-ended; every
|
||||
// non-project source (user, custom, bundled, runtime, …) collapses
|
||||
// to `(user)`.
|
||||
skillCommands = snapshot.skills.map(skill => ({
|
||||
skillCommands = invocable.map(skill => ({
|
||||
name: `skill:${skill.name}`,
|
||||
description: skill.description,
|
||||
argumentHint: skill.source.startsWith('project-') ? '(project)' : '(user)',
|
||||
@@ -1282,19 +1282,40 @@ export function createTuiChat(
|
||||
appendNotice('Skills are not available in this session.', 'warning')
|
||||
return
|
||||
}
|
||||
skills.get(name, { cwd, signal: skillAbort.signal }).then(
|
||||
(skill) => {
|
||||
const lookup = { cwd, signal: skillAbort.signal }
|
||||
const reportFailure = (error: unknown): void => {
|
||||
if (disposed) return
|
||||
appendNotice(`Skill "${name}" failed to load: ${errorChain(error)}`, 'error')
|
||||
}
|
||||
skills.list(lookup).then(
|
||||
(summaries) => {
|
||||
if (disposed) return
|
||||
if (skill === undefined) {
|
||||
const summary = summaries.find(skill => skill.name === name)
|
||||
if (summary === undefined) {
|
||||
appendNotice(`Unknown skill: ${name}`, 'warning')
|
||||
return
|
||||
}
|
||||
deliver(renderSkillInvocation(skill, instructions))
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (disposed) return
|
||||
appendNotice(`Skill "${name}" failed to load: ${errorChain(error)}`, 'error')
|
||||
if (!summary.invocation.userInvocable) {
|
||||
appendNotice(`Skill "${name}" is not available for user invocation.`, 'warning')
|
||||
return
|
||||
}
|
||||
skills.get(name, lookup).then(
|
||||
(skill) => {
|
||||
if (disposed) return
|
||||
if (skill === undefined) {
|
||||
appendNotice(`Unknown skill: ${name}`, 'warning')
|
||||
return
|
||||
}
|
||||
if (!skill.invocation.userInvocable) {
|
||||
appendNotice(`Skill "${name}" is not available for user invocation.`, 'warning')
|
||||
return
|
||||
}
|
||||
deliver(renderSkillInvocation(skill, instructions))
|
||||
},
|
||||
reportFailure,
|
||||
)
|
||||
},
|
||||
reportFailure,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ import { GOAL_CHANGE_VERSION, GoalId, renderGoalChange, type GoalSnapshotChangeM
|
||||
import CommandService, { type CommandInvocation } from '@deepseek-ai/dsh-commands'
|
||||
import SessionStore, { SessionId, type JsonValue, type SessionEvent, type SessionHeader, type TurnEndReason } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionRecord } from '@deepseek-ai/dsh-session-query'
|
||||
import SkillService, { type SkillCatalogSnapshot, type SkillDefinition, type SkillProvider } from '@deepseek-ai/dsh-skill'
|
||||
import SkillService, { type SkillCatalogSnapshot, type SkillDefinition, type SkillProvider, type SkillSummary } from '@deepseek-ai/dsh-skill'
|
||||
import type {} from '@deepseek-ai/dsh-session-title'
|
||||
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
||||
import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
|
||||
@@ -3828,10 +3828,30 @@ describe('skill slash command', () => {
|
||||
if (skills === undefined) throw new Error('skills service not mounted')
|
||||
skills.register({ name: 'demo-skill', description: 'Demo skill for tests', source: 'runtime', provider: 'runtime', content: 'Demo instructions body.' })
|
||||
skills.register({ name: 'project-skill', description: 'Project skill for tests', source: 'project-dsh', provider: 'runtime', content: 'Project instructions body.' })
|
||||
skills.register({ name: 'hidden-skill', description: 'Model-hidden skill', source: 'runtime', provider: 'runtime', content: 'Hidden instructions body.', disableModelInvocation: true })
|
||||
skills.register({
|
||||
name: 'user-only-skill',
|
||||
description: 'User-only skill',
|
||||
invocation: { modelInvocable: false, userInvocable: true },
|
||||
source: 'runtime',
|
||||
content: 'User-only instructions body.',
|
||||
})
|
||||
skills.register({
|
||||
name: 'model-only-skill',
|
||||
description: 'Model-only skill',
|
||||
invocation: { modelInvocable: true, userInvocable: false },
|
||||
source: 'runtime',
|
||||
content: 'Model-only instructions body.',
|
||||
})
|
||||
skills.register({
|
||||
name: 'trusted-only-skill',
|
||||
description: 'Trusted-only skill',
|
||||
invocation: { modelInvocable: false, userInvocable: false },
|
||||
source: 'runtime',
|
||||
content: 'Trusted-only instructions body.',
|
||||
})
|
||||
}
|
||||
|
||||
it('labels slash completions by scope and hides model-disabled skills', async () => {
|
||||
it('labels slash completions by scope and applies user invocation policy', async () => {
|
||||
const result = await setup({ configureContext: withSkills })
|
||||
result.terminal.send('/skill')
|
||||
await tick()
|
||||
@@ -3839,8 +3859,10 @@ describe('skill slash command', () => {
|
||||
expect(result.terminal.output).toContain('(user)')
|
||||
expect(result.terminal.output).toContain('project-skill')
|
||||
expect(result.terminal.output).toContain('(project)')
|
||||
expect(result.terminal.output).toContain('user-only-skill')
|
||||
expect(result.terminal.output).not.toContain('[instructions]')
|
||||
expect(result.terminal.output).not.toContain('hidden-skill')
|
||||
expect(result.terminal.output).not.toContain('model-only-skill')
|
||||
expect(result.terminal.output).not.toContain('trusted-only-skill')
|
||||
await dispose(result)
|
||||
})
|
||||
|
||||
@@ -3894,6 +3916,7 @@ describe('skill slash command', () => {
|
||||
return [{
|
||||
name: 'stable-skill',
|
||||
description: 'STABLE_COMPLETION_MARKER',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'test',
|
||||
provider: 'flaky-completion',
|
||||
rank: 1,
|
||||
@@ -3946,6 +3969,7 @@ describe('skill slash command', () => {
|
||||
skills: [{
|
||||
name: 'latest-skill',
|
||||
description: 'LATEST_COMPLETION_MARKER',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
}],
|
||||
@@ -3953,11 +3977,11 @@ describe('skill slash command', () => {
|
||||
})
|
||||
await tick()
|
||||
pendingSnapshots[0]?.resolve({
|
||||
skills: [{ name: 'stale-first', description: 'STALE_FIRST', source: 'runtime', provider: 'runtime' }],
|
||||
skills: [{ name: 'stale-first', description: 'STALE_FIRST', invocation: { modelInvocable: true, userInvocable: true }, source: 'runtime', provider: 'runtime' }],
|
||||
complete: true,
|
||||
})
|
||||
pendingSnapshots[1]?.resolve({
|
||||
skills: [{ name: 'stale-second', description: 'STALE_SECOND', source: 'runtime', provider: 'runtime' }],
|
||||
skills: [{ name: 'stale-second', description: 'STALE_SECOND', invocation: { modelInvocable: true, userInvocable: true }, source: 'runtime', provider: 'runtime' }],
|
||||
complete: true,
|
||||
})
|
||||
await tick()
|
||||
@@ -3986,12 +4010,62 @@ describe('skill slash command', () => {
|
||||
await dispose(result)
|
||||
})
|
||||
|
||||
it('invokes a model-disabled skill by its exact name', async () => {
|
||||
it('invokes a user-only skill by its exact name', async () => {
|
||||
const result = await setup({ configureContext: withSkills })
|
||||
result.terminal.send('/skill:hidden-skill')
|
||||
result.terminal.send('/skill:user-only-skill')
|
||||
result.terminal.send('\r')
|
||||
await tick()
|
||||
expect(result.agent.sent).toEqual([[{ type: 'text', text: '<skill name="hidden-skill">\nHidden instructions body.\n</skill>' }]])
|
||||
expect(result.agent.sent).toEqual([[{ type: 'text', text: '<skill name="user-only-skill">\nUser-only instructions body.\n</skill>' }]])
|
||||
await dispose(result)
|
||||
})
|
||||
|
||||
it('checks user policy before loading and rechecks the loaded definition', async () => {
|
||||
const summaries: SkillSummary[] = [
|
||||
{
|
||||
name: 'model-only-skill',
|
||||
description: 'Model-only skill',
|
||||
invocation: { modelInvocable: true, userInvocable: false },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
},
|
||||
{
|
||||
name: 'policy-race-skill',
|
||||
description: 'Policy race skill',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
},
|
||||
]
|
||||
const get = vi.fn((name: string) => Promise.resolve<SkillDefinition | undefined>({
|
||||
name,
|
||||
description: 'Policy race skill',
|
||||
invocation: { modelInvocable: true, userInvocable: false },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
content: 'Instructions must not be delivered.',
|
||||
}))
|
||||
const result = await setup({
|
||||
configureContext: async (ctx) => {
|
||||
ctx.provide('tools', { get() { return undefined } } as never)
|
||||
ctx.provide('skills', {
|
||||
snapshot: () => Promise.resolve({ skills: summaries, complete: true }),
|
||||
list: () => Promise.resolve(summaries),
|
||||
get,
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
result.terminal.send('/skill:model-only-skill')
|
||||
result.terminal.send('\r')
|
||||
await tick()
|
||||
result.terminal.send('/skill:policy-race-skill')
|
||||
result.terminal.send('\r')
|
||||
await tick()
|
||||
expect(result.agent.sent).toEqual([])
|
||||
expect(get).toHaveBeenCalledTimes(1)
|
||||
expect(get).toHaveBeenCalledWith('policy-race-skill', expect.objectContaining({ cwd: '/workspace' }))
|
||||
expect(result.terminal.output).toContain('Skill "model-only-skill" is not available for user invocation.')
|
||||
expect(result.terminal.output).toContain('Skill "policy-race-skill" is not available for user invocation.')
|
||||
expect(result.terminal.output).not.toContain('Instructions must not be delivered.')
|
||||
await dispose(result)
|
||||
})
|
||||
|
||||
@@ -4047,6 +4121,7 @@ describe('skill slash command', () => {
|
||||
ctx.provide('tools', { get() { return undefined } } as never)
|
||||
ctx.provide('skills', {
|
||||
snapshot: () => Promise.reject(new Error('list boom')),
|
||||
list: () => Promise.reject(new Error('list boom')),
|
||||
get: () => Promise.reject(new Error('get boom')),
|
||||
} as never)
|
||||
},
|
||||
@@ -4055,11 +4130,13 @@ describe('skill slash command', () => {
|
||||
result.terminal.send('\r')
|
||||
await tick()
|
||||
expect(result.terminal.output).toContain('failed to load')
|
||||
expect(result.terminal.output).toContain('get boom')
|
||||
expect(result.terminal.output).toContain('list boom')
|
||||
await dispose(result)
|
||||
})
|
||||
|
||||
it('drops skill list and lookup results that settle after disposal', async () => {
|
||||
let listCalls = 0
|
||||
let resolvePendingList: ((value: SkillSummary[]) => void) | undefined
|
||||
const pendingSnapshots: Array<(value: SkillCatalogSnapshot) => void> = []
|
||||
const pendingGet: Array<{ resolve: (value: SkillDefinition | undefined) => void; reject: (error: unknown) => void }> = []
|
||||
const result = await setup({
|
||||
@@ -4067,13 +4144,31 @@ describe('skill slash command', () => {
|
||||
ctx.provide('tools', { get() { return undefined } } as never)
|
||||
ctx.provide('skills', {
|
||||
snapshot: () => new Promise<SkillCatalogSnapshot>((resolve) => { pendingSnapshots.push(resolve) }),
|
||||
list: () => {
|
||||
listCalls += 1
|
||||
if (listCalls === 1 || listCalls === 2) {
|
||||
const name = listCalls === 1 ? 'demo-skill' : 'error-skill'
|
||||
return Promise.resolve<SkillSummary[]>([{
|
||||
name,
|
||||
description: 'demo',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
}])
|
||||
}
|
||||
return new Promise<SkillSummary[]>((resolve) => { resolvePendingList = resolve })
|
||||
},
|
||||
get: () => new Promise<SkillDefinition | undefined>((resolve, reject) => { pendingGet.push({ resolve, reject }) }),
|
||||
} as never)
|
||||
},
|
||||
})
|
||||
await tick()
|
||||
result.terminal.send('/skill:demo-skill')
|
||||
result.terminal.send('\r')
|
||||
await tick()
|
||||
result.terminal.send('/skill:error-skill')
|
||||
result.terminal.send('\r')
|
||||
await tick()
|
||||
result.terminal.send('/skill:other-skill')
|
||||
result.terminal.send('\r')
|
||||
await tick()
|
||||
@@ -4083,16 +4178,36 @@ describe('skill slash command', () => {
|
||||
expect(pendingSnapshots).toHaveLength(1)
|
||||
for (const resolve of pendingSnapshots) {
|
||||
resolve({
|
||||
skills: [{ name: 'late', description: 'late', source: 'runtime', provider: 'runtime' }],
|
||||
skills: [{
|
||||
name: 'late',
|
||||
description: 'late',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
}],
|
||||
complete: true,
|
||||
})
|
||||
}
|
||||
pendingGet[0]?.resolve({ name: 'demo-skill', description: 'late', source: 'runtime', provider: 'runtime', content: 'late body' })
|
||||
resolvePendingList?.([{
|
||||
name: 'other-skill',
|
||||
description: 'late',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
}])
|
||||
pendingGet[0]?.resolve({
|
||||
name: 'demo-skill',
|
||||
description: 'late',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
content: 'late body',
|
||||
})
|
||||
pendingGet[1]?.reject(new Error('late failure'))
|
||||
await tick()
|
||||
expect(result.agent.sent).toEqual([])
|
||||
expect(result.terminal.output).not.toContain('late failure')
|
||||
expect(result.terminal.output).not.toContain('late body')
|
||||
expect(result.terminal.output).not.toContain('late failure')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4100,6 +4215,7 @@ describe('renderSkillInvocation', () => {
|
||||
const skill: SkillDefinition = {
|
||||
name: 'demo-skill',
|
||||
description: 'Demo skill',
|
||||
invocation: { modelInvocable: true, userInvocable: true },
|
||||
source: 'runtime',
|
||||
provider: 'runtime',
|
||||
content: 'Body text.',
|
||||
|
||||
Reference in New Issue
Block a user