types.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /**
  2. * `@mavis/agent-runtime` — pluggable extension SPI + per-turn assembler on top of
  3. * `@mavis/agent-core`.
  4. *
  5. * Aligned with the `packages/agent-runtime` Feishu design document v1.0 after review. Key
  6. * constraints:
  7. * - Extensions must not import one another; host assembly load order alone determines execution
  8. * order.
  9. * - `assembleTurn(ctx)` only assembles contributions; the host constructs `RunTurnInput` from the
  10. * result.
  11. * - Registry state is in-memory only; the host owns persistence (e.g. `extensionOverrides`).
  12. *
  13. * Event names follow document §4.2, including `on_step_end` aligned with pi's current
  14. * step-completion semantics. `AssemblyResult.hooks` maps to agent-core's
  15. * `PiTurnHooks.onStepEndHook` (the preferred name introduced in §11.6 Step A). agent-core still
  16. * reads the deprecated per-step slot `onTurnEndHook`, but agent-runtime only writes the new,
  17. * semantically explicit field; see `HOOK_MAPPINGS` in `registry.ts`.
  18. */
  19. import type {
  20. PiAfterLlmCallHook,
  21. PiAfterLlmCallHookDecision,
  22. PiAfterLlmCallHookInput,
  23. PiAfterToolCallHook,
  24. PiBeforeLlmCallHook,
  25. PiBeforeLlmCallHookDecision,
  26. PiBeforeLlmCallHookInput,
  27. PiBeforeToolCallHook,
  28. PiHistoryChangedHookInput,
  29. PiLlmCallPreparedHookInput,
  30. PiOnHistoryChangedHook,
  31. PiOnStepEndHook,
  32. PiStepEndHookInput,
  33. PiTurnHooks,
  34. } from '@mavis/agent-core/pi-turn-runner';
  35. import type { RuntimeTool, ToolExecutionContext } from '@mavis/agent-core/tools';
  36. import type { AgentMessage as PiAgentMessage } from '@earendil-works/pi-agent-core';
  37. import type { TSchema } from '@sinclair/typebox';
  38. import type { PromptReadScope } from './prompt-read.js';
  39. /**
  40. * Pi runtime history projection used by both `TurnAssemblyCtx` and
  41. * `TurnStartEvent`. Matches what `PiTurnRunner.runTurn` consumes as `history`
  42. * and what pi's `on_history_changed` payload carries — pi's `AgentMessage`
  43. * union (User / Assistant / ToolResult with `role`-discriminated content),
  44. * NOT the flat `@mavis/agent-core/protocol` wire shape.
  45. */
  46. export type TurnHistoryProjection = readonly PiAgentMessage[];
  47. // ─────────────────────────── Utility types ────────────────────────────
  48. export type MaybePromise<T> = T | Promise<T>;
  49. // ─────────────────────────── Turn assembly ctx ────────────────────────
  50. /**
  51. * Read-only per-turn context exposed to extensions. **Intentionally excludes** `eventWriter`,
  52. * `llm`, `signal`, and `toolContext`, which belong to the host. See document §6.2 for the minimal
  53. * field set.
  54. *
  55. * `agentConfig` / `model` are declared only as `Readonly<unknown>` to keep agent-runtime neutral to
  56. * host-specific schemas (local-runtime's `AgentConfigRecord`, cloud-runtime's `ResolvedModel`).
  57. * Extensions assert types when they need specific fields.
  58. */
  59. export interface UserMessageContribution {
  60. readonly text: string;
  61. }
  62. /**
  63. * Secret-free, host-validated product intent for the current Turn. Extensions
  64. * may use it to activate an explicit workflow without receiving raw ingress
  65. * provenance or transport-owned metadata.
  66. */
  67. export interface TurnIntent {
  68. readonly kind: string;
  69. readonly attributes?: Readonly<Record<string, string>>;
  70. }
  71. export interface ModelContextAssemblyCtx {
  72. readonly sessionId: string;
  73. readonly turnId: string;
  74. readonly agentName: string;
  75. readonly workspaceDir: string;
  76. readonly agentConfig: Readonly<Record<string, unknown>>;
  77. readonly model: Readonly<Record<string, unknown>>;
  78. /**
  79. * pi runtime history for this turn — see `TurnHistoryProjection` for shape.
  80. */
  81. readonly history: TurnHistoryProjection;
  82. readonly userInput?: UserMessageContribution;
  83. readonly turnIntent?: TurnIntent;
  84. readonly plan?: {
  85. readonly active: true;
  86. readonly canonicalPath: string;
  87. };
  88. /**
  89. * Optional host-captured template snapshot for this model call. Extensions
  90. * use it only for their managed prompt keys; its absence preserves bundled
  91. * prompt behavior for hosts that have not opted into dynamic templates.
  92. */
  93. readonly promptRead?: PromptReadScope;
  94. // Per-profile config lives on `ExtensionAPI.params` (document §4.4 line 281 + §5 line 749),
  95. // not TurnAssemblyCtx, preserving the minimal read-only projection in §6.2.
  96. }
  97. export interface TurnAssemblyCtx extends ModelContextAssemblyCtx {
  98. readonly userInput: UserMessageContribution;
  99. /** Host-captured output requirements; no credentials or mutable Runtime configuration. */
  100. readonly outputContract?: {
  101. readonly schema?: Readonly<Record<string, unknown>>;
  102. readonly revisionInstruction?: string;
  103. };
  104. }
  105. // ─────────────────────────── Tool contribution ────────────────────────
  106. /**
  107. * Per-turn dynamic tool factory used by `registerTool(fn)`. Return `null` to contribute no tool
  108. * this turn, or an array to contribute a whole domain catalog at once (e.g. local native + MCP
  109. * progressive disclosure).
  110. */
  111. export type RuntimeToolFactory<
  112. S extends TSchema = TSchema,
  113. TCtx extends ToolExecutionContext = ToolExecutionContext,
  114. > = (
  115. ctx: ModelContextAssemblyCtx,
  116. ) => MaybePromise<RuntimeTool<S, TCtx> | readonly RuntimeTool<S, TCtx>[] | null>;
  117. export type RuntimeToolContribution<
  118. S extends TSchema = TSchema,
  119. TCtx extends ToolExecutionContext = ToolExecutionContext,
  120. > = RuntimeTool<S, TCtx> | RuntimeToolFactory<S, TCtx>;
  121. // ─────────────────────────── Prompt / reminder ────────────────────────
  122. export type PromptContributor<TContext extends ModelContextAssemblyCtx = TurnAssemblyCtx> = (
  123. ctx: TContext,
  124. ) => MaybePromise<string | null | undefined>;
  125. export type SystemPromptContributor = PromptContributor<ModelContextAssemblyCtx>;
  126. export type UserPromptContributor = PromptContributor<TurnAssemblyCtx>;
  127. export interface Reminder {
  128. /**
  129. * Exactly one non-empty rendered `<system-reminder>...</system-reminder>`
  130. * block. Raw, nested (including self-closing/attributed same-name tags),
  131. * prefixed, suffixed, or multiple blocks are malformed.
  132. * The host preserves provider order and must not add another wrapper.
  133. */
  134. readonly content: string;
  135. readonly priority?: number;
  136. readonly cooldownKey?: string;
  137. }
  138. export interface ReminderProvider {
  139. readonly name: string;
  140. compute(ctx: TurnAssemblyCtx): MaybePromise<Reminder | null | undefined>;
  141. }
  142. // ─────────────────────────── Hook / event names ───────────────────────
  143. export const HOOK_NAMES = [
  144. 'turn_start',
  145. 'turn_end',
  146. 'on_history_changed',
  147. 'before_llm_call',
  148. 'on_llm_call_prepared',
  149. 'after_llm_call',
  150. 'before_tool_call',
  151. 'after_tool_call',
  152. 'on_step_end',
  153. ] as const;
  154. export type HookName = (typeof HOOK_NAMES)[number];
  155. // ─────────────────────────── Turn / step events ───────────────────────
  156. export interface TurnStartEvent {
  157. readonly sessionId: string;
  158. readonly turnId: string;
  159. readonly agentName: string;
  160. readonly workspaceDir: string;
  161. /**
  162. * pi runtime history for this turn — see `TurnHistoryProjection` for shape.
  163. */
  164. readonly history: TurnHistoryProjection;
  165. readonly userInput: UserMessageContribution;
  166. }
  167. export interface TurnEndEvent {
  168. readonly sessionId: string;
  169. readonly turnId: string;
  170. readonly agentName: string;
  171. readonly workspaceDir: string;
  172. /** Terminal reason exposed by host; see `TurnResult` in pi-turn-runner. */
  173. readonly reason?: string;
  174. }
  175. // ─────────────────────────── Handler shapes ───────────────────────────
  176. export type ExtensionHandler<E, R = void> = (event: E, ctx: TurnAssemblyCtx) => MaybePromise<R>;
  177. export type TurnStartHandler = ExtensionHandler<TurnStartEvent, void>;
  178. export type TurnEndHandler = ExtensionHandler<TurnEndEvent, void>;
  179. export type HistoryChangedHandler = ExtensionHandler<PiHistoryChangedHookInput, void>;
  180. /**
  181. * Step-level handlers reuse existing `agent-core` hook input types, keeping one contract instead of
  182. * redefining pi's per-step payloads in the SPI.
  183. */
  184. export type BeforeLlmCallHandler = ExtensionHandler<
  185. PiBeforeLlmCallHookInput,
  186. PiBeforeLlmCallHookDecision | void | undefined
  187. >;
  188. /** Observation only. Core isolates failures and invokes this once per logical agent call. */
  189. export type LlmCallPreparedHandler = ExtensionHandler<PiLlmCallPreparedHookInput, void>;
  190. export type AfterLlmCallHandler = ExtensionHandler<
  191. PiAfterLlmCallHookInput,
  192. PiAfterLlmCallHookDecision | void | undefined
  193. >;
  194. /**
  195. * Tool hook handlers receive the immutable per-turn assembly context as a
  196. * third argument. The registry closes it over when adapting back to Pi's
  197. * two-argument hook contract, so existing two-argument handlers remain
  198. * source-compatible while extensions that persist artifacts can identify the
  199. * owning session/turn without reaching into Pi internals.
  200. */
  201. export type BeforeToolCallHandler = (
  202. input: Parameters<PiBeforeToolCallHook>[0],
  203. signal: Parameters<PiBeforeToolCallHook>[1],
  204. ctx: TurnAssemblyCtx,
  205. ) => ReturnType<PiBeforeToolCallHook>;
  206. export type AfterToolCallHandler = (
  207. input: Parameters<PiAfterToolCallHook>[0],
  208. signal: Parameters<PiAfterToolCallHook>[1],
  209. ctx: TurnAssemblyCtx,
  210. ) => ReturnType<PiAfterToolCallHook>;
  211. export type StepEndHandler = ExtensionHandler<PiStepEndHookInput, void>;
  212. /**
  213. * Event name → handler type map. Consumed by `Registry` to type its internal
  214. * `Record<HookName, Array<HandlerFor<K>>>` storage so read-side casts to
  215. * per-event handler arrays remain type-safe end-to-end. Extending
  216. * `HOOK_NAMES` requires adding the matching entry here — TS enforces
  217. * exhaustiveness via `HookHandlerMap[HookName]`.
  218. */
  219. export interface HookHandlerMap {
  220. turn_start: TurnStartHandler;
  221. turn_end: TurnEndHandler;
  222. on_history_changed: HistoryChangedHandler;
  223. before_llm_call: BeforeLlmCallHandler;
  224. on_llm_call_prepared: LlmCallPreparedHandler;
  225. after_llm_call: AfterLlmCallHandler;
  226. before_tool_call: BeforeToolCallHandler;
  227. after_tool_call: AfterToolCallHandler;
  228. on_step_end: StepEndHandler;
  229. }
  230. export type HandlerFor<K extends HookName> = HookHandlerMap[K];
  231. // ─────────────────────────── ExtensionAPI ─────────────────────────────
  232. export interface ExtensionAPI {
  233. /**
  234. * Per-profile params merged from `ProfileOverlay.param` (document §4.4 line 281 / §5 line 749:
  235. * per-profile config read during extension init). Extensions read them in `init`, for example to
  236. * select behavior or consume host flags. An empty object means the profile has no overlay or no
  237. * param definition.
  238. */
  239. readonly params: Readonly<Record<string, unknown>>;
  240. registerTool<
  241. S extends TSchema = TSchema,
  242. TCtx extends ToolExecutionContext = ToolExecutionContext,
  243. >(
  244. contribution: RuntimeToolContribution<S, TCtx>,
  245. ): void;
  246. contributeSystemPrompt(fn: SystemPromptContributor): void;
  247. contributeUserPromptPrefix(fn: UserPromptContributor): void;
  248. registerReminderProvider(provider: ReminderProvider): void;
  249. // Turn level
  250. on(event: 'turn_start', handler: TurnStartHandler): void;
  251. on(event: 'turn_end', handler: TurnEndHandler): void;
  252. on(event: 'on_history_changed', handler: HistoryChangedHandler): void;
  253. // Step level
  254. on(event: 'before_llm_call', handler: BeforeLlmCallHandler): void;
  255. on(event: 'on_llm_call_prepared', handler: LlmCallPreparedHandler): void;
  256. on(event: 'after_llm_call', handler: AfterLlmCallHandler): void;
  257. on(event: 'before_tool_call', handler: BeforeToolCallHandler): void;
  258. on(event: 'after_tool_call', handler: AfterToolCallHandler): void;
  259. on(event: 'on_step_end', handler: StepEndHandler): void;
  260. /**
  261. * Generic fallback overload—consumed by `wireHandlers` and any table-driven
  262. * caller that iterates `HOOK_NAMES`. Individual per-event overloads above
  263. * still apply for call sites that pass a literal event name (better error
  264. * messages). Type-safety is preserved by `HandlerFor<K>` throughout the
  265. * pipeline.
  266. */
  267. on<K extends HookName>(event: K, handler: HandlerFor<K>): void;
  268. }
  269. // ─────────────────────────── Extension shape ──────────────────────────
  270. export interface AgentExtension {
  271. /** Open string identifier: extension sets are host/plugin-defined, not a closed enum. */
  272. readonly id: string;
  273. /** Control-plane label returned by `listExtensions`; never affects execution semantics. */
  274. readonly description?: string;
  275. init(pi: ExtensionAPI): MaybePromise<void>;
  276. }
  277. // ─────────────────────────── Assembly result ──────────────────────────
  278. export interface ReminderEmission {
  279. readonly providerName: string;
  280. readonly reminder: Reminder;
  281. }
  282. export interface AssemblyDiagnostic {
  283. readonly loadedExtensions: readonly string[];
  284. readonly enabledExtensions: readonly string[];
  285. readonly disabledExtensions: readonly string[];
  286. readonly toolCount: number;
  287. readonly reminderCount: number;
  288. }
  289. /**
  290. * `PiTurnHooks` covers agent-core's existing step-level contract; the host explicitly consumes turn
  291. * lifecycle handlers as raw arrays. This lets agent-runtime land without modifying
  292. * `@mavis/agent-core` (see document §11.6 migration strategy).
  293. */
  294. export interface AssemblyResult<TCtx extends ToolExecutionContext = ToolExecutionContext> {
  295. readonly systemPromptPrefix: string;
  296. readonly userPromptPrefix: string;
  297. readonly tools: readonly RuntimeTool<TSchema, TCtx>[];
  298. readonly hooks: PiTurnHooks;
  299. readonly reminders: readonly ReminderEmission[];
  300. readonly turnStartHandlers: readonly TurnStartHandler[];
  301. readonly turnEndHandlers: readonly TurnEndHandler[];
  302. readonly diagnostic: AssemblyDiagnostic;
  303. }
  304. export interface ModelContextAssemblyResult<
  305. TCtx extends ToolExecutionContext = ToolExecutionContext,
  306. > {
  307. readonly systemPromptPrefix: string;
  308. readonly tools: readonly RuntimeTool<TSchema, TCtx>[];
  309. }
  310. export interface ModelContextAssemblySeed {
  311. readonly tools: readonly RuntimeTool[];
  312. }
  313. export interface TurnAssemblySeed extends ModelContextAssemblySeed {
  314. readonly userPromptPrefix: string;
  315. }
  316. // ─────────────────────────── Registry state view ──────────────────────
  317. export interface ExtensionContributionStats {
  318. readonly tools: number;
  319. readonly promptContributors: number;
  320. readonly reminderProviders: number;
  321. readonly hooks: Readonly<Record<HookName, number>>;
  322. }
  323. export interface ExtensionState {
  324. readonly id: string;
  325. /** Human-readable control-plane metadata copied from `AgentExtension.description`. */
  326. readonly description?: string;
  327. readonly enabled: boolean;
  328. readonly contributions: ExtensionContributionStats;
  329. }
  330. export interface EnabledScope {
  331. readonly sessionId?: string;
  332. }
  333. // ─────────────────────────── Runtime API ──────────────────────────────
  334. export interface AgentRuntime {
  335. assembleModelContext(
  336. ctx: ModelContextAssemblyCtx,
  337. seed?: ModelContextAssemblySeed,
  338. ): Promise<ModelContextAssemblyResult>;
  339. assembleTurn(ctx: TurnAssemblyCtx, seed?: TurnAssemblySeed): Promise<AssemblyResult>;
  340. setEnabled(extensionId: string, enabled: boolean, scope?: EnabledScope): void;
  341. listExtensions(scope?: EnabledScope): ExtensionState[];
  342. disposeSession(sessionId: string): void;
  343. }
  344. // ─────────────────────────── Runtime options ──────────────────────────
  345. export interface ProfileOverlay {
  346. readonly enable?: readonly string[];
  347. readonly disable?: readonly string[];
  348. readonly replace?: Readonly<Record<string, string>>;
  349. readonly param?: Readonly<Record<string, unknown>>;
  350. }
  351. export interface RuntimeOptions {
  352. readonly base: readonly AgentExtension[];
  353. readonly additions?: readonly AgentExtension[];
  354. readonly overlays?: Readonly<Record<string, ProfileOverlay>>;
  355. readonly profile?: string;
  356. }
  357. // ─────────────────────────── Re-exports ───────────────────────────────
  358. export type {
  359. PiAfterLlmCallHook,
  360. PiAfterLlmCallHookDecision,
  361. PiAfterLlmCallHookInput,
  362. PiAfterToolCallHook,
  363. PiBeforeLlmCallHook,
  364. PiBeforeLlmCallHookDecision,
  365. PiBeforeLlmCallHookInput,
  366. PiBeforeToolCallHook,
  367. PiHistoryChangedHookInput,
  368. PiOnHistoryChangedHook,
  369. PiOnStepEndHook,
  370. PiStepEndHookInput,
  371. PiTurnHooks,
  372. };