factories.ts 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /**
  2. * Extension factory helpers let hosts wrap plain objects as `AgentExtension` in one call, avoiding
  3. * repeated `{ id, description, init(pi) { pi.registerXxx(...) } }` boilerplate.
  4. *
  5. * The design document §4.3 table lists eight extensions (`permission / context-manager / memory /
  6. * system-reminder / mcp-disclosure / desktop-tools / skills / internal-tool-handlers`).
  7. * Module-to-SPI adapters for `context-manager / system-reminder / permission / skills` are exported
  8. * centrally by `@mavis/agent-extension`. Thin wrappers for host-only behavior such as
  9. * `mcp-disclosure / desktop-tools / internal-tool-handlers / memory / output-review-preface` can
  10. * use these generic factories around existing host helpers such as `hookService.beforeToolCall` /
  11. * `mcpDisclosureOptions`, without a separate module-level factory for each host-only module.
  12. *
  13. * Example (local-runtime host assembly):
  14. *
  15. * const userHooksExtension = createHookExtension({
  16. * id: 'internal-tool-handlers',
  17. * description: 'Product-internal tool handlers (before/after tool)',
  18. * handlers: {
  19. * before_tool_call: (toolContext) => hookService.beforeToolCall({ toolContext }),
  20. * after_tool_call: (toolContext) => hookService.afterToolCall({ toolContext }),
  21. * },
  22. * });
  23. *
  24. * const mcpDisclosureExtension = createToolExtension({
  25. * id: 'mcp-disclosure',
  26. * description: 'Per-turn dynamic MCP tool exposure via progressive disclosure',
  27. * tools: [(ctx) => resolveMcpDisclosureTool(ctx, mcpDisclosureOptions)],
  28. * });
  29. *
  30. * All factories are pure; the host manages the lifecycle of captured host state.
  31. */
  32. import type {
  33. AgentExtension,
  34. ExtensionAPI,
  35. HandlerFor,
  36. HookName,
  37. ModelContextAssemblyCtx,
  38. PromptContributor,
  39. ReminderProvider,
  40. RuntimeToolContribution,
  41. SystemPromptContributor,
  42. TurnAssemblyCtx,
  43. UserPromptContributor,
  44. } from './types.js';
  45. import { HOOK_NAMES } from './types.js';
  46. /**
  47. * Shared handler-bucket shape used by both `createHookExtension` and the
  48. * composite `createExtension`. Derived from `HookHandlerMap` in `types.ts` so
  49. * `HOOK_NAMES` + `HookHandlerMap` are the single sources of truth—adding a
  50. * new SPI event never requires editing this file. Each field accepts a single
  51. * handler or an array (host convenience).
  52. */
  53. export type HookHandlers = {
  54. readonly [K in HookName]?: HandlerFor<K> | readonly HandlerFor<K>[];
  55. };
  56. /**
  57. * `createToolExtension`: Expose a host's static tools or per-turn tool factories as an extension.
  58. * Equivalent to calling `pi.registerTool(...)` for each tool.
  59. */
  60. export interface CreateToolExtensionOptions {
  61. readonly id: string;
  62. readonly description?: string;
  63. readonly tools: readonly RuntimeToolContribution[];
  64. /** Optional pre-init hook for host-side setup (metrics, warmup) at extension load. */
  65. readonly onInit?: (pi: ExtensionAPI) => void | Promise<void>;
  66. }
  67. export function createToolExtension(options: CreateToolExtensionOptions): AgentExtension {
  68. const { id, description, tools, onInit } = options;
  69. return {
  70. id,
  71. description,
  72. async init(pi) {
  73. if (onInit) await onInit(pi);
  74. for (const tool of tools) {
  75. pi.registerTool(tool);
  76. }
  77. },
  78. };
  79. }
  80. /**
  81. * `createHookExtension`: Expose a host's lifecycle hooks (e.g. external coding-agent
  82. * internal-tool-handlers) as an extension. All lifecycle events are optional.
  83. */
  84. export interface CreateHookExtensionOptions {
  85. readonly id: string;
  86. readonly description?: string;
  87. readonly handlers?: HookHandlers;
  88. }
  89. /**
  90. * Wire every non-empty handler bucket onto `pi.on(event, handler)`. Iterates
  91. * `HOOK_NAMES` so adding a new SPI event only requires extending that array
  92. * plus `HookHandlerMap` in `types.ts`—no per-factory shotgun edit. Uses the
  93. * generic `ExtensionAPI.on<K>` overload so the per-event handler type stays
  94. * type-safe at every call site.
  95. */
  96. function wireHandlers(pi: ExtensionAPI, handlers: HookHandlers): void {
  97. for (const name of HOOK_NAMES) {
  98. const bucket = handlers[name] as
  99. | HandlerFor<typeof name>
  100. | readonly HandlerFor<typeof name>[]
  101. | undefined;
  102. if (bucket === undefined) continue;
  103. const list = Array.isArray(bucket) ? bucket : [bucket];
  104. for (const h of list) pi.on(name, h);
  105. }
  106. }
  107. export function createHookExtension(options: CreateHookExtensionOptions): AgentExtension {
  108. const { id, description, handlers } = options;
  109. return {
  110. id,
  111. description,
  112. init(pi) {
  113. if (handlers) wireHandlers(pi, handlers);
  114. },
  115. };
  116. }
  117. /**
  118. * `createPromptExtension`: Wrap static host system/user prompt prefixes as an extension. Equivalent
  119. * to `pi.contributeSystemPrompt(fn) + pi.contributeUserPromptPrefix(fn)`. Primarily wraps
  120. * `output-review-preface` constants such as `Read the last review carefully before your next
  121. * assistant turn.`
  122. */
  123. export interface CreatePromptExtensionOptions {
  124. readonly id: string;
  125. readonly description?: string;
  126. readonly systemPrompt?: SystemPromptContributor | string;
  127. readonly userPromptPrefix?: UserPromptContributor | string;
  128. }
  129. function toContributor<TContext extends ModelContextAssemblyCtx>(
  130. v: PromptContributor<TContext> | string | undefined,
  131. ): PromptContributor<TContext> | undefined {
  132. if (v === undefined) return undefined;
  133. return typeof v === 'string' ? () => v : v;
  134. }
  135. export function createPromptExtension(options: CreatePromptExtensionOptions): AgentExtension {
  136. const { id, description, systemPrompt, userPromptPrefix } = options;
  137. const systemFn = toContributor<ModelContextAssemblyCtx>(systemPrompt);
  138. const userFn = toContributor<TurnAssemblyCtx>(userPromptPrefix);
  139. return {
  140. id,
  141. description,
  142. init(pi) {
  143. if (systemFn) pi.contributeSystemPrompt(systemFn);
  144. if (userFn) pi.contributeUserPromptPrefix(userFn);
  145. },
  146. };
  147. }
  148. /**
  149. * `createReminderExtension`: Wrap a host's reminder providers as an extension (`memory`, custom
  150. * host reminder packs, etc.).
  151. */
  152. export interface CreateReminderExtensionOptions {
  153. readonly id: string;
  154. readonly description?: string;
  155. readonly providers: readonly ReminderProvider[];
  156. }
  157. export function createReminderExtension(options: CreateReminderExtensionOptions): AgentExtension {
  158. const { id, description, providers } = options;
  159. return {
  160. id,
  161. description,
  162. init(pi) {
  163. for (const provider of providers) {
  164. pi.registerReminderProvider(provider);
  165. }
  166. },
  167. };
  168. }
  169. /**
  170. * `createExtension` —— composite catch-all when an extension mixes contributions
  171. * across categories. Design doc §4.3 has a natural composite:
  172. * - `mcp-disclosure` → `registerTool` (per-turn factory) + `contributeUserPromptPrefix`
  173. * Hand-rolling `{ id, init }` works but this catch-all keeps everything in one
  174. * option bag so hosts don't have to spread across multiple extensions (which
  175. * would leak internal ids like `mcp-disclosure-tool` / `-prompt` into the
  176. * `listExtensions` / `setEnabled` UX).
  177. */
  178. export interface CreateExtensionOptions {
  179. readonly id: string;
  180. readonly description?: string;
  181. readonly tools?: readonly RuntimeToolContribution[];
  182. readonly systemPrompt?: SystemPromptContributor | string;
  183. readonly userPromptPrefix?: UserPromptContributor | string;
  184. readonly reminderProviders?: readonly ReminderProvider[];
  185. readonly handlers?: HookHandlers;
  186. /** Pre-init hook — runs before any pi.registerXxx / pi.on call. */
  187. readonly onInit?: (pi: ExtensionAPI) => void | Promise<void>;
  188. }
  189. export function createExtension(options: CreateExtensionOptions): AgentExtension {
  190. const {
  191. id,
  192. description,
  193. tools = [],
  194. systemPrompt,
  195. userPromptPrefix,
  196. reminderProviders = [],
  197. handlers,
  198. onInit,
  199. } = options;
  200. const systemFn = toContributor<ModelContextAssemblyCtx>(systemPrompt);
  201. const userFn = toContributor<TurnAssemblyCtx>(userPromptPrefix);
  202. return {
  203. id,
  204. description,
  205. async init(pi) {
  206. if (onInit) await onInit(pi);
  207. for (const tool of tools) pi.registerTool(tool);
  208. if (systemFn) pi.contributeSystemPrompt(systemFn);
  209. if (userFn) pi.contributeUserPromptPrefix(userFn);
  210. for (const provider of reminderProviders) pi.registerReminderProvider(provider);
  211. if (handlers) wireHandlers(pi, handlers);
  212. },
  213. };
  214. }