skills.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. /**
  2. * `skillsExtension`: Installs `SkillRegistry` through the `@mavis/agent-runtime` extension SPI
  3. * (design document §4.3 → `pi.registerTool + pi.registerReminderProvider`).
  4. *
  5. * Deviation from the §4.3 table: skills' `registerTool` refers to the host-side `skill` file reader
  6. * (reading SKILL.md). Catalog rendering adds an adapter-level `contributeSystemPrompt` contribution
  7. * beyond the original table. The host already manually assembles `<available_skills>` into its
  8. * system prompt; this extension moves that declarative portion to the SPI. The `skill` IO tool
  9. * remains host-owned because file reads are not purely declarative; a full migration will add it
  10. * via `pi.registerTool`.
  11. *
  12. * Minimal adapter responsibilities:
  13. * 1. Read `SkillRegistry.getSnapshot()` per turn, render catalog text with
  14. * `renderAvailableSkillsCatalog`, and inject it through `pi.contributeSystemPrompt`. This matches
  15. * current host catalog assembly (`<available_skills>`); the default wrapper is byte-for-byte
  16. * aligned with `packages/local-runtime/src/skills/builtin.ts`.
  17. * 2. Optionally register a reminder provider: when the host supplies `matcher(userInput, snapshot)
  18. * => Reminder | null`, evaluate skill-match reminders per turn, equivalent to the host's existing
  19. * `skillMatchReminderProvider`.
  20. *
  21. * The host defines the `skill` tool (`packages/local-runtime/src/tools/skill-tool.ts`) because it
  22. * reads filesystem SKILL.md files. This extension registers no tool, only the declarative catalog +
  23. * reminder portions. A future host SPI migration will register the skill tool via
  24. * `pi.registerTool`, matching the §4.3 table's semantics.
  25. *
  26. * The host constructs and passes in `SkillRegistry` and retains its lifecycle (`refresh()`
  27. * scheduling, watcher shutdown, etc.). Each extension instance weakly caches its first snapshot by
  28. * `TurnAssemblyCtx` identity: the same context represents one assembly / turn, so the catalog
  29. * contributor and reminder matcher must see the same version. Different contexts do not share a
  30. * cache; snapshots can be collected with their contexts.
  31. */
  32. import type {
  33. AgentExtension,
  34. ExtensionAPI,
  35. ModelContextAssemblyCtx,
  36. Reminder,
  37. TurnAssemblyCtx,
  38. } from '@mavis/agent-runtime';
  39. import {
  40. renderAvailableSkillsCatalog,
  41. type SkillRegistry,
  42. type SkillRenderOptions,
  43. type SkillSnapshot,
  44. } from '@mavis/skills';
  45. export type SkillMatcher = (
  46. ctx: TurnAssemblyCtx,
  47. snapshot: SkillSnapshot | undefined,
  48. ) => Reminder | null | undefined | Promise<Reminder | null | undefined>;
  49. export interface SkillsExtensionOptions {
  50. readonly registry: SkillRegistry;
  51. /** Extension id override; default `'skills'` per design doc §4.3. */
  52. readonly id?: string;
  53. readonly description?: string;
  54. /**
  55. * `renderAvailableSkillsCatalog` options (budgetChars / externalDescriptionChars).
  56. * Static per-runtime; per-profile budget differences go through overlays.
  57. */
  58. readonly renderOptions?: SkillRenderOptions;
  59. /**
  60. * When the rendered catalog is embedded into the system prompt, wrap it in
  61. * this header. Contract:
  62. * - default (undefined) → wraps in `<available_skills>\n...\n</available_skills>`
  63. * (matches `packages/local-runtime/src/skills/builtin.ts` legacy shape).
  64. * - `null` → no wrapper; raw catalog text.
  65. * - string → **must be `<tagName>` form**. The close tag is derived by
  66. * stripping the angle brackets; passing an open tag with attributes
  67. * (`<available_skills version="1">`) will drop the attributes from the
  68. * close tag, and passing a bare `foo` yields the asymmetric
  69. * `foo\n...\n</foo>` — validated by the caller.
  70. */
  71. readonly header?: string | null;
  72. /**
  73. * Optional per-turn skill-match reminder. Host implements the actual match
  74. * logic against `ctx.userInput.text` / `snapshot.entries`.
  75. */
  76. readonly matcher?: SkillMatcher;
  77. /** Reminder provider name override; default `'skills-match'`. */
  78. readonly matchProviderName?: string;
  79. }
  80. const DEFAULT_HEADER = '<available_skills>';
  81. const DEFAULT_HEADER_CLOSE = '</available_skills>';
  82. function wrapCatalog(catalog: string, header: string | null | undefined): string {
  83. if (catalog.length === 0) return '';
  84. if (header === null) return catalog;
  85. if (header === undefined) return `${DEFAULT_HEADER}\n${catalog}\n${DEFAULT_HEADER_CLOSE}`;
  86. const tagName = header.replace(/^<|>$/g, '').replace(/\s.*$/, '');
  87. return `${header}\n${catalog}\n</${tagName}>`;
  88. }
  89. export function skillsExtension(options: SkillsExtensionOptions): AgentExtension {
  90. const { registry, renderOptions, header, matcher } = options;
  91. const id = options.id ?? 'skills';
  92. const description =
  93. options.description ??
  94. 'Render the available-skills catalog into system prompt and optionally emit a skill-match reminder per turn.';
  95. const providerName = options.matchProviderName ?? 'skills-match';
  96. const snapshotsByAssemblyCtx = new WeakMap<ModelContextAssemblyCtx, SkillSnapshot | undefined>();
  97. const snapshotFor = (ctx: ModelContextAssemblyCtx): SkillSnapshot | undefined => {
  98. if (snapshotsByAssemblyCtx.has(ctx)) return snapshotsByAssemblyCtx.get(ctx);
  99. const snapshot = registry.getSnapshot();
  100. snapshotsByAssemblyCtx.set(ctx, snapshot);
  101. return snapshot;
  102. };
  103. return {
  104. id,
  105. description,
  106. init(pi: ExtensionAPI): void {
  107. pi.contributeSystemPrompt((ctx) => {
  108. const snapshot = snapshotFor(ctx);
  109. if (!snapshot || snapshot.winners.length === 0) return null;
  110. const rendered = renderAvailableSkillsCatalog(snapshot, renderOptions ?? {});
  111. return wrapCatalog(rendered.catalog, header);
  112. });
  113. if (matcher) {
  114. pi.registerReminderProvider({
  115. name: providerName,
  116. async compute(ctx) {
  117. const snapshot = snapshotFor(ctx);
  118. const result = await matcher(ctx, snapshot);
  119. return result ?? null;
  120. },
  121. });
  122. }
  123. },
  124. };
  125. }