permission.ts 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. /**
  2. * `permissionExtension`: Installs the permission `PermissionEngine` through the
  3. * `@mavis/agent-runtime` extension SPI's `pi.on('before_tool_call')` short-circuit event (design
  4. * document §4.3).
  5. *
  6. * Boundary policy: `@mavis/permission` is a pure decision engine. `checkPermission(toolName, input,
  7. * ctx) => PermissionDecision` requires a host-provided `ToolPermissionContext` (including
  8. * host-specific rules / mode / sandbox state). This factory therefore accepts a host closure
  9. * `decide(toolName, input, toolCallCtx) => Promise<PermissionDecision>`. The extension only adapts
  10. * pi context to decision arguments and converts results. The host owns the engine's location:
  11. * local-runtime uses `LocalPermissionFacade`, cloud-runtime uses `CloudPermissionFacade`; the §4.3
  12. * table explicitly gives cloud a separate `cloud-permission` extension.
  13. *
  14. * Decision mapping (pi's `BeforeToolCallResult` only exposes `{ block?, reason? }`):
  15. * - `allow`: Write `rewrittenInput` back to live `toolContext.args`, then return `undefined` to
  16. * allow execution.
  17. * - `deny`: Return `{ block: true, reason }`. The host's `reason-format` generates reason for
  18. * UI/log consumption; without `formatReason`, fall back to raw JSON.stringify.
  19. * - `ask`: Default to `{ block: true, reason }`; the pi loop has no native ASK concept, so the
  20. * runtime blocks. **If the host provides `onAsk` and it returns a resolved `PermissionDecision`**
  21. * (the user actually approved/denied), map that decision instead (allow → undefined; deny/ask →
  22. * block). This seam lets the host implement ask fan-out as a blocking promise (UI prompt → user
  23. * click → resolve), applying the user's answer to this tool call. **If the host omits `onAsk` or
  24. * it returns `void`**, pi immediately sees a block and the LLM receives a denial. The UI must
  25. * dispatch ask through a separate event stream (e.g. an HTTP `/permissions` route returns
  26. * requestId and the LLM retries in a later turn). This is the current behavior of
  27. * `LocalPermissionFacade`.
  28. */
  29. import type { AgentExtension, BeforeToolCallHandler, ExtensionAPI } from '@mavis/agent-runtime';
  30. import type { PermissionDecision } from '@mavis/permission';
  31. /** Minimal shape captured from pi `BeforeToolCallContext` — subset actually needed by decision engines. */
  32. export interface PermissionToolCallSummary {
  33. readonly toolName: string;
  34. readonly input: Readonly<Record<string, unknown>>;
  35. }
  36. export type PermissionDecider = (
  37. summary: PermissionToolCallSummary,
  38. ) => PermissionDecision | Promise<PermissionDecision>;
  39. export interface PermissionExtensionOptions {
  40. readonly decide: PermissionDecider;
  41. /** Extension id override; default `'permission'` per design doc §4.3. */
  42. readonly id?: string;
  43. readonly description?: string;
  44. /**
  45. * Convert `PermissionDecision.reason` to a human-readable string embedded in
  46. * the pi `BeforeToolCallResult.reason` field. Defaults to `JSON.stringify`
  47. * on the reason object—hosts wanting the localized `reason-format` output
  48. * pass their own formatter here (e.g. `formatDecisionReason` from
  49. * `@mavis/permission`).
  50. *
  51. * Caveat: default JSON.stringify drops `Map` values (e.g. `subcommandResults`
  52. * in bash-decision reason variants) — host formatters should handle those
  53. * variants explicitly. Path values inside reason are not scrubbed here;
  54. * host formatters can redact if needed before logging.
  55. */
  56. readonly formatReason?: (
  57. decision: PermissionDecision,
  58. summary: PermissionToolCallSummary,
  59. ) => string;
  60. /**
  61. * Optional side-effect / resume seam for `ask` decisions. Two modes:
  62. *
  63. * - **fire-and-forget**: `onAsk` returns `void | Promise<void>`. The original ask is treated as
  64. * `block` and pi sees the tool call denied. Host must fan out the UI prompt on its own channel
  65. * and the LLM will retry the call in a subsequent turn.
  66. * - **await-resolve**: `onAsk` returns `Promise<PermissionDecision>`. The extension awaits it and
  67. * re-maps the resolved decision (allow → let the tool call through, deny / ask → block). This
  68. * lets a host wrap ask as a blocking UI prompt when the pi loop can tolerate the wait.
  69. *
  70. * The third argument is the pi turn's `AbortSignal`; blocking UI prompts should cancel their wait
  71. * when the turn aborts. `onAsk` errors are swallowed (block posture preserved); pass `onAskError`
  72. * to observe failures explicitly.
  73. */
  74. readonly onAsk?: (
  75. decision: PermissionDecision,
  76. summary: PermissionToolCallSummary,
  77. signal?: AbortSignal,
  78. ) => void | Promise<void | PermissionDecision | undefined>;
  79. /** Optional sink for `onAsk` failures — visibility on UI fan-out breakage. */
  80. readonly onAskError?: (
  81. error: unknown,
  82. summary: PermissionToolCallSummary,
  83. signal?: AbortSignal,
  84. ) => void | Promise<void>;
  85. }
  86. function defaultFormatReason(decision: PermissionDecision): string {
  87. try {
  88. return JSON.stringify(decision.reason);
  89. } catch {
  90. return String(decision.reason);
  91. }
  92. }
  93. function applyRewrittenInput(
  94. toolContext: Parameters<BeforeToolCallHandler>[0],
  95. rewrittenInput: Record<string, unknown> | undefined,
  96. ): void {
  97. if (!rewrittenInput) return;
  98. if (
  99. toolContext.args &&
  100. typeof toolContext.args === 'object' &&
  101. !Array.isArray(toolContext.args)
  102. ) {
  103. const target = toolContext.args as Record<string, unknown>;
  104. if (target === rewrittenInput) return;
  105. for (const key of Object.keys(target)) delete target[key];
  106. Object.assign(target, rewrittenInput);
  107. return;
  108. }
  109. toolContext.args = { ...rewrittenInput };
  110. }
  111. export function permissionExtension(options: PermissionExtensionOptions): AgentExtension {
  112. const { decide, formatReason = defaultFormatReason, onAsk, onAskError } = options;
  113. const id = options.id ?? 'permission';
  114. const description =
  115. options.description ??
  116. 'Enforce tool-call permission decisions (allow / deny / ask) via PermissionEngine before pi executes each tool.';
  117. function mapDecision(
  118. decision: PermissionDecision,
  119. summary: PermissionToolCallSummary,
  120. toolContext: Parameters<BeforeToolCallHandler>[0],
  121. fallbackRewrittenInput?: Record<string, unknown>,
  122. ): { block: true; reason: string } | undefined {
  123. if (decision.behavior === 'allow') {
  124. applyRewrittenInput(toolContext, decision.rewrittenInput ?? fallbackRewrittenInput);
  125. return undefined;
  126. }
  127. // deny / ask / any future variant → fail-closed block per AGENTS.md §5.
  128. // The default branch defends against `PermissionBehavior` growing new
  129. // variants without a matching mapDecision arm; today it's unreachable
  130. // (union is `'allow' | 'deny' | 'ask'`), which is exactly the invariant
  131. // this comment records.
  132. return { block: true, reason: formatReason(decision, summary) };
  133. }
  134. const handler: BeforeToolCallHandler = async (toolContext, signal) => {
  135. const summary: PermissionToolCallSummary = {
  136. toolName: toolContext.toolCall.name,
  137. input: (toolContext.args ?? {}) as Readonly<Record<string, unknown>>,
  138. };
  139. const decision = await decide(summary);
  140. if (decision.behavior === 'ask' && onAsk) {
  141. let resolved: PermissionDecision | undefined;
  142. try {
  143. const askResult = await onAsk(decision, summary, signal);
  144. if (askResult && typeof askResult === 'object' && 'behavior' in askResult) {
  145. resolved = askResult as PermissionDecision;
  146. }
  147. } catch (err) {
  148. if (onAskError) {
  149. try {
  150. await onAskError(err, summary, signal);
  151. } catch {
  152. // Observer error must not shadow the block posture.
  153. }
  154. }
  155. }
  156. const effective = resolved ?? decision;
  157. return mapDecision(effective, summary, toolContext, decision.rewrittenInput);
  158. }
  159. return mapDecision(decision, summary, toolContext);
  160. };
  161. return {
  162. id,
  163. description,
  164. init(pi: ExtensionAPI): void {
  165. pi.on('before_tool_call', handler);
  166. },
  167. };
  168. }