http-cloud-gateway-client.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /**
  2. * HttpCloudGatewayClient — production cloud-gateway implementation.
  3. *
  4. * Wire-aligned to the existing managed endpoint
  5. * POST {region-routed-host}/mavis/api/v1/permission/check
  6. * which `cloud-classify-client.ts` already targets. The cloud side is
  7. * intentionally untouched — this client re-uses the exact same
  8. * request/response format and host routing, returning verdicts in the
  9. * {@link CloudClassifyVerdict} vocabulary.
  10. *
  11. * Fail-closed policy:
  12. * - HTTP non-2xx / non-JSON / verdict missing / network error / abort
  13. * → resolves to { kind: 'timeout', reasonLocalized: ... }
  14. *
  15. * The daemon then surfaces an ask-user card so the user is never silently
  16. * bypassed when the gateway is unavailable.
  17. *
  18. * Region / buildEnv routing is delegated to the `getPermissionCheckApiUrl()`
  19. * helper so a single PERMISSION_API_BASE table stays the source of truth.
  20. */
  21. import { getPermissionCheckApiUrl } from './classifier/cloud-classify-client.js';
  22. import { logger, backgroundCtx, getPermissionManagedAuthToken } from './host-utils.js';
  23. import type {
  24. CloudGatewayClient,
  25. CloudClassifyRequest,
  26. CloudClassifyVerdict,
  27. } from './cloud-gateway.js';
  28. export interface HttpCloudGatewayClientOptions {
  29. /** Per-call HTTP timeout (ms). Default 60_000 (matches legacy classifier). */
  30. timeoutMs?: number;
  31. /**
  32. * Optional URL override — primarily for tests pointing at a local
  33. * fixture server. Production always uses `getPermissionCheckApiUrl()`.
  34. */
  35. endpointOverride?: string;
  36. /**
  37. * Optional Bearer token override — primarily for tests. Production
  38. * pulls from `getPermissionManagedAuthToken()`.
  39. */
  40. authTokenProvider?: () => string | undefined;
  41. }
  42. export class HttpCloudGatewayClient implements CloudGatewayClient {
  43. private readonly timeoutMs: number;
  44. private readonly endpointOverride?: string;
  45. private readonly authTokenProvider: () => string | undefined;
  46. constructor(opts: HttpCloudGatewayClientOptions = {}) {
  47. this.timeoutMs = opts.timeoutMs ?? 60_000;
  48. this.endpointOverride = opts.endpointOverride;
  49. this.authTokenProvider = opts.authTokenProvider ?? getPermissionManagedAuthToken;
  50. }
  51. async classify(req: CloudClassifyRequest): Promise<CloudClassifyVerdict> {
  52. const startedAtMs = Date.now();
  53. const url = this.endpointOverride ?? this.resolveUrl();
  54. if (!url) {
  55. return fallbackTimeout('cloud gateway URL not configured');
  56. }
  57. const body = {
  58. tool_name: req.toolName,
  59. input: req.input,
  60. platform: req.platform,
  61. home_dir: req.homeDir,
  62. workspace_root: req.workspaceRoot,
  63. mode: req.mode,
  64. ...(req.conversationContext ? { conversation_context: req.conversationContext } : {}),
  65. ...(req.agentId ? { agent_id: req.agentId } : {}),
  66. ...(req.sessionId ? { session_id: req.sessionId } : {}),
  67. ...(req.daemonPromptVersion ? { daemon_prompt_version: req.daemonPromptVersion } : {}),
  68. };
  69. try {
  70. const resp = await fetch(url, {
  71. method: 'POST',
  72. headers: {
  73. 'User-Agent': 'MiniMaxAgent',
  74. 'Content-Type': 'application/json',
  75. Authorization: `Bearer ${this.authTokenProvider() ?? ''}`,
  76. },
  77. body: JSON.stringify(body),
  78. signal: AbortSignal.timeout(this.timeoutMs),
  79. });
  80. const respText = await resp.text();
  81. const durationMs = Date.now() - startedAtMs;
  82. if (!resp.ok) {
  83. logger.warn(
  84. backgroundCtx(),
  85. `[cloud-gateway-v2] non-2xx: status=${resp.status} body=${respText.slice(0, 200)}`,
  86. );
  87. return fallbackTimeout(`permission/check returned ${resp.status}`, durationMs);
  88. }
  89. let data: {
  90. verdict?: unknown;
  91. reason?: unknown;
  92. model?: unknown;
  93. base_resp?: { status_code?: unknown; status_msg?: unknown };
  94. };
  95. try {
  96. data = JSON.parse(respText) as typeof data;
  97. } catch {
  98. logger.warn(backgroundCtx(), `[cloud-gateway-v2] non-JSON body=${respText.slice(0, 200)}`);
  99. return fallbackTimeout('permission/check returned non-JSON', durationMs);
  100. }
  101. const statusCode = data.base_resp?.status_code;
  102. if (typeof statusCode === 'number' && statusCode !== 0) {
  103. const msg =
  104. typeof data.base_resp?.status_msg === 'string'
  105. ? data.base_resp.status_msg
  106. : `status_code=${statusCode}`;
  107. logger.warn(backgroundCtx(), `[cloud-gateway-v2] biz error: ${msg}`);
  108. return fallbackTimeout(`permission/check biz error: ${msg}`, durationMs);
  109. }
  110. const verdict = data.verdict;
  111. if (verdict !== 'allow' && verdict !== 'confirm' && verdict !== 'block') {
  112. logger.warn(
  113. backgroundCtx(),
  114. `[cloud-gateway-v2] invalid verdict=${String(verdict)} body=${respText.slice(0, 200)}`,
  115. );
  116. return fallbackTimeout('permission/check returned invalid verdict', durationMs);
  117. }
  118. const reason =
  119. typeof data.reason === 'string' && data.reason.length > 0
  120. ? data.reason
  121. : 'No reason provided by server';
  122. const model = typeof data.model === 'string' ? data.model : 'cloud:gemini-flash';
  123. return { kind: verdict, reasonLocalized: reason, durationMs, model };
  124. } catch (err) {
  125. const durationMs = Date.now() - startedAtMs;
  126. // Distinguish a real AbortSignal.timeout() trigger from any other
  127. // throw (network reset, DNS failure, TLS error). The facade keeps the
  128. // same `kind: 'timeout'` verdict for both — fail-closed routing is
  129. // identical — but the reasonLocalized prefix lets the daemon log /
  130. // permission card surface the underlying class of failure rather
  131. // than always saying "timed out".
  132. const isAbort =
  133. err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError');
  134. const reason = isAbort
  135. ? `timed out after ${this.timeoutMs}ms`
  136. : `network error: ${err instanceof Error ? err.message : String(err)}`;
  137. logger.warn(backgroundCtx(), `[cloud-gateway-v2] call failed: ${String(err)}`);
  138. return fallbackTimeout(reason, durationMs);
  139. }
  140. }
  141. private resolveUrl(): string | undefined {
  142. try {
  143. return getPermissionCheckApiUrl();
  144. } catch (err) {
  145. logger.warn(backgroundCtx(), `[cloud-gateway-v2] URL resolution failed: ${String(err)}`);
  146. return undefined;
  147. }
  148. }
  149. }
  150. function fallbackTimeout(reason: string, durationMs?: number): CloudClassifyVerdict {
  151. return {
  152. kind: 'timeout',
  153. reasonLocalized: reason,
  154. model: 'cloud:unavailable',
  155. ...(durationMs !== undefined ? { durationMs } : {}),
  156. };
  157. }