@xopcai/xopc 0.0.484 → 0.0.486

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/telegram/src/inbound-processor.js +4 -6
  3. package/dist/extensions/telegram/xopc.extension.json +1 -1
  4. package/dist/extensions/weixin/src/messaging/process-message.js +2 -1
  5. package/dist/gateway/server/chunks.bin +1166 -1121
  6. package/dist/gateway/server/chunks.json +1 -1
  7. package/dist/gateway/static/root/assets/agent-run-error-parser-DsXmcKt-.js +1 -0
  8. package/dist/gateway/static/root/assets/{api-CGs641OT.js → api-CGrHK9ij.js} +1 -1
  9. package/dist/gateway/static/root/assets/{apps-page-CH9wENBj.js → apps-page-6xeWvMpF.js} +1 -1
  10. package/dist/gateway/static/root/assets/{automations-page-B1Ri4sh8.js → automations-page-BLFBqaPX.js} +1 -1
  11. package/dist/gateway/static/root/assets/{automations-workspace-CNSza6ir.js → automations-workspace-DiO3Iyuj.js} +2 -2
  12. package/dist/gateway/static/root/assets/{capabilities-abgigXV1.js → capabilities-CW-vdkz6.js} +1 -1
  13. package/dist/gateway/static/root/assets/{capabilities-BaKHutgZ.js → capabilities-DZrjA95P.js} +1 -1
  14. package/dist/gateway/static/root/assets/capabilities-page-DQrfkrBA.js +2 -0
  15. package/dist/gateway/static/root/assets/{capabilities-settings-panel-BOwbZn9X.js → capabilities-settings-panel-DIT2dvtc.js} +1 -1
  16. package/dist/gateway/static/root/assets/{channels-DlnXbcOj.js → channels-Dcr5dgqw.js} +1 -1
  17. package/dist/gateway/static/root/assets/{chat-page-LOR5JxDh.js → chat-page-DWZCzxY7.js} +31 -31
  18. package/dist/gateway/static/root/assets/{chat-terminal-dock-DE8j-K9d.js → chat-terminal-dock-DCUuwiTt.js} +1 -1
  19. package/dist/gateway/static/root/assets/command-palette-api-UrqPvWR1.js +1 -0
  20. package/dist/gateway/static/root/assets/composer-payload-handoff-a0quQ25p.js +1 -0
  21. package/dist/gateway/static/root/assets/connected-providers-grid-BJKEp0SE.js +1 -0
  22. package/dist/gateway/static/root/assets/{connectors-page-BJm1jjct.js → connectors-page-BteRI1XM.js} +1 -1
  23. package/dist/gateway/static/root/assets/{extension-debug-page-D3X7SlzG.js → extension-debug-page-4jJ1uVQJ.js} +1 -1
  24. package/dist/gateway/static/root/assets/{extension-iframe-host-CIAq7PSn.js → extension-iframe-host-CJV5JETm.js} +1 -1
  25. package/dist/gateway/static/root/assets/{extension-message-router-B2wbucV7.js → extension-message-router-B4I-Y6qs.js} +1 -1
  26. package/dist/gateway/static/root/assets/{extension-page-qwY7r1_p.js → extension-page-lc7a84nG.js} +1 -1
  27. package/dist/gateway/static/root/assets/{extension-provider-DFcRbTHI.js → extension-provider-D8_mIBI0.js} +1 -1
  28. package/dist/gateway/static/root/assets/{extension-settings-page-Cpnh9lcZ.js → extension-settings-page-Uw2lfWRh.js} +1 -1
  29. package/dist/gateway/static/root/assets/{home-page-BusNFHe-.js → home-page-mSRCU81k.js} +4 -4
  30. package/dist/gateway/static/root/assets/{home-task-actions-C8Fi6GBq.js → home-task-actions-_ZAc57Y7.js} +1 -1
  31. package/dist/gateway/static/root/assets/{index-DE6GguFZ.js → index-CJAEAcZV.js} +7 -7
  32. package/dist/gateway/static/root/assets/{local-app-workbench-page-B9uSL1Mi.js → local-app-workbench-page-C3Lqi8E1.js} +1 -1
  33. package/dist/gateway/static/root/assets/{note-detail-panel-DXzfoiyk.js → note-detail-panel-uc-5k3a2.js} +3 -3
  34. package/dist/gateway/static/root/assets/{notes-page-BNTgiHSk.js → notes-page-RPfvHnl6.js} +1 -1
  35. package/dist/gateway/static/root/assets/{page-context-capture-button-BXSBeGms.js → page-context-capture-button-CVHz9b6c.js} +1 -1
  36. package/dist/gateway/static/root/assets/{personal-page-D7zTHQ0K.js → personal-page-Dt1d3tQT.js} +1 -1
  37. package/dist/gateway/static/root/assets/{personal-profile-settings-TcI0Zfwr.js → personal-profile-settings-XiT1MgTK.js} +1 -1
  38. package/dist/gateway/static/root/assets/{personal-settings-panel-BJ46T7ZO.js → personal-settings-panel-bcw04REt.js} +1 -1
  39. package/dist/gateway/static/root/assets/{preview-runtime-C1U57WSM.js → preview-runtime-FtWOW5i4.js} +1 -1
  40. package/dist/gateway/static/root/assets/{product-automation-feedback-GA_YPLkr.js → product-automation-feedback-DdFoCDzG.js} +1 -1
  41. package/dist/gateway/static/root/assets/product-preview-content-B3mzl6-f.js +1 -0
  42. package/dist/gateway/static/root/assets/product-preview-modal-5kTp_7Qk.js +2 -0
  43. package/dist/gateway/static/root/assets/project-detail-page-DGPfKx5M.js +7 -0
  44. package/dist/gateway/static/root/assets/{projects-page-BHQxQGTd.js → projects-page-C-9x23LR.js} +1 -1
  45. package/dist/gateway/static/root/assets/route-preload-CzorjVc9.js +2 -0
  46. package/dist/gateway/static/root/assets/routine-panel-n4IstC8Y.js +2 -0
  47. package/dist/gateway/static/root/assets/session-manager-C2MCS4C5.js +28 -0
  48. package/dist/gateway/static/root/assets/{settings-page-BOzzOS6k.js → settings-page-DsM_f07M.js} +1 -1
  49. package/dist/gateway/static/root/assets/{share-preview-page-Di5_ukH8.js → share-preview-page-C32Mq-BY.js} +1 -1
  50. package/dist/gateway/static/root/assets/{shares-settings-CirGM67m.js → shares-settings-BDGbs8wz.js} +1 -1
  51. package/dist/gateway/static/root/assets/{skills-page-gGU0LZ5e.js → skills-page-kL8E5zgi.js} +1 -1
  52. package/dist/gateway/static/root/assets/space-page-DwyuUvI3.js +2 -0
  53. package/dist/gateway/static/root/assets/task-copy-CtcqCQ78.js +1 -0
  54. package/dist/gateway/static/root/assets/task-detail-page-DdCpNW8K.js +3 -0
  55. package/dist/gateway/static/root/assets/{task-header-title-Cdgp2rCs.js → task-header-title-CLt_lmjb.js} +1 -1
  56. package/dist/gateway/static/root/assets/task-result-presentation-CgvcqEMD.js +1 -0
  57. package/dist/gateway/static/root/assets/task-run-issue-notice-8FX876PP.js +1 -0
  58. package/dist/gateway/static/root/assets/tasks-CvOAtEHv.js +1 -0
  59. package/dist/gateway/static/root/assets/turn-outcome-Dtw6OgwL.js +1 -0
  60. package/dist/gateway/static/root/assets/{use-composer-attachments-DJsIzJ1c.js → use-composer-attachments-BEuyorVm.js} +1 -1
  61. package/dist/gateway/static/root/assets/{use-file-preview-expanded-BFF2vXm5.js → use-file-preview-expanded-Cehu0745.js} +1 -1
  62. package/dist/gateway/static/root/assets/use-personal-work-B25WRGHj.js +1 -0
  63. package/dist/gateway/static/root/assets/{use-realtime-voice-9OvLwHzk.js → use-realtime-voice-CV3GIt_T.js} +1 -1
  64. package/dist/gateway/static/root/assets/{use-workspace-tree-LCIT1H-D.js → use-workspace-tree-C0C861cb.js} +1 -1
  65. package/dist/gateway/static/root/assets/{voice-settings-j8o-hGTm.js → voice-settings-JpPo3BvX.js} +1 -1
  66. package/dist/gateway/static/root/assets/workspace-api-CQOuWbVv.js +2 -0
  67. package/dist/gateway/static/root/assets/{workspace-file-preview-dialog-DwVWTehC.js → workspace-file-preview-dialog-CmMueTmW.js} +1 -1
  68. package/dist/gateway/static/root/index.html +30 -28
  69. package/dist/package.js +1 -1
  70. package/dist/packages/gateway-contract/src/index.js +3 -1
  71. package/dist/packages/gateway-contract/src/notifications.js +1 -8
  72. package/dist/packages/gateway-contract/src/task-display.js +9 -2
  73. package/dist/packages/gateway-contract/src/task-lifecycle.js +1 -0
  74. package/dist/packages/gateway-contract/src/task-research-result.js +2 -1
  75. package/dist/packages/gateway-contract/src/tasks.js +6 -1
  76. package/dist/packages/gateway-contract/src/user-message-text.js +64 -0
  77. package/dist/src/agent/embedded/run-for-session.js +27 -28
  78. package/dist/src/agent/embedded/session-runner.js +14 -1
  79. package/dist/src/agent/fallback/candidates.d.ts +1 -0
  80. package/dist/src/agent/fallback/candidates.js +1 -1
  81. package/dist/src/agent/image/generation/provider-registry.js +3 -1
  82. package/dist/src/agent/mcp/connection-drafts.d.ts +3 -1
  83. package/dist/src/agent/mcp/connection-drafts.js +24 -11
  84. package/dist/src/agent/mcp/connection-setup.js +13 -10
  85. package/dist/src/agent/mcp/native-mcp.js +1 -0
  86. package/dist/src/agent/mcp/network-policy.d.ts +6 -0
  87. package/dist/src/agent/mcp/network-policy.js +49 -0
  88. package/dist/src/agent/mcp/transport.js +14 -7
  89. package/dist/src/agent/messaging/message-router.js +2 -2
  90. package/dist/src/agent/models/manager.d.ts +1 -1
  91. package/dist/src/agent/models/manager.js +2 -1
  92. package/dist/src/agent/models/turn-candidates.d.ts +16 -0
  93. package/dist/src/agent/models/turn-candidates.js +55 -0
  94. package/dist/src/agent/service/direct-turn-helpers.js +9 -24
  95. package/dist/src/agent/service.d.ts +1 -0
  96. package/dist/src/agent/service.js +12 -0
  97. package/dist/src/agent/skills/installer.js +2 -2
  98. package/dist/src/auth/credentials.js +3 -1
  99. package/dist/src/auth/oauth/index.d.ts +0 -1
  100. package/dist/src/auth/oauth/index.js +1 -4
  101. package/dist/src/auth/oauth/registry.js +0 -4
  102. package/dist/src/auth/oauth/xopc-cloud.js +1 -1
  103. package/dist/src/chat-commands/command-parse.d.ts +1 -0
  104. package/dist/src/chat-commands/command-parse.js +8 -10
  105. package/dist/src/chat-commands/registry.d.ts +5 -0
  106. package/dist/src/chat-commands/registry.js +8 -0
  107. package/dist/src/cli/command-manifest.js +1 -1
  108. package/dist/src/cli/commands/auth.js +4 -2
  109. package/dist/src/cli/commands/models.js +12 -10
  110. package/dist/src/config/models-json.js +1 -2
  111. package/dist/src/config/schema.d.ts +54 -4
  112. package/dist/src/config/schema.js +3 -1
  113. package/dist/src/gateway/agent-reactions/reaction.d.ts +1 -2
  114. package/dist/src/gateway/agent-reactions/reaction.js +10 -21
  115. package/dist/src/gateway/custom-image-providers.js +4 -1
  116. package/dist/src/gateway/hono/oauth.js +3 -0
  117. package/dist/src/gateway/hono/routes/device-push.js +55 -15
  118. package/dist/src/gateway/hono/routes/mobile-capability-panels.d.ts +67 -0
  119. package/dist/src/gateway/hono/routes/mobile-capability-panels.js +16 -131
  120. package/dist/src/gateway/hono/routes/mobile-mcp-setup.d.ts +9 -0
  121. package/dist/src/gateway/hono/routes/mobile-mcp-setup.js +949 -0
  122. package/dist/src/gateway/hono/routes/notifications.js +12 -1
  123. package/dist/src/gateway/hono/routes/session-command-handler.js +1 -4
  124. package/dist/src/gateway/hono/routes/session-input-handler.js +1 -4
  125. package/dist/src/gateway/hono/routes/sessions.js +1 -13
  126. package/dist/src/gateway/next-turn-suggestions/generator.js +16 -2
  127. package/dist/src/gateway/next-turn-suggestions/service.d.ts +2 -1
  128. package/dist/src/gateway/next-turn-suggestions/service.js +17 -5
  129. package/dist/src/gateway/next-turn-suggestions/snapshot.d.ts +11 -0
  130. package/dist/src/gateway/next-turn-suggestions/snapshot.js +31 -2
  131. package/dist/src/gateway/security/gateway-scopes.js +1 -0
  132. package/dist/src/gateway/service/config-coordinator.d.ts +14 -1
  133. package/dist/src/gateway/service/run-gateway-agent.js +2 -13
  134. package/dist/src/gateway/service.js +80 -60
  135. package/dist/src/local-apps/capabilities/projections.d.ts +5 -5
  136. package/dist/src/media/generation-changes.d.ts +4 -0
  137. package/dist/src/media/generation-changes.js +37 -0
  138. package/dist/src/music-generation/repository.js +12 -6
  139. package/dist/src/notifications/device-store.d.ts +3 -0
  140. package/dist/src/notifications/device-store.js +14 -1
  141. package/dist/src/notifications/platform-push.d.ts +17 -0
  142. package/dist/src/notifications/platform-push.js +58 -0
  143. package/dist/src/notifications/service.d.ts +2 -2
  144. package/dist/src/notifications/service.js +26 -12
  145. package/dist/src/notifications/store.d.ts +1 -1
  146. package/dist/src/notifications/store.js +3 -2
  147. package/dist/src/providers/env-keys.js +0 -1
  148. package/dist/src/providers/index.js +1 -7
  149. package/dist/src/providers/model-catalog-sync-service.js +3 -1
  150. package/dist/src/providers/model-registry.js +6 -2
  151. package/dist/src/providers/presentation.js +1 -2
  152. package/dist/src/providers/provider-policy.js +2 -1
  153. package/dist/src/session/client-history.js +3 -3
  154. package/dist/src/session/reset-triggers.js +1 -1
  155. package/dist/src/session/user-message-display.js +3 -2
  156. package/dist/src/storage/sqlite/agent-reaction-repository.d.ts +2 -4
  157. package/dist/src/storage/sqlite/agent-reaction-repository.js +18 -13
  158. package/dist/src/storage/sqlite/device-access-repository.js +2 -1
  159. package/dist/src/tasks/capabilities/write.d.ts +2 -0
  160. package/dist/src/tasks/home-query-service.js +2 -1
  161. package/dist/src/tasks/task-contract-planner.js +1 -0
  162. package/dist/src/tasks/task-conversation-summary.d.ts +1 -1
  163. package/dist/src/tasks/task-delivery-checks.d.ts +12 -0
  164. package/dist/src/tasks/task-delivery-checks.js +91 -0
  165. package/dist/src/tasks/task-final-reply.d.ts +3 -1
  166. package/dist/src/tasks/task-final-reply.js +17 -4
  167. package/dist/src/tasks/task-model-call.js +4 -2
  168. package/dist/src/tasks/task-origin-repository.d.ts +1 -1
  169. package/dist/src/tasks/task-read-model-projector.js +24 -7
  170. package/dist/src/tasks/task-research-result.js +12 -27
  171. package/dist/src/tasks/task-result-delivery-repository.js +3 -2
  172. package/dist/src/tasks/task-retry-service.js +2 -1
  173. package/dist/src/tasks/task-run-coordinator.js +14 -4
  174. package/dist/src/tasks/task-run-dispatcher.d.ts +1 -0
  175. package/dist/src/tasks/task-run-dispatcher.js +78 -48
  176. package/dist/src/tasks/task-run-repository.js +1 -1
  177. package/dist/src/tui/tui-commands.d.ts +2 -1
  178. package/dist/src/tui/tui-commands.js +3 -3
  179. package/dist/src/tui/tui-submit.d.ts +1 -1
  180. package/dist/src/tui/tui-submit.js +2 -4
  181. package/dist/src/video-generation/drafts.js +2 -0
  182. package/dist/src/video-generation/repository.js +13 -6
  183. package/package.json +1 -1
  184. package/dist/gateway/static/root/assets/capabilities-page-EENl65YY.js +0 -2
  185. package/dist/gateway/static/root/assets/command-palette-api-YP0zV_Ol.js +0 -1
  186. package/dist/gateway/static/root/assets/composer-payload-handoff-ClWsunJ2.js +0 -1
  187. package/dist/gateway/static/root/assets/connected-providers-grid-BgW-ioIt.js +0 -1
  188. package/dist/gateway/static/root/assets/product-preview-content-BOq3gtSJ.js +0 -1
  189. package/dist/gateway/static/root/assets/product-preview-modal-DIh_CsXp.js +0 -2
  190. package/dist/gateway/static/root/assets/project-detail-page-Dgs8ImMC.js +0 -7
  191. package/dist/gateway/static/root/assets/route-preload-7WVrzJca.js +0 -2
  192. package/dist/gateway/static/root/assets/routine-panel-Bfbiz0IN.js +0 -2
  193. package/dist/gateway/static/root/assets/session-manager-DUWeBdeG.js +0 -28
  194. package/dist/gateway/static/root/assets/space-page-CKVuhV2i.js +0 -2
  195. package/dist/gateway/static/root/assets/task-detail-page-DEpYIaok.js +0 -3
  196. package/dist/gateway/static/root/assets/task-run-issue-notice-CGrUMy0s.js +0 -1
  197. package/dist/gateway/static/root/assets/tasks-CwyNaa-j.js +0 -1
  198. package/dist/gateway/static/root/assets/turn-outcome-BSbEJx8h.js +0 -1
  199. package/dist/gateway/static/root/assets/use-personal-work-Dd2jRUpz.js +0 -1
  200. package/dist/gateway/static/root/assets/workspace-api-BuNWyNvA.js +0 -2
  201. package/dist/src/auth/oauth/google-antigravity.d.ts +0 -4
  202. package/dist/src/auth/oauth/google-antigravity.js +0 -9
  203. package/dist/src/auth/oauth/google-oauth/google-antigravity.d.ts +0 -25
  204. package/dist/src/auth/oauth/google-oauth/google-antigravity.js +0 -309
  205. package/dist/src/notifications/harmony-push.d.ts +0 -27
  206. package/dist/src/notifications/harmony-push.js +0 -96
@@ -0,0 +1,949 @@
1
+ import { McpServerSchema, init_schema } from "../../../config/schema.js";
2
+ import { isRecord } from "../../../utils/is-record.js";
3
+ import { isPrivateMcpTarget, isPublicMcpTarget, suggestsPrivateMcpHostname } from "../../../agent/mcp/network-policy.js";
4
+ import { McpDraftError } from "../../../agent/mcp/connection-drafts.js";
5
+ import { basename, resolve } from "node:path";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { z } from "zod";
8
+ import { validateHeaderName, validateHeaderValue } from "node:http";
9
+ //#region src/gateway/hono/routes/mobile-mcp-setup.ts
10
+ init_schema();
11
+ const TTL_MS = 10 * 6e4;
12
+ const AUTHORIZATION_HEADER = "authorization";
13
+ const transportHeaders = new Set([
14
+ "accept",
15
+ "connection",
16
+ "content-length",
17
+ "content-type",
18
+ "expect",
19
+ "host",
20
+ "keep-alive",
21
+ "last-event-id",
22
+ "mcp-protocol-version",
23
+ "mcp-session-id",
24
+ "proxy-authorization",
25
+ "te",
26
+ "trailer",
27
+ "transfer-encoding",
28
+ "upgrade"
29
+ ]);
30
+ const oauthSchema = z.strictObject({
31
+ clientId: z.string().trim().min(1).max(512).optional(),
32
+ clientSecret: z.string().trim().min(1).max(4096).optional(),
33
+ clientName: z.string().trim().min(1).max(128).optional(),
34
+ clientRegistration: z.enum(["dcr", "cimd"]).optional(),
35
+ scope: z.string().trim().max(512).optional()
36
+ });
37
+ const authSchema = z.enum([
38
+ "auto",
39
+ "none",
40
+ "bearer",
41
+ "apiKey",
42
+ "headers",
43
+ "oauth"
44
+ ]);
45
+ const urlTransport = z.enum([
46
+ "http",
47
+ "streamable-http",
48
+ "sse"
49
+ ]);
50
+ const networkSchema = z.enum(["auto", "private"]);
51
+ const envName = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
52
+ const isProcessText = (value) => !value.includes("\0") && !value.includes("\r") && !value.includes("\n");
53
+ const executionSchema = z.object({
54
+ command: z.string().trim().min(1).max(1024).refine(isProcessText),
55
+ args: z.array(z.string().max(4096).refine((value) => !value.includes("\0"))).max(64).optional(),
56
+ cwd: z.string().trim().max(2048).refine(isProcessText).optional()
57
+ });
58
+ const commonImportKeys = [
59
+ "type",
60
+ "displayName",
61
+ "description",
62
+ "timeout",
63
+ "exposure",
64
+ "toolExposure",
65
+ "enabled"
66
+ ];
67
+ const httpImportKeys = [
68
+ ...commonImportKeys,
69
+ "url",
70
+ "headers",
71
+ "oauth",
72
+ "network"
73
+ ];
74
+ const stdioImportKeys = [
75
+ ...commonImportKeys,
76
+ "command",
77
+ "args",
78
+ "cwd",
79
+ "env"
80
+ ];
81
+ function serverAddress(value, network, t) {
82
+ const parsed = z.url().max(2048).safeParse(typeof value === "string" ? value.trim() : value);
83
+ if (parsed.success) {
84
+ const url = new URL(parsed.data);
85
+ if (["http:", "https:"].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash) {
86
+ const privateNetwork = network === "private" || url.protocol === "http:" || suggestsPrivateMcpHostname(url.hostname);
87
+ if (privateNetwork ? isPrivateMcpTarget(url) : isPublicMcpTarget(url)) return {
88
+ url: url.href,
89
+ xopcPrivateNetwork: privateNetwork
90
+ };
91
+ }
92
+ }
93
+ throw new McpDraftError(400, t("请输入公共 HTTPS 或 Gateway 内网 HTTP(S) 地址。地址中请勿包含账号、查询参数或片段。", "Enter a public HTTPS or Gateway-private HTTP(S) address without credentials, query parameters, or a fragment."));
94
+ }
95
+ function environment(entries, t) {
96
+ const names = /* @__PURE__ */ new Set();
97
+ return Object.fromEntries(entries.filter(([name, value]) => name.trim() || value).map(([name, value]) => {
98
+ const key = name.trim();
99
+ const normalized = key.toUpperCase();
100
+ if (entries.length > 32 || !envName.test(key) || key.length > 128 || value.length > 4096 || value.includes("\0") || [
101
+ "__PROTO__",
102
+ "CONSTRUCTOR",
103
+ "PROTOTYPE"
104
+ ].includes(normalized) || names.has(normalized)) throw new McpDraftError(400, t("请检查环境变量名称、值及重复项。", "Check the environment variable names, values, and duplicates."));
105
+ names.add(normalized);
106
+ return [key, value];
107
+ }));
108
+ }
109
+ function keyValueRows(raw, t) {
110
+ let input;
111
+ try {
112
+ input = raw ? JSON.parse(raw) : [];
113
+ } catch {
114
+ input = void 0;
115
+ }
116
+ const parsed = z.array(z.tuple([z.string(), z.string()])).safeParse(input);
117
+ if (!parsed.success) throw new McpDraftError(400, t("请检查键值配置。", "Check the name and value pairs."));
118
+ return parsed.data.map(([name, value]) => [name, value]);
119
+ }
120
+ function headerMap(entries, t) {
121
+ const seen = /* @__PURE__ */ new Set();
122
+ if (!entries.length || entries.length > 16) throw new McpDraftError(400, t("请填写 1 至 16 个请求头。", "Enter between 1 and 16 request headers."));
123
+ return Object.fromEntries(entries.map(([key, raw]) => {
124
+ const name = key.trim();
125
+ const value = raw.trim();
126
+ const normalized = name.toLowerCase();
127
+ try {
128
+ validateHeaderName(name);
129
+ validateHeaderValue(name, value);
130
+ if (name.length > 128 || value.length > 4096 || !value || seen.has(normalized) || transportHeaders.has(normalized) || [
131
+ "__proto__",
132
+ "constructor",
133
+ "prototype"
134
+ ].includes(normalized)) throw new Error();
135
+ } catch {
136
+ throw new McpDraftError(400, t("请检查请求头的名称、值及重复项。", "Check the header names, values, and duplicates."));
137
+ }
138
+ seen.add(normalized);
139
+ return [name, value];
140
+ }));
141
+ }
142
+ function bearerHeaders(raw, t) {
143
+ const token = raw?.trim().replace(/^Bearer\s+/i, "") ?? "";
144
+ if (!/^[!-~]+$/.test(token) || token.length > 4096) throw new McpDraftError(400, t("请输入服务商提供的 Bearer 令牌。", "Enter the Bearer token provided by the service."));
145
+ return { Authorization: `Bearer ${token}` };
146
+ }
147
+ function importedHeaderEntries(value, t) {
148
+ const parsed = z.record(z.string(), z.string()).safeParse(value);
149
+ if (!parsed.success) throw new McpDraftError(400, t("请求头的值应为文本。", "Header values must be text."));
150
+ return Object.entries(parsed.data);
151
+ }
152
+ function candidateId(label, identity, importId) {
153
+ if (/^[a-zA-Z0-9_-]{1,64}$/.test(importId) && ![
154
+ "__proto__",
155
+ "constructor",
156
+ "prototype"
157
+ ].includes(importId.toLowerCase())) return importId;
158
+ const slug = label.replace(/[^a-zA-Z0-9-]/g, "-").slice(0, 42);
159
+ const hash = createHash("sha256").update(importId ? JSON.stringify([identity, importId]) : identity).digest("hex").slice(0, 12);
160
+ return slug + "-" + hash;
161
+ }
162
+ function linkCandidate(address, name, overrides = {}, importId = "") {
163
+ const { url, xopcPrivateNetwork } = address;
164
+ const host = new URL(url).hostname;
165
+ const displayName = name || host;
166
+ return {
167
+ id: candidateId(host, url, importId),
168
+ name: displayName,
169
+ server: {
170
+ type: "http",
171
+ ...overrides,
172
+ url,
173
+ displayName,
174
+ xopcPublicOnly: !xopcPrivateNetwork,
175
+ xopcPrivateNetwork
176
+ }
177
+ };
178
+ }
179
+ function stdioCandidate(execution, name, host, t, overrides = {}, env, importId = "") {
180
+ const parsed = executionSchema.safeParse(execution);
181
+ if (!parsed.success) throw new McpDraftError(400, t("请检查可执行程序、参数和工作目录。", "Check the executable, arguments, and working directory."));
182
+ const { command, args = [], cwd } = parsed.data;
183
+ const directory = resolve(host.workspace, cwd || ".");
184
+ const executable = basename(command.replaceAll("\\", "/"));
185
+ const displayName = name || executable || command;
186
+ const signature = JSON.stringify([
187
+ command,
188
+ args,
189
+ directory
190
+ ]);
191
+ return {
192
+ id: candidateId(executable || "stdio", signature, importId),
193
+ name: displayName,
194
+ server: {
195
+ ...overrides,
196
+ type: "stdio",
197
+ command,
198
+ args,
199
+ cwd: directory,
200
+ env,
201
+ displayName,
202
+ xopcManagedStdio: true
203
+ }
204
+ };
205
+ }
206
+ function importCandidates(raw, host, t) {
207
+ let input;
208
+ try {
209
+ input = JSON.parse(raw ?? "");
210
+ } catch {
211
+ throw new McpDraftError(400, t("JSON 格式有误,请检查后重试。", "The JSON is invalid. Check the syntax and try again."));
212
+ }
213
+ if (!isRecord(input)) throw new McpDraftError(400, t("请粘贴一个 MCP 配置对象。", "Paste an MCP configuration object."));
214
+ const collection = input.mcpServers ?? (isRecord(input.mcp) ? input.mcp.servers : void 0) ?? input.servers;
215
+ if (collection !== void 0 && !isRecord(collection)) throw new McpDraftError(400, t("服务列表必须是 JSON 对象。", "The server list must be a JSON object."));
216
+ const entries = collection ? Object.entries(collection) : [["", input]];
217
+ const candidates = [];
218
+ let firstError;
219
+ for (const [key, item] of entries) try {
220
+ if (!isRecord(item)) throw new McpDraftError(400, t("每个服务都需要一个配置对象。", "Each server needs a configuration object."));
221
+ const { type, displayName, description, timeout, exposure, toolExposure, enabled } = item;
222
+ const stdio = Object.hasOwn(item, "command") || type === "stdio";
223
+ if (Object.keys(item).some((field) => !(stdio ? stdioImportKeys : httpImportKeys).includes(field)) || type !== void 0 && (stdio ? type !== "stdio" : !urlTransport.safeParse(type).success)) throw new McpDraftError(400, t("此配置包含不兼容的传输方式或字段。", "This configuration mixes incompatible transports or fields."));
224
+ const assignedName = z.string().trim().max(64).safeParse(displayName ?? key.slice(0, 64));
225
+ if (!assignedName.success) throw new McpDraftError(400, t("请检查服务名称。", "Check the server name."));
226
+ const shared = {
227
+ description,
228
+ timeout,
229
+ exposure,
230
+ toolExposure,
231
+ enabled
232
+ };
233
+ if (stdio) {
234
+ const base = McpServerSchema.safeParse({
235
+ ...shared,
236
+ command: item.command,
237
+ type: "stdio"
238
+ });
239
+ if (!base.success) throw new McpDraftError(400, t("请检查命令服务配置。", "Check the stdio server configuration."));
240
+ const rawEnv = z.record(z.string(), z.string()).optional().safeParse(item.env);
241
+ if (!rawEnv.success) throw new McpDraftError(400, t("环境变量的值应为文本。", "Environment variable values must be text."));
242
+ const env = rawEnv.data ? environment(Object.entries(rawEnv.data), t) : void 0;
243
+ candidates.push(stdioCandidate(item, assignedName.data, host, t, base.data, env, key));
244
+ continue;
245
+ }
246
+ const network = networkSchema.safeParse(item.network ?? "auto");
247
+ if (!network.success) throw new McpDraftError(400, t("请检查网络范围。", "Check the network scope."));
248
+ const address = serverAddress(item.url, network.data, t);
249
+ const base = McpServerSchema.safeParse({
250
+ ...shared,
251
+ url: address.url,
252
+ type
253
+ });
254
+ const oauthConfig = oauthSchema.optional().safeParse(item.oauth);
255
+ if (!base.success || !oauthConfig.success) throw new McpDraftError(400, t("请检查配置字段和 OAuth 设置。", "Check the configuration fields and OAuth settings."));
256
+ const entries = item.headers === void 0 ? [] : importedHeaderEntries(item.headers, t);
257
+ const staticHeaders = entries.length ? headerMap(entries, t) : void 0;
258
+ if (oauthConfig.data && Object.keys(staticHeaders ?? {}).some((name) => name.toLowerCase() === AUTHORIZATION_HEADER)) throw new McpDraftError(400, t("OAuth 配置不能同时指定 Authorization 请求头。", "An OAuth configuration cannot also specify an Authorization header."));
259
+ candidates.push(linkCandidate(address, assignedName.data, {
260
+ ...base.data,
261
+ type: base.data.type ?? "http",
262
+ headers: staticHeaders,
263
+ oauth: oauthConfig.data
264
+ }, key));
265
+ } catch (error) {
266
+ if (!(error instanceof McpDraftError)) throw error;
267
+ firstError ??= error;
268
+ }
269
+ if (!candidates.length) throw firstError ?? new McpDraftError(400, t("配置中没有可添加的服务。", "The configuration has no servers to add."));
270
+ return {
271
+ candidates,
272
+ unsupported: entries.length - candidates.length
273
+ };
274
+ }
275
+ function entry(t, options = {}) {
276
+ const server = options.candidate?.server;
277
+ const link = {
278
+ field: "mcp-mode",
279
+ value: "link"
280
+ };
281
+ const json = {
282
+ field: "mcp-mode",
283
+ value: "json"
284
+ };
285
+ const stdio = {
286
+ field: "mcp-mode",
287
+ value: "stdio"
288
+ };
289
+ return {
290
+ message: options.message,
291
+ fields: [
292
+ {
293
+ id: "mcp-mode",
294
+ label: t("添加方式", "Add method"),
295
+ type: "select",
296
+ presentation: "segmented",
297
+ value: options.source ?? "link",
298
+ options: [
299
+ {
300
+ id: "link",
301
+ label: t("服务链接", "Server URL")
302
+ },
303
+ {
304
+ id: "json",
305
+ label: t("粘贴 JSON", "Paste JSON")
306
+ },
307
+ {
308
+ id: "stdio",
309
+ label: t("命令启动", "Command")
310
+ }
311
+ ]
312
+ },
313
+ {
314
+ id: "url",
315
+ label: t("服务地址", "Server URL"),
316
+ type: "text",
317
+ value: typeof server?.url === "string" ? server.url : "",
318
+ hint: "https://example.com/mcp",
319
+ visibleWhen: link
320
+ },
321
+ {
322
+ id: "mcp-json",
323
+ label: t("MCP JSON 配置", "MCP JSON configuration"),
324
+ type: "multiline",
325
+ retain: true,
326
+ hint: "{ \"mcpServers\": { … } }",
327
+ visibleWhen: json
328
+ },
329
+ {
330
+ id: "command",
331
+ label: t("可执行程序", "Executable"),
332
+ type: "text",
333
+ value: server?.command ?? "",
334
+ hint: t("Gateway 上的程序名称或路径", "Program name or path on the Gateway"),
335
+ visibleWhen: stdio
336
+ },
337
+ {
338
+ id: "args",
339
+ label: t("参数(选填)", "Arguments (optional)"),
340
+ type: "multiline",
341
+ value: server?.args?.join("\n") ?? "",
342
+ hint: t("每行一个参数,空格会保留", "One argument per line. Spaces are preserved."),
343
+ visibleWhen: stdio
344
+ },
345
+ {
346
+ id: "id",
347
+ label: t("名称(选填)", "Name (optional)"),
348
+ type: "text",
349
+ value: options.candidate?.name ?? "",
350
+ hint: t("默认使用服务域名", "Defaults to the server domain"),
351
+ advanced: true,
352
+ visibleWhen: link
353
+ },
354
+ {
355
+ id: "transport",
356
+ label: t("传输协议", "Transport"),
357
+ type: "select",
358
+ value: server?.type === "sse" ? "sse" : "http",
359
+ advanced: true,
360
+ visibleWhen: link,
361
+ options: [{
362
+ id: "http",
363
+ label: "Streamable HTTP"
364
+ }, {
365
+ id: "sse",
366
+ label: t("旧版 SSE", "Legacy SSE")
367
+ }]
368
+ },
369
+ {
370
+ id: "network",
371
+ label: t("网络范围", "Network scope"),
372
+ type: "select",
373
+ value: server?.xopcPrivateNetwork ? "private" : "auto",
374
+ advanced: true,
375
+ visibleWhen: link,
376
+ options: [{
377
+ id: "auto",
378
+ label: t("自动识别", "Detect automatically")
379
+ }, {
380
+ id: "private",
381
+ label: t("Gateway 内网", "Gateway private network")
382
+ }]
383
+ },
384
+ {
385
+ id: "authMethod",
386
+ label: t("认证方式", "Authentication"),
387
+ type: "select",
388
+ value: options.method ?? "auto",
389
+ visibleWhen: link,
390
+ options: authOptions(t)
391
+ },
392
+ {
393
+ id: "commandName",
394
+ label: t("名称(选填)", "Name (optional)"),
395
+ type: "text",
396
+ value: options.source === "stdio" ? options.candidate?.name : "",
397
+ advanced: true,
398
+ visibleWhen: stdio
399
+ },
400
+ {
401
+ id: "cwd",
402
+ label: t("工作目录(选填)", "Working directory (optional)"),
403
+ type: "text",
404
+ value: server?.cwd ?? "",
405
+ hint: t("默认使用 Gateway 工作区", "Defaults to the Gateway workspace"),
406
+ advanced: true,
407
+ visibleWhen: stdio
408
+ },
409
+ {
410
+ id: "mcp-env",
411
+ label: t("环境变量(选填)", "Environment variables (optional)"),
412
+ type: "headers",
413
+ retain: true,
414
+ advanced: true,
415
+ visibleWhen: stdio
416
+ }
417
+ ],
418
+ advancedLabel: t("高级设置", "Advanced settings"),
419
+ detailsLabel: t("连接与数据说明", "Connection and data"),
420
+ details: t("检查由 Gateway 执行。使用工具时,任务数据可能发送给服务;命令模式会在 Gateway 主机启动程序。", "The Gateway performs the check. Tool usage may send task data to the service. Command mode starts a program on the Gateway host."),
421
+ actions: [
422
+ {
423
+ id: "create",
424
+ label: t("检查连接", "Check connection"),
425
+ visibleWhen: link
426
+ },
427
+ {
428
+ id: "preview",
429
+ label: t("预览配置", "Preview configuration"),
430
+ visibleWhen: json
431
+ },
432
+ {
433
+ id: "review-command",
434
+ label: t("审阅命令", "Review command"),
435
+ visibleWhen: stdio
436
+ }
437
+ ]
438
+ };
439
+ }
440
+ function authOptions(t) {
441
+ return [
442
+ {
443
+ id: "auto",
444
+ label: t("自动探测", "Detect automatically")
445
+ },
446
+ {
447
+ id: "oauth",
448
+ label: t("OAuth 浏览器授权", "OAuth in browser")
449
+ },
450
+ {
451
+ id: "bearer",
452
+ label: "Bearer Token"
453
+ },
454
+ {
455
+ id: "apiKey",
456
+ label: "API Key"
457
+ },
458
+ {
459
+ id: "headers",
460
+ label: t("自定义请求头", "Custom request headers")
461
+ },
462
+ {
463
+ id: "none",
464
+ label: t("无需认证", "No authentication")
465
+ }
466
+ ];
467
+ }
468
+ function backAction(t) {
469
+ return {
470
+ id: "edit",
471
+ label: t("返回配置", "Back to configuration")
472
+ };
473
+ }
474
+ function reviewSummary(candidate, t) {
475
+ if (!candidate) return {};
476
+ const { server } = candidate;
477
+ const transport = server.type === "sse" ? t("旧版 SSE", "Legacy SSE") : "Streamable HTTP";
478
+ const network = server.xopcPrivateNetwork ? t("Gateway 内网", "Gateway private network") : transport;
479
+ return {
480
+ headline: candidate.name,
481
+ subtitle: typeof server.url === "string" ? `${server.url} · ${network}${server.xopcPrivateNetwork && server.type === "sse" ? ` · ${transport}` : ""}` : t("在 Gateway 上运行 · stdio", "Runs on the Gateway · stdio")
482
+ };
483
+ }
484
+ function createMobileMcpSetup(drafts, readHost, publish) {
485
+ const flows = /* @__PURE__ */ new Map();
486
+ function clearDraft(flow) {
487
+ if (flow.draftId) drafts.remove(flow.owner, flow.draftId);
488
+ flow.draftId = void 0;
489
+ flow.toolCount = void 0;
490
+ }
491
+ function renew(flow, expiresAt = Date.now() + TTL_MS) {
492
+ clearTimeout(flow.timer);
493
+ flow.timer = setTimeout(() => {
494
+ if (flow.busy) {
495
+ renew(flow, Date.now() + 1e3);
496
+ return;
497
+ }
498
+ clearDraft(flow);
499
+ flows.delete(flow.id);
500
+ }, Math.max(1, expiresAt - Date.now()));
501
+ flow.timer.unref();
502
+ }
503
+ function newFlow(owner, t) {
504
+ const owned = [...flows.values()].filter((flow) => flow.owner === owner);
505
+ if (owned.filter((flow) => flow.phase !== "saved").length >= 8) {
506
+ const idle = owned.find((flow) => !flow.busy && flow.phase !== "authorizing" && flow.phase !== "saved");
507
+ if (idle) {
508
+ clearTimeout(idle.timer);
509
+ clearDraft(idle);
510
+ flows.delete(idle.id);
511
+ }
512
+ }
513
+ if (flows.size >= 100 || [...flows.values()].filter((flow) => flow.owner === owner && flow.phase !== "saved").length >= 8) throw new McpDraftError(429, t("未完成的配置过多,请稍后重试。", "Too many unfinished configurations. Try again shortly."));
514
+ const id = randomUUID();
515
+ const flow = {
516
+ id,
517
+ owner,
518
+ phase: "preview",
519
+ revision: 1,
520
+ busy: false
521
+ };
522
+ flows.set(id, flow);
523
+ renew(flow);
524
+ return flow;
525
+ }
526
+ function preview(flow, t) {
527
+ const candidates = flow.candidates ?? [];
528
+ const skipped = flow.unsupported ?? 0;
529
+ return {
530
+ flow: flow.id,
531
+ headline: t("选择服务", "Choose a server"),
532
+ message: skipped ? t(`每次添加一个服务。另有 ${skipped} 项配置在移动端不可用。`, `Add one server at a time. ${skipped} other configurations are unavailable on mobile.`) : t("每次添加一个服务。", "Add one server at a time."),
533
+ fields: [{
534
+ id: "selection",
535
+ label: t("服务", "Server"),
536
+ type: "select",
537
+ value: String(Math.max(0, candidates.indexOf(flow.selected ?? candidates[0]))),
538
+ options: candidates.map((item, index) => ({
539
+ id: String(index),
540
+ label: `${item.name} · ${typeof item.server.url === "string" ? item.server.url.replace(/^https?:\/\//, "").slice(0, 112) : t("命令启动", "Command")}`
541
+ }))
542
+ }],
543
+ actions: [{
544
+ id: "select",
545
+ label: t("检查所选连接", "Check selected connection")
546
+ }, backAction(t)]
547
+ };
548
+ }
549
+ function needsAuth(flow, t, message) {
550
+ flow.phase = "auth";
551
+ const initial = flow.method && flow.method !== "auto" && flow.method !== "oauth" ? flow.method : flow.rejectedHeaders ? "headers" : "";
552
+ const apiKey = {
553
+ field: "method",
554
+ value: "apiKey"
555
+ };
556
+ const previousKeyHeader = flow.method === "apiKey" ? Object.keys(flow.candidate?.server.headers ?? {})[0] : void 0;
557
+ return {
558
+ flow: flow.id,
559
+ ...reviewSummary(flow.candidate, t),
560
+ message: message ?? t("填写服务商提供的凭据。", "Enter the credentials provided by the service."),
561
+ fields: [
562
+ {
563
+ id: "method",
564
+ label: t("认证方式", "Authentication"),
565
+ type: "select",
566
+ value: initial,
567
+ options: [{
568
+ id: "",
569
+ label: t("选择认证方式", "Choose an authentication method")
570
+ }, ...authOptions(t)]
571
+ },
572
+ {
573
+ id: "token",
574
+ label: "Bearer Token",
575
+ type: "secret",
576
+ visibleWhen: {
577
+ field: "method",
578
+ value: "bearer"
579
+ }
580
+ },
581
+ {
582
+ id: "apiKeyHeader",
583
+ label: t("API Key 请求头名称", "API Key header name"),
584
+ type: "text",
585
+ value: previousKeyHeader ?? "X-API-Key",
586
+ hint: "X-API-Key",
587
+ visibleWhen: apiKey
588
+ },
589
+ {
590
+ id: "apiKey",
591
+ label: "API Key",
592
+ type: "secret",
593
+ visibleWhen: apiKey
594
+ },
595
+ {
596
+ id: "requestHeaders",
597
+ label: t("请求头", "Request headers"),
598
+ type: "headers",
599
+ visibleWhen: {
600
+ field: "method",
601
+ value: "headers"
602
+ }
603
+ }
604
+ ],
605
+ actions: [{
606
+ id: "verify",
607
+ label: t("检查连接", "Check connection")
608
+ }, backAction(t)]
609
+ };
610
+ }
611
+ function oauthReady(flow, t, message) {
612
+ flow.phase = "oauth";
613
+ return {
614
+ flow: flow.id,
615
+ ...reviewSummary(flow.candidate, t),
616
+ message: message ?? t("在服务商页面登录并授权。", "Sign in and authorize access on the provider’s website."),
617
+ actions: [
618
+ {
619
+ id: "authorize",
620
+ label: t("打开浏览器授权", "Authorize in browser")
621
+ },
622
+ {
623
+ id: "change-auth",
624
+ label: t("更改认证方式", "Change authentication")
625
+ },
626
+ backAction(t)
627
+ ]
628
+ };
629
+ }
630
+ function verified(flow, t, toolCount) {
631
+ flow.phase = "verified";
632
+ flow.toolCount = toolCount;
633
+ return {
634
+ flow: flow.id,
635
+ ...reviewSummary(flow.candidate, t),
636
+ tone: "success",
637
+ message: toolCount === 0 ? t("连接检查通过 · 未发现工具", "Connection verified · No tools found") : t(`连接检查通过 · 发现 ${toolCount} 个工具`, `Connection verified · ${toolCount} tools found`),
638
+ actions: [{
639
+ id: "save",
640
+ label: t("添加连接", "Add connection")
641
+ }, backAction(t)]
642
+ };
643
+ }
644
+ function retry(flow, t, result) {
645
+ flow.phase = "retry";
646
+ const stdio = flow.candidate?.server.type === "stdio";
647
+ const message = stdio ? t("程序未通过 MCP 检查。请核对 Gateway 上的可执行程序、工作目录和依赖。", "The program did not pass the MCP check. Verify the executable, working directory, and dependencies on the Gateway.") : result.errorCode === "rate_limited" ? t("服务请求过于频繁,请稍后重试。", "The service is rate limiting requests. Try again shortly.") : result.errorCode === "not_found" || result.errorCode === "invalid_response" ? t("此地址未返回有效的 MCP 响应,请核对服务地址。", "This address did not return a valid MCP response. Check the URL.") : result.errorCode === "access_denied" ? t("服务拒绝访问,请检查凭据或访问权限。", "Access was denied. Check your credentials or access permissions.") : t("无法连接到此服务,请检查地址和网络后重试。", "Could not reach this service. Check the URL and network, then try again.");
648
+ return {
649
+ flow: flow.id,
650
+ ...reviewSummary(flow.candidate, t),
651
+ message,
652
+ actions: [{
653
+ id: "retry",
654
+ label: stdio ? t("再次运行并检查", "Run and check again") : t("重新检查", "Check again")
655
+ }, backAction(t)]
656
+ };
657
+ }
658
+ function review(flow, candidate, t) {
659
+ flow.phase = "review";
660
+ const { server } = candidate;
661
+ const stdio = server.type === "stdio";
662
+ const command = JSON.stringify([server.command, ...server.args ?? []]);
663
+ const variables = Object.keys(server.env ?? {});
664
+ const message = stdio ? t("确认后,Gateway 会在主机上启动下面的程序并读取工具列表。", "Confirm to start the program on the Gateway host and list its tools.") : t("此地址由 Gateway 所在网络访问。localhost 指向 Gateway 主机。", "The Gateway accesses this address from its own network. Localhost refers to the Gateway host.");
665
+ const details = stdio ? [
666
+ command,
667
+ t(`工作目录 ${server.cwd}`, `Working directory ${server.cwd}`),
668
+ ...variables.length ? [t(`环境变量 ${variables.join(", ")}`, `Environment variables ${variables.join(", ")}`)] : []
669
+ ].join("\n") : void 0;
670
+ return {
671
+ flow: flow.id,
672
+ ...reviewSummary(candidate, t),
673
+ message,
674
+ reviewText: details,
675
+ actions: [{
676
+ id: "confirm-check",
677
+ label: stdio ? t("运行并检查", "Run and check") : t("检查内网连接", "Check private connection")
678
+ }, backAction(t)]
679
+ };
680
+ }
681
+ async function probe(flow, t) {
682
+ if (flow.candidate?.server.type === "stdio") assertMobileStdioAllowed(readHost().allowStdio, t);
683
+ const result = await drafts.probe(flow.owner, flow.draftId);
684
+ if (result.state === "connected") return verified(flow, t, result.toolCount ?? 0);
685
+ if (result.state === "oauth_required" && flow.method !== "none") return oauthReady(flow, t);
686
+ if (result.state === "oauth_required" || result.state === "token_required" || result.state === "auth_unknown" || flow.candidate?.server.url && result.errorCode === "access_denied") {
687
+ const hasCredentials = Object.keys(flow.candidate?.server.headers ?? {}).length > 0;
688
+ flow.rejectedHeaders = hasCredentials;
689
+ return needsAuth(flow, t, hasCredentials ? t("服务拒绝了访问。请检查凭据和权限,或切换认证方式。", "Access was denied. Check your credentials and permissions, or choose another authentication method.") : t("此服务要求认证。请根据服务商的说明选择认证方式。", "This service requires authentication. Choose the method specified by the provider."));
690
+ }
691
+ return retry(flow, t, result);
692
+ }
693
+ async function start(flow, candidate, method, t) {
694
+ flow.candidate = candidate;
695
+ flow.method = method;
696
+ flow.reviewed = false;
697
+ if (candidate.server.type === "stdio") assertMobileStdioAllowed(readHost().allowStdio, t);
698
+ if (candidate.server.type === "stdio" || candidate.server.xopcPrivateNetwork) return review(flow, candidate, t);
699
+ return connect(flow, t);
700
+ }
701
+ async function connect(flow, t) {
702
+ const method = flow.method;
703
+ if (method === "apiKey" || method === "headers" || method === "bearer" && !flow.candidate?.server.headers) return needsAuth(flow, t);
704
+ return testDraft(flow, t);
705
+ }
706
+ async function testDraft(flow, t) {
707
+ const candidate = flow.candidate;
708
+ if ((candidate.server.type === "stdio" || candidate.server.xopcPrivateNetwork) && !flow.reviewed) throw new McpDraftError(409, t("请先审阅连接。", "Review the connection first."));
709
+ if (candidate.server.type === "stdio") assertMobileStdioAllowed(readHost().allowStdio, t);
710
+ clearDraft(flow);
711
+ flow.phase = "retry";
712
+ try {
713
+ const draft = await drafts.create(flow.owner, {
714
+ serverId: candidate.id,
715
+ server: candidate.server
716
+ }, { protectCredentials: true });
717
+ flow.draftId = draft.id;
718
+ renew(flow, draft.expiresAt);
719
+ return flow.method === "oauth" ? oauthReady(flow, t) : await probe(flow, t);
720
+ } catch (error) {
721
+ if (!(error instanceof McpDraftError) || error.status !== 409) throw error;
722
+ return {
723
+ flow: flow.id,
724
+ ...reviewSummary(candidate, t),
725
+ message: t("此服务已添加,请返回修改地址或选择其他配置。", "This server is already added. Go back to change the URL or select another configuration."),
726
+ actions: [backAction(t)]
727
+ };
728
+ }
729
+ }
730
+ function authorization(flow, t, result) {
731
+ if (result.state === "connected") return verified(flow, t, result.toolCount ?? 0);
732
+ if (result.state === "error" || result.state === "cancelled") return oauthReady(flow, t, t("授权未完成,可以重试或返回配置。", "Authorization did not finish. Try again or go back."));
733
+ flow.phase = "authorizing";
734
+ let authorizationUrl;
735
+ if (result.authorizationUrl) {
736
+ authorizationUrl = browserAuthorizationUrl(result.authorizationUrl, flow.candidate?.server);
737
+ if (!authorizationUrl) return oauthReady(flow, t, t("服务未提供可用的授权链接。", "The provider did not return a usable authorization link."));
738
+ }
739
+ return {
740
+ flow: flow.id,
741
+ ...reviewSummary(flow.candidate, t),
742
+ authorizationUrl,
743
+ pollAction: "status",
744
+ message: t("请在浏览器完成授权,返回后将自动检查连接。", "Finish authorization in the browser. The connection will be checked when you return."),
745
+ fields: result.acceptsRedirect ? [{
746
+ id: "callback",
747
+ label: t("浏览器最后打开的地址", "Final browser address"),
748
+ type: "secret",
749
+ advanced: true,
750
+ hint: t("仅在授权未自动完成时使用", "Use only if authorization does not finish automatically")
751
+ }] : void 0,
752
+ actions: [backAction(t), ...result.acceptsRedirect ? [{
753
+ id: "callback",
754
+ label: t("完成授权", "Finish authorization"),
755
+ advanced: true
756
+ }] : []]
757
+ };
758
+ }
759
+ return async function mobileMcpSetup(owner, t, command) {
760
+ if (!command) return entry(t);
761
+ const { action, values } = command;
762
+ if (!command.flow && action === "preview") {
763
+ const imported = importCandidates(values["mcp-json"], readHost(), t);
764
+ const flow = newFlow(owner, t);
765
+ flow.candidates = imported.candidates;
766
+ flow.unsupported = imported.unsupported;
767
+ return {
768
+ ...preview(flow, t),
769
+ revision: flow.revision
770
+ };
771
+ }
772
+ if (!command.flow && (action === "create" || action === "review-command")) {
773
+ const stdio = action === "review-command";
774
+ const name = z.string().trim().max(64).safeParse((stdio ? values.commandName : values.id) ?? "");
775
+ const method = authSchema.safeParse(stdio ? "none" : values.authMethod ?? (values.token ? "bearer" : "auto"));
776
+ if (!name.success || !method.success) throw new McpDraftError(400, t("请检查名称和认证方式。", "Check the name and authentication method."));
777
+ let candidate;
778
+ if (stdio) {
779
+ const host = readHost();
780
+ assertMobileStdioAllowed(host.allowStdio, t);
781
+ candidate = stdioCandidate({
782
+ command: values.command,
783
+ args: values.args?.split(/\r?\n/).filter((line) => line.length > 0),
784
+ cwd: values.cwd
785
+ }, name.data, host, t, {}, environment(keyValueRows(values["mcp-env"], t), t));
786
+ } else {
787
+ const transport = urlTransport.safeParse(values.transport ?? "http");
788
+ const network = networkSchema.safeParse(values.network ?? "auto");
789
+ if (!transport.success || !network.success) throw new McpDraftError(400, t("请检查传输协议和网络范围。", "Check the transport and network scope."));
790
+ const address = serverAddress(values.url, network.data, t);
791
+ const headers = method.data === "bearer" && values.token ? bearerHeaders(values.token, t) : void 0;
792
+ candidate = linkCandidate(address, name.data, {
793
+ type: transport.data,
794
+ headers
795
+ });
796
+ }
797
+ const flow = newFlow(owner, t);
798
+ flow.busy = true;
799
+ try {
800
+ return {
801
+ ...await start(flow, candidate, method.data, t),
802
+ revision: flow.revision
803
+ };
804
+ } catch (error) {
805
+ clearTimeout(flow.timer);
806
+ clearDraft(flow);
807
+ flows.delete(flow.id);
808
+ throw error;
809
+ } finally {
810
+ flow.busy = false;
811
+ }
812
+ }
813
+ const flow = command.flow ? flows.get(command.flow) : void 0;
814
+ if (!flow || flow.owner !== owner) return entry(t, { message: t("配置已过期,请重新检查。", "Setup expired. Check the connection again.") });
815
+ if (flow.busy) throw new McpDraftError(409, t("正在处理,请稍后重试。", "An operation is in progress. Try again shortly."));
816
+ if (flow.receipt?.action === action && flow.receipt.revision === command.revision) return flow.receipt.panel;
817
+ if (command.revision !== flow.revision) throw new McpDraftError(409, t("配置步骤已变更,请刷新后重试。", "The setup step changed. Refresh and try again."));
818
+ const phase = flow.phase;
819
+ flow.busy = true;
820
+ try {
821
+ const panel = await operate(flow, t, command);
822
+ if (!panel.flow) return panel;
823
+ const revision = flow.revision;
824
+ if (action !== "status" || phase !== flow.phase) flow.revision += 1;
825
+ const result = {
826
+ ...panel,
827
+ revision: flow.revision
828
+ };
829
+ if (flow.revision !== revision) flow.receipt = action === "save" || action === "status" || action === "callback" ? {
830
+ action,
831
+ revision,
832
+ panel: result
833
+ } : void 0;
834
+ return result;
835
+ } finally {
836
+ flow.busy = false;
837
+ }
838
+ };
839
+ async function operate(flow, t, { action, values }) {
840
+ const { owner } = flow;
841
+ if (action === "edit" && flow.phase !== "saved") {
842
+ clearDraft(flow);
843
+ if (flow.candidates && flow.phase !== "preview") {
844
+ flow.phase = "preview";
845
+ flow.candidate = void 0;
846
+ flow.method = void 0;
847
+ flow.rejectedHeaders = void 0;
848
+ renew(flow);
849
+ return preview(flow, t);
850
+ }
851
+ clearTimeout(flow.timer);
852
+ flows.delete(flow.id);
853
+ return entry(t, flow.candidates ? { source: "json" } : {
854
+ source: flow.candidate?.server.type === "stdio" ? "stdio" : "link",
855
+ candidate: flow.candidate,
856
+ method: flow.method
857
+ });
858
+ }
859
+ if (action === "select" && flow.phase === "preview") {
860
+ const index = z.string().regex(/^\d+$/).safeParse(values.selection);
861
+ const candidate = index.success ? flow.candidates?.[Number(index.data)] : void 0;
862
+ if (!candidate) throw new McpDraftError(400, t("请选择一个服务。", "Select a server."));
863
+ flow.selected = candidate;
864
+ return await start(flow, candidate, candidate.server.oauth ? "oauth" : "auto", t);
865
+ }
866
+ if (action === "confirm-check" && flow.phase === "review" && flow.candidate) {
867
+ if (flow.candidate.server.type === "stdio") assertMobileStdioAllowed(readHost().allowStdio, t);
868
+ flow.reviewed = true;
869
+ return await connect(flow, t);
870
+ }
871
+ if (action === "verify" && flow.phase === "auth" && flow.candidate) {
872
+ const method = authSchema.safeParse(values.method);
873
+ if (!method.success) throw new McpDraftError(400, t("请选择认证方式。", "Choose an authentication method."));
874
+ const server = { ...flow.candidate.server };
875
+ if (method.data !== "oauth" || flow.method !== "oauth") server.headers = void 0;
876
+ if (method.data === "bearer") server.headers = bearerHeaders(values.token, t);
877
+ else if (method.data === "apiKey") server.headers = headerMap([[values.apiKeyHeader ?? "X-API-Key", values.apiKey ?? ""]], t);
878
+ else if (method.data === "headers") server.headers = headerMap(keyValueRows(values.requestHeaders, t).filter(([name, value]) => name.trim() || value.trim()), t);
879
+ if (method.data !== "oauth") server.oauth = void 0;
880
+ flow.candidate = {
881
+ ...flow.candidate,
882
+ server
883
+ };
884
+ flow.method = method.data;
885
+ flow.rejectedHeaders = false;
886
+ return await testDraft(flow, t);
887
+ }
888
+ if (action === "change-auth" && flow.phase === "oauth") return needsAuth(flow, t);
889
+ if (action === "retry" && flow.phase === "retry" && flow.draftId) return await probe(flow, t);
890
+ if (action === "authorize" && flow.phase === "oauth" && flow.draftId) return authorization(flow, t, drafts.authorize(owner, flow.draftId));
891
+ if ((action === "status" || action === "callback") && flow.phase === "authorizing" && flow.draftId) {
892
+ if (action === "callback") {
893
+ const url = z.url().max(8192).safeParse(values.callback?.trim());
894
+ if (!url.success) throw new McpDraftError(400, t("请粘贴完整的浏览器地址。", "Paste the complete browser address."));
895
+ drafts.redirect(owner, flow.draftId, url.data);
896
+ }
897
+ return authorization(flow, t, drafts.authorization(owner, flow.draftId));
898
+ }
899
+ if (action === "save" && flow.phase === "verified" && flow.draftId && flow.candidate) {
900
+ const candidate = flow.candidate;
901
+ const enable = candidate.server.enabled !== false;
902
+ const result = await publish(owner, flow.draftId, enable, candidate.server.type === "stdio", t);
903
+ const remaining = flow.candidates?.filter((item) => item.id !== candidate.id) ?? [];
904
+ const message = result.reloadRequired ? t("连接已保存,重启网关后生效。", "Connection saved. Restart the Gateway to apply it.") : enable ? t("连接已添加", "Connection added") : t("连接已添加 · 已停用", "Connection added · Disabled");
905
+ const saved = {
906
+ flow: flow.id,
907
+ ...reviewSummary(candidate, t),
908
+ message,
909
+ tone: "success",
910
+ actions: [{
911
+ id: "done",
912
+ label: t("完成", "Done"),
913
+ dismiss: true
914
+ }, ...remaining.length ? [{
915
+ id: "add-another",
916
+ label: t("继续导入其他服务", "Import another server")
917
+ }] : []]
918
+ };
919
+ flow.phase = "saved";
920
+ flow.candidate = void 0;
921
+ flow.selected = void 0;
922
+ flow.candidates = remaining.length ? remaining : void 0;
923
+ flow.draftId = void 0;
924
+ renew(flow);
925
+ return saved;
926
+ }
927
+ if (action === "add-another" && flow.phase === "saved" && flow.candidates?.length) {
928
+ flow.phase = "preview";
929
+ return preview(flow, t);
930
+ }
931
+ if (action === "status" && flow.phase === "verified") return verified(flow, t, flow.toolCount ?? 0);
932
+ throw new McpDraftError(409, t("此操作已失效,请返回当前配置步骤。", "This action is no longer available. Return to the current setup step."));
933
+ }
934
+ }
935
+ function assertMobileStdioAllowed(allowed, t) {
936
+ if (!allowed) throw new McpDraftError(409, t("请由 Gateway 管理员运行 xopc config set gateway.mobileMcpAllowStdio true,启用移动端命令启动。", "Ask the Gateway administrator to run xopc config set gateway.mobileMcpAllowStdio true to enable mobile command launch."));
937
+ }
938
+ function browserAuthorizationUrl(raw, server) {
939
+ try {
940
+ const url = new URL(raw);
941
+ if (url.protocol !== "https:" || url.username || url.password) return;
942
+ if (server?.xopcPrivateNetwork && typeof server.url === "string" && new URL(server.url).origin === url.origin) return isPrivateMcpTarget(url) ? url.href : void 0;
943
+ return isPublicMcpTarget(url) ? url.href : void 0;
944
+ } catch {
945
+ return;
946
+ }
947
+ }
948
+ //#endregion
949
+ export { assertMobileStdioAllowed, createMobileMcpSetup };