api.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import {
  2. classifySafetyTransportError,
  3. isSafetyCheckV2Record,
  4. } from "@mavis/shared/safety-check-v2";
  5. import { createSafetyFailureReporter } from "./diagnostics.js";
  6. import {
  7. getRuntimeBuildEnv,
  8. getRuntimeRegion,
  9. type MavisBuildEnv,
  10. type MavisRegion,
  11. } from "@mavis/config";
  12. import { callTurnSafetyApi } from "./turn-api.js";
  13. import { resolveSafetyApiBase } from "./api-base.js";
  14. import type { LocalRuntimeAuthContext } from "../runtime/model-resolver.js";
  15. import {
  16. managedBackendRoutingHeaders,
  17. type LocalRuntimeRoutingContext,
  18. } from "../runtime/routing-headers.js";
  19. export { resolveSafetyApiBase } from "./api-base.js";
  20. export type SafetyCheckResult = {
  21. pass: boolean;
  22. reason?: string;
  23. suggestion?: string;
  24. /** Model-only guidance; never serialize it to a user-facing response. */
  25. guide_prompt?: string;
  26. action?: "allow" | "reject" | "replace" | "guide";
  27. /** Retry the same failed V2 output review without returning to a V1 window check. */
  28. retryWithV2?: boolean;
  29. /**
  30. * Why a `pass:false` result is not always a policy verdict:
  31. * - `rejected` — the gateway DID review and rejected the content.
  32. * - `api_error` — the gateway responded but with a genuine service-side
  33. * degradation: a 5xx, or an explicit `errorCode:50200` service-unavailable
  34. * body. We reached the gateway; it just could not review right now.
  35. * - `local_error` — we never got a usable verdict because transport failed,
  36. * the response was unusable, or a non-auth 4xx rejected the request.
  37. * - `auth_error` — the gateway returned 401/403 for missing or expired auth.
  38. *
  39. * ONE fail policy everywhere (see `reviewBlocks`): `rejected`, `local_error`, and `auth_error`
  40. * BLOCK (fail closed — if we have no verdict, or an auth failure, we cannot
  41. * confirm the content is safe, so we never let it through), while `api_error`
  42. * DEGRADE-PASSES for legacy V1 checks. V2 errors are mapped to local_error or
  43. * auth_error and always fail closed. Consumers that
  44. * need something other than a block decision (e.g. the desktop route mapping to
  45. * an error code) read `errorKind` directly.
  46. */
  47. errorKind?: "rejected" | "api_error" | "local_error" | "auth_error";
  48. };
  49. /**
  50. * THE single fail-policy predicate for content-safety verdicts — "local blocks,
  51. * remote degrades" — shared by the turn INPUT review, the streaming OUTPUT
  52. * review, and every persisted config write (agent fields / user skill / session
  53. * title).
  54. *
  55. * Returns `true` when a verdict must BLOCK:
  56. * - `rejected` (gateway reviewed and rejected) → block
  57. * - `local_error` (no valid verdict: offline / timeout / invalid response) → block
  58. * - `auth_error` (missing / expired managed login) → block
  59. * - `api_error` (gateway reachable but 5xx-degraded) → degrade-pass
  60. *
  61. * `local_error` ALWAYS fails closed — there is no path where a missing verdict is
  62. * allowed through. Callers MUST route every block/allow decision through this one
  63. * predicate instead of re-deriving from `errorKind`. Consumers that need
  64. * something other than a block decision (e.g. mapping to an HTTP error code) read
  65. * `errorKind` directly.
  66. */
  67. export function reviewBlocks(result: SafetyCheckResult): boolean {
  68. return !result.pass && result.errorKind !== "api_error";
  69. }
  70. export const SAFETY_SCENE = {
  71. MessageOutput: 1,
  72. StreamChunk: 2,
  73. ThinkingContent: 3,
  74. // One content-safety scene for all user-controllable persisted config writes:
  75. // agent display name / description / persona / system prompt / avatar, user
  76. // skill name / description / content, and the session title. These values
  77. // flow into the `<agent-context>` block / skill roster / session list that
  78. // peer-agent LLMs read, so they are a cross-agent prompt-injection vector and
  79. // are gated at the owning Agent runtime service boundary and skill surfaces.
  80. // Reuses IDL `MavisSafetyScene` 205
  81. // rather than fanning out a per-field scene.
  82. ConfigField: 205,
  83. UserInput: 300,
  84. } as const;
  85. export type SafetyScene = (typeof SAFETY_SCENE)[keyof typeof SAFETY_SCENE];
  86. export type SafetyAttachment =
  87. | { objectKey: string; fileUrl?: never; fileName?: string }
  88. | { fileUrl: string; objectKey?: never; fileName?: string };
  89. const CONTENT_REVIEW_TIMEOUT_MS = 10_000;
  90. const UPSTREAM_CODE = {
  91. SERVICE_UNAVAILABLE: 50200,
  92. } as const;
  93. export async function callSafetyApi(input: {
  94. content: string;
  95. scene: SafetyScene;
  96. attachments?: SafetyAttachment[];
  97. authContext?: LocalRuntimeAuthContext;
  98. routingContext?: LocalRuntimeRoutingContext;
  99. fetchImpl: typeof fetch;
  100. region?: () => MavisRegion;
  101. buildEnv?: () => MavisBuildEnv;
  102. /** Loopback-only endpoint used by deterministic external tests in test builds. */
  103. testBaseURL?: string;
  104. }): Promise<SafetyCheckResult> {
  105. const region = input.region ?? getRuntimeRegion;
  106. const buildEnv = input.buildEnv ?? getRuntimeBuildEnv;
  107. const resolvedBuildEnv = buildEnv();
  108. // Keep legacy URL/text requests on the existing auth policy. Private keys
  109. // opt into authenticated ownership checks using the gateway's existing flag.
  110. const authQuery = input.attachments?.some(
  111. (attachment) => attachment.objectKey,
  112. )
  113. ? "?require_auth=true"
  114. : "";
  115. const url = `${resolveSafetyApiBase(region(), resolvedBuildEnv, input.testBaseURL)}/mavis/api/v1/content${authQuery}`;
  116. // Shared OAuth resource requests authenticate with the standard Bearer
  117. // scheme, matching the managed model and File API paths. Omit the header
  118. // entirely when there is no token so an anonymous request stays explicit.
  119. const accessToken =
  120. input.authContext?.accessToken?.trim() ||
  121. process.env.MAVIS_ACCESS_TOKEN?.trim();
  122. const reportFailure = createSafetyFailureReporter(url, "v1", input.scene);
  123. let response: Response;
  124. try {
  125. response = await input.fetchImpl(url, {
  126. method: "POST",
  127. headers: {
  128. "User-Agent": "MiniMaxAgent",
  129. "Content-Type": "application/json",
  130. ...(accessToken ? { Authorization: `Bearer ${accessToken}` } : {}),
  131. ...managedBackendRoutingHeaders(
  132. input.routingContext,
  133. input.buildEnv ? resolvedBuildEnv : undefined,
  134. ),
  135. },
  136. body: JSON.stringify({
  137. content_text: input.content,
  138. scene: input.scene,
  139. ...(input.attachments?.length
  140. ? {
  141. files: input.attachments.map((attachment) => ({
  142. ...(attachment.objectKey
  143. ? { object_key: attachment.objectKey }
  144. : { file_url: attachment.fileUrl }),
  145. file_name: attachment.fileName,
  146. })),
  147. }
  148. : {}),
  149. }),
  150. signal: AbortSignal.timeout(CONTENT_REVIEW_TIMEOUT_MS),
  151. });
  152. } catch (error) {
  153. reportFailure({
  154. failureKind: "transport",
  155. transportKind: classifySafetyTransportError(error),
  156. });
  157. // fetch threw (offline / DNS / connection refused / TLS) or the 10s timeout
  158. // fired: we never reached a verdict. No gateway confirmation → fail closed.
  159. return {
  160. pass: false,
  161. reason: "Service unavailable",
  162. errorKind: "local_error",
  163. };
  164. }
  165. let text: string;
  166. try {
  167. text = await response.text();
  168. } catch (error) {
  169. reportFailure({
  170. failureKind: "transport",
  171. transportKind: classifySafetyTransportError(error),
  172. statusCode: response.status,
  173. });
  174. return {
  175. pass: false,
  176. reason: "Service response could not be read",
  177. errorKind: "local_error",
  178. };
  179. }
  180. if (!response.ok) {
  181. // Non-2xx from the gateway, split by class so an auth failure can never be a
  182. // bypass:
  183. // 5xx → gateway reachable but genuinely degraded → `api_error` (fail open:
  184. // a transient server hiccup must not block a legitimate turn / write).
  185. // 4xx → client-side problem: missing / expired auth token (401/403), bad
  186. // request, etc. We are not authenticated / the request is not
  187. // acceptable, so there is NO valid verdict on our side → `local_error`
  188. // (fail closed). Treating 401/403 as `api_error` would let an
  189. // unauthenticated user bypass every content gate.
  190. reportFailure({
  191. failureKind: response.status === 401 || response.status === 403 ? "auth" : "http",
  192. statusCode: response.status,
  193. });
  194. const error = readErrorText(text);
  195. return {
  196. pass: false,
  197. reason: error ?? `Service returned ${response.status}`,
  198. errorKind:
  199. response.status === 401 || response.status === 403
  200. ? "auth_error"
  201. : response.status >= 500
  202. ? "api_error"
  203. : "local_error",
  204. };
  205. }
  206. let data: {
  207. pass?: unknown;
  208. safe?: unknown;
  209. reason?: unknown;
  210. error?: unknown;
  211. errorCode?: unknown;
  212. suggestion?: unknown;
  213. fix_response?: unknown;
  214. };
  215. try {
  216. data = JSON.parse(text) as typeof data;
  217. } catch {
  218. reportFailure({ failureKind: "response", statusCode: response.status });
  219. // 2xx but the body is not JSON — we cannot read a verdict. Treat as no
  220. // gateway confirmation → fail closed on the input path.
  221. return {
  222. pass: false,
  223. reason: "Service returned non-JSON response",
  224. errorKind: "local_error",
  225. };
  226. }
  227. const pass = isSafetyCheckV2Record(data) ? data.pass ?? data.safe : undefined;
  228. if (typeof pass !== "boolean") {
  229. reportFailure({ failureKind: "response", statusCode: response.status });
  230. // 2xx JSON but no boolean pass/safe field — again no usable verdict → fail
  231. // closed on the input path.
  232. return {
  233. pass: false,
  234. reason: "Service returned unexpected response format",
  235. errorKind: "local_error",
  236. };
  237. }
  238. const activeRegion = region();
  239. const upstreamCode =
  240. typeof data.errorCode === "number" ? data.errorCode : undefined;
  241. if (!pass && upstreamCode === UPSTREAM_CODE.SERVICE_UNAVAILABLE) {
  242. reportFailure({ failureKind: "upstream", statusCode: upstreamCode });
  243. }
  244. return {
  245. pass,
  246. reason:
  247. typeof data.reason === "string"
  248. ? data.reason
  249. : typeof data.error === "string"
  250. ? data.error
  251. : undefined,
  252. suggestion:
  253. activeRegion === "cn"
  254. ? typeof data.suggestion === "string"
  255. ? data.suggestion
  256. : typeof data.fix_response === "string"
  257. ? data.fix_response
  258. : undefined
  259. : undefined,
  260. ...(!pass
  261. ? {
  262. errorKind:
  263. upstreamCode === UPSTREAM_CODE.SERVICE_UNAVAILABLE
  264. ? ("api_error" as const)
  265. : ("rejected" as const),
  266. }
  267. : {}),
  268. };
  269. }
  270. /**
  271. * A content-safety checker bound to one auth source at construction. Callers
  272. * (the runtime host's output review) create it once and then invoke it with only
  273. * the business payload — `content` + `scene` — never threading the access token
  274. * per call. Auth is resolved lazily inside the returned function so a refreshed
  275. * login (the daemon swaps its `authContext`) is always picked up, and `fetch` is
  276. * read at call time so a test `vi.spyOn(globalThis, 'fetch')` still intercepts.
  277. */
  278. export type ContentSafetyChecker = (
  279. content: string,
  280. scene: SafetyScene,
  281. ) => Promise<SafetyCheckResult>;
  282. export function createContentSafetyChecker(deps: {
  283. /** Explicit V2 routing opt-in; callers that omit it retain V1. */
  284. apiVersion?: "v1" | "v2";
  285. authContextGetter?: () => LocalRuntimeAuthContext | undefined;
  286. authContextInvalidator?: (
  287. rejectedAccessToken: string,
  288. ) => void | Promise<void>;
  289. routingContextGetter?: () => LocalRuntimeRoutingContext | undefined;
  290. fetchImpl?: typeof fetch;
  291. region?: () => MavisRegion;
  292. buildEnv?: () => MavisBuildEnv;
  293. testBaseURLGetter?: () => string | undefined;
  294. }): ContentSafetyChecker {
  295. const callApi = deps.apiVersion === "v2" ? callTurnSafetyApi : callSafetyApi;
  296. return async (content, scene) => {
  297. try {
  298. const authContext = deps.authContextGetter?.();
  299. const rejectedToken =
  300. authContext?.accessToken?.trim() ||
  301. process.env.MAVIS_ACCESS_TOKEN?.trim();
  302. const request = {
  303. content,
  304. scene,
  305. authContext,
  306. routingContext: deps.routingContextGetter?.(),
  307. fetchImpl: deps.fetchImpl ?? fetch,
  308. ...(deps.region ? { region: deps.region } : {}),
  309. ...(deps.buildEnv ? { buildEnv: deps.buildEnv } : {}),
  310. ...(deps.testBaseURLGetter
  311. ? { testBaseURL: deps.testBaseURLGetter() }
  312. : {}),
  313. };
  314. const result = await callApi(request);
  315. if (
  316. result.errorKind !== "auth_error" ||
  317. !rejectedToken ||
  318. !deps.authContextInvalidator
  319. ) {
  320. return result;
  321. }
  322. try {
  323. await deps.authContextInvalidator(rejectedToken);
  324. const freshAuth = deps.authContextGetter?.();
  325. const freshToken =
  326. freshAuth?.accessToken?.trim() ||
  327. process.env.MAVIS_ACCESS_TOKEN?.trim();
  328. if (!freshToken || freshToken === rejectedToken) return result;
  329. // A failed V2 output stream retries as its V2 full-reply scene after auth refresh.
  330. const retryScene =
  331. result.retryWithV2 && request.scene === SAFETY_SCENE.StreamChunk
  332. ? SAFETY_SCENE.MessageOutput
  333. : request.scene;
  334. return await callApi({
  335. ...request,
  336. scene: retryScene,
  337. authContext: freshAuth,
  338. });
  339. } catch {
  340. return result;
  341. }
  342. } catch {
  343. // callSafetyApi is designed never to throw (it maps transport / parse
  344. // failures to a `local_error` result). This is a defensive backstop — e.g.
  345. // the auth getter throwing — so the checker's contract is airtight: it
  346. // ALWAYS resolves to a SafetyCheckResult and never rejects. That lets every
  347. // caller trust `errorKind` + `reviewBlocks` and drop its own try/catch.
  348. return { pass: false, errorKind: "local_error" };
  349. }
  350. };
  351. }
  352. function readErrorText(text: string): string | undefined {
  353. try {
  354. const parsed = JSON.parse(text) as { error?: unknown };
  355. return typeof parsed.error === "string" ? parsed.error : undefined;
  356. } catch {
  357. return undefined;
  358. }
  359. }