local-website-deploy-client.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. /**
  2. * LocalWebsiteDeployClient: Local upload/publication delegate for website_deploy, implementing
  3. * desktop LocalWebsiteDeployAdapter.
  4. *
  5. * Option B:
  6. * 1. Walk and filter the local build directory: exclude .env/.git/node_modules, do not follow
  7. * symlinks, and enforce a total-size limit.
  8. * 2. Create site.zip and optional source.zip using existing jszip, without adding tar.
  9. * 3. Reuse Matrix Gateway get_upload_url to obtain a presigned PUT for each temporary upload
  10. * object, then upload sequentially site → source. The local process holds no OSS AK/SK.
  11. * 4. Call the actual backend endpoint: publish_archive for initial publication, update_archive for
  12. * an existing nodeId. Both use site.zip/source.zip; source.zip is only validated and stored
  13. * privately as the original ZIP, never entering stage/CDN.
  14. *
  15. * Routing: Obtain temporary upload objects through managed Matrix Gateway
  16. * `/mavis/api/v1/mcp/get_upload_url`; publish through Drive website
  17. * `/mavis/api/v1/drive/websites/publish_archive`. Gateway authenticates the Bearer access token,
  18. * injects BaseReq, and forwards to archon-server PublishWebsiteArchive.
  19. *
  20. * Identity: Gateway injects userId/BizLine from the managed access token; local sends only
  21. * sessionId as the auditing/ownership anchor.
  22. *
  23. * Prerequisite: archon-server publish_archive is deployed (separate archon_server MR). Before that,
  24. * the tool still appears but calls fail at the backend. If needed, add a configurable runtime gate
  25. * to hide incomplete capabilities in unconfigured environments.
  26. */
  27. import { lstat, realpath } from 'node:fs/promises';
  28. import { basename } from 'node:path';
  29. import type { LocalWebsiteDeployAdapter } from '@mavis/agent-tools/desktop';
  30. import { logger } from '../common/logger.js';
  31. import type { LocalRuntimeAuthContext } from '../runtime/model-resolver.js';
  32. import type { LocalRuntimeRoutingContext } from '../runtime/routing-headers.js';
  33. import { LocalMatrixClient } from '../matrix/local-matrix-client.js';
  34. import {
  35. DEFAULT_IGNORE_PATTERNS,
  36. sanitizeStem,
  37. totalBytes,
  38. uploadArchive,
  39. walkDeployableFiles,
  40. type UploadedArchive,
  41. type WebsiteDeployGateway,
  42. } from './archive-upload.js';
  43. import { materializeWebsiteCover } from './cover-materializer.js';
  44. import { deployFailure, ensureNotAborted, runDeployStage } from './deploy-failure.js';
  45. /** Drive website publication endpoint: archive oss_key → unpack + publish. */
  46. const PUBLISH_ARCHIVE_PATH = '/mavis/api/v1/drive/websites/publish_archive';
  47. /** Drive website update endpoint: retain the existing node and URL while replacing both archives' contents. */
  48. const UPDATE_ARCHIVE_PATH = '/mavis/api/v1/drive/websites/update_archive';
  49. // Mirrors IDL WebsiteManagementCode_CONTENT_REJECTED; non-zero base_resp always wins.
  50. const CONTENT_REJECTED_CODE = 10;
  51. const CONTENT_REJECTED_MESSAGE = '网站正文未通过审核,未发布';
  52. const DEFAULT_UPLOAD_TIMEOUT_MS = 1_500_000;
  53. /** Hard total-byte limit after walking files; defaults to 200 MiB, aligned with cloud. */
  54. const DEFAULT_MAX_TOTAL_BYTES = 200 * 1024 * 1024;
  55. export interface LocalWebsiteDeployClientOptions {
  56. /** Inject a gateway for tests; otherwise construct LocalMatrixClient from authContext/baseUrl. */
  57. gateway?: WebsiteDeployGateway;
  58. authContext?: LocalRuntimeAuthContext;
  59. routingContextGetter?: () => LocalRuntimeRoutingContext | undefined;
  60. baseUrl?: string;
  61. maxTotalBytes?: number;
  62. ignorePatterns?: readonly RegExp[];
  63. uploadTimeoutMs?: number;
  64. /** Desktop data root used by the existing local asset store for website covers. */
  65. dataDir?: string;
  66. /** Injectable only to keep the bounded cover download deterministic in unit tests. */
  67. fetchImpl?: typeof fetch;
  68. }
  69. export class LocalWebsiteDeployClient implements LocalWebsiteDeployAdapter {
  70. private readonly gateway: WebsiteDeployGateway;
  71. private readonly maxTotalBytes: number;
  72. private readonly ignorePatterns: readonly RegExp[];
  73. private readonly uploadTimeoutMs: number;
  74. private readonly dataDir: string | undefined;
  75. private readonly fetchImpl: typeof fetch;
  76. constructor(options: LocalWebsiteDeployClientOptions = {}) {
  77. this.gateway =
  78. options.gateway ??
  79. new LocalMatrixClient({
  80. ...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
  81. ...(options.authContext ? { authContext: options.authContext } : {}),
  82. routingContextGetter: options.routingContextGetter,
  83. });
  84. this.maxTotalBytes = options.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES;
  85. this.ignorePatterns = options.ignorePatterns ?? DEFAULT_IGNORE_PATTERNS;
  86. this.uploadTimeoutMs = options.uploadTimeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS;
  87. this.dataDir = options.dataDir;
  88. this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
  89. }
  90. async deploy(
  91. input: {
  92. dir: string;
  93. sourceDir?: string;
  94. nodeId?: string;
  95. projectName: string;
  96. sessionId: string;
  97. turnId?: string;
  98. watermark_enabled?: boolean;
  99. },
  100. signal?: AbortSignal,
  101. ): Promise<{
  102. cdn_url?: string;
  103. node_id?: string;
  104. cover_path?: string;
  105. error_code?: string;
  106. base_resp?: { status_code?: number; status_msg?: string };
  107. }> {
  108. ensureNotAborted(signal, 'before upload', 'validate_site');
  109. if (input.nodeId !== undefined && input.sourceDir === undefined) {
  110. throw deployFailure(
  111. 'website_deploy update requires a source directory.',
  112. 'validation_failed',
  113. 'validate_site',
  114. );
  115. }
  116. // 1) Walk, filter without following symlinks, and enforce the size limit.
  117. const siteFiles = await runDeployStage('validate_site', signal, () =>
  118. walkDeployableFiles(input.dir, this.ignorePatterns),
  119. );
  120. if (siteFiles.length === 0) {
  121. throw deployFailure(
  122. `Nothing to deploy: '${input.dir}' has no files after filtering.`,
  123. 'validation_failed',
  124. 'validate_site',
  125. );
  126. }
  127. const siteBytes = totalBytes(siteFiles);
  128. if (siteBytes > this.maxTotalBytes) {
  129. throw deployFailure(
  130. `Directory total size ${siteBytes} bytes exceeds the ${this.maxTotalBytes}-byte deploy ` +
  131. `limit. Trim build output or move large assets out before deploying.`,
  132. 'validation_failed',
  133. 'validate_site',
  134. );
  135. }
  136. const sourcePresent = input.sourceDir !== undefined;
  137. logStage('validate_site', 'ok', {
  138. source_present: sourcePresent,
  139. bytes: siteBytes,
  140. files: siteFiles.length,
  141. });
  142. // 2) Package site.zip, obtain its presigned PUT, and upload; process source.zip only afterward.
  143. const siteUpload = await uploadArchive({
  144. files: siteFiles,
  145. archiveName: `${sanitizeStem(basename(input.dir)) || 'website'}.zip`,
  146. gateway: this.gateway,
  147. signal,
  148. timeoutMs: this.uploadTimeoutMs,
  149. source: false,
  150. });
  151. logStage('upload_site', 'ok', {
  152. source_present: sourcePresent,
  153. bytes: siteBytes,
  154. files: siteFiles.length,
  155. });
  156. let sourceUpload: UploadedArchive | undefined;
  157. let sourceBytes = 0;
  158. let sourceFiles = 0;
  159. const sourceDir = input.sourceDir;
  160. if (sourceDir !== undefined) {
  161. const sourceRootStat = await runDeployStage('validate_source', signal, () =>
  162. lstat(sourceDir),
  163. );
  164. if (!sourceRootStat.isDirectory()) {
  165. throw deployFailure(
  166. 'website_deploy source directory must be a regular directory.',
  167. 'validation_failed',
  168. 'validate_source',
  169. );
  170. }
  171. ensureNotAborted(signal, 'before source validation', 'validate_source');
  172. const [siteRoot, sourceRoot] = await runDeployStage('validate_source', signal, () =>
  173. Promise.all([realpath(input.dir), realpath(sourceDir)]),
  174. );
  175. const sourceEntries =
  176. siteRoot === sourceRoot
  177. ? siteFiles
  178. : await runDeployStage('validate_source', signal, () =>
  179. walkDeployableFiles(sourceDir, this.ignorePatterns, input.dir),
  180. );
  181. if (sourceEntries.length === 0) {
  182. throw deployFailure(
  183. 'Nothing to archive: source directory has no files after filtering.',
  184. 'validation_failed',
  185. 'validate_source',
  186. );
  187. }
  188. sourceFiles = sourceEntries.length;
  189. sourceBytes = totalBytes(sourceEntries);
  190. if (sourceBytes > this.maxTotalBytes) {
  191. throw deployFailure(
  192. `Source directory total size ${sourceBytes} bytes exceeds the ${this.maxTotalBytes}-byte ` +
  193. `source archive limit. Trim source files before deploying.`,
  194. 'validation_failed',
  195. 'validate_source',
  196. );
  197. }
  198. logStage('validate_source', 'ok', {
  199. source_present: true,
  200. bytes: sourceBytes,
  201. files: sourceFiles,
  202. });
  203. sourceUpload = await uploadArchive({
  204. files: sourceEntries,
  205. archiveName: `${sanitizeStem(basename(sourceDir)) || 'website'}-source.zip`,
  206. gateway: this.gateway,
  207. signal,
  208. timeoutMs: this.uploadTimeoutMs,
  209. source: true,
  210. differentFromOssKey: siteUpload.ossKey,
  211. });
  212. logStage('upload_source', 'ok', {
  213. source_present: true,
  214. bytes: sourceBytes,
  215. files: sourceFiles,
  216. });
  217. }
  218. const isUpdate = input.nodeId !== undefined;
  219. const archiveOperation = isUpdate ? 'update_archive' : 'publish_archive';
  220. const archivePath = isUpdate ? UPDATE_ARCHIVE_PATH : PUBLISH_ARCHIVE_PATH;
  221. ensureNotAborted(signal, `before ${archiveOperation}`, archiveOperation);
  222. logStage(archiveOperation, 'started', {
  223. source_present: sourcePresent,
  224. bytes: siteBytes + sourceBytes,
  225. files: siteFiles.length + sourceFiles,
  226. });
  227. const published = (await runDeployStage(archiveOperation, signal, () =>
  228. this.gateway.postGatewayJson(
  229. archivePath,
  230. {
  231. ...(input.nodeId !== undefined ? { node_id: input.nodeId } : {}),
  232. oss_key: siteUpload.ossKey,
  233. ...(sourceUpload ? { source_oss_key: sourceUpload.ossKey } : {}),
  234. project_name: input.projectName,
  235. session_id: input.sessionId,
  236. ...(input.nodeId === undefined && input.watermark_enabled !== undefined
  237. ? { watermark_enabled: input.watermark_enabled }
  238. : {}),
  239. },
  240. signal,
  241. this.uploadTimeoutMs,
  242. ),
  243. )) as {
  244. code?: number;
  245. message?: string;
  246. cdn_url?: string;
  247. node_id?: string;
  248. node?: { cdn_url?: string; node_id?: string; screenshot_url?: string };
  249. error_code?: string;
  250. base_resp?: { status_code?: number; status_msg?: string };
  251. };
  252. const baseStatusCode = published.base_resp?.status_code ?? 0;
  253. const statusCode = baseStatusCode !== 0 ? baseStatusCode : (published.code ?? 0);
  254. if (statusCode !== 0) {
  255. const statusMsg =
  256. baseStatusCode !== 0
  257. ? (published.base_resp?.status_msg ?? published.message)
  258. : statusCode === CONTENT_REJECTED_CODE
  259. ? CONTENT_REJECTED_MESSAGE
  260. : published.message;
  261. const errorCode =
  262. baseStatusCode === 0 ? normalizeNonEmptyString(published.error_code) : undefined;
  263. // Observability anchor for rejection. The tool layer (agent-tools/desktop local-website-deploy.ts)
  264. // owns no logger, and user-facing reasons depend entirely on whether the backend returns status_msg.
  265. // Record error_code and status_msg_present here, noting only presence, never message text,
  266. // consistent with this logger's no-business-content constraint. status_msg_present=false means
  267. // the tool can only use neutral fallback wording, allowing the exact failure branch to be reconstructed.
  268. logStage(archiveOperation, 'failed', {
  269. source_present: sourcePresent,
  270. bytes: siteBytes + sourceBytes,
  271. files: siteFiles.length + sourceFiles,
  272. status_code: statusCode,
  273. status_msg_present: Boolean(normalizeNonEmptyString(statusMsg)),
  274. ...(errorCode ? { error_code: errorCode } : {}),
  275. });
  276. return {
  277. base_resp: {
  278. status_code: statusCode,
  279. status_msg: statusMsg ?? `publish service returned status_code=${statusCode}`,
  280. },
  281. ...(errorCode ? { error_code: errorCode } : {}),
  282. };
  283. }
  284. const cdnUrl = published.cdn_url ?? published.node?.cdn_url ?? '';
  285. const returnedNodeId = normalizeNonEmptyString(published.node_id ?? published.node?.node_id);
  286. if (isUpdate && (!returnedNodeId || returnedNodeId !== input.nodeId || !cdnUrl)) {
  287. throw deployFailure(
  288. 'website_deploy update_archive returned an invalid success response.',
  289. 'publish_contract_failed',
  290. 'update_archive',
  291. );
  292. }
  293. const nodeId = returnedNodeId ?? input.nodeId;
  294. const screenshotUrl = normalizeNonEmptyString(published.node?.screenshot_url);
  295. logStage('complete', 'ok', {
  296. source_present: sourcePresent,
  297. bytes: siteBytes + sourceBytes,
  298. files: siteFiles.length + sourceFiles,
  299. });
  300. // Cover acquisition is strictly best-effort after publish success. A bad or expired signed
  301. // URL must never rewrite a successful deployment into a retryable tool failure.
  302. const coverPath = await materializeWebsiteCover({
  303. screenshotUrl,
  304. nodeId,
  305. sessionId: input.sessionId,
  306. turnId: input.turnId,
  307. dataDir: this.dataDir,
  308. fetchImpl: this.fetchImpl,
  309. signal,
  310. });
  311. return {
  312. ...(cdnUrl ? { cdn_url: cdnUrl } : {}),
  313. ...(nodeId ? { node_id: nodeId } : {}),
  314. ...(coverPath ? { cover_path: coverPath } : {}),
  315. };
  316. }
  317. }
  318. function normalizeNonEmptyString(value: unknown): string | undefined {
  319. return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  320. }
  321. function logStage(
  322. stage:
  323. | 'validate_site'
  324. | 'upload_site'
  325. | 'validate_source'
  326. | 'upload_source'
  327. | 'publish_archive'
  328. | 'update_archive'
  329. | 'complete',
  330. result: 'started' | 'ok' | 'failed',
  331. fields: {
  332. source_present: boolean;
  333. bytes: number;
  334. files: number;
  335. status_code?: number;
  336. /** Record only whether the backend supplied a business-reason message, never its contents. */
  337. status_msg_present?: boolean;
  338. error_code?: string;
  339. },
  340. ): void {
  341. logger.info({ stage, result, ...fields }, 'website deploy stage');
  342. }