@zortexhq/indra-v2.5 0.2.5 → 0.2.7

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 (790) hide show
  1. package/README.md +129 -109
  2. package/dist/cli-run.js +1 -1
  3. package/dist/codex-setup.js +1 -1
  4. package/dist/connector-worker.js +1 -1
  5. package/dist/content-find.js +2 -0
  6. package/dist/ensure-ready.js +1 -0
  7. package/dist/gateway.js +1 -1
  8. package/dist/help-launch.js +1 -1
  9. package/dist/local-cloud-policy.js +1 -1
  10. package/dist/mcp.js +2 -2
  11. package/dist/onboarding.js +1 -1
  12. package/dist/operation-telemetry.js +1 -1
  13. package/dist/profile-upgrade.js +1 -1
  14. package/dist/public-tool.js +1 -0
  15. package/dist/recovery-progress.js +1 -1
  16. package/dist/recovery-text.js +1 -1
  17. package/dist/recovery.js +1 -1
  18. package/dist/resident-ensure-ready.js +1 -0
  19. package/dist/resident-host.js +2 -2
  20. package/dist/resident-jobs.js +1 -1
  21. package/dist/resident-platform.js +1 -1
  22. package/dist/resident-telemetry.js +1 -1
  23. package/dist/source-catalog.js +1 -1
  24. package/dist/startup.js +1 -2
  25. package/dist/supervised-sync.js +1 -1
  26. package/dist/tools.js +1 -1
  27. package/dist/update-cli.js +1 -1
  28. package/dist/web.js +2 -2
  29. package/node_modules/@zortexhq/plugin-auth-core/dist/device-admission.js +2 -2
  30. package/node_modules/@zortexhq/plugin-auth-core/dist/index.js +1 -1
  31. package/node_modules/@zortexhq/plugin-auth-core/package.json +1 -8
  32. package/node_modules/@zortexhq/plugin-auto-connect/dist/api/index.js +1 -1
  33. package/node_modules/@zortexhq/plugin-auto-connect/package.json +0 -3
  34. package/node_modules/@zortexhq/plugin-connector-calendar/dist/actions.js +1 -1
  35. package/node_modules/@zortexhq/plugin-connector-core/dist/api/index.js +1 -1
  36. package/node_modules/@zortexhq/plugin-connector-core/dist/enrollment.js +1 -1
  37. package/node_modules/@zortexhq/plugin-connector-core/dist/hub.js +1 -1
  38. package/node_modules/@zortexhq/plugin-connector-core/package.json +1 -3
  39. package/node_modules/@zortexhq/plugin-connector-fleet/dist/index.js +1 -1
  40. package/node_modules/@zortexhq/plugin-connector-fleet/package.json +1 -4
  41. package/node_modules/@zortexhq/plugin-connector-framework/dist/api/browser-authorization.js +1 -0
  42. package/node_modules/@zortexhq/plugin-connector-framework/dist/api/index.js +1 -1
  43. package/node_modules/@zortexhq/plugin-connector-framework/dist/runner.js +1 -1
  44. package/node_modules/@zortexhq/plugin-connector-framework/package.json +0 -3
  45. package/node_modules/@zortexhq/plugin-connector-level1/dist/additional-sources.js +1 -1
  46. package/node_modules/@zortexhq/plugin-connector-level1/dist/index.js +1 -1
  47. package/node_modules/@zortexhq/plugin-connector-level1/dist/matrix-login.js +1 -1
  48. package/node_modules/@zortexhq/plugin-connector-level1/dist/provisioning.js +1 -1
  49. package/node_modules/@zortexhq/plugin-connector-level1/dist/shallow.js +1 -1
  50. package/node_modules/@zortexhq/plugin-connector-level1/dist/sources.js +1 -1
  51. package/node_modules/@zortexhq/plugin-connector-level1/package.json +1 -4
  52. package/node_modules/@zortexhq/plugin-connector-notion/dist/broker.js +1 -1
  53. package/node_modules/@zortexhq/plugin-connector-notion/dist/index.js +1 -1
  54. package/node_modules/@zortexhq/plugin-connector-notion/dist/provider.js +1 -1
  55. package/node_modules/@zortexhq/plugin-connector-notion/package.json +1 -3
  56. package/node_modules/@zortexhq/plugin-connector-steam/dist/index.js +1 -1
  57. package/node_modules/@zortexhq/plugin-connector-steam/dist/provider.js +1 -1
  58. package/node_modules/@zortexhq/plugin-connector-steam/package.json +1 -3
  59. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/app-model.js +1 -1
  60. package/node_modules/@zortexhq/plugin-galaxy-ui/src/integration/connection-panel.js +1 -1
  61. package/node_modules/@zortexhq/plugin-google-auth/dist/index.js +1 -1
  62. package/node_modules/@zortexhq/plugin-google-auth/package.json +1 -3
  63. package/node_modules/@zortexhq/plugin-telemetry/dist/api/telemetry.js +1 -1
  64. package/node_modules/@zortexhq/plugin-vault-sqlite/dist/index.js +1 -1
  65. package/package.json +6 -20
  66. package/profiles/core.yml +0 -18
  67. package/release-provenance.json +27 -93
  68. package/update-manifest.json +362 -4744
  69. package/dist/cloud-action-proof.js +0 -1
  70. package/dist/cloud-device-host.js +0 -1
  71. package/dist/cloud-device-identity.js +0 -1
  72. package/dist/cloud-download-sink.js +0 -1
  73. package/dist/cloud-gmail-actions.js +0 -1
  74. package/dist/cloud-gmail-audit.js +0 -1
  75. package/dist/cloud-gmail-bound-audit-runner.js +0 -1
  76. package/dist/cloud-gmail-bound-epoch.js +0 -1
  77. package/dist/cloud-gmail-bound-identity.js +0 -1
  78. package/dist/cloud-gmail-bound-runner.js +0 -1
  79. package/dist/cloud-gmail-provider.js +0 -1
  80. package/dist/cloud-gmail-rpc.js +0 -1
  81. package/dist/cloud-gmail-sync.js +0 -1
  82. package/node_modules/@zortexhq/plugin-auth-core/dist/cloud-frame.js +0 -1
  83. package/node_modules/@zortexhq/plugin-auth-core/dist/cloud-vault-keyring.js +0 -1
  84. package/node_modules/@zortexhq/plugin-cloud-ai/dist/account.js +0 -1
  85. package/node_modules/@zortexhq/plugin-cloud-ai/dist/adopt.js +0 -1
  86. package/node_modules/@zortexhq/plugin-cloud-ai/dist/index.js +0 -1
  87. package/node_modules/@zortexhq/plugin-cloud-ai/dist/pack.js +0 -1
  88. package/node_modules/@zortexhq/plugin-cloud-ai/dist/publish.js +0 -1
  89. package/node_modules/@zortexhq/plugin-cloud-ai/dist/records.js +0 -1
  90. package/node_modules/@zortexhq/plugin-cloud-ai/package.json +0 -17
  91. package/node_modules/@zortexhq/plugin-cloud-vault/dist/device-trust.js +0 -1
  92. package/node_modules/@zortexhq/plugin-cloud-vault/dist/owner-admission.js +0 -1
  93. package/node_modules/@zortexhq/plugin-cloud-vault/package.json +0 -19
  94. package/node_modules/@zortexhq/plugin-connector-core/dist/api/browser-authorization.js +0 -1
  95. package/node_modules/@zortexhq/plugin-connector-framework/dist/api/original-miner.js +0 -1
  96. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-codec.js +0 -2
  97. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-fs.js +0 -1
  98. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-move-worker.js +0 -1
  99. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-move.js +0 -1
  100. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-posix.js +0 -1
  101. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-public.js +0 -1
  102. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-replay.js +0 -1
  103. package/node_modules/@zortexhq/plugin-connector-framework/dist/checkpoint-store.js +0 -1
  104. package/node_modules/@zortexhq/plugin-connector-framework/dist/chromium-local/chromium-history.js +0 -1
  105. package/node_modules/@zortexhq/plugin-connector-framework/dist/chromium-local/index.js +0 -1
  106. package/node_modules/@zortexhq/plugin-connector-framework/dist/chromium-local/normalize-visit.js +0 -1
  107. package/node_modules/@zortexhq/plugin-connector-framework/dist/connection-health.js +0 -1
  108. package/node_modules/@zortexhq/plugin-connector-framework/dist/connector.js +0 -1
  109. package/node_modules/@zortexhq/plugin-connector-framework/dist/failure-type.js +0 -1
  110. package/node_modules/@zortexhq/plugin-connector-framework/dist/index.js +0 -1
  111. package/node_modules/@zortexhq/plugin-connector-framework/dist/windows-custody.js +0 -1
  112. package/node_modules/@zortexhq/plugin-connector-level1/dist/chatgpt.js +0 -1
  113. package/node_modules/@zortexhq/plugin-connector-level1/dist/signed-in.js +0 -1
  114. package/node_modules/@zortexhq/plugin-connector-social/dist/full-sync.js +0 -1
  115. package/node_modules/@zortexhq/plugin-connector-social/dist/index.js +0 -1
  116. package/node_modules/@zortexhq/plugin-connector-social/dist/provider.js +0 -1
  117. package/node_modules/@zortexhq/plugin-connector-social/dist/sites.js +0 -1
  118. package/node_modules/@zortexhq/plugin-connector-social/package.json +0 -22
  119. package/node_modules/@zortexhq/plugin-connector-steam/dist/browser-session.js +0 -1
  120. package/node_modules/@zortexhq/plugin-connectors/package.json +0 -17
  121. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/attached.js +0 -11
  122. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/browser.js +0 -1
  123. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/decision.js +0 -1
  124. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/extension-transport.js +0 -1
  125. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/feedback.js +0 -1
  126. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-bridge.js +0 -1
  127. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-oauth-driver.js +0 -1
  128. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/google-uia-decision.js +0 -1
  129. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/index.js +0 -1
  130. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/microsoft-oauth-bridge.js +0 -1
  131. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/microsoft-oauth-driver.js +0 -1
  132. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/page-inspect.js +0 -6
  133. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/runner.js +0 -1
  134. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/slack-oauth-bridge.js +0 -1
  135. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/slack-oauth-driver.js +0 -1
  136. package/node_modules/@zortexhq/plugin-jev-autopilot/dist/whatsapp-session.js +0 -1
  137. package/node_modules/@zortexhq/plugin-jev-autopilot/extension/manifest.json +0 -9
  138. package/node_modules/@zortexhq/plugin-jev-autopilot/package.json +0 -21
  139. package/node_modules/@zortexhq/plugin-jev-browser-driver/assets/ax-page.js +0 -1
  140. package/node_modules/@zortexhq/plugin-jev-browser-driver/assets/uia-page.ps1 +0 -545
  141. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/approved-control.js +0 -1
  142. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/attached-session.js +0 -8
  143. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-account-policy.js +0 -1
  144. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-memory.js +0 -1
  145. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-planner.js +0 -8
  146. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/authorization-task.js +0 -1
  147. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-actions.js +0 -1
  148. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/browser-task.js +0 -7
  149. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/combined.js +0 -1
  150. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/decision.js +0 -5
  151. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/driver.js +0 -1
  152. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/google-oauth-driver.js +0 -1
  153. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/index.js +0 -1
  154. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/isolated-display.js +0 -1
  155. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/microsoft-oauth-driver.js +0 -1
  156. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/native-session.js +0 -1
  157. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/notion-oauth-driver.js +0 -1
  158. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/observe-log.js +0 -1
  159. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/operational-browser.js +0 -1
  160. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/page-settle.js +0 -1
  161. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/planned-oauth.js +0 -1
  162. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/session-routes.js +0 -1
  163. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/shared-session.js +0 -1
  164. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/site-read.js +0 -1
  165. package/node_modules/@zortexhq/plugin-jev-browser-driver/dist/slack-oauth-driver.js +0 -1
  166. package/node_modules/@zortexhq/plugin-jev-browser-driver/package.json +0 -20
  167. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-background.cs +0 -492
  168. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-guard-x64.build.json +0 -30
  169. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-guard-x64.dll +0 -0
  170. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-oauth-guard.c +0 -692
  171. package/node_modules/@zortexhq/plugin-oauth-browser-driver/assets/windows-uia-oauth.ps1 +0 -3840
  172. package/node_modules/@zortexhq/plugin-oauth-browser-driver/dist/api/index.js +0 -1
  173. package/node_modules/@zortexhq/plugin-oauth-browser-driver/dist/driver.js +0 -3
  174. package/node_modules/@zortexhq/plugin-oauth-browser-driver/dist/index.js +0 -1
  175. package/node_modules/@zortexhq/plugin-oauth-browser-driver/package.json +0 -19
  176. package/node_modules/chatgpt-web-mcp/.env.example +0 -30
  177. package/node_modules/chatgpt-web-mcp/CONTRIBUTING.md +0 -65
  178. package/node_modules/chatgpt-web-mcp/LICENSE +0 -21
  179. package/node_modules/chatgpt-web-mcp/README.en.md +0 -149
  180. package/node_modules/chatgpt-web-mcp/README.md +0 -194
  181. package/node_modules/chatgpt-web-mcp/SECURITY.md +0 -37
  182. package/node_modules/chatgpt-web-mcp/node_modules/zod/LICENSE +0 -21
  183. package/node_modules/chatgpt-web-mcp/node_modules/zod/README.md +0 -208
  184. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.cjs +0 -33
  185. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.d.cts +0 -4
  186. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.d.ts +0 -4
  187. package/node_modules/chatgpt-web-mcp/node_modules/zod/index.js +0 -4
  188. package/node_modules/chatgpt-web-mcp/node_modules/zod/package.json +0 -118
  189. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/index.ts +0 -4
  190. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/ZodError.ts +0 -330
  191. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/datetime.ts +0 -58
  192. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/discriminatedUnion.ts +0 -80
  193. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/index.ts +0 -59
  194. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/ipv4.ts +0 -57
  195. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/object.ts +0 -69
  196. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/primitives.ts +0 -162
  197. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/realworld.ts +0 -63
  198. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/string.ts +0 -55
  199. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/benchmarks/union.ts +0 -80
  200. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/errors.ts +0 -13
  201. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/external.ts +0 -6
  202. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/enumUtil.ts +0 -17
  203. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/errorUtil.ts +0 -8
  204. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/parseUtil.ts +0 -176
  205. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/partialUtil.ts +0 -34
  206. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/typeAliases.ts +0 -2
  207. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/helpers/util.ts +0 -224
  208. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/index.ts +0 -4
  209. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/locales/en.ts +0 -124
  210. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/standard-schema.ts +0 -113
  211. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/Mocker.ts +0 -54
  212. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/all-errors.test.ts +0 -157
  213. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/anyunknown.test.ts +0 -28
  214. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/array.test.ts +0 -71
  215. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/async-parsing.test.ts +0 -388
  216. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/async-refinements.test.ts +0 -46
  217. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/base.test.ts +0 -29
  218. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/bigint.test.ts +0 -55
  219. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/branded.test.ts +0 -53
  220. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/catch.test.ts +0 -220
  221. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/coerce.test.ts +0 -133
  222. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/complex.test.ts +0 -56
  223. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/custom.test.ts +0 -31
  224. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/date.test.ts +0 -32
  225. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/deepmasking.test.ts +0 -186
  226. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/default.test.ts +0 -112
  227. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/description.test.ts +0 -33
  228. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/discriminated-unions.test.ts +0 -315
  229. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/enum.test.ts +0 -80
  230. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/error.test.ts +0 -551
  231. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/firstparty.test.ts +0 -87
  232. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/firstpartyschematypes.test.ts +0 -21
  233. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/function.test.ts +0 -257
  234. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/generics.test.ts +0 -48
  235. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/instanceof.test.ts +0 -37
  236. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/intersection.test.ts +0 -110
  237. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/language-server.source.ts +0 -76
  238. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/language-server.test.ts +0 -207
  239. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/literal.test.ts +0 -36
  240. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/map.test.ts +0 -110
  241. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/masking.test.ts +0 -4
  242. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/mocker.test.ts +0 -19
  243. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/nan.test.ts +0 -21
  244. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/nativeEnum.test.ts +0 -87
  245. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/nullable.test.ts +0 -42
  246. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/number.test.ts +0 -176
  247. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/object-augmentation.test.ts +0 -29
  248. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/object-in-es5-env.test.ts +0 -29
  249. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/object.test.ts +0 -434
  250. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/optional.test.ts +0 -42
  251. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/parseUtil.test.ts +0 -23
  252. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/parser.test.ts +0 -41
  253. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/partials.test.ts +0 -243
  254. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/pickomit.test.ts +0 -111
  255. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/pipeline.test.ts +0 -29
  256. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/preprocess.test.ts +0 -186
  257. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/primitive.test.ts +0 -440
  258. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/promise.test.ts +0 -90
  259. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/readonly.test.ts +0 -194
  260. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/record.test.ts +0 -171
  261. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/recursive.test.ts +0 -197
  262. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/refine.test.ts +0 -313
  263. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/safeparse.test.ts +0 -27
  264. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/set.test.ts +0 -142
  265. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/standard-schema.test.ts +0 -83
  266. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/string.test.ts +0 -916
  267. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/transformer.test.ts +0 -233
  268. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/tuple.test.ts +0 -90
  269. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/unions.test.ts +0 -57
  270. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/validations.test.ts +0 -133
  271. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/tests/void.test.ts +0 -15
  272. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v3/types.ts +0 -5136
  273. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/checks.ts +0 -30
  274. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/coerce.ts +0 -27
  275. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/compat.ts +0 -66
  276. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/errors.ts +0 -75
  277. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/external.ts +0 -50
  278. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/index.ts +0 -5
  279. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/iso.ts +0 -90
  280. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/parse.ts +0 -33
  281. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/schemas.ts +0 -2054
  282. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/anyunknown.test.ts +0 -26
  283. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/array.test.ts +0 -264
  284. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/assignability.test.ts +0 -210
  285. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/async-parsing.test.ts +0 -381
  286. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/async-refinements.test.ts +0 -68
  287. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/base.test.ts +0 -7
  288. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/bigint.test.ts +0 -54
  289. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/brand.test.ts +0 -63
  290. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/catch.test.ts +0 -252
  291. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/coalesce.test.ts +0 -20
  292. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/coerce.test.ts +0 -160
  293. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/continuability.test.ts +0 -352
  294. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/custom.test.ts +0 -40
  295. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/date.test.ts +0 -31
  296. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/datetime.test.ts +0 -296
  297. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/default.test.ts +0 -313
  298. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/description.test.ts +0 -32
  299. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +0 -619
  300. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/enum.test.ts +0 -285
  301. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +0 -527
  302. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/error.test.ts +0 -711
  303. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/file.test.ts +0 -91
  304. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/firstparty.test.ts +0 -175
  305. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/function.test.ts +0 -268
  306. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/generics.test.ts +0 -72
  307. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/index.test.ts +0 -829
  308. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +0 -34
  309. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/intersection.test.ts +0 -171
  310. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/json.test.ts +0 -108
  311. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/lazy.test.ts +0 -227
  312. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/literal.test.ts +0 -92
  313. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/map.test.ts +0 -196
  314. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nan.test.ts +0 -21
  315. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nested-refine.test.ts +0 -168
  316. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nonoptional.test.ts +0 -86
  317. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/nullable.test.ts +0 -22
  318. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/number.test.ts +0 -247
  319. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/object.test.ts +0 -563
  320. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/optional.test.ts +0 -123
  321. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/partial.test.ts +0 -147
  322. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/pickomit.test.ts +0 -127
  323. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/pipe.test.ts +0 -81
  324. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/prefault.test.ts +0 -37
  325. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/preprocess.test.ts +0 -298
  326. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/primitive.test.ts +0 -175
  327. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/promise.test.ts +0 -81
  328. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/prototypes.test.ts +0 -23
  329. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/readonly.test.ts +0 -252
  330. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/record.test.ts +0 -342
  331. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +0 -356
  332. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/refine.test.ts +0 -532
  333. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/registries.test.ts +0 -204
  334. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/set.test.ts +0 -179
  335. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/standard-schema.test.ts +0 -57
  336. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/string-formats.test.ts +0 -109
  337. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/string.test.ts +0 -881
  338. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +0 -66
  339. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +0 -758
  340. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +0 -2314
  341. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/transform.test.ts +0 -250
  342. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/tuple.test.ts +0 -163
  343. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/union.test.ts +0 -94
  344. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/validations.test.ts +0 -283
  345. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/classic/tests/void.test.ts +0 -12
  346. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/api.ts +0 -1594
  347. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/checks.ts +0 -1283
  348. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/config.ts +0 -15
  349. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/core.ts +0 -134
  350. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/doc.ts +0 -44
  351. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/errors.ts +0 -424
  352. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/function.ts +0 -176
  353. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/index.ts +0 -15
  354. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/json-schema.ts +0 -143
  355. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/parse.ts +0 -94
  356. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/regexes.ts +0 -135
  357. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/registries.ts +0 -96
  358. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/schemas.ts +0 -3842
  359. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/standard-schema.ts +0 -64
  360. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/index.test.ts +0 -46
  361. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/be.test.ts +0 -124
  362. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/en.test.ts +0 -22
  363. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/ru.test.ts +0 -128
  364. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/tests/locales/tr.test.ts +0 -69
  365. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/to-json-schema.ts +0 -977
  366. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/util.ts +0 -775
  367. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/versions.ts +0 -5
  368. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/core/zsf.ts +0 -323
  369. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/index.ts +0 -4
  370. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ar.ts +0 -125
  371. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/az.ts +0 -121
  372. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/be.ts +0 -184
  373. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ca.ts +0 -127
  374. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/cs.ts +0 -142
  375. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/de.ts +0 -124
  376. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/en.ts +0 -127
  377. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/eo.ts +0 -125
  378. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/es.ts +0 -125
  379. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fa.ts +0 -134
  380. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fi.ts +0 -131
  381. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fr-CA.ts +0 -126
  382. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/fr.ts +0 -124
  383. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/he.ts +0 -125
  384. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/hu.ts +0 -126
  385. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/id.ts +0 -125
  386. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/index.ts +0 -39
  387. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/it.ts +0 -125
  388. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ja.ts +0 -122
  389. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/kh.ts +0 -126
  390. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ko.ts +0 -131
  391. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/mk.ts +0 -127
  392. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ms.ts +0 -124
  393. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/nl.ts +0 -126
  394. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/no.ts +0 -124
  395. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ota.ts +0 -125
  396. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/pl.ts +0 -126
  397. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ps.ts +0 -133
  398. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/pt.ts +0 -123
  399. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ru.ts +0 -184
  400. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/sl.ts +0 -126
  401. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/sv.ts +0 -127
  402. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ta.ts +0 -125
  403. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/th.ts +0 -126
  404. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/tr.ts +0 -121
  405. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ua.ts +0 -126
  406. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/ur.ts +0 -126
  407. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/vi.ts +0 -125
  408. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/zh-CN.ts +0 -123
  409. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/locales/zh-TW.ts +0 -125
  410. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/checks.ts +0 -32
  411. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/coerce.ts +0 -22
  412. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/external.ts +0 -40
  413. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/index.ts +0 -3
  414. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/iso.ts +0 -62
  415. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/parse.ts +0 -1
  416. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/schemas.ts +0 -1579
  417. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/assignability.test.ts +0 -129
  418. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/brand.test.ts +0 -51
  419. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/checks.test.ts +0 -144
  420. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/computed.test.ts +0 -36
  421. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/error.test.ts +0 -22
  422. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/functions.test.ts +0 -43
  423. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/index.test.ts +0 -871
  424. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/number.test.ts +0 -95
  425. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/object.test.ts +0 -185
  426. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/prototypes.test.ts +0 -43
  427. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/recursive-types.test.ts +0 -275
  428. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4/mini/tests/string.test.ts +0 -299
  429. package/node_modules/chatgpt-web-mcp/node_modules/zod/src/v4-mini/index.ts +0 -1
  430. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.cjs +0 -138
  431. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.d.cts +0 -164
  432. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.d.ts +0 -164
  433. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/ZodError.js +0 -133
  434. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.cjs +0 -17
  435. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.d.cts +0 -5
  436. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.d.ts +0 -5
  437. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/errors.js +0 -9
  438. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.cjs +0 -22
  439. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.d.cts +0 -6
  440. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.d.ts +0 -6
  441. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/external.js +0 -6
  442. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.cjs +0 -2
  443. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.d.cts +0 -8
  444. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.d.ts +0 -8
  445. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/enumUtil.js +0 -1
  446. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.cjs +0 -9
  447. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.d.cts +0 -9
  448. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.d.ts +0 -9
  449. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/errorUtil.js +0 -6
  450. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.cjs +0 -124
  451. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.d.cts +0 -78
  452. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.d.ts +0 -78
  453. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/parseUtil.js +0 -109
  454. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.cjs +0 -2
  455. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.d.cts +0 -8
  456. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.d.ts +0 -8
  457. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/partialUtil.js +0 -1
  458. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.cjs +0 -2
  459. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.d.cts +0 -2
  460. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.d.ts +0 -2
  461. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/typeAliases.js +0 -1
  462. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.cjs +0 -137
  463. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.d.cts +0 -85
  464. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.d.ts +0 -85
  465. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/helpers/util.js +0 -133
  466. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.cjs +0 -33
  467. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.d.cts +0 -4
  468. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.d.ts +0 -4
  469. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/index.js +0 -4
  470. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.cjs +0 -111
  471. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.d.cts +0 -3
  472. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.d.ts +0 -3
  473. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/locales/en.js +0 -109
  474. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.cjs +0 -2
  475. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.d.cts +0 -102
  476. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.d.ts +0 -102
  477. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/standard-schema.js +0 -1
  478. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.cjs +0 -3775
  479. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.d.cts +0 -1031
  480. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.d.ts +0 -1031
  481. package/node_modules/chatgpt-web-mcp/node_modules/zod/v3/types.js +0 -3693
  482. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.cjs +0 -32
  483. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.d.cts +0 -1
  484. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.d.ts +0 -1
  485. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/checks.js +0 -1
  486. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.cjs +0 -47
  487. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.d.cts +0 -17
  488. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.d.ts +0 -17
  489. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/coerce.js +0 -17
  490. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.cjs +0 -57
  491. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.d.cts +0 -46
  492. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.d.ts +0 -46
  493. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/compat.js +0 -27
  494. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.cjs +0 -67
  495. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.d.cts +0 -30
  496. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.d.ts +0 -30
  497. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/errors.js +0 -41
  498. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.cjs +0 -70
  499. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.d.cts +0 -13
  500. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.d.ts +0 -13
  501. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/external.js +0 -18
  502. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.cjs +0 -33
  503. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.d.cts +0 -4
  504. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.d.ts +0 -4
  505. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/index.js +0 -4
  506. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.cjs +0 -60
  507. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.d.cts +0 -22
  508. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.d.ts +0 -22
  509. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/iso.js +0 -30
  510. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.cjs +0 -32
  511. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.d.cts +0 -23
  512. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.d.ts +0 -23
  513. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/parse.js +0 -6
  514. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.cjs +0 -1109
  515. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.d.cts +0 -630
  516. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.d.ts +0 -630
  517. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/classic/schemas.js +0 -1006
  518. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.cjs +0 -1039
  519. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.d.cts +0 -284
  520. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.d.ts +0 -284
  521. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/api.js +0 -906
  522. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.cjs +0 -591
  523. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.d.cts +0 -278
  524. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.d.ts +0 -278
  525. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/checks.js +0 -565
  526. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.cjs +0 -67
  527. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.d.cts +0 -49
  528. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.d.ts +0 -49
  529. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/core.js +0 -61
  530. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.cjs +0 -39
  531. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.d.cts +0 -14
  532. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.d.ts +0 -14
  533. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/doc.js +0 -35
  534. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.cjs +0 -226
  535. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.d.cts +0 -208
  536. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.d.ts +0 -208
  537. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/errors.js +0 -195
  538. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.cjs +0 -102
  539. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.d.cts +0 -52
  540. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.d.ts +0 -52
  541. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/function.js +0 -75
  542. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.cjs +0 -44
  543. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.d.cts +0 -15
  544. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.d.ts +0 -15
  545. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/index.js +0 -15
  546. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.cjs +0 -2
  547. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.d.cts +0 -87
  548. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.d.ts +0 -87
  549. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/json-schema.js +0 -1
  550. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.cjs +0 -87
  551. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.d.cts +0 -25
  552. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.d.ts +0 -25
  553. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/parse.js +0 -57
  554. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.cjs +0 -103
  555. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.d.cts +0 -62
  556. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.d.ts +0 -62
  557. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/regexes.js +0 -95
  558. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.cjs +0 -56
  559. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.d.cts +0 -35
  560. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.d.ts +0 -35
  561. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/registries.js +0 -51
  562. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.cjs +0 -1748
  563. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.d.cts +0 -1041
  564. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.d.ts +0 -1041
  565. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/schemas.js +0 -1717
  566. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.cjs +0 -2
  567. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.d.cts +0 -55
  568. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.d.ts +0 -55
  569. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/standard-schema.js +0 -1
  570. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.cjs +0 -854
  571. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.d.cts +0 -88
  572. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.d.ts +0 -88
  573. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/to-json-schema.js +0 -849
  574. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.cjs +0 -539
  575. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.d.cts +0 -183
  576. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.d.ts +0 -183
  577. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/util.js +0 -493
  578. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.cjs +0 -8
  579. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.d.cts +0 -5
  580. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.d.ts +0 -5
  581. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/core/versions.js +0 -5
  582. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.cjs +0 -22
  583. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.d.cts +0 -3
  584. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.d.ts +0 -3
  585. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/index.js +0 -3
  586. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.cjs +0 -142
  587. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.d.cts +0 -4
  588. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.d.ts +0 -4
  589. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ar.js +0 -116
  590. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.cjs +0 -141
  591. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.d.cts +0 -4
  592. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.d.ts +0 -4
  593. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/az.js +0 -115
  594. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.cjs +0 -190
  595. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.d.cts +0 -4
  596. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.d.ts +0 -4
  597. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/be.js +0 -164
  598. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.cjs +0 -144
  599. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.d.cts +0 -4
  600. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.d.ts +0 -4
  601. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ca.js +0 -118
  602. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.cjs +0 -161
  603. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.d.cts +0 -4
  604. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.d.ts +0 -4
  605. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/cs.js +0 -135
  606. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.cjs +0 -142
  607. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.d.cts +0 -4
  608. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.d.ts +0 -4
  609. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/de.js +0 -116
  610. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.cjs +0 -145
  611. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.d.cts +0 -5
  612. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.d.ts +0 -5
  613. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/en.js +0 -117
  614. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.cjs +0 -144
  615. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.d.cts +0 -5
  616. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.d.ts +0 -5
  617. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/eo.js +0 -116
  618. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.cjs +0 -143
  619. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.d.cts +0 -4
  620. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.d.ts +0 -4
  621. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/es.js +0 -117
  622. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.cjs +0 -148
  623. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.d.cts +0 -4
  624. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.d.ts +0 -4
  625. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fa.js +0 -122
  626. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.cjs +0 -148
  627. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.d.cts +0 -4
  628. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.d.ts +0 -4
  629. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fi.js +0 -122
  630. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.cjs +0 -143
  631. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.d.cts +0 -4
  632. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.d.ts +0 -4
  633. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr-CA.js +0 -117
  634. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.cjs +0 -142
  635. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.d.cts +0 -4
  636. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.d.ts +0 -4
  637. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/fr.js +0 -116
  638. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.cjs +0 -143
  639. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.d.cts +0 -4
  640. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.d.ts +0 -4
  641. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/he.js +0 -117
  642. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.cjs +0 -143
  643. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.d.cts +0 -4
  644. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.d.ts +0 -4
  645. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/hu.js +0 -117
  646. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.cjs +0 -142
  647. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.d.cts +0 -4
  648. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.d.ts +0 -4
  649. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/id.js +0 -116
  650. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.cjs +0 -84
  651. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.d.cts +0 -39
  652. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.d.ts +0 -39
  653. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/index.js +0 -39
  654. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.cjs +0 -143
  655. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.d.cts +0 -4
  656. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.d.ts +0 -4
  657. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/it.js +0 -117
  658. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.cjs +0 -141
  659. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.d.cts +0 -4
  660. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.d.ts +0 -4
  661. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ja.js +0 -115
  662. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.cjs +0 -143
  663. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.d.cts +0 -4
  664. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.d.ts +0 -4
  665. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/kh.js +0 -117
  666. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.cjs +0 -147
  667. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.d.cts +0 -4
  668. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.d.ts +0 -4
  669. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ko.js +0 -121
  670. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.cjs +0 -144
  671. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.d.cts +0 -4
  672. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.d.ts +0 -4
  673. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/mk.js +0 -118
  674. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.cjs +0 -142
  675. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.d.cts +0 -4
  676. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.d.ts +0 -4
  677. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ms.js +0 -116
  678. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.cjs +0 -143
  679. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.d.cts +0 -4
  680. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.d.ts +0 -4
  681. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/nl.js +0 -117
  682. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.cjs +0 -142
  683. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.d.cts +0 -4
  684. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.d.ts +0 -4
  685. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/no.js +0 -116
  686. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.cjs +0 -143
  687. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.d.cts +0 -4
  688. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.d.ts +0 -4
  689. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ota.js +0 -117
  690. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.cjs +0 -143
  691. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.d.cts +0 -4
  692. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.d.ts +0 -4
  693. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pl.js +0 -117
  694. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.cjs +0 -148
  695. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.d.cts +0 -4
  696. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.d.ts +0 -4
  697. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ps.js +0 -122
  698. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.cjs +0 -142
  699. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.d.cts +0 -4
  700. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.d.ts +0 -4
  701. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/pt.js +0 -116
  702. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.cjs +0 -190
  703. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.d.cts +0 -4
  704. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.d.ts +0 -4
  705. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ru.js +0 -164
  706. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.cjs +0 -143
  707. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.d.cts +0 -4
  708. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.d.ts +0 -4
  709. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sl.js +0 -117
  710. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.cjs +0 -144
  711. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.d.cts +0 -4
  712. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.d.ts +0 -4
  713. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/sv.js +0 -118
  714. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.cjs +0 -143
  715. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.d.cts +0 -4
  716. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.d.ts +0 -4
  717. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ta.js +0 -117
  718. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.cjs +0 -143
  719. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.d.cts +0 -4
  720. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.d.ts +0 -4
  721. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/th.js +0 -117
  722. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.cjs +0 -143
  723. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.d.cts +0 -5
  724. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.d.ts +0 -5
  725. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/tr.js +0 -115
  726. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.cjs +0 -143
  727. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.d.cts +0 -4
  728. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.d.ts +0 -4
  729. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ua.js +0 -117
  730. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.cjs +0 -143
  731. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.d.cts +0 -4
  732. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.d.ts +0 -4
  733. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/ur.js +0 -117
  734. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.cjs +0 -142
  735. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.d.cts +0 -4
  736. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.d.ts +0 -4
  737. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/vi.js +0 -116
  738. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.cjs +0 -142
  739. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.d.cts +0 -4
  740. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.d.ts +0 -4
  741. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-CN.js +0 -116
  742. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.cjs +0 -143
  743. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.d.cts +0 -4
  744. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.d.ts +0 -4
  745. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/locales/zh-TW.js +0 -117
  746. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.cjs +0 -34
  747. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.d.cts +0 -1
  748. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.d.ts +0 -1
  749. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/checks.js +0 -1
  750. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.cjs +0 -47
  751. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.d.cts +0 -7
  752. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.d.ts +0 -7
  753. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/coerce.js +0 -17
  754. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.cjs +0 -62
  755. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.d.cts +0 -11
  756. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.d.ts +0 -11
  757. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/external.js +0 -13
  758. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.cjs +0 -32
  759. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.d.cts +0 -3
  760. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.d.ts +0 -3
  761. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/index.js +0 -3
  762. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.cjs +0 -60
  763. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.d.cts +0 -22
  764. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.d.ts +0 -22
  765. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/iso.js +0 -30
  766. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.cjs +0 -8
  767. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.d.cts +0 -1
  768. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.d.ts +0 -1
  769. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/parse.js +0 -1
  770. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.cjs +0 -839
  771. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.d.cts +0 -356
  772. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.d.ts +0 -356
  773. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4/mini/schemas.js +0 -732
  774. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.cjs +0 -17
  775. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.d.cts +0 -1
  776. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.d.ts +0 -1
  777. package/node_modules/chatgpt-web-mcp/node_modules/zod/v4-mini/index.js +0 -1
  778. package/node_modules/chatgpt-web-mcp/package.json +0 -50
  779. package/node_modules/chatgpt-web-mcp/scripts/doctor.js +0 -40
  780. package/node_modules/chatgpt-web-mcp/scripts/inspect.js +0 -16
  781. package/node_modules/chatgpt-web-mcp/scripts/login.js +0 -32
  782. package/node_modules/chatgpt-web-mcp/scripts/smoke-mcp.js +0 -26
  783. package/node_modules/chatgpt-web-mcp/src/browser.js +0 -4670
  784. package/node_modules/chatgpt-web-mcp/src/cli.js +0 -27
  785. package/node_modules/chatgpt-web-mcp/src/config.js +0 -210
  786. package/node_modules/chatgpt-web-mcp/src/errors.js +0 -20
  787. package/node_modules/chatgpt-web-mcp/src/index.js +0 -381
  788. package/node_modules/chatgpt-web-mcp/src/login-lifecycle.js +0 -39
  789. package/node_modules/chatgpt-web-mcp/src/selectors.js +0 -151
  790. package/profiles/social-worker.yml +0 -18
@@ -1,4670 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import { spawn } from "node:child_process";
3
- import { closeOwnedChild, closeVerifiedBrowser } from "./login-lifecycle.js";
4
- import net from "node:net";
5
- import path from "node:path";
6
-
7
- import { chromium } from "playwright-core";
8
-
9
- import {
10
- ACTION_TIMEOUT_MS,
11
- AUTH_CACHE_MS,
12
- CHATGPT_URL,
13
- CHROME_EXECUTABLE,
14
- CONVERSATION_CHANGE_INTERVAL_MS,
15
- CONTEXT_ARCHIVE_DIR,
16
- DEFAULT_ANSWER_TIER,
17
- HEADLESS,
18
- HISTORY_QUIET_PERIOD_MS,
19
- MAX_HISTORY_RESULTS,
20
- MAX_CONVERSATION_TURNS,
21
- BROWSER_STATE_FILE,
22
- NETWORK_LOG_FILE,
23
- OPERATION_LOCK_FILE,
24
- PAGE_INTERACTION_INTERVAL_MS,
25
- PAGE_STARTUP_DELAY_MS,
26
- POST_BREAKER_COOLDOWN_MS,
27
- POST_RESPONSE_CONVERSATION_COOLDOWN_MS,
28
- PROBE_ACCEPT_CLASSIFICATION,
29
- PROBE_ACCEPT_PATTERN,
30
- PROBE_ENABLED,
31
- PROBE_FALLBACK_CLASSIFICATION,
32
- PROBE_FALLBACK_PATTERN,
33
- PROBE_NETWORK_ACCEPT_CLASSIFICATION,
34
- PROBE_POLICY_KEY,
35
- PROBE_PROMPT,
36
- PRO_ANSWER_TIER,
37
- PRO_PROBE_RECHECK_AFTER_CLOSE_MS,
38
- RECONNECT_DELAY_MS,
39
- REFRESH_BEFORE_NEW_CHAT,
40
- RESPONSE_TIMEOUT_MS,
41
- RUNTIME_LOCK_FILE,
42
- RUNTIME_STATE_FILE,
43
- SEND_INTERVAL_MS,
44
- SITE_ACTION_INTERVAL_MS,
45
- USER_DATA_DIR,
46
- } from "./config.js";
47
- import { ChatGPTWebError } from "./errors.js";
48
- import { SELECTORS, TEXT } from "./selectors.js";
49
-
50
- // `:has-text()` is a Playwright-only selector and cannot be passed to
51
- // document.querySelectorAll() inside page.evaluate(). Filter stale thinking
52
- // wrappers in JavaScript instead, using an anchored match so a real answer
53
- // mentioning the word "thinking" is not discarded.
54
- const THINKING_WRAPPER_RE = /^\s*(?:thinking|思考)(?:\s*(?:[.…::]|$))/iu;
55
-
56
- function normalize(value) {
57
- return String(value || "")
58
- .replace(/\s+/g, " ")
59
- .trim()
60
- .toLocaleLowerCase();
61
- }
62
-
63
- /**
64
- * Decide whether an automation request may write to the composer.
65
- *
66
- * A non-empty composer is user-owned state. It must never be replaced by a
67
- * tool retry or by a follow-up sent to the currently selected conversation.
68
- */
69
- export function promptWriteAction(existingText, requestedText, { append = false } = {}) {
70
- const existing = String(existingText || "");
71
- const requested = String(requestedText || "");
72
- if (append) return "append";
73
- if (!normalize(existing)) return "replace-empty";
74
- if (normalize(existing) === normalize(requested)) return "already-present";
75
- return "reject-nonempty";
76
- }
77
-
78
- export function composerEditReason({ insideUserMessage = false, visibleCancel = false } = {}) {
79
- if (insideUserMessage) return "composer-inside-user-message";
80
- if (visibleCancel) return "visible-edit-cancel-control";
81
- return null;
82
- }
83
-
84
- export function isProModel(value) {
85
- return /(^|[\s._-])pro($|[\s._-])/i.test(String(value || "").trim());
86
- }
87
-
88
- export function isProTier(value) {
89
- return (
90
- normalize(value) === normalize(PRO_ANSWER_TIER) ||
91
- isProModel(value)
92
- );
93
- }
94
-
95
- export function parseAnswerTier(valueText) {
96
- const text = String(valueText || "").replace(/\s+/g, " ").trim();
97
- return text ? text.split(/[,,]/, 1)[0]?.trim() || null : null;
98
- }
99
-
100
- export function normalizeModelSlug(value) {
101
- return String(value || "")
102
- .trim()
103
- .toLocaleLowerCase()
104
- .replace(/[_\s.]+/g, "-")
105
- .replace(/-+/g, "-");
106
- }
107
-
108
- export function classifyNetworkModelSlug(
109
- modelSlug,
110
- {
111
- fallbackClassification = PROBE_FALLBACK_CLASSIFICATION,
112
- acceptClassification = PROBE_NETWORK_ACCEPT_CLASSIFICATION,
113
- } = {},
114
- ) {
115
- const normalized = normalizeModelSlug(modelSlug);
116
- if (!normalized) return null;
117
- if (/^gpt-5-5-mini(?:-|$)/u.test(normalized)) return fallbackClassification;
118
- return acceptClassification;
119
- }
120
-
121
- export function interruptedGenerationFields(runtime, interruptedAt = Date.now()) {
122
- return runtime?.activeGeneration?.active
123
- ? { activeGeneration: null, lastGenerationInterruptedAt: interruptedAt }
124
- : { activeGeneration: null };
125
- }
126
-
127
- function matchesConfiguredPattern(text, pattern) {
128
- try {
129
- return new RegExp(pattern, "iu").test(text);
130
- } catch (error) {
131
- throw new ChatGPTWebError("身份探针的匹配表达式无效。", {
132
- pattern,
133
- cause: error instanceof Error ? error.message : String(error),
134
- });
135
- }
136
- }
137
-
138
- export function classifyProbeModel(
139
- response,
140
- {
141
- acceptPattern = PROBE_ACCEPT_PATTERN,
142
- fallbackPattern = PROBE_FALLBACK_PATTERN,
143
- acceptClassification = PROBE_ACCEPT_CLASSIFICATION,
144
- fallbackClassification = PROBE_FALLBACK_CLASSIFICATION,
145
- networkAcceptClassification = PROBE_NETWORK_ACCEPT_CLASSIFICATION,
146
- networkModelSlug = null,
147
- requireNetworkModelSlug = false,
148
- } = {},
149
- ) {
150
- if (networkModelSlug != null) {
151
- const networkClassification = classifyNetworkModelSlug(networkModelSlug, {
152
- acceptClassification: networkAcceptClassification,
153
- fallbackClassification,
154
- });
155
- if (networkClassification) return networkClassification;
156
- }
157
- if (requireNetworkModelSlug) return "unknown";
158
- const text = String(response || "");
159
- if (matchesConfiguredPattern(text, acceptPattern)) return acceptClassification;
160
- if (matchesConfiguredPattern(text, fallbackPattern)) return fallbackClassification;
161
- return "unknown";
162
- }
163
-
164
- export function classifyRateLimitText(text) {
165
- const body = normalize(text);
166
- const limited =
167
- /请求过于频繁|too many requests|request.*too frequent/.test(body) &&
168
- /稍等|分钟|try again|wait/.test(body);
169
- if (!limited) return { limited: false, scope: null };
170
-
171
- if (
172
- /访问对话记录|对话记录|聊天记录|conversation history|chat history|conversation list/.test(
173
- body,
174
- )
175
- ) {
176
- return { limited: true, scope: "history" };
177
- }
178
- if (/发送|消息|生成|回答|prompt|message|generation|response/.test(body)) {
179
- return { limited: true, scope: "generation" };
180
- }
181
- return { limited: true, scope: "unknown" };
182
- }
183
-
184
- /**
185
- * Detect the page-level conversation length failure before another prompt is
186
- * submitted. ChatGPT has shipped both English and Chinese variants of this
187
- * banner; matching the stable meaning keeps the guard independent of wording.
188
- */
189
- export function classifyConversationLengthText(text) {
190
- const body = normalize(text);
191
- const limited =
192
- /you(?:'|’)ve reached the maximum length for this conversation/.test(body) ||
193
- /maximum length .*conversation.*start(?:ing)? a new chat/.test(body) ||
194
- /对话(?:已)?达到(?:最大)?长度(?:上限)?|对话长度上限|此对话的长度上限/.test(body) ||
195
- /conversation (?:is )?(?:too long|at maximum length)/.test(body);
196
- return {
197
- limited,
198
- scope: limited ? "conversation-length" : null,
199
- };
200
- }
201
-
202
- export function conversationTurnLimitState(
203
- { userMessageCount = 0, assistantMessageCount = 0, lengthLimitDetected = false } = {},
204
- limit = MAX_CONVERSATION_TURNS,
205
- ) {
206
- const users = Math.max(0, Number(userMessageCount) || 0);
207
- const assistants = Math.max(0, Number(assistantMessageCount) || 0);
208
- const turns = Math.max(users, assistants);
209
- const threshold = Math.max(1, Number(limit) || MAX_CONVERSATION_TURNS);
210
- return {
211
- userMessageCount: users,
212
- assistantMessageCount: assistants,
213
- turnCount: turns,
214
- limit: threshold,
215
- limitReached: turns >= threshold,
216
- lengthLimitDetected: Boolean(lengthLimitDetected),
217
- shouldRotate: Boolean(lengthLimitDetected || turns >= threshold),
218
- };
219
- }
220
-
221
- export function siteActionDelayMs(
222
- lastActionAt,
223
- now = Date.now(),
224
- intervalMs = SITE_ACTION_INTERVAL_MS,
225
- ) {
226
- const elapsed = now - Number(lastActionAt || 0);
227
- return Math.max(0, Number(intervalMs || 0) - elapsed);
228
- }
229
-
230
- export function networkRateLimitScope(pathname) {
231
- const value = String(pathname || "");
232
- if (/^\/backend-api\/conversations(?:\/|$)/i.test(value)) return "history";
233
- if (/^\/backend-api\/conversation(?:\/|$)/i.test(value)) return "generation";
234
- return "http-429";
235
- }
236
-
237
- const CONVERSATION_CHANGE_ACTIONS = new Set([
238
- "refresh-before-new-chat",
239
- "new-chat",
240
- "enable-temporary-chat",
241
- "disable-temporary-chat",
242
- "select-history",
243
- ]);
244
-
245
- const HISTORY_QUIET_ACTIONS = new Set([
246
- "refresh-before-new-chat",
247
- "read-history-api",
248
- "new-chat",
249
- "disable-temporary-chat",
250
- "open-history-sidebar",
251
- "open-history-search",
252
- "search-history",
253
- "select-history",
254
- ]);
255
-
256
- function isConversationChangeAction(action) {
257
- return CONVERSATION_CHANGE_ACTIONS.has(action);
258
- }
259
-
260
- function isHistoryQuietAction(action) {
261
- return HISTORY_QUIET_ACTIONS.has(action);
262
- }
263
-
264
- export function siteActionWaitMs(
265
- state,
266
- action,
267
- now = Date.now(),
268
- {
269
- siteActionIntervalMs = SITE_ACTION_INTERVAL_MS,
270
- sendIntervalMs = SEND_INTERVAL_MS,
271
- conversationChangeIntervalMs = CONVERSATION_CHANGE_INTERVAL_MS,
272
- postResponseConversationCooldownMs = POST_RESPONSE_CONVERSATION_COOLDOWN_MS,
273
- postBreakerCooldownMs = POST_BREAKER_COOLDOWN_MS,
274
- } = {},
275
- ) {
276
- const lastPageActionAt = Math.max(
277
- Number(state?.lastSiteActionAt || 0),
278
- Number(state?.lastPageInteractionAt || 0),
279
- );
280
- const siteWaitMs = siteActionDelayMs(lastPageActionAt, now, siteActionIntervalMs);
281
- const sendWaitMs =
282
- action === "send-prompt"
283
- ? siteActionDelayMs(state?.lastSendAt, now, sendIntervalMs)
284
- : 0;
285
- const conversationChangeWaitMs = isConversationChangeAction(action)
286
- ? siteActionDelayMs(
287
- state?.lastConversationChangeAt,
288
- now,
289
- conversationChangeIntervalMs,
290
- )
291
- : 0;
292
- const postResponseWaitMs = isConversationChangeAction(action)
293
- ? siteActionDelayMs(
294
- state?.lastGenerationCompletedAt,
295
- now,
296
- postResponseConversationCooldownMs,
297
- )
298
- : 0;
299
- const historyQuietWaitMs = isHistoryQuietAction(action)
300
- ? Math.max(0, Number(state?.historyQuietUntil || 0) - now)
301
- : 0;
302
- const cooldownWaitMs = state?.postBreakerCooldownPending
303
- ? siteActionDelayMs(
304
- state?.circuitBreakerClearedAt,
305
- now,
306
- postBreakerCooldownMs,
307
- )
308
- : 0;
309
- return Math.max(
310
- siteWaitMs,
311
- sendWaitMs,
312
- conversationChangeWaitMs,
313
- postResponseWaitMs,
314
- historyQuietWaitMs,
315
- cooldownWaitMs,
316
- );
317
- }
318
-
319
- export function validProbeCache(
320
- value,
321
- {
322
- mode,
323
- session = {},
324
- now = Date.now(),
325
- recheckAfterCloseMs = PRO_PROBE_RECHECK_AFTER_CLOSE_MS,
326
- } = {},
327
- ) {
328
- if (!value) return null;
329
- if (value.policyKey !== PROBE_POLICY_KEY) return null;
330
- if (value.modelSlugSource !== "conversation-response" || !value.modelSlug) {
331
- return null;
332
- }
333
- if (classifyNetworkModelSlug(value.modelSlug) !== value.classification) {
334
- return null;
335
- }
336
- if (
337
- ![
338
- PROBE_ACCEPT_CLASSIFICATION,
339
- PROBE_FALLBACK_CLASSIFICATION,
340
- PROBE_NETWORK_ACCEPT_CLASSIFICATION,
341
- ].includes(
342
- value.classification,
343
- )
344
- ) {
345
- return null;
346
- }
347
- if (normalize(value.mode) !== normalize(mode)) return null;
348
-
349
- const browserSessionId = String(session.browserSessionId || "");
350
- const chatgptPageId = String(session.chatgptPageId || "");
351
- const legacySessionCanBind =
352
- !value.browserSessionId &&
353
- Number(session.browserStartedAt || 0) > 0 &&
354
- Number(session.browserStartedAt) <= Number(value.checkedAt || 0);
355
- const sameBrowserSession = value.browserSessionId
356
- ? value.browserSessionId === browserSessionId
357
- : legacySessionCanBind;
358
- const sameChatGPTPage = value.chatgptPageId
359
- ? value.chatgptPageId === chatgptPageId
360
- : legacySessionCanBind;
361
-
362
- if (
363
- session.browserRunning &&
364
- session.chatgptPageOpen &&
365
- sameBrowserSession &&
366
- sameChatGPTPage
367
- ) {
368
- if (
369
- value.browserSessionId === browserSessionId &&
370
- value.chatgptPageId === chatgptPageId &&
371
- !value.sessionInterruptedAt &&
372
- !value.recheckAfter &&
373
- value.expiresAt == null
374
- ) {
375
- return value;
376
- }
377
- return {
378
- ...value,
379
- browserSessionId,
380
- chatgptPageId,
381
- sessionInterruptedAt: null,
382
- recheckAfter: null,
383
- expiresAt: null,
384
- };
385
- }
386
-
387
- const sessionInterruptedAt = Number(value.sessionInterruptedAt) || now;
388
- const recheckAfter =
389
- Number(value.recheckAfter) ||
390
- sessionInterruptedAt + Number(recheckAfterCloseMs || 0);
391
- if (now >= recheckAfter) return null;
392
- if (
393
- Number(value.sessionInterruptedAt) === sessionInterruptedAt &&
394
- Number(value.recheckAfter) === recheckAfter
395
- ) {
396
- return value;
397
- }
398
- return {
399
- ...value,
400
- sessionInterruptedAt,
401
- recheckAfter,
402
- expiresAt: recheckAfter,
403
- };
404
- }
405
-
406
- export function redactDiagnosticPath(value) {
407
- return String(value || "")
408
- .replace(/\/(c|conversation|share)\/[^/?#]+/gi, "/$1/:id")
409
- .replace(/[0-9a-f]{8}-[0-9a-f-]{27,}/gi, ":id")
410
- .replace(/\b[a-zA-Z0-9_-]{24,}\b/g, ":id");
411
- }
412
-
413
- function abortReason(signal) {
414
- return new ChatGPTWebError("MCP 调用已取消,后台操作已经停止。", {
415
- cancelled: true,
416
- cause: signal?.reason instanceof Error ? signal.reason.message : undefined,
417
- });
418
- }
419
-
420
- function throwIfAborted(signal) {
421
- if (signal?.aborted) throw abortReason(signal);
422
- }
423
-
424
- async function waitWithAbort(ms, signal) {
425
- throwIfAborted(signal);
426
- if (!(ms > 0)) return;
427
- await new Promise((resolve, reject) => {
428
- const timeout = setTimeout(done, ms);
429
- const onAbort = () => done(abortReason(signal));
430
- function done(error) {
431
- clearTimeout(timeout);
432
- signal?.removeEventListener("abort", onAbort);
433
- if (error) reject(error);
434
- else resolve();
435
- }
436
- signal?.addEventListener("abort", onAbort, { once: true });
437
- });
438
- }
439
-
440
- async function raceWithAbort(promise, signal, onAbort) {
441
- throwIfAborted(signal);
442
- if (!signal) return promise;
443
- return new Promise((resolve, reject) => {
444
- let settled = false;
445
- const finish = (callback, value) => {
446
- if (settled) return;
447
- settled = true;
448
- signal.removeEventListener("abort", handleAbort);
449
- callback(value);
450
- };
451
- const handleAbort = () => {
452
- if (settled) return;
453
- settled = true;
454
- signal.removeEventListener("abort", handleAbort);
455
- Promise.resolve(onAbort?.())
456
- .catch(() => {})
457
- .finally(() => reject(abortReason(signal)));
458
- };
459
- signal.addEventListener("abort", handleAbort, { once: true });
460
- Promise.resolve(promise).then(
461
- (value) => finish(resolve, value),
462
- (error) => finish(reject, error),
463
- );
464
- });
465
- }
466
-
467
- function uniqueBy(items, key) {
468
- const seen = new Set();
469
- return items.filter((item) => {
470
- const value = key(item);
471
- if (!value || seen.has(value)) return false;
472
- seen.add(value);
473
- return true;
474
- });
475
- }
476
-
477
- function conversationIdFromUrl(value) {
478
- const match = String(value || "").match(/\/c\/([a-zA-Z0-9-]+)/);
479
- return match?.[1] || null;
480
- }
481
-
482
- /**
483
- * Parse the complete transcript returned by ChatGPT's conversation endpoint.
484
- * The page virtualizes old turns, so the API mapping is the authoritative
485
- * source for turn counting and archival whenever it is available.
486
- */
487
- export function parseConversationApiTranscript(payload) {
488
- const parseMessage = (message, fallbackId = null) => {
489
- const author = message?.author?.role;
490
- if (author !== "user" && author !== "assistant") return null;
491
- const parts = Array.isArray(message?.content?.parts) ? message.content.parts : [];
492
- const text = parts
493
- .map((part) => {
494
- if (typeof part === "string") return part;
495
- if (part && typeof part.text === "string") return part.text;
496
- return "";
497
- })
498
- .join("");
499
- if (!text.trim()) return null;
500
- return { author, id: message?.id || fallbackId, text };
501
- };
502
- if (Array.isArray(payload?.messages)) {
503
- return payload.messages.map((message) => parseMessage(message)).filter(Boolean);
504
- }
505
- const mapping = payload?.mapping;
506
- if (!mapping || typeof mapping !== "object") return [];
507
- const nodes = Array.isArray(mapping)
508
- ? mapping.map((message, index) => ({ id: message?.id || `index-${index}`, message }))
509
- : Object.entries(mapping).map(([id, node]) => ({ id, message: node?.message || node }));
510
- const byId = new Map(nodes.map((node) => [node.id, node.message]));
511
- const orderedMessages = [];
512
- const seen = new Set();
513
- let nodeId = payload?.current_node || null;
514
- while (nodeId && !seen.has(nodeId)) {
515
- seen.add(nodeId);
516
- const message = byId.get(nodeId);
517
- if (!message) break;
518
- orderedMessages.unshift({ id: nodeId, message });
519
- nodeId = mapping?.[nodeId]?.parent || null;
520
- }
521
- if (!orderedMessages.length) {
522
- const fallback = nodes
523
- .map((node, index) => ({ ...node, index }))
524
- .sort((a, b) => {
525
- const aTime = Number(a.message?.create_time);
526
- const bTime = Number(b.message?.create_time);
527
- if (Number.isFinite(aTime) && Number.isFinite(bTime) && aTime !== bTime) {
528
- return aTime - bTime;
529
- }
530
- return a.index - b.index;
531
- });
532
- orderedMessages.push(...fallback);
533
- }
534
- return orderedMessages.map(({ id, message }) => parseMessage(message, id)).filter(Boolean);
535
- }
536
-
537
- function absoluteChatUrl(href) {
538
- return new URL(href, CHATGPT_URL).toString();
539
- }
540
-
541
- async function freeLoopbackPort() {
542
- const server = net.createServer();
543
- await new Promise((resolve, reject) => {
544
- server.once("error", reject);
545
- server.listen(0, "127.0.0.1", resolve);
546
- });
547
- const address = server.address();
548
- const port = typeof address === "object" && address ? address.port : null;
549
- await new Promise((resolve) => server.close(resolve));
550
- if (!port) throw new Error("无法分配本机调试端口。");
551
- return port;
552
- }
553
-
554
- async function waitForChromeEndpoint(port, process, stderrLines, signal) {
555
- const endpoint = `http://127.0.0.1:${port}`;
556
- const deadline = Date.now() + ACTION_TIMEOUT_MS;
557
- while (Date.now() < deadline) {
558
- throwIfAborted(signal);
559
- if (process.exitCode != null || process.signalCode != null) {
560
- throw new Error(
561
- `Chrome 在控制通道就绪前退出(${process.exitCode}):${stderrLines.join("").slice(-1200)}`,
562
- );
563
- }
564
- const liveEndpoint = await chromeEndpoint(port);
565
- if (liveEndpoint) return liveEndpoint;
566
- await new Promise((resolve) => setTimeout(resolve, 150));
567
- }
568
- throw new Error(`等待 Chrome 本机控制通道超时:${endpoint}`);
569
- }
570
-
571
- async function navigate(page, url, options, signal) {
572
- await waitForPageInteraction("navigate", signal);
573
- return page.goto(url, options);
574
- }
575
-
576
- async function chromeEndpoint(port) {
577
- if (!Number.isInteger(port) || port < 1 || port > 65_535) return null;
578
- const endpoint = `http://127.0.0.1:${port}`;
579
- try {
580
- const response = await fetch(`${endpoint}/json/version`, {
581
- redirect: "error",
582
- signal: AbortSignal.timeout(Math.min(ACTION_TIMEOUT_MS, 2_000)),
583
- });
584
- if (!response.ok) return null;
585
- const value = (await response.json())?.webSocketDebuggerUrl;
586
- return validBrowserEndpoint(value, port) ? value : null;
587
- } catch {
588
- return null;
589
- }
590
- }
591
-
592
- function validBrowserEndpoint(value, port) {
593
- if (typeof value !== "string" || value.length > 2_048) return false;
594
- try {
595
- const url = new URL(value);
596
- return url.protocol === "ws:" && url.hostname === "127.0.0.1" &&
597
- url.port === String(port) && !url.username && !url.password && !url.search && !url.hash &&
598
- /^\/devtools\/browser\/[a-f0-9-]{32,36}$/i.test(url.pathname);
599
- } catch { return false; }
600
- }
601
-
602
- function browserOwnershipError() {
603
- return new ChatGPTWebError(
604
- "The saved dedicated browser cannot be verified. Close that dedicated window manually, remove only its stale browser-state.json file, then run ChatGPT login again. Your browser profile and saved sign-in are preserved.",
605
- { code: "browser_ownership_unverified", profile: USER_DATA_DIR, stateFile: BROWSER_STATE_FILE },
606
- );
607
- }
608
-
609
- async function verifiedBrowserEndpoint(state) {
610
- if (!state || (!state.port && !state.pid && !state.webSocketDebuggerUrl)) return null;
611
- if (state.profile !== USER_DATA_DIR || !validBrowserEndpoint(state.webSocketDebuggerUrl, state.port)) {
612
- throw browserOwnershipError();
613
- }
614
- const endpoint = await chromeEndpoint(state.port);
615
- if (endpoint && endpoint !== state.webSocketDebuggerUrl) throw browserOwnershipError();
616
- return endpoint;
617
- }
618
-
619
- function browserSessionId(state) {
620
- return state?.webSocketDebuggerUrl || null;
621
- }
622
-
623
- async function browserSessionSnapshot() {
624
- const state = await readBrowserState();
625
- const snapshot = {
626
- browserRunning: false,
627
- browserStartedAt: Number(state?.startedAt || 0) || null,
628
- browserSessionId: browserSessionId(state),
629
- chatgptPageOpen: false,
630
- chatgptPageId: null,
631
- };
632
- const endpoint = await verifiedBrowserEndpoint(state);
633
- if (!endpoint) return snapshot;
634
- let browser;
635
- try {
636
- // Use the verified browser UUID for the read too; the localhost port may be reused.
637
- browser = await chromium.connectOverCDP(endpoint, {timeout: ACTION_TIMEOUT_MS});
638
- const session = await browser.newBrowserCDPSession();
639
- const {targetInfos: targets} = await session.send("Target.getTargets");
640
- const chatgptPage = Array.isArray(targets)
641
- ? targets.find((target) => {
642
- if (target?.type !== "page") return false;
643
- try {
644
- return /(^|\.)chatgpt\.com$/i.test(new URL(target.url).hostname);
645
- } catch {
646
- return false;
647
- }
648
- })
649
- : null;
650
- return {
651
- ...snapshot,
652
- browserRunning: true,
653
- chatgptPageOpen: Boolean(chatgptPage),
654
- chatgptPageId: chatgptPage?.targetId || null,
655
- };
656
- } catch {
657
- return snapshot;
658
- } finally {
659
- await browser?.close().catch(() => {});
660
- }
661
- }
662
-
663
- async function readBrowserState() {
664
- try {
665
- return JSON.parse(await fs.readFile(BROWSER_STATE_FILE, "utf8"));
666
- } catch {
667
- return null;
668
- }
669
- }
670
-
671
- async function writeBrowserState(value) {
672
- await fs.mkdir(path.dirname(BROWSER_STATE_FILE), { recursive: true });
673
- await fs.writeFile(BROWSER_STATE_FILE, `${JSON.stringify(value, null, 2)}\n`, {
674
- mode: 0o600,
675
- });
676
- }
677
-
678
- async function readRuntimeState() {
679
- try {
680
- return JSON.parse(await fs.readFile(RUNTIME_STATE_FILE, "utf8"));
681
- } catch {
682
- return {};
683
- }
684
- }
685
-
686
- async function withRuntimeState(update, { signal } = {}) {
687
- await fs.mkdir(path.dirname(RUNTIME_STATE_FILE), { recursive: true });
688
- const deadline = Date.now() + ACTION_TIMEOUT_MS;
689
- let lock = null;
690
- while (!lock && Date.now() < deadline) {
691
- throwIfAborted(signal);
692
- try {
693
- lock = await fs.open(RUNTIME_LOCK_FILE, "wx", 0o600);
694
- } catch (error) {
695
- if (error?.code !== "EEXIST") throw error;
696
- const stat = await fs.stat(RUNTIME_LOCK_FILE).catch(() => null);
697
- if (stat && Date.now() - stat.mtimeMs > ACTION_TIMEOUT_MS) {
698
- await fs.unlink(RUNTIME_LOCK_FILE).catch(() => {});
699
- continue;
700
- }
701
- await waitWithAbort(50, signal);
702
- }
703
- }
704
- if (!lock) {
705
- throw new ChatGPTWebError("等待 ChatGPT MCP 的全局节流锁超时。", {
706
- lock: RUNTIME_LOCK_FILE,
707
- });
708
- }
709
-
710
- try {
711
- const state = await readRuntimeState();
712
- const { state: nextState = state, result } = await update(state);
713
- await fs.writeFile(RUNTIME_STATE_FILE, `${JSON.stringify(nextState, null, 2)}\n`, {
714
- mode: 0o600,
715
- });
716
- return result;
717
- } finally {
718
- await lock.close().catch(() => {});
719
- await fs.unlink(RUNTIME_LOCK_FILE).catch(() => {});
720
- }
721
- }
722
-
723
- async function waitForSiteAction(action, signal) {
724
- let initial = await readRuntimeState();
725
- if (initial.circuitBreaker?.active) {
726
- throw new ChatGPTWebError(
727
- "ChatGPT 安全熔断已开启。不会执行新的网页操作;请先人工确认限流提示已经消失。",
728
- { circuitBreaker: initial.circuitBreaker, action },
729
- );
730
- }
731
- if (generationIsStale(initial)) {
732
- initial = await clearStaleActiveGeneration(initial);
733
- }
734
- if (initial.activeGeneration?.active) {
735
- throw new ChatGPTWebError(
736
- "当前 ChatGPT 页面仍有一条生成任务或尚未确认完成的回答。为避免并发请求,已拒绝新的网页操作。",
737
- {
738
- activeGeneration: initial.activeGeneration,
739
- action,
740
- nextStep: "只调用 chatgpt_get_latest_response 检查一次;不要重新发送。",
741
- },
742
- );
743
- }
744
- const now = Date.now();
745
- const cooldownWaitMs = initial.postBreakerCooldownPending
746
- ? siteActionDelayMs(
747
- initial.circuitBreakerClearedAt,
748
- now,
749
- POST_BREAKER_COOLDOWN_MS,
750
- )
751
- : 0;
752
- const waitMs = siteActionWaitMs(initial, action, now);
753
- if (waitMs > 0) await waitWithAbort(waitMs, signal);
754
-
755
- return withRuntimeState(async (state) => {
756
- if (state.circuitBreaker?.active) {
757
- throw new ChatGPTWebError(
758
- "等待期间 ChatGPT 安全熔断已开启,当前网页操作已取消。",
759
- { circuitBreaker: state.circuitBreaker, action },
760
- );
761
- }
762
- if (generationIsStale(state)) {
763
- state = {
764
- ...state,
765
- activeGeneration: null,
766
- lastGenerationInterruptedAt: Date.now(),
767
- };
768
- }
769
- if (state.activeGeneration?.active) {
770
- throw new ChatGPTWebError(
771
- "等待期间检测到未完成的生成任务,当前网页操作已取消。",
772
- { activeGeneration: state.activeGeneration, action },
773
- );
774
- }
775
- const performedAt = Date.now();
776
- return {
777
- state: {
778
- ...state,
779
- lastSiteActionAt: performedAt,
780
- lastSiteAction: action,
781
- lastPageInteractionAt: performedAt,
782
- lastPageInteraction: `site-action:${action}`,
783
- ...(isConversationChangeAction(action)
784
- ? {
785
- lastConversationChangeAt: performedAt,
786
- lastConversationChange: action,
787
- }
788
- : {}),
789
- ...(state.postBreakerCooldownPending
790
- ? { postBreakerCooldownPending: false }
791
- : {}),
792
- },
793
- result: {
794
- action,
795
- waitMs,
796
- siteActionIntervalMs: SITE_ACTION_INTERVAL_MS,
797
- sendIntervalMs: action === "send-prompt" ? SEND_INTERVAL_MS : null,
798
- conversationChangeIntervalMs: isConversationChangeAction(action)
799
- ? CONVERSATION_CHANGE_INTERVAL_MS
800
- : null,
801
- postResponseConversationCooldownMs: isConversationChangeAction(action)
802
- ? POST_RESPONSE_CONVERSATION_COOLDOWN_MS
803
- : null,
804
- historyQuietUntil: isHistoryQuietAction(action)
805
- ? initial.historyQuietUntil || null
806
- : null,
807
- postBreakerCooldownApplied: cooldownWaitMs > 0,
808
- performedAt,
809
- },
810
- };
811
- }, { signal });
812
- }
813
-
814
- async function waitForPageInteraction(interaction, signal) {
815
- const initial = await readRuntimeState();
816
- if (initial.circuitBreaker?.active) {
817
- throw new ChatGPTWebError(
818
- "ChatGPT 安全熔断已开启。不会执行新的页面交互。",
819
- { circuitBreaker: initial.circuitBreaker, interaction },
820
- );
821
- }
822
- const now = Date.now();
823
- const regularWaitMs = siteActionDelayMs(
824
- Math.max(
825
- Number(initial.lastPageInteractionAt || 0),
826
- Number(initial.lastSiteActionAt || 0),
827
- ),
828
- now,
829
- PAGE_INTERACTION_INTERVAL_MS,
830
- );
831
- const cooldownWaitMs = initial.postBreakerCooldownPending
832
- ? siteActionDelayMs(
833
- initial.circuitBreakerClearedAt,
834
- now,
835
- POST_BREAKER_COOLDOWN_MS,
836
- )
837
- : 0;
838
- const waitMs = Math.max(regularWaitMs, cooldownWaitMs);
839
- if (waitMs > 0) await waitWithAbort(waitMs, signal);
840
-
841
- return withRuntimeState(async (state) => {
842
- if (state.circuitBreaker?.active) {
843
- throw new ChatGPTWebError(
844
- "等待期间 ChatGPT 安全熔断已开启,当前页面交互已取消。",
845
- { circuitBreaker: state.circuitBreaker, interaction },
846
- );
847
- }
848
- const performedAt = Date.now();
849
- return {
850
- state: {
851
- ...state,
852
- lastPageInteractionAt: performedAt,
853
- lastPageInteraction: interaction,
854
- ...(state.postBreakerCooldownPending
855
- ? { postBreakerCooldownPending: false }
856
- : {}),
857
- },
858
- result: {
859
- interaction,
860
- waitMs,
861
- postBreakerCooldownApplied: cooldownWaitMs > 0,
862
- performedAt,
863
- },
864
- };
865
- }, { signal });
866
- }
867
-
868
- async function updateRuntimeState(fields) {
869
- return withRuntimeState(async (state) => ({
870
- state: { ...state, ...fields },
871
- result: { ...state, ...fields },
872
- }));
873
- }
874
-
875
- function processIsAlive(pid) {
876
- if (!Number.isInteger(pid) || pid <= 0) return false;
877
- try {
878
- process.kill(pid, 0);
879
- return true;
880
- } catch {
881
- return false;
882
- }
883
- }
884
-
885
- export function generationIsStale(runtime) {
886
- const generation = runtime?.activeGeneration;
887
- const ownerPid = Number(generation?.ownerPid || 0);
888
- return Boolean(
889
- generation?.active &&
890
- ownerPid > 0 &&
891
- ownerPid !== process.pid &&
892
- !processIsAlive(ownerPid),
893
- );
894
- }
895
-
896
- async function clearStaleActiveGeneration(runtime) {
897
- if (!generationIsStale(runtime)) return runtime;
898
- const interruptedAt = Date.now();
899
- await updateRuntimeState({
900
- activeGeneration: null,
901
- lastGenerationInterruptedAt: interruptedAt,
902
- });
903
- return {
904
- ...runtime,
905
- activeGeneration: null,
906
- lastGenerationInterruptedAt: interruptedAt,
907
- };
908
- }
909
-
910
- async function acquireOperationLock(operation, signal) {
911
- await fs.mkdir(path.dirname(OPERATION_LOCK_FILE), { recursive: true });
912
- const deadline = Date.now() + ACTION_TIMEOUT_MS;
913
- const token = `${process.pid}-${Date.now()}`;
914
- while (Date.now() < deadline) {
915
- throwIfAborted(signal);
916
- let handle;
917
- try {
918
- handle = await fs.open(OPERATION_LOCK_FILE, "wx", 0o600);
919
- await handle.writeFile(
920
- `${JSON.stringify({ pid: process.pid, operation, startedAt: Date.now(), token })}\n`,
921
- );
922
- return async () => {
923
- await handle.close().catch(() => {});
924
- const current = await fs
925
- .readFile(OPERATION_LOCK_FILE, "utf8")
926
- .then((value) => JSON.parse(value))
927
- .catch(() => null);
928
- if (current?.token === token) await fs.unlink(OPERATION_LOCK_FILE).catch(() => {});
929
- };
930
- } catch (error) {
931
- await handle?.close().catch(() => {});
932
- if (error?.code !== "EEXIST") throw error;
933
- const owner = await fs
934
- .readFile(OPERATION_LOCK_FILE, "utf8")
935
- .then((value) => JSON.parse(value))
936
- .catch(() => null);
937
- if (!processIsAlive(Number(owner?.pid))) {
938
- await fs.unlink(OPERATION_LOCK_FILE).catch(() => {});
939
- continue;
940
- }
941
- await waitWithAbort(100, signal);
942
- }
943
- }
944
- const owner = await fs
945
- .readFile(OPERATION_LOCK_FILE, "utf8")
946
- .then((value) => JSON.parse(value))
947
- .catch(() => null);
948
- throw new ChatGPTWebError("另一个 ChatGPT MCP 操作仍在进行,已拒绝并发控制网页。", {
949
- requestedOperation: operation,
950
- activeOperation: owner?.operation || null,
951
- activeSince: owner?.startedAt || null,
952
- });
953
- }
954
-
955
- export function rankTextMatch(items, query, getText = (item) => item) {
956
- const wanted = normalize(query);
957
- return items
958
- .map((item) => {
959
- const text = normalize(getText(item));
960
- let score = -1;
961
- if (text === wanted) score = 100;
962
- else if (text.startsWith(wanted)) score = 80;
963
- else if (text.includes(wanted)) score = 60;
964
- else if (wanted.includes(text)) score = 40;
965
- return { item, score, text };
966
- })
967
- .filter((entry) => entry.score >= 0)
968
- .sort((a, b) => b.score - a.score || a.text.length - b.text.length);
969
- }
970
-
971
- export function parseAdvancedRowValue(text, labels) {
972
- let value = String(text || "").replace(/\s+/g, " ").trim();
973
- for (const label of labels) {
974
- value = value.replace(new RegExp(`^${label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*`, "i"), "");
975
- }
976
- return value.replace(/[›>⌄⌃∨∧]+$/g, "").trim() || null;
977
- }
978
-
979
- export class ChatGPTBrowser {
980
- #browser = null;
981
- #chromeProcess = null;
982
- #manualLogin = false;
983
- #manualBrowserState = null;
984
- #shutdownController = new AbortController();
985
- #browserState = null;
986
- #context = null;
987
- #page = null;
988
- #queue = Promise.resolve();
989
- #signedInUntil = 0;
990
- #settingsCache = null;
991
- #answerTier = null;
992
- #requestSignal = null;
993
- #networkLoggingPages = new WeakSet();
994
- #apiHeaders = {};
995
-
996
- async captureConversationModelSlug(operation) {
997
- const page = await this.page();
998
- const modelSlugs = [];
999
- const bodyReads = [];
1000
- const onResponse = (response) => {
1001
- let pathname;
1002
- try {
1003
- pathname = new URL(response.url()).pathname;
1004
- } catch {
1005
- return;
1006
- }
1007
- if (!/^\/backend-api\/(?:f\/)?conversation(?:\/|$)/iu.test(pathname)) return;
1008
- const read = response
1009
- .body()
1010
- .then((body) => {
1011
- const text = body.toString("utf8");
1012
- for (const match of text.matchAll(/"model_slug"\s*:\s*"([^"]+)"/gu)) {
1013
- if (match[1]) modelSlugs.push(match[1]);
1014
- }
1015
- })
1016
- .catch(() => {});
1017
- bodyReads.push(read);
1018
- };
1019
- page.on("response", onResponse);
1020
- try {
1021
- const result = await operation();
1022
- await Promise.allSettled(bodyReads);
1023
- return {
1024
- result,
1025
- modelSlug: modelSlugs.at(-1) || null,
1026
- modelSlugs: [...new Set(modelSlugs)],
1027
- };
1028
- } finally {
1029
- page.off("response", onResponse);
1030
- }
1031
- }
1032
-
1033
- async close({ terminateBrowser = false, confirmExit = false } = {}) {
1034
- const chromeProcess = this.#chromeProcess;
1035
- let browser = this.#browser;
1036
- const state = this.#manualLogin
1037
- ? this.#manualBrowserState
1038
- : this.#browserState || (terminateBrowser ? await readBrowserState() : null);
1039
- let closed = false;
1040
- let cleanupComplete = !terminateBrowser;
1041
- try {
1042
- if (terminateBrowser) {
1043
- if (chromeProcess && chromeProcess.exitCode == null && chromeProcess.signalCode == null) {
1044
- // Only a live ChildProcess handle created by this controller may be signalled.
1045
- closed = confirmExit ? await closeOwnedChild(chromeProcess) : chromeProcess.kill("SIGTERM");
1046
- } else if (chromeProcess && this.#manualLogin) {
1047
- // Our child already exited. Never replace its identity with another
1048
- // controller's newer state, even when that controller uses our profile.
1049
- closed = true;
1050
- } else {
1051
- const endpoint = await verifiedBrowserEndpoint(state);
1052
- if (endpoint) {
1053
- if (!browser?.isConnected()) browser = await chromium.connectOverCDP(endpoint, {timeout: ACTION_TIMEOUT_MS});
1054
- const session = await browser.newBrowserCDPSession();
1055
- if (confirmExit) await closeVerifiedBrowser(session);
1056
- else await session.send("Browser.close");
1057
- closed = true;
1058
- }
1059
- }
1060
- if (closed) {
1061
- // Never erase a replacement session written while the old controller was closing.
1062
- const current = await readBrowserState();
1063
- if (state?.webSocketDebuggerUrl && current?.webSocketDebuggerUrl === state.webSocketDebuggerUrl && current?.profile === state.profile) {
1064
- await fs.unlink(BROWSER_STATE_FILE).catch(() => {});
1065
- }
1066
- }
1067
- }
1068
- cleanupComplete = true;
1069
- return closed;
1070
- } finally {
1071
- // A failed confirmed close retains the owner so an explicit cleanup can retry.
1072
- if (!confirmExit || cleanupComplete) {
1073
- await browser?.close().catch(() => {});
1074
- this.#browser = null;
1075
- // Manual sign-in keeps its live child handle across status calls.
1076
- if (terminateBrowser || !this.#manualLogin) this.#chromeProcess = null;
1077
- this.#browserState = null;
1078
- this.#context = null;
1079
- this.#page = null;
1080
- this.#signedInUntil = 0;
1081
- this.#settingsCache = null;
1082
- this.#answerTier = null;
1083
- }
1084
- }
1085
- }
1086
-
1087
- async runExclusive(operation, { signal, name = "tool-call" } = {}) {
1088
- const execute = async () => {
1089
- throwIfAborted(signal);
1090
- const release = await acquireOperationLock(name, signal);
1091
- const requestSignal = signal ? AbortSignal.any([signal, this.#shutdownController.signal]) : this.#shutdownController.signal;
1092
- this.#requestSignal = requestSignal;
1093
- try {
1094
- // A manual launch must settle before cleanup, including spawn -> state-write.
1095
- // Racing it against cancellation can otherwise leave a late orphan Chrome.
1096
- if (this.#manualLogin || name === "chatgpt_open_login" || name === "chatgpt_finish_login") {
1097
- throwIfAborted(requestSignal);
1098
- const value = await operation();
1099
- throwIfAborted(requestSignal);
1100
- return value;
1101
- }
1102
- return await raceWithAbort(operation(), requestSignal, () => this.close());
1103
- } finally {
1104
- this.#requestSignal = null;
1105
- try {
1106
- if (this.#manualLogin && requestSignal.aborted) await this.finishManualLogin();
1107
- await this.close();
1108
- } finally { await release(); }
1109
- }
1110
- };
1111
- const run = this.#queue.then(execute, execute);
1112
- this.#queue = run.catch(() => {});
1113
- return run;
1114
- }
1115
-
1116
- signal() {
1117
- return this.#requestSignal;
1118
- }
1119
-
1120
- async siteAction(action) {
1121
- return waitForSiteAction(action, this.signal());
1122
- }
1123
-
1124
- async pageInteraction(interaction) {
1125
- return waitForPageInteraction(interaction, this.signal());
1126
- }
1127
-
1128
- async markSendPerformed() {
1129
- const lastSendAt = Date.now();
1130
- await updateRuntimeState({ lastSendAt });
1131
- return lastSendAt;
1132
- }
1133
-
1134
- async click(target, interaction, options) {
1135
- await this.pageInteraction(interaction);
1136
- return options === undefined ? target.click() : target.click(options);
1137
- }
1138
-
1139
- async press(target, key, interaction, options) {
1140
- await this.pageInteraction(interaction);
1141
- return options === undefined ? target.press(key) : target.press(key, options);
1142
- }
1143
-
1144
- async fill(target, value, interaction, options) {
1145
- await this.pageInteraction(interaction);
1146
- return options === undefined ? target.fill(value) : target.fill(value, options);
1147
- }
1148
-
1149
- async type(target, value, interaction, options) {
1150
- await this.pageInteraction(interaction);
1151
- return options === undefined ? target.type(value) : target.type(value, options);
1152
- }
1153
-
1154
- async keyboardPress(page, key, interaction) {
1155
- await this.pageInteraction(interaction);
1156
- return page.keyboard.press(key);
1157
- }
1158
-
1159
- async domClick(locator, interaction) {
1160
- await this.pageInteraction(interaction);
1161
- return locator.evaluate((element) => {
1162
- if (!(element instanceof HTMLElement)) throw new Error("目标控件不是 HTML 元素。");
1163
- element.click();
1164
- });
1165
- }
1166
-
1167
- async assertActionsAllowed(action = "tool-call") {
1168
- let state = await readRuntimeState();
1169
- if (state.circuitBreaker?.active) {
1170
- throw new ChatGPTWebError(
1171
- "ChatGPT 安全熔断已开启。不会执行新的网页操作;请先人工确认限流提示已经消失。",
1172
- { circuitBreaker: state.circuitBreaker, action },
1173
- );
1174
- }
1175
- if (generationIsStale(state)) {
1176
- state = await clearStaleActiveGeneration(state);
1177
- return { allowed: true, staleGenerationCleared: true };
1178
- }
1179
- if (state.activeGeneration?.active) {
1180
- throw new ChatGPTWebError(
1181
- "当前页面仍有一条生成任务或尚未确认完成的回答,已拒绝新的网页操作。",
1182
- {
1183
- activeGeneration: state.activeGeneration,
1184
- action,
1185
- nextStep: "只调用 chatgpt_get_latest_response 检查一次;不要重新发送。",
1186
- },
1187
- );
1188
- }
1189
- return { allowed: true };
1190
- }
1191
-
1192
- async circuitBreakerStatus() {
1193
- const state = await readRuntimeState();
1194
- return {
1195
- active: Boolean(state.circuitBreaker?.active),
1196
- circuitBreaker: state.circuitBreaker || null,
1197
- activeGeneration: state.activeGeneration || null,
1198
- historyQuietUntil: state.historyQuietUntil || null,
1199
- historyQuietRemainingMs: Math.max(
1200
- 0,
1201
- Number(state.historyQuietUntil || 0) - Date.now(),
1202
- ),
1203
- networkLog: NETWORK_LOG_FILE,
1204
- };
1205
- }
1206
-
1207
- async clearCircuitBreaker({ confirmed = false } = {}) {
1208
- if (!confirmed) {
1209
- throw new ChatGPTWebError(
1210
- "只有人工确认 ChatGPT 限流提示已经消失后才能清除熔断。",
1211
- { required: { confirmed: true } },
1212
- );
1213
- }
1214
- const clearedAt = Date.now();
1215
- const state = await updateRuntimeState({
1216
- circuitBreaker: null,
1217
- circuitBreakerClearedAt: clearedAt,
1218
- postBreakerCooldownPending: true,
1219
- });
1220
- return {
1221
- active: false,
1222
- clearedAt,
1223
- firstActionCooldownMs: POST_BREAKER_COOLDOWN_MS,
1224
- historyQuietUntil: state.historyQuietUntil || null,
1225
- historyQuietRemainingMs: Math.max(
1226
- 0,
1227
- Number(state.historyQuietUntil || 0) - clearedAt,
1228
- ),
1229
- };
1230
- }
1231
-
1232
- async tripCircuitBreaker(scope, source = "page") {
1233
- return withRuntimeState(async (state) => {
1234
- const nextScope = scope || "unknown";
1235
- const trippedAt = Date.now();
1236
- const genericScopes = new Set(["unknown", "http-429"]);
1237
- const existing = state.circuitBreaker;
1238
- const keepExisting =
1239
- existing?.active &&
1240
- !genericScopes.has(existing.scope) &&
1241
- genericScopes.has(nextScope);
1242
- const circuitBreaker = keepExisting
1243
- ? existing
1244
- : {
1245
- active: true,
1246
- scope: nextScope,
1247
- source,
1248
- trippedAt,
1249
- manualClearRequired: true,
1250
- };
1251
- const historyQuietUntil =
1252
- nextScope === "history"
1253
- ? Math.max(
1254
- Number(state.historyQuietUntil || 0),
1255
- trippedAt + HISTORY_QUIET_PERIOD_MS,
1256
- )
1257
- : state.historyQuietUntil;
1258
- return {
1259
- state: { ...state, circuitBreaker, historyQuietUntil },
1260
- result: circuitBreaker,
1261
- };
1262
- });
1263
- }
1264
-
1265
- async networkDiagnostics({ limit = 100 } = {}) {
1266
- const safeLimit = Math.max(1, Math.min(Number(limit) || 100, 500));
1267
- const raw = await fs.readFile(NETWORK_LOG_FILE, "utf8").catch(() => "");
1268
- const entries = raw
1269
- .split("\n")
1270
- .filter(Boolean)
1271
- .slice(-safeLimit)
1272
- .map((line) => {
1273
- try {
1274
- return JSON.parse(line);
1275
- } catch {
1276
- return null;
1277
- }
1278
- })
1279
- .filter(Boolean);
1280
- return { log: NETWORK_LOG_FILE, entries, returned: entries.length };
1281
- }
1282
-
1283
- async appendNetworkDiagnostic(entry) {
1284
- await fs.mkdir(path.dirname(NETWORK_LOG_FILE), { recursive: true });
1285
- await fs.appendFile(NETWORK_LOG_FILE, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
1286
- }
1287
-
1288
- attachNetworkDiagnostics(page) {
1289
- if (this.#networkLoggingPages.has(page)) return;
1290
- this.#networkLoggingPages.add(page);
1291
- page.on("request", (request) => {
1292
- let pathname;
1293
- try {
1294
- pathname = new URL(request.url()).pathname;
1295
- } catch {
1296
- return;
1297
- }
1298
- if (!/^\/backend-api\//iu.test(pathname)) return;
1299
- const headers = request.headers();
1300
- if (!headers.authorization) return;
1301
- // Reuse the browser's complete request fingerprint. ChatGPT's edge
1302
- // rejects a hand-built Node request even when the bearer token is valid.
1303
- // Cookie and body headers are supplied separately by the API reader.
1304
- this.#apiHeaders = Object.fromEntries(
1305
- Object.entries(headers).filter(
1306
- ([name]) => !["cookie", "content-length", "host"].includes(name),
1307
- ),
1308
- );
1309
- });
1310
- page.on("response", (response) => {
1311
- const status = response.status();
1312
- if (status !== 403 && status !== 429 && status < 500) return;
1313
- let diagnosticPath;
1314
- try {
1315
- const parsed = new URL(response.url());
1316
- if (!/chatgpt\.com$/i.test(parsed.hostname)) return;
1317
- diagnosticPath = redactDiagnosticPath(parsed.pathname);
1318
- } catch {
1319
- return;
1320
- }
1321
- const entry = {
1322
- timestamp: Date.now(),
1323
- method: response.request().method(),
1324
- path: diagnosticPath,
1325
- status,
1326
- resourceType: response.request().resourceType(),
1327
- };
1328
- this.appendNetworkDiagnostic(entry).catch(() => {});
1329
- if (status === 429) {
1330
- const scope = networkRateLimitScope(diagnosticPath);
1331
- // History failures are diagnostic-only; page-visible rate-limit
1332
- // warnings still stop operations through the existing text checks.
1333
- if (scope === "history") return;
1334
- this.tripCircuitBreaker(scope, `network-response:${diagnosticPath}`).catch(() => {});
1335
- page
1336
- .evaluate(
1337
- ({ networkScope, networkPath }) =>
1338
- window.dispatchEvent(
1339
- new CustomEvent("__chatgpt_mcp_network_rate_limit__", {
1340
- detail: { scope: networkScope, path: networkPath },
1341
- }),
1342
- ),
1343
- { networkScope: scope, networkPath: diagnosticPath },
1344
- )
1345
- .catch(() => {});
1346
- }
1347
- });
1348
- }
1349
-
1350
- async launch() {
1351
- if (this.#context && this.#page && !this.#page.isClosed()) {
1352
- return this.#page;
1353
- }
1354
-
1355
- await fs.mkdir(USER_DATA_DIR, { recursive: true });
1356
-
1357
- if (!CHROME_EXECUTABLE) {
1358
- throw new ChatGPTWebError(
1359
- "没有检测到 Chrome、Chromium 或 Edge。请安装浏览器,或设置 CHATGPT_WEB_CHROME。",
1360
- { platform: process.platform, environmentVariable: "CHATGPT_WEB_CHROME" },
1361
- );
1362
- }
1363
-
1364
- let openedChatGPTPage = false;
1365
- try {
1366
- const prior = await readBrowserState();
1367
- if (this.#manualLogin && this.#manualBrowserState &&
1368
- (prior?.profile !== this.#manualBrowserState.profile ||
1369
- prior?.webSocketDebuggerUrl !== this.#manualBrowserState.webSocketDebuggerUrl)) {
1370
- throw new ChatGPTWebError("Dedicated manual browser ownership changed.", {
1371
- code: "browser_ownership_unverified",
1372
- });
1373
- }
1374
- const priorEndpoint = await verifiedBrowserEndpoint(prior);
1375
- if (priorEndpoint) {
1376
- this.#browser = await chromium.connectOverCDP(priorEndpoint, {timeout: ACTION_TIMEOUT_MS});
1377
- this.#browserState = prior;
1378
- this.#context = this.#browser.contexts()[0];
1379
- if (!this.#context) throw new Error("常驻 Chrome 没有返回默认浏览器上下文。");
1380
- }
1381
-
1382
- if (!this.#context && prior?.lastFailureAt) {
1383
- const remaining = RECONNECT_DELAY_MS - (Date.now() - Number(prior.lastFailureAt));
1384
- if (remaining > 0) await new Promise((resolve) => setTimeout(resolve, remaining));
1385
- }
1386
-
1387
- if (!this.#context) {
1388
- await this.siteAction("launch-chatgpt");
1389
- const port = await freeLoopbackPort();
1390
- const stderrLines = [];
1391
- const args = [
1392
- `--user-data-dir=${USER_DATA_DIR}`,
1393
- "--profile-directory=Default",
1394
- `--remote-debugging-port=${port}`,
1395
- "--remote-debugging-address=127.0.0.1",
1396
- "--no-first-run",
1397
- "--no-default-browser-check",
1398
- "--disable-background-mode",
1399
- "--start-maximized",
1400
- "--new-window",
1401
- ];
1402
- if (HEADLESS && !this.#manualLogin) args.push("--headless=new");
1403
- args.push(CHATGPT_URL);
1404
-
1405
- throwIfAborted(this.signal());
1406
- this.#chromeProcess = spawn(CHROME_EXECUTABLE, args, {
1407
- detached: true,
1408
- stdio: ["ignore", "ignore", "ignore"],
1409
- });
1410
- this.#chromeProcess.unref();
1411
- openedChatGPTPage = true;
1412
-
1413
- const endpoint = await waitForChromeEndpoint(port, this.#chromeProcess, stderrLines, this.signal());
1414
- this.#browser = await chromium.connectOverCDP(endpoint, {timeout: ACTION_TIMEOUT_MS});
1415
- this.#context = this.#browser.contexts()[0];
1416
- if (!this.#context) throw new Error("Chrome 没有返回默认浏览器上下文。");
1417
- this.#browserState = {
1418
- port,
1419
- pid: this.#chromeProcess.pid,
1420
- startedAt: Date.now(),
1421
- profile: USER_DATA_DIR,
1422
- webSocketDebuggerUrl: endpoint,
1423
- };
1424
- if (this.#manualLogin) this.#manualBrowserState = this.#browserState;
1425
- await writeBrowserState(this.#browserState);
1426
- await updateRuntimeState({ authenticatedUntil: 0 });
1427
- }
1428
- } catch (error) {
1429
- if (error?.details?.code === "browser_ownership_unverified") throw error;
1430
- // A failed new launch may only clean up the child this controller created.
1431
- if (this.#chromeProcess) await this.close({terminateBrowser: true, confirmExit: this.#manualLogin});
1432
- await writeBrowserState({
1433
- ...(await readBrowserState()),
1434
- lastFailureAt: Date.now(),
1435
- profile: USER_DATA_DIR,
1436
- }).catch(() => {});
1437
- const message = error instanceof Error ? error.message : String(error);
1438
- if (/SingletonLock|profile.*in use|ProcessSingleton|already running/i.test(message)) {
1439
- throw new ChatGPTWebError(
1440
- "ChatGPT MCP 的专用浏览器配置正在被另一个进程使用。请关闭登录窗口或另一个 MCP 实例后重试。",
1441
- { profile: USER_DATA_DIR },
1442
- );
1443
- }
1444
- throw new ChatGPTWebError("无法启动 ChatGPT MCP 的专用浏览器。", {
1445
- cause: message,
1446
- chrome: CHROME_EXECUTABLE,
1447
- profile: USER_DATA_DIR,
1448
- });
1449
- }
1450
-
1451
- this.#context.setDefaultTimeout(ACTION_TIMEOUT_MS);
1452
- this.#page =
1453
- this.#context.pages().find((page) => /chatgpt\.com/i.test(page.url())) ||
1454
- this.#context.pages()[0] ||
1455
- (await this.#context.newPage());
1456
- const trackPage = (page) => {
1457
- if (/chatgpt\.com/i.test(page.url())) this.#page = page;
1458
- this.attachNetworkDiagnostics(page);
1459
- page.on("framenavigated", (frame) => {
1460
- if (frame === page.mainFrame() && /chatgpt\.com/i.test(frame.url())) this.#page = page;
1461
- });
1462
- };
1463
- this.#context.pages().forEach(trackPage);
1464
- this.#context.on("page", trackPage);
1465
-
1466
- if (!/chatgpt\.com/i.test(this.#page.url())) {
1467
- await this.siteAction("open-chatgpt");
1468
- await navigate(
1469
- this.#page,
1470
- CHATGPT_URL,
1471
- { waitUntil: "domcontentloaded" },
1472
- this.signal(),
1473
- );
1474
- openedChatGPTPage = true;
1475
- }
1476
-
1477
- if (openedChatGPTPage && PAGE_STARTUP_DELAY_MS > 0) {
1478
- await this.#page.waitForLoadState("domcontentloaded", { timeout: ACTION_TIMEOUT_MS });
1479
- await waitWithAbort(PAGE_STARTUP_DELAY_MS, this.signal());
1480
- }
1481
-
1482
- return this.#page;
1483
- }
1484
-
1485
- async browserLifecycle() {
1486
- const state = await readBrowserState();
1487
- const runtime = await readRuntimeState();
1488
- const browserRunning = Boolean(await verifiedBrowserEndpoint(state));
1489
- return {
1490
- persistent: true,
1491
- browserRunning,
1492
- reconnectDelayMs: RECONNECT_DELAY_MS,
1493
- pageStartupDelayMs: PAGE_STARTUP_DELAY_MS,
1494
- proProbeEnabled: PROBE_ENABLED,
1495
- refreshBeforeNewChat: REFRESH_BEFORE_NEW_CHAT,
1496
- siteActionIntervalMs: SITE_ACTION_INTERVAL_MS,
1497
- pageInteractionIntervalMs: PAGE_INTERACTION_INTERVAL_MS,
1498
- sendIntervalMs: SEND_INTERVAL_MS,
1499
- conversationChangeIntervalMs: CONVERSATION_CHANGE_INTERVAL_MS,
1500
- postResponseConversationCooldownMs: POST_RESPONSE_CONVERSATION_COOLDOWN_MS,
1501
- postBreakerCooldownMs: POST_BREAKER_COOLDOWN_MS,
1502
- historyQuietPeriodMs: HISTORY_QUIET_PERIOD_MS,
1503
- proProbeRecheckAfterCloseMs: PRO_PROBE_RECHECK_AFTER_CLOSE_MS,
1504
- pid: state?.pid || null,
1505
- port: state?.port || null,
1506
- lastSiteAction: runtime.lastSiteAction || null,
1507
- lastSiteActionAt: runtime.lastSiteActionAt || null,
1508
- circuitBreaker: runtime.circuitBreaker || null,
1509
- activeGeneration: runtime.activeGeneration || null,
1510
- lastGenerationCompletedAt: runtime.lastGenerationCompletedAt || null,
1511
- lastConversationChangeAt: runtime.lastConversationChangeAt || null,
1512
- historyQuietUntil: runtime.historyQuietUntil || null,
1513
- historyQuietRemainingMs: Math.max(
1514
- 0,
1515
- Number(runtime.historyQuietUntil || 0) - Date.now(),
1516
- ),
1517
- postBreakerCooldownPending: Boolean(runtime.postBreakerCooldownPending),
1518
- };
1519
- }
1520
-
1521
- async terminateBrowser({ confirmExit = false } = {}) {
1522
- const state = await readBrowserState();
1523
- const runtime = await readRuntimeState();
1524
- const closedAt = Date.now();
1525
- const reliableProbe =
1526
- runtime.proProbe?.policyKey === PROBE_POLICY_KEY &&
1527
- [
1528
- PROBE_ACCEPT_CLASSIFICATION,
1529
- PROBE_FALLBACK_CLASSIFICATION,
1530
- PROBE_NETWORK_ACCEPT_CLASSIFICATION,
1531
- ].includes(
1532
- runtime.proProbe?.classification,
1533
- )
1534
- ? {
1535
- ...runtime.proProbe,
1536
- sessionInterruptedAt: closedAt,
1537
- recheckAfter: closedAt + PRO_PROBE_RECHECK_AFTER_CLOSE_MS,
1538
- expiresAt: closedAt + PRO_PROBE_RECHECK_AFTER_CLOSE_MS,
1539
- }
1540
- : null;
1541
- const closed = await this.close({ terminateBrowser: true, confirmExit });
1542
- await updateRuntimeState({
1543
- authenticatedUntil: 0,
1544
- proProbe: reliableProbe,
1545
- ...interruptedGenerationFields(runtime, closedAt),
1546
- });
1547
- return {
1548
- closed,
1549
- pid: closed ? state?.pid || null : null,
1550
- proProbeRecheckAfter: reliableProbe?.recheckAfter || null,
1551
- };
1552
- }
1553
-
1554
- async page() {
1555
- await this.launch();
1556
- const liveChatGPTPage = this.#context
1557
- .pages()
1558
- .find((page) => !page.isClosed() && /chatgpt\.com/i.test(page.url()));
1559
- if (liveChatGPTPage) this.#page = liveChatGPTPage;
1560
- return this.#page;
1561
- }
1562
-
1563
- async openManualLogin() {
1564
- if (this.#manualLogin) return {opened:true};
1565
- // Verify and wait for the old headless process to exit before reusing its profile.
1566
- await this.terminateBrowser({confirmExit:true});
1567
- throwIfAborted(this.signal());
1568
- this.#manualLogin = true;
1569
- try {
1570
- const opened = await this.openLogin();
1571
- if (opened.automationFlag) throw new ChatGPTWebError("Dedicated browser automation check failed.");
1572
- throwIfAborted(this.signal());
1573
- return {opened:true};
1574
- } catch(error) {
1575
- await this.finishManualLogin();
1576
- throw error;
1577
- }
1578
- }
1579
-
1580
- async finishManualLogin() {
1581
- if (!this.#manualLogin) return {cleaned:true};
1582
- await this.terminateBrowser({confirmExit:true});
1583
- this.#manualLogin = false;
1584
- this.#manualBrowserState = null;
1585
- return {cleaned:true};
1586
- }
1587
-
1588
- async shutdown() {
1589
- this.#shutdownController.abort();
1590
- await this.#queue;
1591
- await this.finishManualLogin();
1592
- await this.close();
1593
- }
1594
-
1595
- async openLogin() {
1596
- const page = await this.page();
1597
- await this.siteAction("open-login");
1598
- await navigate(
1599
- page,
1600
- new URL("/auth/login", CHATGPT_URL).toString(),
1601
- { waitUntil: "domcontentloaded" },
1602
- this.signal(),
1603
- );
1604
- this.#signedInUntil = 0;
1605
- await updateRuntimeState({ authenticatedUntil: 0 });
1606
- return {
1607
- url: page.url(),
1608
- automationFlag: await page.evaluate(() => navigator.webdriver),
1609
- profile: USER_DATA_DIR,
1610
- };
1611
- }
1612
-
1613
- async firstVisible(selectors, { timeout = 1_000 } = {}) {
1614
- const page = await this.page();
1615
- for (const selector of selectors) {
1616
- const locator = page.locator(selector).first();
1617
- try {
1618
- if (await locator.isVisible({ timeout })) return locator;
1619
- } catch {
1620
- // Try the next semantic fallback.
1621
- }
1622
- }
1623
- return null;
1624
- }
1625
-
1626
- async composer() {
1627
- const page = await this.page();
1628
- const deadline = Date.now() + ACTION_TIMEOUT_MS;
1629
- while (Date.now() < deadline) {
1630
- const locator = await this.firstVisible(SELECTORS.composer, { timeout: 400 });
1631
- if (locator) return locator;
1632
- await page.waitForTimeout(250);
1633
- }
1634
- return null;
1635
- }
1636
-
1637
- async composerText(composer = null) {
1638
- const target = composer || (await this.composer());
1639
- if (!target) return "";
1640
- return target.evaluate((element) => {
1641
- if (element instanceof HTMLTextAreaElement || element instanceof HTMLInputElement) {
1642
- return element.value;
1643
- }
1644
- // ProseMirror keeps capability pills (for example the selected Web
1645
- // search pill) inside the contenteditable. They are UI state, not
1646
- // user-authored prompt text, and must not trip the draft guard.
1647
- const clone = element.cloneNode(true);
1648
- clone
1649
- .querySelectorAll(
1650
- "[data-inline-selection-pill], [data-inline-selection-pill-cursor-target]",
1651
- )
1652
- .forEach((node) => node.remove());
1653
- return clone.innerText || clone.textContent || "";
1654
- });
1655
- }
1656
-
1657
- /**
1658
- * Archived conversations render their transcript without a composer. The
1659
- * selected project conversation can still be continued, but only after the
1660
- * page's explicit Unarchive action restores the composer. Do this lazily
1661
- * on write paths; read-only history/status calls must not mutate archive
1662
- * state.
1663
- */
1664
- async unarchiveConversationIfNeeded() {
1665
- const page = await this.page();
1666
- const button = await this.firstVisible(SELECTORS.unarchiveButtons, {
1667
- timeout: 500,
1668
- });
1669
- if (!button) return { unarchived: false };
1670
-
1671
- await this.domClick(button, "unarchive-conversation");
1672
- await page.waitForTimeout(1_000);
1673
- const remaining = await this.firstVisible(SELECTORS.unarchiveButtons, {
1674
- timeout: 500,
1675
- });
1676
- // The clicked menu item can remain mounted briefly during the archive
1677
- // mutation. The composer is the durable write-path signal; only fail if
1678
- // both the button and the missing composer persist after the transition.
1679
- const composer = remaining ? await this.composer() : null;
1680
- if (remaining && !composer) {
1681
- throw new ChatGPTWebError("取消归档后页面仍显示归档状态,已停止发送。", {
1682
- url: page.url(),
1683
- unarchiveVerified: false,
1684
- });
1685
- }
1686
- return { unarchived: true, unarchiveVerified: !remaining || Boolean(composer) };
1687
- }
1688
-
1689
- /**
1690
- * Reload the currently selected ChatGPT conversation immediately before a
1691
- * tool-managed send. The browser page is persistent across MCP calls, so a
1692
- * stale React tree can otherwise keep an old user turn selected and a new
1693
- * prompt may replace that turn instead of appending a message.
1694
- *
1695
- * The caller must invoke this before uploading files or changing the
1696
- * composer. A direct submit of an existing draft is also supported: the
1697
- * draft is captured, the page is reloaded, and the exact text is restored
1698
- * only when the refreshed composer is empty. Any unexpected change is a
1699
- * hard error rather than an overwrite.
1700
- */
1701
- async refreshBeforeSend({ reason = "send" } = {}) {
1702
- const page = await this.page();
1703
- await this.ensureSignedIn();
1704
- const unarchiveResult = await this.unarchiveConversationIfNeeded();
1705
- const beforeUrl = page.url();
1706
- const beforeParsed = new URL(beforeUrl);
1707
- const beforeConversationId = conversationIdFromUrl(beforeUrl);
1708
- const beforeTemporary = beforeParsed.searchParams.get("temporary-chat") === "true";
1709
- const beforeComposer = await this.composer();
1710
- if (!beforeComposer) throw new ChatGPTWebError("刷新发送页面前没有找到提示词输入框。", { url: beforeUrl });
1711
- await this.assertComposerWritable(`refresh-before-${reason}`, beforeComposer);
1712
- const beforeDraft = await this.composerText(beforeComposer);
1713
- const beforeSearch = await this.webSearchState();
1714
- const pendingFiles = await page
1715
- .locator(SELECTORS.fileInput.join(", "))
1716
- .evaluateAll((inputs) =>
1717
- inputs.reduce((count, input) => count + Number(input.files?.length || 0), 0),
1718
- )
1719
- .catch(() => 0);
1720
-
1721
- // File inputs are cleared by a full page reload. Refuse to risk silently
1722
- // dropping an attachment; the atomic chatgpt_send_message path refreshes
1723
- // before upload and remains safe.
1724
- if (pendingFiles > 0) {
1725
- throw new ChatGPTWebError(
1726
- "发送前检测到尚未发送的附件;为避免刷新丢失附件,请使用 chatgpt_send_message 原子操作重试。",
1727
- { pendingFiles, url: beforeUrl, refreshRequired: true },
1728
- );
1729
- }
1730
-
1731
- await this.pageInteraction("refresh-before-send");
1732
- await page.reload({ waitUntil: "domcontentloaded" });
1733
- await page.waitForTimeout(500);
1734
- // Do not trust the pre-reload auth cache for the refreshed document.
1735
- this.#signedInUntil = 0;
1736
- await this.ensureSignedIn();
1737
-
1738
- const afterUrl = page.url();
1739
- const afterParsed = new URL(afterUrl);
1740
- const afterConversationId = conversationIdFromUrl(afterUrl);
1741
- const afterTemporary = afterParsed.searchParams.get("temporary-chat") === "true";
1742
- if (
1743
- afterParsed.pathname !== beforeParsed.pathname ||
1744
- afterConversationId !== beforeConversationId ||
1745
- afterTemporary !== beforeTemporary
1746
- ) {
1747
- throw new ChatGPTWebError(
1748
- "发送前刷新改变了当前对话,已停止以避免把消息写入错误会话。",
1749
- {
1750
- beforeUrl,
1751
- afterUrl,
1752
- beforeConversationId,
1753
- afterConversationId,
1754
- beforeTemporary,
1755
- afterTemporary,
1756
- refreshRequired: true,
1757
- },
1758
- );
1759
- }
1760
-
1761
- const afterComposer = await this.composer();
1762
- if (!afterComposer) {
1763
- throw new ChatGPTWebError("发送前刷新完成,但输入框未恢复。", {
1764
- url: afterUrl,
1765
- refreshRequired: true,
1766
- });
1767
- }
1768
- await this.assertComposerWritable(`refresh-after-${reason}`, afterComposer);
1769
- const afterDraft = await this.composerText(afterComposer);
1770
- if (normalize(beforeDraft) !== normalize(afterDraft)) {
1771
- if (!normalize(afterDraft) && normalize(beforeDraft)) {
1772
- await this.fill(afterComposer, beforeDraft, "restore-draft-after-refresh");
1773
- } else {
1774
- throw new ChatGPTWebError(
1775
- "发送前刷新后输入框内容发生变化,已拒绝继续以保护用户草稿。",
1776
- {
1777
- beforeCharacters: beforeDraft.length,
1778
- afterCharacters: afterDraft.length,
1779
- beforePreview: beforeDraft.slice(0, 160),
1780
- afterPreview: afterDraft.slice(0, 160),
1781
- overwritePrevented: true,
1782
- refreshRequired: true,
1783
- },
1784
- );
1785
- }
1786
- }
1787
-
1788
- if (beforeSearch.selected && !(await this.webSearchState()).selected) {
1789
- await this.enableWebSearch();
1790
- }
1791
- return {
1792
- refreshed: true,
1793
- ...unarchiveResult,
1794
- beforeUrl,
1795
- afterUrl,
1796
- conversationId: afterConversationId,
1797
- draftRestored: Boolean(normalize(beforeDraft) && !normalize(afterDraft)),
1798
- webSearchRestored: Boolean(beforeSearch.selected),
1799
- };
1800
- }
1801
-
1802
- async composerEditState(composer = null) {
1803
- const target = composer || (await this.composer());
1804
- if (!target) return { editing: false, reason: null };
1805
- const signals = await target.evaluate((element) => {
1806
- const userMessage = element.closest(
1807
- "[data-message-author-role='user'], article[data-turn='user'], section[data-turn='user']",
1808
- );
1809
- if (userMessage) {
1810
- return { insideUserMessage: true, visibleCancel: false };
1811
- }
1812
-
1813
- // ChatGPT keeps the composer in the page root during ordinary sends,
1814
- // but moves it into the selected user turn when the pencil action is
1815
- // active. The cancel control is a second signal for layouts that do
1816
- // not preserve the user-turn ancestor.
1817
- const scope = element.closest("form") || element.parentElement;
1818
- const visible = (node) => {
1819
- if (!(node instanceof HTMLElement)) return false;
1820
- const style = getComputedStyle(node);
1821
- const rect = node.getBoundingClientRect();
1822
- return style.visibility !== "hidden" && style.display !== "none" && rect.width > 0 && rect.height > 0;
1823
- };
1824
- const cancel = [...(scope?.querySelectorAll("button") || [])].find((button) => {
1825
- if (!visible(button)) return false;
1826
- const label = `${button.getAttribute("aria-label") || ""} ${button.innerText || ""}`;
1827
- return /cancel\s+edit|取消编辑|cancel|取消/i.test(label) &&
1828
- !/stop|停止|close|关闭/i.test(label);
1829
- });
1830
- return { insideUserMessage: false, visibleCancel: Boolean(cancel) };
1831
- });
1832
- const reason = composerEditReason(signals);
1833
- return { editing: Boolean(reason), reason };
1834
- }
1835
-
1836
- async assertComposerWritable(action, composer = null) {
1837
- const state = await this.composerEditState(composer);
1838
- if (!state.editing) return state;
1839
- throw new ChatGPTWebError(
1840
- "当前输入框处于用户消息编辑态,已拒绝写入或发送,避免覆盖原用户消息。",
1841
- {
1842
- action,
1843
- editState: state,
1844
- nextStep: "请先由用户取消编辑或完成人工编辑,再重试网页操作。",
1845
- overwritePrevented: true,
1846
- },
1847
- );
1848
- }
1849
-
1850
- async assertComposerEmpty(action) {
1851
- const composer = await this.composer();
1852
- if (!composer) return;
1853
- await this.assertComposerWritable(action, composer);
1854
- const existing = await this.composerText(composer);
1855
- if (!normalize(existing)) return;
1856
- throw new ChatGPTWebError(
1857
- "输入框已有用户草稿,已拒绝切换或新建对话以避免覆盖。",
1858
- {
1859
- action,
1860
- existingCharacters: existing.length,
1861
- existingPreview: existing.slice(0, 160),
1862
- nextStep: "请先由用户手动处理当前草稿,再重试网页操作。",
1863
- },
1864
- );
1865
- }
1866
-
1867
- async signedIn() {
1868
- if (Date.now() < this.#signedInUntil) return true;
1869
- const page = await this.page();
1870
- const loginControls = page.locator(
1871
- "button[data-testid='login-button']:visible, button[data-testid='signup-button']:visible",
1872
- );
1873
- if ((await loginControls.count()) > 0) {
1874
- this.#signedInUntil = 0;
1875
- await updateRuntimeState({ authenticatedUntil: 0 });
1876
- return false;
1877
- }
1878
-
1879
- const runtime = await readRuntimeState();
1880
- if (Number(runtime.authenticatedUntil) > Date.now()) {
1881
- this.#signedInUntil = Number(runtime.authenticatedUntil);
1882
- return true;
1883
- }
1884
-
1885
- const profile = page.locator("[data-testid='accounts-profile-button']:visible").first();
1886
- const history = page.locator("a[href^='/c/']:visible").first();
1887
- const workspaceControls = page.locator(
1888
- "button[aria-label*='profile' i]:visible, button[aria-label*='个人资料']:visible",
1889
- ).first();
1890
- if (
1891
- (await profile.count()) > 0 ||
1892
- (await history.count()) > 0 ||
1893
- (await workspaceControls.count()) > 0
1894
- ) {
1895
- const authenticatedUntil = Date.now() + AUTH_CACHE_MS;
1896
- this.#signedInUntil = authenticatedUntil;
1897
- await updateRuntimeState({ authenticatedUntil });
1898
- return true;
1899
- }
1900
-
1901
- const composer = await this.composer();
1902
- if (!composer) return false;
1903
- const authenticatedUntil = Date.now() + AUTH_CACHE_MS;
1904
- this.#signedInUntil = authenticatedUntil;
1905
- await updateRuntimeState({ authenticatedUntil });
1906
- return true;
1907
- }
1908
-
1909
- async ensureSignedIn() {
1910
- const page = await this.page();
1911
- const body = normalize(await page.locator("body").innerText().catch(() => ""));
1912
- const rateLimit = classifyRateLimitText(body);
1913
- if (rateLimit.limited) {
1914
- const circuitBreaker = await this.tripCircuitBreaker(rateLimit.scope, "page-text");
1915
- throw new ChatGPTWebError(
1916
- "ChatGPT 网页出现请求频率限制,安全熔断已开启。不会继续或自动重试。",
1917
- {
1918
- url: page.url(),
1919
- retryManually: false,
1920
- scope: rateLimit.scope,
1921
- circuitBreaker,
1922
- },
1923
- );
1924
- }
1925
- if (await this.signedIn()) return;
1926
-
1927
- const loginVisible = TEXT.login.some((label) => body.includes(normalize(label)));
1928
- const cloudflare = /just a moment|checking your browser|verify you are human|安全验证/.test(body);
1929
-
1930
- throw new ChatGPTWebError(
1931
- cloudflare
1932
- ? "ChatGPT 网页正在等待人工安全验证。请运行 npm run login 并在浏览器中完成验证。"
1933
- : "ChatGPT MCP 的专用浏览器尚未登录。请在项目目录运行 npm run login,完成登录后再调用。",
1934
- {
1935
- url: page.url(),
1936
- loginVisible,
1937
- profile: USER_DATA_DIR,
1938
- },
1939
- );
1940
- }
1941
-
1942
- isRateLimitedText(text) {
1943
- return classifyRateLimitText(text).limited;
1944
- }
1945
-
1946
- async throwIfRateLimited() {
1947
- const page = await this.page();
1948
- const body = await page.locator("body").innerText().catch(() => "");
1949
- const rateLimit = classifyRateLimitText(body);
1950
- if (rateLimit.limited) {
1951
- const circuitBreaker = await this.tripCircuitBreaker(rateLimit.scope, "page-text");
1952
- throw new ChatGPTWebError(
1953
- "ChatGPT 网页出现请求频率限制,已停止当前操作并开启安全熔断。",
1954
- {
1955
- url: page.url(),
1956
- retryManually: false,
1957
- scope: rateLimit.scope,
1958
- circuitBreaker,
1959
- },
1960
- );
1961
- }
1962
- return rateLimit;
1963
- }
1964
-
1965
- cachedSettings() {
1966
- return this.#settingsCache?.expiresAt > Date.now()
1967
- ? this.#settingsCache.value
1968
- : { model: null, thinkingLevel: null };
1969
- }
1970
-
1971
- async status({ includeSettings = false } = {}) {
1972
- const page = await this.page();
1973
- const signedIn = await this.signedIn();
1974
- const settings =
1975
- signedIn && includeSettings ? await this.advancedSettings() : this.cachedSettings();
1976
- const conversation = signedIn ? await this.conversationTurnStats() : null;
1977
- return {
1978
- browserRunning: true,
1979
- signedIn,
1980
- url: page.url(),
1981
- title: await page.title(),
1982
- conversationId: conversationIdFromUrl(page.url()),
1983
- model: signedIn ? settings.model : null,
1984
- mode: signedIn ? await this.currentMode() : null,
1985
- thinkingLevel: signedIn ? settings.thinkingLevel : null,
1986
- temporary: signedIn ? await this.temporaryState() : null,
1987
- conversationTurns: conversation?.turnCount ?? null,
1988
- userMessageCount: conversation?.userMessageCount ?? null,
1989
- assistantMessageCount: conversation?.assistantMessageCount ?? null,
1990
- maxConversationTurns: MAX_CONVERSATION_TURNS,
1991
- conversationRotationRequired: conversation?.shouldRotate ?? false,
1992
- conversationLengthLimitDetected: conversation?.lengthLimitDetected ?? false,
1993
- transcriptMessageCount: conversation?.transcriptMessageCount ?? null,
1994
- transcriptLoaded: conversation?.transcriptLoaded ?? false,
1995
- transcriptLoadPasses: conversation?.transcriptLoadPasses ?? 0,
1996
- transcriptSource: conversation?.transcriptSource ?? null,
1997
- profile: USER_DATA_DIR,
1998
- };
1999
- }
2000
-
2001
- async openRoot({ temporary = false } = {}) {
2002
- const page = await this.page();
2003
- await this.ensureSignedIn();
2004
- const currentTemporary = await this.temporaryState();
2005
- const userCount = await this.userLocator().count();
2006
- const assistantCount = await this.assistantLocator().count();
2007
- const currentUrl = new URL(page.url());
2008
- const blank =
2009
- currentUrl.pathname === "/" &&
2010
- userCount === 0 &&
2011
- assistantCount === 0 &&
2012
- Boolean(await this.composer());
2013
- let navigation = "reused-blank-page";
2014
-
2015
- if (!(blank && currentTemporary === temporary)) {
2016
- if (!blank) {
2017
- const newChat = await this.firstVisible(SELECTORS.newChatLinks, { timeout: 1_500 });
2018
- if (newChat) {
2019
- await this.assertComposerEmpty("new-chat");
2020
- await this.siteAction("new-chat");
2021
- // ChatGPT can animate two overlapping sidebar layers. A regular
2022
- // Playwright click then waits on an inner SVG that intercepts the
2023
- // pointer even though the semantic new-chat link is visible.
2024
- await this.domClick(newChat, "new-chat-click");
2025
- await page
2026
- .waitForFunction(
2027
- ({ userSelectors, assistantSelectors }) =>
2028
- location.pathname === "/" &&
2029
- document.querySelectorAll(userSelectors).length === 0 &&
2030
- [...document.querySelectorAll(assistantSelectors)].filter(
2031
- (element) => !/^\s*(?:thinking|思考)(?:\s*(?:[.…::]|$))/iu.test(
2032
- element.innerText || element.textContent || "",
2033
- ),
2034
- ).length === 0,
2035
- {
2036
- userSelectors: SELECTORS.userMessages.join(", "),
2037
- assistantSelectors: SELECTORS.assistantMessages.join(", "),
2038
- },
2039
- { timeout: ACTION_TIMEOUT_MS },
2040
- )
2041
- .catch(() => {});
2042
- navigation = "in-page-new-chat";
2043
- }
2044
- }
2045
-
2046
- const afterNewChatUrl = new URL(page.url());
2047
- const afterNewChatBlank =
2048
- afterNewChatUrl.pathname === "/" &&
2049
- (await this.userLocator().count()) === 0 &&
2050
- (await this.assistantLocator().count()) === 0;
2051
- if (afterNewChatBlank && (await this.temporaryState()) !== temporary) {
2052
- await this.setTemporary(temporary, { includeStatus: false });
2053
- navigation =
2054
- navigation === "in-page-new-chat"
2055
- ? "in-page-new-chat-and-temporary-toggle"
2056
- : "temporary-toggle";
2057
- }
2058
-
2059
- const afterClickUserCount = await this.userLocator().count();
2060
- const afterClickAssistantCount = await this.assistantLocator().count();
2061
- const afterClickUrl = new URL(page.url());
2062
- const needsFallback =
2063
- afterClickUrl.pathname !== "/" ||
2064
- afterClickUserCount > 0 ||
2065
- afterClickAssistantCount > 0 ||
2066
- (await this.temporaryState()) !== temporary;
2067
- if (needsFallback) {
2068
- throw new ChatGPTWebError(
2069
- "站内新建或临时对话切换后未通过校验。为避免重新加载整个 ChatGPT,操作已停止。",
2070
- {
2071
- requestedTemporary: temporary,
2072
- observedUrl: page.url(),
2073
- userMessageCount: afterClickUserCount,
2074
- assistantMessageCount: afterClickAssistantCount,
2075
- },
2076
- );
2077
- }
2078
- }
2079
-
2080
- await this.ensureSignedIn();
2081
- const composer = await this.composer();
2082
- if (!composer) throw new ChatGPTWebError("新对话页面未出现输入框。", { url: page.url() });
2083
- this.#settingsCache = null;
2084
- this.#answerTier = null;
2085
- return {
2086
- url: page.url(),
2087
- conversationId: conversationIdFromUrl(page.url()),
2088
- temporary: await this.temporaryState(),
2089
- navigation,
2090
- };
2091
- }
2092
-
2093
- async refreshBeforeNewChat() {
2094
- const page = await this.page();
2095
- await this.ensureSignedIn();
2096
- await this.assertComposerEmpty("refresh-before-new-chat");
2097
- const pendingFiles = await page
2098
- .locator(SELECTORS.fileInput.join(", "))
2099
- .evaluateAll((inputs) =>
2100
- inputs.reduce((count, input) => count + Number(input.files?.length || 0), 0),
2101
- );
2102
- if (pendingFiles > 0) {
2103
- throw new ChatGPTWebError("当前有未发送的附件,已拒绝刷新并新建对话。", { pendingFiles });
2104
- }
2105
- await this.siteAction("refresh-before-new-chat");
2106
- await this.pageInteraction("refresh-before-new-chat-reload");
2107
- const beforeUrl = page.url();
2108
- const startedAt = Date.now();
2109
- await page.reload({ waitUntil: "domcontentloaded" });
2110
- this.#signedInUntil = 0;
2111
- await this.ensureSignedIn();
2112
- await this.throwIfRateLimited();
2113
- return { refreshed: true, beforeUrl, afterUrl: page.url(), startedAt, completedAt: Date.now() };
2114
- }
2115
-
2116
- async newChat(
2117
- { temporary = false, model, mode, thinkingLevel, answerTier } = {},
2118
- { includeStatus = true, refreshBeforeNewChat = REFRESH_BEFORE_NEW_CHAT } = {},
2119
- ) {
2120
- const refreshResult = refreshBeforeNewChat ? await this.refreshBeforeNewChat() : null;
2121
- const root = await this.openRoot({ temporary });
2122
- if (mode) await this.selectMode(mode);
2123
- if (model) await this.selectModel(model);
2124
- if (thinkingLevel) await this.selectThinkingLevel(thinkingLevel);
2125
- if (answerTier) await this.selectAnswerTier(answerTier);
2126
- if (temporary && !root.temporary) await this.setTemporary(true, { includeStatus: false });
2127
- if (includeStatus) {
2128
- const status = await this.status();
2129
- return refreshResult ? { ...status, newChatRefresh: refreshResult } : status;
2130
- }
2131
- return {
2132
- ...root,
2133
- ...(refreshResult ? { newChatRefresh: refreshResult } : {}),
2134
- configured: {
2135
- mode: mode || null,
2136
- model: model || null,
2137
- thinkingLevel: thinkingLevel || null,
2138
- answerTier: answerTier || null,
2139
- },
2140
- };
2141
- }
2142
-
2143
- async temporaryState() {
2144
- const page = await this.page();
2145
- const url = new URL(page.url());
2146
- if (url.searchParams.get("temporary-chat") === "true") return true;
2147
-
2148
- const button = await this.firstVisible(SELECTORS.temporaryChatButtons, { timeout: 300 });
2149
- if (button) {
2150
- const pressed = await button.getAttribute("aria-pressed");
2151
- const checked = await button.getAttribute("aria-checked");
2152
- const state = await button.getAttribute("data-state");
2153
- if (pressed != null) return pressed === "true";
2154
- if (checked != null) return checked === "true";
2155
- if (state) return /on|checked|active/i.test(state);
2156
- const label = normalize(
2157
- `${await button.getAttribute("aria-label")} ${await button.innerText().catch(() => "")}`,
2158
- );
2159
- if (/turn off|关闭临时|退出临时/.test(label)) return true;
2160
- if (/turn on|开启临时|临时对话|临时聊天/.test(label)) return false;
2161
- }
2162
-
2163
- const body = normalize(await page.locator("body").innerText().catch(() => ""));
2164
- if (
2165
- /won't appear in your history|不会出现在历史记录|temporary chat is on|临时聊天已开启|这是临时聊天/.test(
2166
- body,
2167
- )
2168
- ) {
2169
- return true;
2170
- }
2171
- return false;
2172
- }
2173
-
2174
- async setTemporary(enabled, { includeStatus = true } = {}) {
2175
- await this.ensureSignedIn();
2176
- const page = await this.page();
2177
- const current = await this.temporaryState();
2178
- if (current === enabled) {
2179
- return includeStatus
2180
- ? this.status()
2181
- : { enabled: current, changed: false, url: page.url() };
2182
- }
2183
-
2184
- const button = await this.firstVisible(SELECTORS.temporaryChatButtons, { timeout: 1_500 });
2185
- if (button) {
2186
- await this.assertComposerEmpty(enabled ? "enable-temporary-chat" : "disable-temporary-chat");
2187
- await this.siteAction(enabled ? "enable-temporary-chat" : "disable-temporary-chat");
2188
- await this.click(button, enabled ? "enable-temporary-chat-click" : "disable-temporary-chat-click");
2189
- await page.waitForTimeout(500);
2190
- } else {
2191
- throw new ChatGPTWebError(
2192
- "没有找到临时对话开关。为避免重新加载整个 ChatGPT,操作已停止。",
2193
- { requested: enabled, url: page.url() },
2194
- );
2195
- }
2196
-
2197
- const verified = await this.temporaryState();
2198
- if (verified !== enabled) {
2199
- throw new ChatGPTWebError("临时对话状态切换后未通过页面校验。", {
2200
- requested: enabled,
2201
- observed: verified,
2202
- url: page.url(),
2203
- });
2204
- }
2205
- return includeStatus
2206
- ? this.status()
2207
- : { enabled: verified, changed: true, url: page.url() };
2208
- }
2209
-
2210
- async modelButton() {
2211
- return this.firstVisible(SELECTORS.modelButtons, { timeout: 500 });
2212
- }
2213
-
2214
- async modeOptions() {
2215
- const page = await this.page();
2216
- const controls = page.locator(SELECTORS.modeButtons.join(", "));
2217
- const raw = await controls.evaluateAll((elements) =>
2218
- elements
2219
- .filter((element) => {
2220
- const rect = element.getBoundingClientRect();
2221
- const style = getComputedStyle(element);
2222
- return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden";
2223
- })
2224
- .map((element) => ({
2225
- name: (element.innerText || element.getAttribute("aria-label") || "")
2226
- .replace(/\s+/g, " ")
2227
- .trim(),
2228
- selected:
2229
- element.getAttribute("aria-checked") === "true" ||
2230
- element.getAttribute("aria-pressed") === "true",
2231
- })),
2232
- );
2233
- return uniqueBy(raw.filter((item) => item.name), (item) => normalize(item.name));
2234
- }
2235
-
2236
- async currentMode() {
2237
- const modes = await this.modeOptions();
2238
- return modes.find((item) => item.selected)?.name || null;
2239
- }
2240
-
2241
- async listModes() {
2242
- await this.ensureSignedIn();
2243
- const modes = await this.modeOptions();
2244
- return { current: modes.find((item) => item.selected)?.name || null, modes };
2245
- }
2246
-
2247
- async capabilities({ historyLimit = 5 } = {}) {
2248
- await this.ensureSignedIn();
2249
- const page = await this.page();
2250
- const modes = await this.modeOptions();
2251
- const settings = await this.advancedSettings();
2252
- const conversations = (await this.historyLinks()).slice(
2253
- 0,
2254
- Math.max(0, Math.min(Number(historyLimit) || 0, MAX_HISTORY_RESULTS)),
2255
- );
2256
- return {
2257
- url: page.url(),
2258
- conversationId: conversationIdFromUrl(page.url()),
2259
- mode: modes.find((item) => item.selected)?.name || null,
2260
- modes,
2261
- model: settings.model,
2262
- thinkingLevel: settings.thinkingLevel,
2263
- temporary: await this.temporaryState(),
2264
- visibleHistory: conversations,
2265
- };
2266
- }
2267
-
2268
- async selectMode(mode) {
2269
- await this.ensureSignedIn();
2270
- const page = await this.page();
2271
- const modes = await this.modeOptions();
2272
- const matches = rankTextMatch(modes, mode, (item) => item.name);
2273
- if (!matches.length) {
2274
- throw new ChatGPTWebError("请求的工作模式不在当前页面显示的选项中。", {
2275
- requested: mode,
2276
- available: modes.map((item) => item.name),
2277
- });
2278
- }
2279
- const best = matches[0];
2280
- const tied = matches.filter((entry) => entry.score === best.score);
2281
- if (best.score < 100 && tied.length > 1) {
2282
- throw new ChatGPTWebError("工作模式名称匹配到多个选项,请使用完整名称。", {
2283
- requested: mode,
2284
- matches: tied.map((entry) => entry.item.name),
2285
- });
2286
- }
2287
-
2288
- if (best.item.selected) {
2289
- return { requested: mode, selected: best.item.name, changed: false };
2290
- }
2291
-
2292
- const option = page.getByRole("radio", { name: best.item.name, exact: true }).last();
2293
- await this.click(option, "select-mode");
2294
- await page.waitForTimeout(250);
2295
- const selected = await this.currentMode();
2296
- if (normalize(selected) !== normalize(best.item.name)) {
2297
- throw new ChatGPTWebError("工作模式切换后未通过页面校验。", {
2298
- requested: mode,
2299
- observed: selected,
2300
- });
2301
- }
2302
- this.#settingsCache = null;
2303
- return { requested: mode, selected };
2304
- }
2305
-
2306
- async advancedControlButton() {
2307
- const page = await this.page();
2308
- const composer = await this.composer();
2309
- const composerBox = await composer?.boundingBox();
2310
- if (!composerBox) return null;
2311
-
2312
- // This class is on the answer-tier pill itself in the current ChatGPT UI.
2313
- // It is unique to the composer and therefore safer than inferring a parent
2314
- // <main> when temporary-chat layouts render multiple main regions.
2315
- const semanticTierButton = page.locator("button.__composer-pill:visible").last();
2316
- if (await semanticTierButton.isVisible({ timeout: 3_000 }).catch(() => false)) {
2317
- return semanticTierButton;
2318
- }
2319
-
2320
- // The current ChatGPT UI no longer consistently exposes aria-haspopup on
2321
- // the answer-tier button (for example, the visible button may only say
2322
- // “极高”). Use its position beside the composer plus semantic exclusions.
2323
- // Resolve the exact <main> that owns this composer. ChatGPT can render
2324
- // another <main> earlier in the DOM, so page.locator("main").first()
2325
- // can silently search the wrong subtree.
2326
- const composerMain = composer.locator("xpath=ancestor::main[1]");
2327
- const scope = (await composerMain.count()) > 0 ? composerMain : page.locator("main").last();
2328
- const candidates = scope.locator("button:visible, [role='button']:visible");
2329
- const count = await candidates.count();
2330
- let best = null;
2331
- for (let index = 0; index < count; index += 1) {
2332
- const candidate = candidates.nth(index);
2333
- const text = (
2334
- (await candidate.innerText().catch(() => "")) ||
2335
- (await candidate.getAttribute("aria-label")) ||
2336
- (await candidate.getAttribute("title")) ||
2337
- ""
2338
- )
2339
- .replace(/\s+/g, " ")
2340
- .trim();
2341
- const box = await candidate.boundingBox();
2342
- if (!text || text.length > 40 || !box) continue;
2343
- if (
2344
- /聊天|工作|chat|work|语音|听写|voice|dictation|添加|文件|attach|upload|发送|停止|send|stop|麦克风|microphone/i.test(
2345
- text,
2346
- )
2347
- ) {
2348
- continue;
2349
- }
2350
-
2351
- const centerY = box.y + box.height / 2;
2352
- const centerX = box.x + box.width / 2;
2353
- const composerCenterY = composerBox.y + composerBox.height / 2;
2354
- const distance = Math.abs(centerY - composerCenterY);
2355
- if (distance > Math.max(90, composerBox.height * 2)) continue;
2356
- const answerTierBonus = /^(快速|标准|较高|高|极高|pro|fast|standard|high|very high)$/i.test(
2357
- text,
2358
- )
2359
- ? -100
2360
- : 0;
2361
- const horizontalDistance = Math.abs(centerX - (composerBox.x + composerBox.width));
2362
- const score = distance + horizontalDistance * 0.02 + answerTierBonus;
2363
- if (!best || score < best.score) best = { locator: candidate, score };
2364
- }
2365
- return best?.locator || null;
2366
- }
2367
-
2368
- async answerTierSliderState(slider) {
2369
- if (!slider) return null;
2370
- return slider.evaluate((element) => {
2371
- const input = element instanceof HTMLInputElement ? element : null;
2372
- const number = (name, fallback) => {
2373
- const raw = element.getAttribute(name) ?? fallback;
2374
- const value = Number(raw);
2375
- return Number.isFinite(value) ? value : null;
2376
- };
2377
- const valueText =
2378
- element.getAttribute("aria-valuetext") ||
2379
- element.getAttribute("aria-label") ||
2380
- input?.value ||
2381
- (element.textContent || "").replace(/\s+/g, " ").trim() ||
2382
- null;
2383
- return {
2384
- valueText,
2385
- current: valueText ? valueText.split(/[,,]/, 1)[0].trim() : null,
2386
- now: number("aria-valuenow", input?.value),
2387
- min: number("aria-valuemin", input?.min),
2388
- max: number("aria-valuemax", input?.max),
2389
- };
2390
- });
2391
- }
2392
-
2393
- async answerTierControlLabel() {
2394
- const trigger = await this.advancedControlButton();
2395
- if (!trigger) return null;
2396
- const values = await trigger.evaluate((element) => ({
2397
- text: (element.innerText || element.textContent || "").replace(/\s+/g, " ").trim(),
2398
- ariaLabel: element.getAttribute("aria-label") || "",
2399
- title: element.getAttribute("title") || "",
2400
- }));
2401
- const explicitPro = [values.text, values.ariaLabel, values.title].find((value) =>
2402
- /(^|[\s._-])pro($|[\s._-])/i.test(value),
2403
- );
2404
- return explicitPro ? "Pro" : parseAnswerTier(values.text || values.ariaLabel || values.title);
2405
- }
2406
-
2407
- async openAnswerTierControl() {
2408
- await this.ensureSignedIn();
2409
- const page = await this.page();
2410
- const trigger = await this.advancedControlButton();
2411
- if (!trigger) {
2412
- throw new ChatGPTWebError("没有找到输入框右侧的能力档位控件。", { url: page.url() });
2413
- }
2414
- await this.click(trigger, "open-answer-tier-control");
2415
- await page.waitForTimeout(180);
2416
- const slider = await this.firstVisible(SELECTORS.answerTierSliders, { timeout: 1_500 });
2417
- return { trigger, slider };
2418
- }
2419
-
2420
- async openAnswerTierSlider() {
2421
- const { slider } = await this.openAnswerTierControl();
2422
- if (slider) return slider;
2423
- const page = await this.page();
2424
- await this.closeAdvancedMenus();
2425
- throw new ChatGPTWebError("能力档位菜单已打开,但没有找到其滑杆。", { url: page.url() });
2426
- }
2427
-
2428
- async selectVisibleAnswerTierOption(answerTier) {
2429
- const page = await this.page();
2430
- const matches = page.getByText(answerTier, { exact: true });
2431
- for (let index = (await matches.count()) - 1; index >= 0; index -= 1) {
2432
- const text = matches.nth(index);
2433
- if (!(await text.isVisible().catch(() => false))) continue;
2434
- const interactive = text.locator(
2435
- "xpath=ancestor-or-self::*[self::button or @role='button' or @role='menuitem' or @role='menuitemradio' or @role='option' or @tabindex][1]",
2436
- );
2437
- const target = (await interactive.count()) > 0 ? interactive : text;
2438
- await this.domClick(target, "select-answer-tier-option");
2439
- await page.waitForTimeout(250);
2440
- await this.closeAdvancedMenus();
2441
- const displayed = await this.answerTierControlLabel();
2442
- if (normalize(displayed) === normalize(answerTier)) {
2443
- return { selected: displayed, verifiedBy: "visible-menu-option" };
2444
- }
2445
- return null;
2446
- }
2447
- return null;
2448
- }
2449
-
2450
- async answerTierStatus() {
2451
- const displayed = await this.answerTierControlLabel();
2452
- const { slider } = await this.openAnswerTierControl();
2453
- if (!slider) {
2454
- const options = await this.visibleMenuOptions({ exclude: [displayed] });
2455
- await this.closeAdvancedMenus();
2456
- if (displayed) this.#answerTier = displayed;
2457
- return {
2458
- current: displayed,
2459
- type: "menu",
2460
- options: options.map((item) => item.name),
2461
- };
2462
- }
2463
- const state = await this.answerTierSliderState(slider);
2464
- await this.closeAdvancedMenus();
2465
- if (state?.current) this.#answerTier = state.current;
2466
- return { ...state, type: "slider" };
2467
- }
2468
-
2469
- async selectAnswerTier(answerTier) {
2470
- const wanted = normalize(answerTier);
2471
- const displayedBefore = await this.answerTierControlLabel();
2472
- if (normalize(displayedBefore) === wanted) {
2473
- this.#answerTier = displayedBefore;
2474
- return {
2475
- requested: answerTier,
2476
- selected: displayedBefore,
2477
- changed: false,
2478
- verifiedBy: "displayed-tier-control",
2479
- };
2480
- }
2481
- const { slider } = await this.openAnswerTierControl();
2482
- const menuSelection = slider
2483
- ? null
2484
- : await this.selectVisibleAnswerTierOption(answerTier);
2485
- if (menuSelection) {
2486
- this.#answerTier = menuSelection.selected;
2487
- return {
2488
- requested: answerTier,
2489
- selected: menuSelection.selected,
2490
- changed: true,
2491
- verifiedBy: menuSelection.verifiedBy,
2492
- };
2493
- }
2494
- if (!slider) {
2495
- await this.closeAdvancedMenus();
2496
- throw new ChatGPTWebError("能力档位菜单中没有找到目标档位,也没有可访问滑杆。", {
2497
- requested: answerTier,
2498
- displayedBefore,
2499
- url: (await this.page()).url(),
2500
- });
2501
- }
2502
- const before = await this.answerTierSliderState(slider);
2503
- if (normalize(before?.current) === wanted) {
2504
- this.#answerTier = before.current;
2505
- await this.closeAdvancedMenus();
2506
- return { requested: answerTier, selected: before.current, changed: false, control: before };
2507
- }
2508
-
2509
- if (!isProTier(answerTier)) {
2510
- await this.closeAdvancedMenus();
2511
- throw new ChatGPTWebError(
2512
- "能力滑杆目前只支持按可访问名称直接选择 Pro;其他档位请传模型和思考强度。",
2513
- { requested: answerTier, current: before },
2514
- );
2515
- }
2516
-
2517
- await slider.focus();
2518
- await this.press(slider, "End", "answer-tier-end");
2519
- await (await this.page()).waitForTimeout(250);
2520
- let selected = await this.answerTierSliderState(slider);
2521
- if (!isProTier(selected?.current)) {
2522
- for (let step = 0; step < 8 && !isProTier(selected?.current); step += 1) {
2523
- const previous = selected?.valueText;
2524
- await this.press(slider, "ArrowRight", "answer-tier-increment");
2525
- await (await this.page()).waitForTimeout(120);
2526
- selected = await this.answerTierSliderState(slider);
2527
- if (selected?.valueText === previous && selected?.max === selected?.now) break;
2528
- }
2529
- }
2530
- await this.closeAdvancedMenus();
2531
- const displayed = await this.answerTierControlLabel();
2532
- const verifiedTier = isProTier(selected?.current)
2533
- ? selected.current
2534
- : isProTier(displayed)
2535
- ? displayed
2536
- : null;
2537
- if (!verifiedTier) {
2538
- throw new ChatGPTWebError("能力档位没有切换到 Pro,因此未发送提示词。", {
2539
- requested: answerTier,
2540
- before,
2541
- observed: selected,
2542
- displayed,
2543
- });
2544
- }
2545
- this.#answerTier = verifiedTier;
2546
- return {
2547
- requested: answerTier,
2548
- selected: verifiedTier,
2549
- changed: normalize(before?.current) !== normalize(verifiedTier),
2550
- before,
2551
- control: selected,
2552
- verifiedBy: isProTier(selected?.current) ? "slider-text" : "displayed-tier-control",
2553
- };
2554
- }
2555
-
2556
- async selectExtremeTier(answerTier = DEFAULT_ANSWER_TIER) {
2557
- const displayedBefore = await this.answerTierControlLabel();
2558
- if (normalize(displayedBefore) === normalize(answerTier)) {
2559
- this.#answerTier = answerTier;
2560
- return {
2561
- requested: answerTier,
2562
- selected: answerTier,
2563
- changed: false,
2564
- verifiedBy: "displayed-tier-control",
2565
- };
2566
- }
2567
-
2568
- const { slider } = await this.openAnswerTierControl();
2569
- const menuSelection = slider
2570
- ? null
2571
- : await this.selectVisibleAnswerTierOption(answerTier);
2572
- if (menuSelection) {
2573
- this.#answerTier = answerTier;
2574
- return {
2575
- requested: answerTier,
2576
- selected: answerTier,
2577
- changed: true,
2578
- verifiedBy: menuSelection.verifiedBy,
2579
- };
2580
- }
2581
- if (!slider) {
2582
- await this.closeAdvancedMenus();
2583
- throw new ChatGPTWebError("能力档位菜单中没有找到默认档位,也没有可访问滑杆。", {
2584
- requested: answerTier,
2585
- displayedBefore,
2586
- url: (await this.page()).url(),
2587
- });
2588
- }
2589
- const before = await this.answerTierSliderState(slider);
2590
- await slider.focus();
2591
- await this.press(slider, "End", "extreme-tier-end");
2592
- await (await this.page()).waitForTimeout(120);
2593
- await this.press(slider, "ArrowLeft", "extreme-tier-decrement");
2594
- await (await this.page()).waitForTimeout(250);
2595
- const observed = await this.answerTierSliderState(slider);
2596
- await this.closeAdvancedMenus();
2597
- const displayed = await this.answerTierControlLabel();
2598
- if (normalize(displayed) !== normalize(answerTier)) {
2599
- throw new ChatGPTWebError("能力档位没有切换到配置的默认档位,因此未发送提示词。", {
2600
- requested: answerTier,
2601
- before,
2602
- observed,
2603
- displayed,
2604
- });
2605
- }
2606
- this.#answerTier = answerTier;
2607
- return {
2608
- requested: answerTier,
2609
- selected: answerTier,
2610
- changed: true,
2611
- before,
2612
- control: observed,
2613
- verifiedBy: "displayed-tier-control",
2614
- };
2615
- }
2616
-
2617
- async advancedRow(labels) {
2618
- const page = await this.page();
2619
- for (const label of labels) {
2620
- const matches = page.getByText(label, { exact: true });
2621
- for (let index = (await matches.count()) - 1; index >= 0; index -= 1) {
2622
- const locator = matches.nth(index);
2623
- if (!(await locator.isVisible().catch(() => false))) continue;
2624
- const rowText = await locator.evaluate((element, exactLabel) => {
2625
- let node = element;
2626
- for (let depth = 0; node && depth < 6; depth += 1, node = node.parentElement) {
2627
- const text = (node.innerText || node.textContent || "").replace(/\s+/g, " ").trim();
2628
- const rect = node.getBoundingClientRect();
2629
- if (text !== exactLabel && text.length <= 180 && rect.height > 20 && rect.height <= 120) {
2630
- return text;
2631
- }
2632
- }
2633
- return exactLabel;
2634
- }, label);
2635
- const interactive = locator.locator(
2636
- "xpath=ancestor-or-self::*[self::button or @role='button' or @role='menuitem' or @role='menuitemradio' or @role='option' or @tabindex][1]",
2637
- );
2638
- return {
2639
- label,
2640
- locator: (await interactive.count()) > 0 ? interactive : locator,
2641
- text: rowText,
2642
- value: parseAdvancedRowValue(rowText, labels),
2643
- };
2644
- }
2645
- }
2646
- return null;
2647
- }
2648
-
2649
- async clickAdvancedRow(row) {
2650
- if (!row?.locator) throw new ChatGPTWebError("高级菜单行缺少可点击元素。");
2651
- await this.domClick(row.locator, "advanced-menu-row");
2652
- await (await this.page()).waitForTimeout(180);
2653
- }
2654
-
2655
- async closeAdvancedMenus() {
2656
- const page = await this.page();
2657
- await this.keyboardPress(page, "Escape", "close-advanced-menu").catch(() => {});
2658
- await this.keyboardPress(page, "Escape", "close-advanced-menu-fallback").catch(() => {});
2659
- }
2660
-
2661
- async clickMenuOption(option) {
2662
- const page = await this.page();
2663
- const text = page.getByText(option.name, { exact: true }).last();
2664
- const byTestId = option.testId
2665
- ? page.locator(`[data-testid=${JSON.stringify(option.testId)}]`).last()
2666
- : null;
2667
- const base = byTestId && (await byTestId.count()) > 0 ? byTestId : text;
2668
- const interactive = base.locator(
2669
- "xpath=ancestor-or-self::*[self::button or @role='button' or @role='menuitem' or @role='menuitemradio' or @role='option' or @tabindex][1]",
2670
- );
2671
- const target = (await interactive.count()) > 0 ? interactive : base;
2672
- await this.domClick(target, "select-menu-option");
2673
- await page.waitForTimeout(250);
2674
- }
2675
-
2676
- async directAdvancedSettings() {
2677
- const page = await this.page();
2678
- const picker = page
2679
- .locator("[data-testid='composer-intelligence-picker-content']:visible")
2680
- .last();
2681
- if (!(await picker.isVisible().catch(() => false))) return null;
2682
-
2683
- const simpleView = picker
2684
- .locator("[data-testid='composer-model-picker-slider-simple-view']")
2685
- .last();
2686
- const advancedView = picker
2687
- .locator("[data-testid='composer-model-picker-slider-advanced-view']")
2688
- .last();
2689
- const toggle = picker
2690
- .locator(
2691
- "[role='menuitem'][aria-label='Select model'], [role='menuitem'][aria-label='选择模型']",
2692
- )
2693
- .last();
2694
- const slider = simpleView.locator("[role='slider']").last();
2695
- const checkedModel = advancedView
2696
- .locator("[role='menuitemradio'][aria-checked='true']")
2697
- .last();
2698
- if (
2699
- !(await simpleView.count()) ||
2700
- !(await advancedView.count()) ||
2701
- !(await toggle.count()) ||
2702
- !(await slider.count()) ||
2703
- !(await checkedModel.count())
2704
- ) {
2705
- return null;
2706
- }
2707
-
2708
- const thinkingLevel = parseAnswerTier(await toggle.innerText().catch(() => ""));
2709
- const model = (await checkedModel.innerText().catch(() => "")).replace(/\s+/g, " ").trim();
2710
- if (!thinkingLevel || !model) return null;
2711
-
2712
- return {
2713
- layout: "direct-picker",
2714
- picker,
2715
- slider,
2716
- modelRow: {
2717
- label: "Model",
2718
- locator: toggle,
2719
- text: `Model ${model}`,
2720
- value: model,
2721
- },
2722
- thinkingRow: {
2723
- label: "Thinking effort",
2724
- locator: slider,
2725
- text: `Thinking effort ${thinkingLevel}`,
2726
- value: thinkingLevel,
2727
- },
2728
- };
2729
- }
2730
-
2731
- async openAdvancedSettings() {
2732
- await this.ensureSignedIn();
2733
- const page = await this.page();
2734
- let modelRow = await this.advancedRow(SELECTORS.modelRowLabels);
2735
- let thinkingRow = await this.advancedRow(SELECTORS.thinkingRowLabels);
2736
- if (modelRow && thinkingRow) {
2737
- this.rememberSettings(modelRow.value, thinkingRow.value);
2738
- return { modelRow, thinkingRow };
2739
- }
2740
-
2741
- const trigger = await this.advancedControlButton();
2742
- if (!trigger) {
2743
- throw new ChatGPTWebError(
2744
- "没有找到输入框右侧的回答档位控件,无法打开高级模型设置。",
2745
- { url: page.url() },
2746
- );
2747
- }
2748
- await this.click(trigger, "open-advanced-settings");
2749
- await page.waitForTimeout(180);
2750
-
2751
- const direct = await this.directAdvancedSettings();
2752
- if (direct) return direct;
2753
-
2754
- modelRow = await this.advancedRow(SELECTORS.modelRowLabels);
2755
- thinkingRow = await this.advancedRow(SELECTORS.thinkingRowLabels);
2756
- if (!modelRow || !thinkingRow) {
2757
- const advanced = await this.advancedRow(SELECTORS.advancedLabels);
2758
- if (!advanced) {
2759
- await this.closeAdvancedMenus();
2760
- throw new ChatGPTWebError("回答档位菜单已打开,但没有找到“高级”入口。", {
2761
- url: page.url(),
2762
- });
2763
- }
2764
- await this.clickAdvancedRow(advanced);
2765
- modelRow = await this.advancedRow(SELECTORS.modelRowLabels);
2766
- thinkingRow = await this.advancedRow(SELECTORS.thinkingRowLabels);
2767
- }
2768
-
2769
- if (!modelRow || !thinkingRow) {
2770
- await this.closeAdvancedMenus();
2771
- throw new ChatGPTWebError("高级菜单已展开,但没有同时找到“模型”和“思考强度”。", {
2772
- modelRowFound: Boolean(modelRow),
2773
- thinkingRowFound: Boolean(thinkingRow),
2774
- url: page.url(),
2775
- });
2776
- }
2777
- this.rememberSettings(modelRow.value, thinkingRow.value);
2778
- return { modelRow, thinkingRow };
2779
- }
2780
-
2781
- rememberSettings(model, thinkingLevel) {
2782
- this.#settingsCache = {
2783
- value: { model: model || null, thinkingLevel: thinkingLevel || null },
2784
- expiresAt: Date.now() + 5 * 60_000,
2785
- };
2786
- }
2787
-
2788
- async advancedSettings({ force = false } = {}) {
2789
- if (!force && this.#settingsCache?.expiresAt > Date.now()) {
2790
- return this.#settingsCache.value;
2791
- }
2792
- const page = await this.page();
2793
- const { modelRow, thinkingRow } = await this.openAdvancedSettings();
2794
- const value = {
2795
- model: modelRow.value,
2796
- thinkingLevel: thinkingRow.value,
2797
- };
2798
- await this.closeAdvancedMenus();
2799
- this.rememberSettings(value.model, value.thinkingLevel);
2800
- return value;
2801
- }
2802
-
2803
- async currentModel() {
2804
- const button = await this.modelButton();
2805
- if (button) {
2806
- const text = await button.innerText().catch(() => "");
2807
- const label = await button.getAttribute("aria-label");
2808
- return (text || label || "").replace(/\s+/g, " ").trim() || null;
2809
- }
2810
- return (await this.advancedSettings()).model;
2811
- }
2812
-
2813
- async currentThinkingLevel() {
2814
- return (await this.advancedSettings()).thinkingLevel;
2815
- }
2816
-
2817
- async openLegacyModelMenu() {
2818
- await this.ensureSignedIn();
2819
- const page = await this.page();
2820
- const button = await this.modelButton();
2821
- if (!button) {
2822
- throw new ChatGPTWebError("没有找到模型选择器。当前账号、工作区或页面版本可能未显示该控件。", {
2823
- url: page.url(),
2824
- });
2825
- }
2826
- await this.click(button, "open-model-menu");
2827
- await page.waitForTimeout(300);
2828
- return button;
2829
- }
2830
-
2831
- async visibleMenuOptions({ exclude = [] } = {}) {
2832
- const page = await this.page();
2833
- const candidates = page.locator(
2834
- [
2835
- "[role='menuitem']:visible",
2836
- "[role='menuitemradio']:visible",
2837
- "[role='menuitemcheckbox']:visible",
2838
- "[role='option']:visible",
2839
- "[role='menu']:visible button:visible",
2840
- "[role='listbox']:visible button:visible",
2841
- "[data-testid*='model']:visible",
2842
- "[data-radix-popper-content-wrapper]:visible button:visible",
2843
- "[data-radix-popper-content-wrapper]:visible [role='button']:visible",
2844
- ].join(", "),
2845
- );
2846
- const raw = await candidates.evaluateAll((elements) =>
2847
- elements.map((element) => ({
2848
- text: (element.innerText || element.textContent || "").replace(/\s+/g, " ").trim(),
2849
- ariaLabel: element.getAttribute("aria-label") || "",
2850
- testId: element.getAttribute("data-testid") || "",
2851
- role: element.getAttribute("role") || "",
2852
- })),
2853
- );
2854
- return uniqueBy(
2855
- raw
2856
- .map((item) => ({
2857
- ...item,
2858
- name: item.text || item.ariaLabel,
2859
- }))
2860
- .filter((item) => {
2861
- if (!item.name || item.name.length >= 220) return false;
2862
- if (item.testId === "model-switcher-dropdown-button") return false;
2863
- if (exclude.some((value) => normalize(value) === normalize(item.name))) return false;
2864
- if (
2865
- [...SELECTORS.advancedLabels, ...SELECTORS.modelRowLabels, ...SELECTORS.thinkingRowLabels]
2866
- .some((value) => normalize(value) === normalize(item.name))
2867
- ) return false;
2868
- return !/^(log in|sign up|登录|免费注册)$/i.test(item.name);
2869
- }),
2870
- (item) => normalize(item.name),
2871
- );
2872
- }
2873
-
2874
- async listModels() {
2875
- const page = await this.page();
2876
- const legacy = await this.modelButton();
2877
- let current;
2878
- let models;
2879
- if (legacy) {
2880
- await this.openLegacyModelMenu();
2881
- models = await this.visibleMenuOptions();
2882
- current = await this.currentModel();
2883
- } else {
2884
- const { modelRow, thinkingRow } = await this.openAdvancedSettings();
2885
- current = modelRow.value;
2886
- await this.clickAdvancedRow(modelRow);
2887
- models = await this.visibleMenuOptions({
2888
- exclude: [modelRow.text, thinkingRow.text],
2889
- });
2890
- }
2891
- await this.closeAdvancedMenus();
2892
- return { current, models };
2893
- }
2894
-
2895
- async selectModel(model) {
2896
- const page = await this.page();
2897
- const legacy = await this.modelButton();
2898
- let options;
2899
- let observedThinkingLevel = null;
2900
- if (legacy) {
2901
- await this.openLegacyModelMenu();
2902
- options = await this.visibleMenuOptions();
2903
- } else {
2904
- const { modelRow, thinkingRow } = await this.openAdvancedSettings();
2905
- observedThinkingLevel = thinkingRow.value;
2906
- if (normalize(modelRow.value) === normalize(model)) {
2907
- await this.closeAdvancedMenus();
2908
- return { requested: model, selected: modelRow.value, changed: false };
2909
- }
2910
- await this.clickAdvancedRow(modelRow);
2911
- options = await this.visibleMenuOptions({
2912
- exclude: [modelRow.text, thinkingRow.text],
2913
- });
2914
- }
2915
- const matches = rankTextMatch(options, model, (item) => item.name);
2916
-
2917
- if (!matches.length) {
2918
- const exactText = page.getByText(model, { exact: true }).last();
2919
- if (await exactText.isVisible().catch(() => false)) {
2920
- await this.clickMenuOption({ name: model, testId: "" });
2921
- if (!legacy) this.rememberSettings(model, observedThinkingLevel);
2922
- return { selected: model, requested: model, verifiedBy: "exact-menu-option" };
2923
- }
2924
- }
2925
-
2926
- if (!matches.length) {
2927
- await this.closeAdvancedMenus();
2928
- throw new ChatGPTWebError("请求的模型不在当前账号显示的模型菜单中。", {
2929
- requested: model,
2930
- available: options.map((item) => item.name),
2931
- });
2932
- }
2933
-
2934
- const best = matches[0];
2935
- const tied = matches.filter((entry) => entry.score === best.score);
2936
- if (best.score < 100 && tied.length > 1) {
2937
- await this.closeAdvancedMenus();
2938
- throw new ChatGPTWebError("模型名称匹配到多个选项,请使用更完整的名称。", {
2939
- requested: model,
2940
- matches: tied.map((entry) => entry.item.name),
2941
- });
2942
- }
2943
-
2944
- const option = options.find((item) => item === best.item);
2945
- await this.clickMenuOption(option);
2946
- if (!legacy) this.rememberSettings(option.name, observedThinkingLevel);
2947
- const selected = legacy ? await this.currentModel() : option.name;
2948
- if (selected && best.score === 100 && !normalize(selected).includes(normalize(model))) {
2949
- // Some UI versions display a family name rather than the selected mode. Return both signals.
2950
- return { requested: model, clicked: option.name, selected, verifiedBy: "menu-click" };
2951
- }
2952
- return { requested: model, clicked: option.name, selected, verifiedBy: "switcher" };
2953
- }
2954
-
2955
- async listThinkingLevels() {
2956
- const { modelRow, thinkingRow, layout, slider: directSlider } =
2957
- await this.openAdvancedSettings();
2958
- const current = thinkingRow.value;
2959
- if (layout === "direct-picker") {
2960
- const slider = await this.answerTierSliderState(directSlider);
2961
- await this.closeAdvancedMenus();
2962
- return {
2963
- current,
2964
- levels: [],
2965
- control: { type: "slider", ...slider, current },
2966
- note:
2967
- "当前网页把思考强度直接显示为 Power 滑杆;返回其当前语义和值域。",
2968
- };
2969
- }
2970
- await this.clickAdvancedRow(thinkingRow);
2971
- const levels = await this.visibleMenuOptions({
2972
- exclude: [modelRow.text, thinkingRow.text],
2973
- });
2974
- const slider = await this.thinkingSliderState();
2975
- await this.closeAdvancedMenus();
2976
- return {
2977
- current,
2978
- levels,
2979
- control: slider ? { type: "slider", ...slider } : { type: "menu" },
2980
- note:
2981
- levels.length === 0 && slider
2982
- ? "网页仅公开滑块当前语义和值域;选择时会按滑块可访问状态校验,不会按坐标盲点。"
2983
- : undefined,
2984
- };
2985
- }
2986
-
2987
- async thinkingSliderState() {
2988
- const slider = await this.firstVisible(SELECTORS.thinkingSliders, { timeout: 250 });
2989
- if (!slider) return null;
2990
- return slider.evaluate((element) => {
2991
- const input = element instanceof HTMLInputElement ? element : null;
2992
- const number = (name, fallback) => {
2993
- const raw = element.getAttribute(name) ?? fallback;
2994
- const value = Number(raw);
2995
- return Number.isFinite(value) ? value : null;
2996
- };
2997
- return {
2998
- valueText:
2999
- element.getAttribute("aria-valuetext") ||
3000
- element.getAttribute("aria-label") ||
3001
- input?.value ||
3002
- null,
3003
- now: number("aria-valuenow", input?.value),
3004
- min: number("aria-valuemin", input?.min),
3005
- max: number("aria-valuemax", input?.max),
3006
- step: number("aria-valuestep", input?.step) || 1,
3007
- };
3008
- });
3009
- }
3010
-
3011
- async selectThinkingSliderValue(slider, value) {
3012
- const state = await this.thinkingSliderState();
3013
- if (!state || state.min == null || state.max == null || state.min === state.max) {
3014
- throw new ChatGPTWebError("思考强度滑块没有公开可校验的数值范围。", {
3015
- requested: value,
3016
- slider: state,
3017
- });
3018
- }
3019
- const requested = Number(value);
3020
- if (!Number.isFinite(requested) || requested < state.min || requested > state.max) {
3021
- throw new ChatGPTWebError("请求的思考强度滑块值超出网页公开范围。", {
3022
- requested: value,
3023
- slider: state,
3024
- });
3025
- }
3026
-
3027
- const orientation = (await slider.getAttribute("aria-orientation")) || "horizontal";
3028
- const step = state.step || 1;
3029
- const stepCount = Math.round((requested - state.min) / step);
3030
- const snapped = state.min + stepCount * step;
3031
- if (Math.abs(snapped - requested) > 1e-9 || stepCount > 100) {
3032
- throw new ChatGPTWebError("请求值不符合思考强度滑块公开的步长。", {
3033
- requested,
3034
- slider: state,
3035
- });
3036
- }
3037
-
3038
- await slider.focus();
3039
- await this.press(slider, "Home", "thinking-slider-home");
3040
- const incrementKey = orientation === "vertical" ? "ArrowUp" : "ArrowRight";
3041
- for (let index = 0; index < stepCount; index += 1) {
3042
- await this.press(slider, incrementKey, "thinking-slider-increment");
3043
- }
3044
- await (await this.page()).waitForTimeout(180);
3045
- const observed = await this.thinkingSliderState();
3046
- if (!observed || Math.abs(Number(observed.now) - requested) > 1e-9) {
3047
- throw new ChatGPTWebError("思考强度滑块操作后未通过数值校验。", {
3048
- requested,
3049
- observed,
3050
- });
3051
- }
3052
- return observed;
3053
- }
3054
-
3055
- async selectThinkingLevel(thinkingLevel) {
3056
- const page = await this.page();
3057
- const opened = await this.openAdvancedSettings();
3058
- const { modelRow, thinkingRow } = opened;
3059
- if (normalize(thinkingRow.value) === normalize(thinkingLevel)) {
3060
- await this.closeAdvancedMenus();
3061
- return { requested: thinkingLevel, selected: thinkingRow.value, changed: false };
3062
- }
3063
- if (opened.layout === "direct-picker") {
3064
- const sliderState = await this.answerTierSliderState(opened.slider);
3065
- const min = Number(sliderState?.min);
3066
- const max = Number(sliderState?.max);
3067
- const original = Number(sliderState?.now);
3068
- if (
3069
- !Number.isFinite(min) ||
3070
- !Number.isFinite(max) ||
3071
- !Number.isFinite(original) ||
3072
- max < min ||
3073
- max - min > 20
3074
- ) {
3075
- await this.closeAdvancedMenus();
3076
- throw new ChatGPTWebError("思考强度滑块没有公开可安全遍历的范围。", {
3077
- requested: thinkingLevel,
3078
- slider: sliderState,
3079
- });
3080
- }
3081
-
3082
- const available = [];
3083
- await opened.slider.focus();
3084
- await this.press(opened.slider, "Home", "thinking-slider-home");
3085
- for (let position = min; position <= max; position += 1) {
3086
- await page.waitForTimeout(100);
3087
- const observed = parseAnswerTier(
3088
- await opened.modelRow.locator.innerText().catch(() => ""),
3089
- );
3090
- if (observed) available.push(observed);
3091
- if (normalize(observed) === normalize(thinkingLevel)) {
3092
- await this.closeAdvancedMenus();
3093
- const selected = await this.answerTierControlLabel();
3094
- if (normalize(selected) !== normalize(thinkingLevel)) {
3095
- throw new ChatGPTWebError("思考强度切换后未通过页面校验。", {
3096
- requested: thinkingLevel,
3097
- observed: selected,
3098
- });
3099
- }
3100
- this.rememberSettings(modelRow.value, selected);
3101
- return {
3102
- requested: thinkingLevel,
3103
- selected,
3104
- changed: original !== position,
3105
- available,
3106
- verifiedBy: "power-slider-label",
3107
- };
3108
- }
3109
- if (position < max) {
3110
- await this.press(opened.slider, "ArrowRight", "thinking-slider-increment");
3111
- }
3112
- }
3113
-
3114
- await this.press(opened.slider, "Home", "thinking-slider-restore-home");
3115
- for (let position = min; position < original; position += 1) {
3116
- await this.press(opened.slider, "ArrowRight", "thinking-slider-restore");
3117
- }
3118
- await this.closeAdvancedMenus();
3119
- throw new ChatGPTWebError("请求的思考强度不在当前 Power 滑杆中。", {
3120
- requested: thinkingLevel,
3121
- available,
3122
- });
3123
- }
3124
- await this.clickAdvancedRow(thinkingRow);
3125
- const options = await this.visibleMenuOptions({
3126
- exclude: [modelRow.text, thinkingRow.text],
3127
- });
3128
- const matches = rankTextMatch(options, thinkingLevel, (item) => item.name);
3129
- if (!matches.length) {
3130
- const slider = await this.firstVisible(SELECTORS.thinkingSliders, { timeout: 300 });
3131
- const sliderState = slider ? await this.thinkingSliderState() : null;
3132
- const requestedSliderValue = Number(thinkingLevel);
3133
- if (slider && Number.isFinite(requestedSliderValue)) {
3134
- const selectedSlider = await this.selectThinkingSliderValue(slider, requestedSliderValue);
3135
- await this.closeAdvancedMenus();
3136
- this.rememberSettings(
3137
- modelRow.value,
3138
- selectedSlider.valueText || String(selectedSlider.now),
3139
- );
3140
- return {
3141
- requested: thinkingLevel,
3142
- selected: selectedSlider.valueText,
3143
- slider: selectedSlider,
3144
- };
3145
- }
3146
- await this.closeAdvancedMenus();
3147
- throw new ChatGPTWebError(
3148
- slider
3149
- ? "当前网页只显示思考强度滑块,但没有公开目标档位的可访问名称;为避免盲选,未更改设置。"
3150
- : "请求的思考强度不在当前账号显示的选项中。",
3151
- {
3152
- requested: thinkingLevel,
3153
- available: options.map((item) => item.name),
3154
- slider: sliderState,
3155
- },
3156
- );
3157
- }
3158
- const best = matches[0];
3159
- const tied = matches.filter((entry) => entry.score === best.score);
3160
- if (best.score < 100 && tied.length > 1) {
3161
- await this.closeAdvancedMenus();
3162
- throw new ChatGPTWebError("思考强度匹配到多个选项,请使用完整名称。", {
3163
- requested: thinkingLevel,
3164
- matches: tied.map((entry) => entry.item.name),
3165
- });
3166
- }
3167
-
3168
- const option = best.item;
3169
- await this.clickMenuOption(option);
3170
- this.rememberSettings(modelRow.value, option.name);
3171
- const selected = option.name;
3172
- if (normalize(selected) !== normalize(option.name)) {
3173
- throw new ChatGPTWebError("思考强度切换后未通过页面校验。", {
3174
- requested: thinkingLevel,
3175
- clicked: option.name,
3176
- observed: selected,
3177
- });
3178
- }
3179
- return { requested: thinkingLevel, clicked: option.name, selected };
3180
- }
3181
-
3182
- async writePrompt(prompt, { append = false } = {}) {
3183
- await this.ensureSignedIn();
3184
- const composer = await this.composer();
3185
- if (!composer) throw new ChatGPTWebError("没有找到提示词输入框。");
3186
- await this.assertComposerWritable("write-prompt", composer);
3187
-
3188
- const before = await this.composerText(composer);
3189
- const action = promptWriteAction(before, prompt, { append });
3190
- if (action === "reject-nonempty") {
3191
- throw new ChatGPTWebError(
3192
- "输入框已有用户草稿,已拒绝覆盖。请使用 append=true 或由用户先清空草稿。",
3193
- {
3194
- existingCharacters: before.length,
3195
- existingPreview: before.slice(0, 160),
3196
- requestedCharacters: prompt.length,
3197
- overwritePrevented: true,
3198
- },
3199
- );
3200
- }
3201
- if (action === "already-present") {
3202
- return {
3203
- written: false,
3204
- alreadyPresent: true,
3205
- protected: true,
3206
- characters: before.length,
3207
- preview: before.slice(0, 300),
3208
- };
3209
- }
3210
-
3211
- // React's contenteditable composer can drop characters when a long
3212
- // append is sent through Playwright's per-keystroke `type()`. Append is
3213
- // already explicitly authorized by the caller, so update the complete
3214
- // value atomically and preserve the exact existing draft.
3215
- if (action === "append") await this.fill(composer, `${before}${prompt}`, "append-prompt");
3216
- else await this.fill(composer, prompt, "write-prompt");
3217
-
3218
- // Do not validate the rendered composer text after writing. ChatGPT may
3219
- // normalize whitespace or insert capability pills (for example Web
3220
- // search), so a post-write text comparison can reject a successful write
3221
- // and leave the request in an ambiguous state. The pre-write draft guard
3222
- // above still protects user-owned text from accidental replacement.
3223
- const value = await this.composerText(composer).catch(() => "");
3224
- return {
3225
- written: true,
3226
- verificationSkipped: true,
3227
- characters: value.length,
3228
- preview: value.slice(0, 300),
3229
- };
3230
- }
3231
-
3232
- async webSearchState() {
3233
- const composer = await this.composer();
3234
- const hint = composer.locator(SELECTORS.webSearchHints.join(", ")).first();
3235
- const selected =
3236
- (await hint.count()) > 0 && (await hint.isVisible().catch(() => false));
3237
- return {
3238
- selected,
3239
- label: selected
3240
- ? (await hint.innerText().catch(() => "")).replace(/\s+/g, " ").trim() || null
3241
- : null,
3242
- };
3243
- }
3244
-
3245
- async waitForWebSearchSelection({ timeoutMs = 2_000, pollMs = 50 } = {}) {
3246
- const page = await this.page();
3247
- const deadline = Date.now() + timeoutMs;
3248
- let state = await this.webSearchState();
3249
- while (!state.selected && Date.now() < deadline) {
3250
- await page.waitForTimeout(Math.min(pollMs, Math.max(1, deadline - Date.now())));
3251
- state = await this.webSearchState();
3252
- }
3253
- return state;
3254
- }
3255
-
3256
- async enableWebSearch() {
3257
- await this.ensureSignedIn();
3258
- const current = await this.webSearchState();
3259
- if (current.selected) return { ...current, changed: false };
3260
-
3261
- const page = await this.page();
3262
- const menuButton = await this.firstVisible(SELECTORS.attachmentButton, { timeout: 1_500 });
3263
- if (!menuButton) {
3264
- throw new ChatGPTWebError("没有找到 ChatGPT 输入框的能力菜单。", {
3265
- url: page.url(),
3266
- });
3267
- }
3268
- await this.click(menuButton, "open-composer-menu-for-web-search");
3269
- await page.waitForTimeout(250);
3270
-
3271
- let item = null;
3272
- for (const label of ["Web search", "网页搜索"]) {
3273
- // The page can already contain a Web search pill in an older assistant
3274
- // message. Selecting the first text match therefore clicks stale
3275
- // content instead of the newly opened composer menu. Current ChatGPT
3276
- // menu entries expose `data-fill` and `tabindex=0`; prefer those and
3277
- // keep role/class fallbacks for older layouts.
3278
- const selectors = [
3279
- "[data-fill][tabindex='0']",
3280
- ".group.__menu-item[tabindex='0']",
3281
- "[role='menuitem'], [role='menuitemradio'], [role='option']",
3282
- ];
3283
- for (const selector of selectors) {
3284
- const matches = page.locator(selector).filter({ hasText: label });
3285
- for (let index = 0; index < (await matches.count()); index += 1) {
3286
- const candidate = matches.nth(index);
3287
- if (!(await candidate.isVisible().catch(() => false))) continue;
3288
- const isComposerPill = await candidate
3289
- .evaluate((element) => Boolean(element.closest("[contenteditable='true']")))
3290
- .catch(() => false);
3291
- if (isComposerPill) continue;
3292
- item = candidate;
3293
- break;
3294
- }
3295
- if (item) break;
3296
- }
3297
- if (item) break;
3298
- }
3299
- if (!item) {
3300
- await this.keyboardPress(page, "Escape", "close-composer-menu").catch(() => {});
3301
- throw new ChatGPTWebError(
3302
- "当前账号、工作区或页面版本没有显示“网页搜索”能力。",
3303
- { url: page.url() },
3304
- );
3305
- }
3306
-
3307
- const interactive = item.locator(
3308
- "xpath=ancestor-or-self::*[self::button or @role='button' or @role='menuitem' or @role='menuitemradio' or @tabindex][1]",
3309
- );
3310
- await this.domClick((await interactive.count()) > 0 ? interactive : item, "enable-web-search");
3311
- await page.waitForTimeout(250);
3312
-
3313
- // The composer inserts the inline selection pill asynchronously. A fixed
3314
- // 250 ms sleep races the UI on slower pages and reported a false failure
3315
- // even though the click had succeeded.
3316
- const verified = await this.waitForWebSearchSelection();
3317
- if (!verified.selected) {
3318
- throw new ChatGPTWebError("已点击“网页搜索”,但输入框未出现选中标记。", {
3319
- url: page.url(),
3320
- });
3321
- }
3322
- return { ...verified, changed: true };
3323
- }
3324
-
3325
- async validateFiles(files) {
3326
- if (!files?.length) return [];
3327
- const result = [];
3328
- for (const file of files) {
3329
- const resolved = path.resolve(file);
3330
- let stat;
3331
- try {
3332
- stat = await fs.stat(resolved);
3333
- } catch {
3334
- throw new ChatGPTWebError("待上传文件不存在。", { file: resolved });
3335
- }
3336
- if (!stat.isFile()) {
3337
- throw new ChatGPTWebError("只能上传普通文件,不能上传目录。", { file: resolved });
3338
- }
3339
- result.push({ path: resolved, name: path.basename(resolved), size: stat.size });
3340
- }
3341
- return result;
3342
- }
3343
-
3344
- async uploadFiles(files) {
3345
- await this.ensureSignedIn();
3346
- const page = await this.page();
3347
- const validated = await this.validateFiles(files);
3348
- if (!validated.length) return { uploaded: [] };
3349
- const paths = validated.map((file) => file.path);
3350
- await this.siteAction("upload-files");
3351
-
3352
- let input = null;
3353
- for (const selector of SELECTORS.fileInput) {
3354
- const locator = page.locator(selector).last();
3355
- if ((await locator.count()) > 0) {
3356
- input = locator;
3357
- break;
3358
- }
3359
- }
3360
-
3361
- if (input) {
3362
- await this.pageInteraction("set-upload-files");
3363
- await input.setInputFiles(paths);
3364
- } else {
3365
- const attach = await this.firstVisible(SELECTORS.attachmentButton, { timeout: 800 });
3366
- if (!attach) throw new ChatGPTWebError("没有找到 ChatGPT 的文件上传控件。");
3367
- let chooserPromise = page.waitForEvent("filechooser", { timeout: 1_200 }).catch(() => null);
3368
- await this.click(attach, "open-attachment-menu");
3369
- let chooser = await chooserPromise;
3370
- if (!chooser) {
3371
- const uploadItem = await this.firstVisible(SELECTORS.uploadMenuItems, { timeout: 1_500 });
3372
- if (!uploadItem) {
3373
- throw new ChatGPTWebError("附件菜单已打开,但没有找到“添加照片和文件”选项。");
3374
- }
3375
- chooserPromise = page
3376
- .waitForEvent("filechooser", { timeout: ACTION_TIMEOUT_MS })
3377
- .catch(() => null);
3378
- await this.click(uploadItem, "select-upload-files");
3379
- chooser = await chooserPromise;
3380
- }
3381
- if (!chooser) throw new ChatGPTWebError("已点击上传入口,但网页没有打开文件选择器。");
3382
- await this.pageInteraction("confirm-upload-files");
3383
- await chooser.setFiles(paths);
3384
- }
3385
-
3386
- for (const file of validated) {
3387
- const filename = page.getByText(file.name, { exact: false }).last();
3388
- await filename.waitFor({ state: "visible", timeout: ACTION_TIMEOUT_MS }).catch(() => {});
3389
- }
3390
-
3391
- const send = await this.firstVisible(SELECTORS.sendButton, { timeout: 500 });
3392
- return {
3393
- uploaded: validated,
3394
- composerReady: Boolean(await this.composer()),
3395
- sendEnabled: send ? await send.isEnabled().catch(() => null) : null,
3396
- };
3397
- }
3398
-
3399
- /**
3400
- * Return the message nodes that represent one message each. New ChatGPT
3401
- * layouts put a role node inside a section wrapper; SELECTORS excludes such
3402
- * wrappers, so this remains compatible with older section-only layouts.
3403
- */
3404
- async renderedConversationMessages() {
3405
- const page = await this.page();
3406
- const selector = [
3407
- ...SELECTORS.userMessages,
3408
- ...SELECTORS.assistantMessages,
3409
- ].join(", ");
3410
- return page.locator(selector).evaluateAll((elements) =>
3411
- elements.map((element, index) => ({
3412
- index,
3413
- author:
3414
- element.getAttribute("data-message-author-role") ||
3415
- element.getAttribute("data-turn") ||
3416
- null,
3417
- id:
3418
- element.getAttribute("data-message-id") ||
3419
- element.getAttribute("data-testid") ||
3420
- element.id ||
3421
- null,
3422
- text: element.innerText || element.textContent || "",
3423
- })),
3424
- );
3425
- }
3426
-
3427
- async conversationApiTranscript() {
3428
- const page = await this.page();
3429
- const currentUrl = typeof page.url === "function" ? page.url() : "";
3430
- if (!this.#context || typeof page.evaluate !== "function") {
3431
- return { available: false, messages: [], error: "page-evaluate-unavailable" };
3432
- }
3433
- const conversationId = conversationIdFromUrl(currentUrl);
3434
- if (!conversationId) return { available: false, messages: [], error: "no-conversation-id" };
3435
- // Only reuse headers already observed from the user's current page.
3436
- // Do not open an extra conversation page just to prime an API request.
3437
- if (!this.#apiHeaders.authorization) {
3438
- return { available: false, messages: [], error: "api-headers-unavailable" };
3439
- }
3440
- await this.siteAction("read-history-api");
3441
- const cookieHeader = (await this.#context.cookies("https://chatgpt.com").catch(() => []))
3442
- .map((cookie) => `${cookie.name}=${cookie.value}`)
3443
- .join("; ");
3444
- const endpoint = `${CHATGPT_URL.replace(/\/$/u, "")}/backend-api/conversations/${encodeURIComponent(conversationId)}?include_has_versions=true&num_turns=100`;
3445
- const requestApi = () =>
3446
- fetch(endpoint, {
3447
- headers: {
3448
- ...this.#apiHeaders,
3449
- accept: "application/json",
3450
- ...(cookieHeader ? { cookie: cookieHeader } : {}),
3451
- referer: currentUrl,
3452
- "x-openai-target-path": `/backend-api/conversations/${conversationId}`,
3453
- "x-openai-target-route": "/backend-api/conversations/{conversation_id}",
3454
- },
3455
- }).catch((error) => ({ ok: false, status: 0, error: String(error?.message || error) }));
3456
- const response = await requestApi();
3457
- const responseBody = response.ok ? await response.json().catch(() => null) : null;
3458
- if (!response.ok || !responseBody) {
3459
- return {
3460
- available: false,
3461
- messages: [],
3462
- status: response.status || null,
3463
- error: response.error || `http-${response.status || "unknown"}`,
3464
- };
3465
- }
3466
- return {
3467
- available: true,
3468
- messages: parseConversationApiTranscript(responseBody),
3469
- status: response.status,
3470
- };
3471
- }
3472
-
3473
- async transcriptScrollMetrics() {
3474
- const page = await this.page();
3475
- return page.evaluate(() => {
3476
- const anchor =
3477
- document.querySelector("[data-message-author-role]") ||
3478
- document.querySelector("section[data-turn], article[data-turn]");
3479
- let element = anchor;
3480
- while (element) {
3481
- const style = getComputedStyle(element);
3482
- if (
3483
- (style.overflowY === "auto" || style.overflowY === "scroll") &&
3484
- element.scrollHeight > element.clientHeight
3485
- ) {
3486
- return {
3487
- available: true,
3488
- top: element.scrollTop,
3489
- scrollHeight: element.scrollHeight,
3490
- clientHeight: element.clientHeight,
3491
- };
3492
- }
3493
- element = element.parentElement;
3494
- }
3495
- const fallback = document.scrollingElement;
3496
- return {
3497
- available: Boolean(fallback && fallback.scrollHeight > fallback.clientHeight),
3498
- top: fallback?.scrollTop || 0,
3499
- scrollHeight: fallback?.scrollHeight || 0,
3500
- clientHeight: fallback?.clientHeight || 0,
3501
- };
3502
- });
3503
- }
3504
-
3505
- async scrollTranscriptToTop() {
3506
- const page = await this.page();
3507
- return page.evaluate(() => {
3508
- const anchor =
3509
- document.querySelector("[data-message-author-role]") ||
3510
- document.querySelector("section[data-turn], article[data-turn]");
3511
- let element = anchor;
3512
- while (element) {
3513
- const style = getComputedStyle(element);
3514
- if (
3515
- (style.overflowY === "auto" || style.overflowY === "scroll") &&
3516
- element.scrollHeight > element.clientHeight
3517
- ) {
3518
- element.scrollTop = 0;
3519
- element.dispatchEvent(new Event("scroll", { bubbles: true }));
3520
- return true;
3521
- }
3522
- element = element.parentElement;
3523
- }
3524
- if (document.scrollingElement) {
3525
- document.scrollingElement.scrollTop = 0;
3526
- window.scrollTo(0, 0);
3527
- return true;
3528
- }
3529
- return false;
3530
- });
3531
- }
3532
-
3533
- async restoreTranscriptScroll(top) {
3534
- const page = await this.page();
3535
- await page.evaluate((desiredTop) => {
3536
- const anchor =
3537
- document.querySelector("[data-message-author-role]") ||
3538
- document.querySelector("section[data-turn], article[data-turn]");
3539
- let element = anchor;
3540
- while (element) {
3541
- const style = getComputedStyle(element);
3542
- if (
3543
- (style.overflowY === "auto" || style.overflowY === "scroll") &&
3544
- element.scrollHeight > element.clientHeight
3545
- ) {
3546
- element.scrollTop = Math.max(
3547
- 0,
3548
- Math.min(Number(desiredTop) || 0, element.scrollHeight - element.clientHeight),
3549
- );
3550
- return;
3551
- }
3552
- element = element.parentElement;
3553
- }
3554
- window.scrollTo(0, Number(desiredTop) || 0);
3555
- }, top);
3556
- }
3557
-
3558
- /**
3559
- * ChatGPT virtualizes long conversations and loads older turns when the
3560
- * transcript scroller reaches its top. Count/archival code must therefore
3561
- * walk to the top and retain every message observed, instead of trusting
3562
- * the shallow DOM snapshot at the current viewport.
3563
- */
3564
- async loadCompleteTranscript({ maxPasses = 40, waitMs = 450, restoreScroll = true } = {}) {
3565
- const apiTranscript = await this.conversationApiTranscript();
3566
- if (apiTranscript.available) {
3567
- return {
3568
- messages: apiTranscript.messages,
3569
- messageCount: apiTranscript.messages.length,
3570
- userMessageCount: apiTranscript.messages.filter((message) => message.author === "user").length,
3571
- assistantMessageCount: apiTranscript.messages.filter((message) => message.author === "assistant").length,
3572
- passes: 0,
3573
- complete: true,
3574
- source: "conversation-api",
3575
- initialScrollTop: null,
3576
- };
3577
- }
3578
- const initial = await this.transcriptScrollMetrics();
3579
- const initialTop = initial.top;
3580
- const messagesByKey = new Map();
3581
- let orderedKeys = [];
3582
- let passes = 0;
3583
- let stablePasses = 0;
3584
- let complete = !initial.available;
3585
-
3586
- const collect = async () => {
3587
- const entries = await this.renderedConversationMessages();
3588
- const currentKeys = [];
3589
- for (const entry of entries) {
3590
- if (entry.author !== "user" && entry.author !== "assistant") continue;
3591
- const text = String(entry.text || "");
3592
- const key = entry.id
3593
- ? `${entry.author}:id:${entry.id}`
3594
- : `${entry.author}:text:${normalize(text).slice(0, 2_000)}`;
3595
- currentKeys.push(key);
3596
- messagesByKey.set(key, {
3597
- author: entry.author,
3598
- id: entry.id,
3599
- text,
3600
- });
3601
- }
3602
- const currentSet = new Set(currentKeys);
3603
- orderedKeys = [
3604
- ...currentKeys,
3605
- ...orderedKeys.filter((key) => !currentSet.has(key)),
3606
- ];
3607
- return {
3608
- count: messagesByKey.size,
3609
- currentCount: currentKeys.length,
3610
- };
3611
- };
3612
-
3613
- await collect();
3614
- const safePasses = Math.max(1, Math.min(Number(maxPasses) || 40, 120));
3615
- const safeWaitMs = Math.max(100, Math.min(Number(waitMs) || 450, 2_000));
3616
- while (!complete && passes < safePasses) {
3617
- const beforeCount = messagesByKey.size;
3618
- await this.scrollTranscriptToTop();
3619
- await (await this.page()).waitForTimeout(safeWaitMs);
3620
- passes += 1;
3621
- await collect();
3622
- const metrics = await this.transcriptScrollMetrics();
3623
- const added = messagesByKey.size > beforeCount;
3624
- if (added || metrics.top > 1) stablePasses = 0;
3625
- else stablePasses += 1;
3626
- if (!metrics.available || stablePasses >= 2) complete = true;
3627
- }
3628
-
3629
- if (restoreScroll && initial.available) {
3630
- await this.restoreTranscriptScroll(initialTop);
3631
- }
3632
- const messages = orderedKeys
3633
- .map((key) => messagesByKey.get(key))
3634
- .filter(Boolean);
3635
- return {
3636
- messages,
3637
- messageCount: messages.length,
3638
- userMessageCount: messages.filter((message) => message.author === "user").length,
3639
- assistantMessageCount: messages.filter((message) => message.author === "assistant").length,
3640
- passes,
3641
- complete,
3642
- source: "dom-scroll",
3643
- initialScrollTop: initialTop,
3644
- };
3645
- }
3646
-
3647
- assistantLocator() {
3648
- return this.#page
3649
- .locator(SELECTORS.assistantMessages.join(", "))
3650
- .filter({ hasNotText: THINKING_WRAPPER_RE });
3651
- }
3652
-
3653
- userLocator() {
3654
- return this.#page.locator(SELECTORS.userMessages.join(", "));
3655
- }
3656
-
3657
- async userMessageSnapshot() {
3658
- const users = this.userLocator();
3659
- const count = await users.count();
3660
- if (!count) return { count: 0, lastText: "", lastId: null };
3661
- const last = users.last();
3662
- const detail = await last.evaluate((element) => ({
3663
- text: element.innerText || element.textContent || "",
3664
- lastId:
3665
- element.getAttribute("data-message-id") ||
3666
- element.getAttribute("data-testid") ||
3667
- element.id ||
3668
- null,
3669
- }));
3670
- return { count, lastText: detail.text, lastId: detail.lastId };
3671
- }
3672
-
3673
- async conversationTurnStats() {
3674
- const page = await this.page();
3675
- const [transcript, body] = await Promise.all([
3676
- this.loadCompleteTranscript(),
3677
- page.locator("body").innerText().catch(() => ""),
3678
- ]);
3679
- const { userMessageCount, assistantMessageCount } = transcript;
3680
- const lengthLimitDetected = classifyConversationLengthText(body).limited;
3681
- const state = conversationTurnLimitState(
3682
- { userMessageCount, assistantMessageCount, lengthLimitDetected },
3683
- MAX_CONVERSATION_TURNS,
3684
- );
3685
- return {
3686
- ...state,
3687
- conversationId: conversationIdFromUrl(page.url()),
3688
- url: page.url(),
3689
- transcriptMessageCount: transcript.messageCount,
3690
- transcriptLoaded: transcript.complete,
3691
- transcriptLoadPasses: transcript.passes,
3692
- transcriptSource: transcript.source || "unknown",
3693
- };
3694
- }
3695
-
3696
- async archiveConversation({ reason = "conversation-limit", stats = null } = {}) {
3697
- const page = await this.page();
3698
- const conversationId = conversationIdFromUrl(page.url()) || "unknown";
3699
- const transcript = await this.loadCompleteTranscript({ restoreScroll: false });
3700
- const turns = [];
3701
- const roleCounts = { user: 0, assistant: 0 };
3702
- for (const message of transcript.messages) {
3703
- const text = message.text.trim();
3704
- if (!text || !(message.author in roleCounts)) continue;
3705
- roleCounts[message.author] += 1;
3706
- const label = message.author === "user" ? "User" : "Assistant";
3707
- turns.push(`## ${label} ${roleCounts[message.author]}\n\n${text}`);
3708
- }
3709
- const now = new Date();
3710
- const stamp = now.toISOString().replace(/[:.]/g, "-");
3711
- const safeConversationId = conversationId.replace(/[^a-zA-Z0-9_-]/g, "_");
3712
- const fileName = `${stamp}_${safeConversationId}.md`;
3713
- const outputPath = path.join(CONTEXT_ARCHIVE_DIR, fileName);
3714
- const metadata = stats || await this.conversationTurnStats();
3715
- const content = [
3716
- "# ChatGPT conversation archive",
3717
- "",
3718
- `- archived_at: ${now.toISOString()}`,
3719
- `- conversation_id: ${conversationId}`,
3720
- `- source_url: ${page.url()}`,
3721
- `- reason: ${reason}`,
3722
- `- turn_count: ${metadata.turnCount}`,
3723
- `- user_message_count: ${metadata.userMessageCount}`,
3724
- `- assistant_message_count: ${metadata.assistantMessageCount}`,
3725
- `- transcript_message_count: ${transcript.messageCount}`,
3726
- `- transcript_load_passes: ${transcript.passes}`,
3727
- `- transcript_source: ${transcript.source || "unknown"}`,
3728
- "",
3729
- ...turns,
3730
- turns.length ? "" : "(No complete transcript was available.)",
3731
- "",
3732
- ].join("\n");
3733
- await fs.mkdir(CONTEXT_ARCHIVE_DIR, { recursive: true });
3734
- const temporaryPath = `${outputPath}.${process.pid}.tmp`;
3735
- await fs.writeFile(temporaryPath, content, { mode: 0o600 });
3736
- await fs.rename(temporaryPath, outputPath);
3737
- return {
3738
- archived: true,
3739
- archivePath: outputPath,
3740
- conversationId,
3741
- turnCount: metadata.turnCount,
3742
- userMessageCount: metadata.userMessageCount,
3743
- assistantMessageCount: metadata.assistantMessageCount,
3744
- transcriptMessageCount: transcript.messageCount,
3745
- transcriptLoadPasses: transcript.passes,
3746
- };
3747
- }
3748
-
3749
- async ensureConversationCapacity({ allowRotate = false } = {}) {
3750
- const stats = await this.conversationTurnStats();
3751
- if (!stats.shouldRotate) return { rotated: false, stats };
3752
- if (!allowRotate) {
3753
- throw new ChatGPTWebError(
3754
- "当前对话已达到自动轮换阈值,发送已拦截;请先新建对话。",
3755
- {
3756
- conversationRotationRequired: true,
3757
- maxConversationTurns: stats.limit,
3758
- ...stats,
3759
- nextStep: "调用 chatgpt_new_chat 或 chatgpt_route_new_chat 后重新发送。",
3760
- },
3761
- );
3762
- }
3763
- const archive = await this.archiveConversation({
3764
- reason: stats.lengthLimitDetected ? "page-length-limit" : "turn-limit",
3765
- stats,
3766
- });
3767
- const previousConversationId = stats.conversationId;
3768
- const root = await this.newChat({ temporary: false }, { includeStatus: false });
3769
- return {
3770
- rotated: true,
3771
- previousConversationId,
3772
- previousUrl: stats.url,
3773
- archive,
3774
- newConversation: root,
3775
- stats,
3776
- };
3777
- }
3778
-
3779
- async submitPrompt({
3780
- wait = true,
3781
- timeoutMs = RESPONSE_TIMEOUT_MS,
3782
- refresh = true,
3783
- } = {}) {
3784
- const refreshResult = refresh
3785
- ? await this.refreshBeforeSend({ reason: "submit-prompt" })
3786
- : null;
3787
- await this.ensureSignedIn();
3788
- const page = await this.page();
3789
- // Direct write_prompt → submit_prompt callers must be stopped before a
3790
- // capped conversation can trigger the server-side banner. Atomic
3791
- // sendMessage performs the safe archive-and-rotate path instead.
3792
- const capacity = await this.ensureConversationCapacity({ allowRotate: false });
3793
- const composer = await this.composer();
3794
- if (!composer) throw new ChatGPTWebError("没有找到提示词输入框。");
3795
- await this.assertComposerWritable("submit-prompt", composer);
3796
- const promptText = await this.composerText(composer);
3797
- if (!normalize(promptText)) throw new ChatGPTWebError("输入框为空,无法发送。");
3798
-
3799
- const assistantBefore = await this.assistantLocator().count();
3800
- const assistantBeforeText = assistantBefore
3801
- ? await this.assistantLocator().last().innerText().catch(() => "")
3802
- : "";
3803
- const userBeforeSnapshot = await this.userMessageSnapshot();
3804
- const userBefore = userBeforeSnapshot.count;
3805
- await this.siteAction("send-prompt");
3806
- const send = await this.firstVisible(SELECTORS.sendButton, { timeout: 1_000 });
3807
- if (send && (await send.isEnabled().catch(() => true))) {
3808
- await this.domClick(send, "send-prompt-click");
3809
- } else {
3810
- await this.press(composer, "Enter", "send-prompt-enter");
3811
- }
3812
- await this.markSendPerformed();
3813
-
3814
- const generationStartedAt = Date.now();
3815
- await updateRuntimeState({
3816
- activeGeneration: {
3817
- active: true,
3818
- startedAt: generationStartedAt,
3819
- url: page.url(),
3820
- ownerPid: process.pid,
3821
- assistantBefore,
3822
- baselineResponse: assistantBeforeText,
3823
- status: wait ? "waiting" : "unobserved",
3824
- },
3825
- });
3826
-
3827
- await page.waitForFunction(
3828
- ({ selectors, count }) => {
3829
- const elements = document.querySelectorAll(selectors);
3830
- return elements.length > count;
3831
- },
3832
- { selectors: SELECTORS.userMessages.join(", "), count: userBefore },
3833
- { timeout: ACTION_TIMEOUT_MS },
3834
- ).catch(() => {});
3835
-
3836
- const userAfterSnapshot = await this.userMessageSnapshot();
3837
- const userMessageAppendVerified =
3838
- userAfterSnapshot.count > userBeforeSnapshot.count ||
3839
- (Boolean(userBeforeSnapshot.lastId) &&
3840
- Boolean(userAfterSnapshot.lastId) &&
3841
- userBeforeSnapshot.lastId !== userAfterSnapshot.lastId);
3842
- const sameTurn =
3843
- userBeforeSnapshot.count === userAfterSnapshot.count &&
3844
- userBeforeSnapshot.lastId &&
3845
- userBeforeSnapshot.lastId === userAfterSnapshot.lastId;
3846
- if (
3847
- sameTurn &&
3848
- normalize(userBeforeSnapshot.lastText) !== normalize(userAfterSnapshot.lastText) &&
3849
- normalize(userAfterSnapshot.lastText) === normalize(promptText)
3850
- ) {
3851
- throw new ChatGPTWebError(
3852
- "发送后未创建新的用户消息,检测到原用户消息内容被替换;已停止后续网页操作。",
3853
- {
3854
- overwriteDetected: true,
3855
- userMessageCount: userAfterSnapshot.count,
3856
- userMessageId: userAfterSnapshot.lastId,
3857
- previousCharacters: userBeforeSnapshot.lastText.length,
3858
- observedCharacters: userAfterSnapshot.lastText.length,
3859
- nextStep: "请人工恢复原消息后再继续;本工具不会自动重试或再次发送。",
3860
- },
3861
- );
3862
- }
3863
-
3864
- if (!wait) {
3865
- return {
3866
- sent: true,
3867
- waiting: false,
3868
- url: page.url(),
3869
- conversationId: conversationIdFromUrl(page.url()),
3870
- userMessageAppendVerified,
3871
- userMessageCountBefore: userBeforeSnapshot.count,
3872
- userMessageCountAfter: userAfterSnapshot.count,
3873
- pageRefreshedBeforeSend: Boolean(refreshResult),
3874
- };
3875
- }
3876
- const effectiveTimeoutMs =
3877
- isProModel(this.cachedSettings().model) || isProTier(this.#answerTier)
3878
- ? null
3879
- : timeoutMs;
3880
- try {
3881
- const result = await this.waitForResponse({
3882
- assistantBefore,
3883
- baselineResponse: assistantBeforeText,
3884
- timeoutMs: effectiveTimeoutMs,
3885
- conversationCapacity: capacity,
3886
- });
3887
- await updateRuntimeState({ activeGeneration: null, lastGenerationCompletedAt: Date.now() });
3888
- return {
3889
- ...result,
3890
- userMessageAppendVerified,
3891
- userMessageCountBefore: userBeforeSnapshot.count,
3892
- userMessageCountAfter: userAfterSnapshot.count,
3893
- pageRefreshedBeforeSend: Boolean(refreshResult),
3894
- };
3895
- } catch (error) {
3896
- if (this.signal()?.aborted) {
3897
- await updateRuntimeState({
3898
- activeGeneration: {
3899
- active: true,
3900
- startedAt: generationStartedAt,
3901
- url: page.url(),
3902
- ownerPid: null,
3903
- assistantBefore,
3904
- baselineResponse: assistantBeforeText,
3905
- status: "client-cancelled-generation-may-continue",
3906
- },
3907
- });
3908
- } else {
3909
- // A client-side timeout must not leave a completed/non-generating page
3910
- // permanently locked. Keep the lock only while the page still shows
3911
- // an active generation; getLatestResponse can then clear it once the
3912
- // final text is observable. This check does not fetch history.
3913
- const latest = await this.getLatestResponse({ includeTranscript: false }).catch(() => null);
3914
- if (latest && !latest.generating) {
3915
- await updateRuntimeState({
3916
- activeGeneration: null,
3917
- lastGenerationInterruptedAt: Date.now(),
3918
- });
3919
- }
3920
- }
3921
- throw error;
3922
- }
3923
- }
3924
-
3925
- async waitForResponse({
3926
- assistantBefore,
3927
- baselineResponse = "",
3928
- timeoutMs = RESPONSE_TIMEOUT_MS,
3929
- conversationCapacity = null,
3930
- } = {}) {
3931
- const page = await this.page();
3932
- const signal = this.signal();
3933
- throwIfAborted(signal);
3934
- const baseline =
3935
- assistantBefore ?? Math.max(0, (await this.assistantLocator().count()) - 1);
3936
- const unlimited = timeoutMs == null;
3937
- const observerPromise = page.evaluate(
3938
- ({ assistantSelectors, stopSelectors, baselineCount, baselineResponse, timeout }) =>
3939
- new Promise((resolve) => {
3940
- const visible = (element) => {
3941
- if (!(element instanceof HTMLElement)) return false;
3942
- const style = getComputedStyle(element);
3943
- const rect = element.getBoundingClientRect();
3944
- return rect.width > 0 && rect.height > 0 && style.visibility !== "hidden";
3945
- };
3946
- const read = () => {
3947
- const body = document.body?.innerText || "";
3948
- const rateLimited =
3949
- /请求过于频繁|too many requests|request.*too frequent/i.test(body) &&
3950
- /稍等|分钟|try again|wait/i.test(body);
3951
- const assistant = [...document.querySelectorAll(assistantSelectors)].filter(
3952
- (element) =>
3953
- !/^\s*(?:thinking|思考)(?:\s*(?:[.…::]|$))/iu.test(
3954
- element.innerText || element.textContent || "",
3955
- ),
3956
- );
3957
- const last = assistant.at(-1);
3958
- const response = (last?.innerText || last?.textContent || "").trim();
3959
- const stop = [...document.querySelectorAll(stopSelectors)].some(visible);
3960
- // Deep-research/web-search responses can expose a progress-only
3961
- // assistant node (for example "Planning …") without a stop
3962
- // button or the legacy streaming marker. Treat its shimmer as
3963
- // active generation; otherwise waitForResponse returns before
3964
- // the final answer is attached to the same assistant node.
3965
- const streaming = Boolean(
3966
- last?.querySelector(
3967
- "[data-is-streaming='true'], .result-streaming, [class*='loading-shimmer'], [data-testid*='thinking']",
3968
- ),
3969
- );
3970
- return { count: assistant.length, response, stop, streaming, rateLimited };
3971
- };
3972
- let stableText = "";
3973
- let stableSince = Date.now();
3974
- let stableTimer = null;
3975
- let timeoutTimer = null;
3976
- let observer = null;
3977
- let done = false;
3978
- const cleanup = () => {
3979
- observer?.disconnect();
3980
- clearTimeout(stableTimer);
3981
- clearTimeout(timeoutTimer);
3982
- window.removeEventListener("__chatgpt_mcp_network_rate_limit__", onNetworkLimit);
3983
- window.removeEventListener("__chatgpt_mcp_cancel_wait__", onCancel);
3984
- };
3985
- const finish = (value) => {
3986
- if (done) return;
3987
- done = true;
3988
- cleanup();
3989
- resolve(value);
3990
- };
3991
- const inspect = () => {
3992
- const state = read();
3993
- if (state.rateLimited) return finish({ status: "rate-limited", ...state });
3994
- if (state.response !== stableText) {
3995
- stableText = state.response;
3996
- stableSince = Date.now();
3997
- }
3998
- clearTimeout(stableTimer);
3999
- const hasNewResponse =
4000
- state.count > baselineCount ||
4001
- (Boolean(state.response) && state.response !== baselineResponse);
4002
- if (
4003
- hasNewResponse &&
4004
- state.response &&
4005
- !state.stop &&
4006
- !state.streaming
4007
- ) {
4008
- const remaining = Math.max(0, 2_000 - (Date.now() - stableSince));
4009
- stableTimer = setTimeout(() => {
4010
- const verified = read();
4011
- const verifiedHasNewResponse =
4012
- verified.count > baselineCount ||
4013
- (Boolean(verified.response) && verified.response !== baselineResponse);
4014
- if (
4015
- verifiedHasNewResponse &&
4016
- verified.response === stableText &&
4017
- !verified.stop &&
4018
- !verified.streaming
4019
- ) {
4020
- finish({ status: "completed", ...verified });
4021
- }
4022
- }, remaining);
4023
- }
4024
- };
4025
- const onNetworkLimit = (event) =>
4026
- finish({
4027
- status: "network-rate-limited",
4028
- networkScope: event?.detail?.scope || "http-429",
4029
- networkPath: event?.detail?.path || null,
4030
- ...read(),
4031
- });
4032
- const onCancel = () => finish({ status: "cancelled" });
4033
- window.addEventListener("__chatgpt_mcp_network_rate_limit__", onNetworkLimit);
4034
- window.addEventListener("__chatgpt_mcp_cancel_wait__", onCancel);
4035
- observer = new MutationObserver(inspect);
4036
- observer.observe(document.documentElement, {
4037
- childList: true,
4038
- subtree: true,
4039
- characterData: true,
4040
- attributes: true,
4041
- attributeFilter: ["data-is-streaming", "aria-label", "disabled"],
4042
- });
4043
- if (timeout != null) {
4044
- timeoutTimer = setTimeout(() => finish({ status: "timeout", ...read() }), timeout);
4045
- }
4046
- inspect();
4047
- }),
4048
- {
4049
- assistantSelectors: SELECTORS.assistantMessages.join(", "),
4050
- stopSelectors: SELECTORS.stopButton.join(", "),
4051
- baselineCount: baseline,
4052
- baselineResponse,
4053
- timeout: unlimited ? null : timeoutMs,
4054
- },
4055
- );
4056
- const observed = await raceWithAbort(observerPromise, signal, () =>
4057
- page.evaluate(() => {
4058
- window.dispatchEvent(new Event("__chatgpt_mcp_cancel_wait__"));
4059
- }),
4060
- );
4061
-
4062
- if (observed.status === "rate-limited" || observed.status === "network-rate-limited") {
4063
- const scope =
4064
- observed.status === "network-rate-limited"
4065
- ? observed.networkScope || "http-429"
4066
- : "unknown";
4067
- const circuitBreaker = await this.tripCircuitBreaker(scope, observed.status);
4068
- throw new ChatGPTWebError("检测到 ChatGPT 请求频率限制,已开启安全熔断。", {
4069
- scope,
4070
- path: observed.networkPath || null,
4071
- circuitBreaker,
4072
- url: page.url(),
4073
- });
4074
- }
4075
- if (observed.status === "timeout") {
4076
- throw new ChatGPTWebError("等待 ChatGPT 完成回答超时。", {
4077
- timeoutMs,
4078
- partialResponse: observed.response,
4079
- url: page.url(),
4080
- });
4081
- }
4082
- const lengthLimit = classifyConversationLengthText(observed.response);
4083
- if (lengthLimit.limited) {
4084
- throw new ChatGPTWebError(
4085
- "ChatGPT 拒绝了本次发送:当前对话已达到长度上限。",
4086
- {
4087
- conversationRotationRequired: true,
4088
- maxConversationTurns: MAX_CONVERSATION_TURNS,
4089
- conversationId: conversationIdFromUrl(page.url()),
4090
- response: observed.response,
4091
- nextStep: "调用 chatgpt_new_chat 或 chatgpt_route_new_chat 后重新发送。",
4092
- },
4093
- );
4094
- }
4095
- return {
4096
- sent: true,
4097
- completed: true,
4098
- response: observed.response,
4099
- url: page.url(),
4100
- conversationId: conversationIdFromUrl(page.url()),
4101
- model: this.cachedSettings().model,
4102
- thinkingLevel: this.cachedSettings().thinkingLevel,
4103
- answerTier: this.#answerTier,
4104
- mode: await this.currentMode(),
4105
- temporary: await this.temporaryState(),
4106
- waitPolicy: unlimited ? "unlimited-for-pro" : `timeout-${timeoutMs}ms`,
4107
- waitMechanism: "mutation-observer",
4108
- rateLimited: false,
4109
- rateLimitScope: null,
4110
- conversationCapacity,
4111
- };
4112
- }
4113
-
4114
- async sendMessage({
4115
- prompt,
4116
- files = [],
4117
- webSearch = false,
4118
- model,
4119
- mode,
4120
- thinkingLevel,
4121
- answerTier,
4122
- newChat = false,
4123
- temporary = false,
4124
- wait = true,
4125
- timeoutMs = RESPONSE_TIMEOUT_MS,
4126
- }) {
4127
- let rotation = null;
4128
- if (newChat || temporary) {
4129
- await this.newChat(
4130
- { temporary, model, mode, thinkingLevel, answerTier },
4131
- { includeStatus: false },
4132
- );
4133
- } else {
4134
- rotation = await this.ensureConversationCapacity({ allowRotate: true });
4135
- // An archived historical thread has no composer or settings trigger.
4136
- // Restore it before applying optional settings so a requested
4137
- // thinkingLevel/high tier does not fail with a misleading missing
4138
- // control error.
4139
- await this.unarchiveConversationIfNeeded();
4140
- if (mode) await this.selectMode(mode);
4141
- if (model) await this.selectModel(model);
4142
- if (thinkingLevel) await this.selectThinkingLevel(thinkingLevel);
4143
- if (answerTier) await this.selectAnswerTier(answerTier);
4144
- }
4145
- // Refresh after conversation/settings changes and before any upload or
4146
- // composer mutation. This prevents a stale page tree from targeting an
4147
- // existing user turn while keeping attachments intact.
4148
- const refreshResult = await this.refreshBeforeSend({ reason: "send-message" });
4149
- if (files.length) await this.uploadFiles(files);
4150
- await this.writePrompt(prompt);
4151
- const search = webSearch ? await this.enableWebSearch() : { selected: false };
4152
- const effectiveTimeoutMs =
4153
- isProModel(model) || isProTier(answerTier) || isProTier(this.#answerTier)
4154
- ? null
4155
- : timeoutMs;
4156
- const result = await this.submitPrompt({
4157
- wait,
4158
- timeoutMs: effectiveTimeoutMs,
4159
- refresh: false,
4160
- });
4161
- return {
4162
- ...result,
4163
- webSearch: search,
4164
- pageRefreshedBeforeSend: refreshResult.refreshed,
4165
- conversationRotation: rotation,
4166
- };
4167
- }
4168
-
4169
- assertProbeEnabled() {
4170
- if (!PROBE_ENABLED) {
4171
- throw new ChatGPTWebError("临时 Pro 身份探针默认停用;未打开临时对话,也未发送测试消息。", {
4172
- probeEnabled: false,
4173
- configuration: "CHATGPT_WEB_PROBE_ENABLED=false",
4174
- nextStep: "使用 requestPro=false 的普通极高路由;仅在明确需要实验性身份探针时手动启用该配置。",
4175
- });
4176
- }
4177
- }
4178
-
4179
- async probeProIdentity({ mode, force = false } = {}) {
4180
- this.assertProbeEnabled();
4181
- if (!force) {
4182
- const runtime = await readRuntimeState();
4183
- const session = await browserSessionSnapshot();
4184
- const cached = validProbeCache(runtime.proProbe, { mode, session });
4185
- if (cached) {
4186
- if (cached !== runtime.proProbe) {
4187
- await updateRuntimeState({ proProbe: cached });
4188
- }
4189
- return {
4190
- prompt: PROBE_PROMPT,
4191
- modelSlug: cached.modelSlug || null,
4192
- modelSlugSource: cached.modelSlug ? "conversation-response" : null,
4193
- classification: cached.classification,
4194
- temporary: true,
4195
- answerTier: cached.answerTier || null,
4196
- url: cached.url || null,
4197
- waitPolicy: "cached-probe",
4198
- cachePolicy: cached.sessionInterruptedAt
4199
- ? "closed-page-grace"
4200
- : "same-page-session",
4201
- cached: true,
4202
- checkedAt: cached.checkedAt,
4203
- expiresAt: cached.expiresAt || null,
4204
- recheckAfter: cached.recheckAfter || null,
4205
- rateLimited: false,
4206
- rateLimitScope: null,
4207
- };
4208
- }
4209
- }
4210
-
4211
- // The visible Pro tier may be unavailable even when the backend serves a
4212
- // valid non-mini model. Identity is determined by model_slug, so probe the
4213
- // temporary chat at the currently available tier instead of failing early
4214
- // while trying to select an unavailable UI option.
4215
- await this.newChat({ temporary: true, mode }, { includeStatus: false });
4216
- const refreshResult = await this.refreshBeforeSend({ reason: "probe-pro-identity" });
4217
- await this.writePrompt(PROBE_PROMPT);
4218
- const captured = await this.captureConversationModelSlug(() =>
4219
- this.submitPrompt({ wait: true, timeoutMs: null, refresh: false }),
4220
- );
4221
- const result = captured.result;
4222
- const modelSlug = captured.modelSlug;
4223
- const probe = {
4224
- prompt: PROBE_PROMPT,
4225
- modelSlug,
4226
- modelSlugSource: modelSlug ? "conversation-response" : null,
4227
- modelSlugs: captured.modelSlugs,
4228
- classification: classifyProbeModel(result.response, {
4229
- networkModelSlug: modelSlug,
4230
- requireNetworkModelSlug: true,
4231
- }),
4232
- temporary: result.temporary,
4233
- answerTier: result.answerTier,
4234
- url: result.url,
4235
- waitPolicy: result.waitPolicy,
4236
- cached: false,
4237
- rateLimited: result.rateLimited,
4238
- rateLimitScope: result.rateLimitScope,
4239
- pageRefreshedBeforeSend: refreshResult.refreshed,
4240
- };
4241
- if (probe.classification !== "unknown") {
4242
- const checkedAt = Date.now();
4243
- const session = await browserSessionSnapshot();
4244
- const continuousPageSession =
4245
- session.browserRunning && session.chatgptPageOpen;
4246
- const cachedProbe = {
4247
- modelSlug: probe.modelSlug,
4248
- modelSlugSource: probe.modelSlugSource,
4249
- classification: probe.classification,
4250
- answerTier: probe.answerTier || null,
4251
- policyKey: PROBE_POLICY_KEY,
4252
- mode: mode || null,
4253
- url: probe.url,
4254
- checkedAt,
4255
- browserSessionId: continuousPageSession
4256
- ? session.browserSessionId
4257
- : null,
4258
- chatgptPageId: continuousPageSession ? session.chatgptPageId : null,
4259
- sessionInterruptedAt: continuousPageSession ? null : checkedAt,
4260
- recheckAfter: continuousPageSession
4261
- ? null
4262
- : checkedAt + PRO_PROBE_RECHECK_AFTER_CLOSE_MS,
4263
- expiresAt: continuousPageSession
4264
- ? null
4265
- : checkedAt + PRO_PROBE_RECHECK_AFTER_CLOSE_MS,
4266
- };
4267
- await updateRuntimeState({ proProbe: cachedProbe });
4268
- probe.checkedAt = cachedProbe.checkedAt;
4269
- probe.expiresAt = cachedProbe.expiresAt;
4270
- probe.recheckAfter = cachedProbe.recheckAfter;
4271
- probe.cachePolicy = continuousPageSession
4272
- ? "same-page-session"
4273
- : "closed-page-grace";
4274
- }
4275
- return probe;
4276
- }
4277
-
4278
- async routeNewChat({
4279
- prompt,
4280
- files = [],
4281
- webSearch = false,
4282
- requestPro = false,
4283
- forceProbe = false,
4284
- mode,
4285
- wait = true,
4286
- timeoutMs = RESPONSE_TIMEOUT_MS,
4287
- }) {
4288
- if (requestPro) this.assertProbeEnabled();
4289
- if (!requestPro) {
4290
- const newConversation = await this.newChat({ temporary: false, mode }, { includeStatus: false });
4291
- const tier = await this.selectExtremeTier(DEFAULT_ANSWER_TIER);
4292
- const refreshResult = await this.refreshBeforeSend({ reason: "route-new-chat" });
4293
- if (files.length) await this.uploadFiles(files);
4294
- await this.writePrompt(prompt);
4295
- const search = webSearch ? await this.enableWebSearch() : { selected: false };
4296
- const result = await this.submitPrompt({ wait, timeoutMs, refresh: false });
4297
- return {
4298
- route: "default-extreme",
4299
- ...(newConversation.newChatRefresh
4300
- ? { newChatRefresh: newConversation.newChatRefresh }
4301
- : {}),
4302
- probe: null,
4303
- finalConversation: { tier: DEFAULT_ANSWER_TIER, temporary: false },
4304
- tier,
4305
- result: {
4306
- ...result,
4307
- webSearch: search,
4308
- pageRefreshedBeforeSend: refreshResult.refreshed,
4309
- },
4310
- };
4311
- }
4312
-
4313
- const probe = await this.probeProIdentity({ mode, force: forceProbe });
4314
- const classification = probe.classification;
4315
-
4316
- if (classification === "unknown") {
4317
- throw new ChatGPTWebError(
4318
- "Pro 临时探针的回答不符合已配置的接受或回退规则;未创建正常对话。",
4319
- {
4320
- modelSlug: probe.modelSlug,
4321
- modelSlugSource: probe.modelSlugSource,
4322
- acceptedClassification: PROBE_ACCEPT_CLASSIFICATION,
4323
- fallbackClassification: PROBE_FALLBACK_CLASSIFICATION,
4324
- networkAcceptedClassification: PROBE_NETWORK_ACCEPT_CLASSIFICATION,
4325
- temporary: true,
4326
- },
4327
- );
4328
- }
4329
-
4330
- await this.newChat({ temporary: false, mode }, { includeStatus: false });
4331
- let finalTier;
4332
- let route;
4333
- const networkVerified = classification === PROBE_NETWORK_ACCEPT_CLASSIFICATION;
4334
- if (classification === PROBE_ACCEPT_CLASSIFICATION) {
4335
- finalTier = await this.selectAnswerTier(PRO_ANSWER_TIER);
4336
- route = `verified-${classification}`;
4337
- } else if (networkVerified) {
4338
- finalTier = await this.selectExtremeTier(DEFAULT_ANSWER_TIER);
4339
- route = `verified-${classification}-to-default`;
4340
- } else {
4341
- finalTier = await this.selectExtremeTier(DEFAULT_ANSWER_TIER);
4342
- route = `fallback-${classification}-to-default`;
4343
- }
4344
- const refreshResult = await this.refreshBeforeSend({ reason: "route-new-chat" });
4345
- if (files.length) await this.uploadFiles(files);
4346
- await this.writePrompt(prompt);
4347
- const search = webSearch ? await this.enableWebSearch() : { selected: false };
4348
- const result = await this.submitPrompt({
4349
- wait,
4350
- timeoutMs: classification === PROBE_ACCEPT_CLASSIFICATION ? null : timeoutMs,
4351
- refresh: false,
4352
- });
4353
- return {
4354
- route,
4355
- probe: {
4356
- prompt: probe.prompt,
4357
- modelSlug: probe.modelSlug,
4358
- modelSlugSource: probe.modelSlugSource,
4359
- classification,
4360
- temporary: probe.temporary,
4361
- cached: probe.cached,
4362
- checkedAt: probe.checkedAt,
4363
- expiresAt: probe.expiresAt,
4364
- recheckAfter: probe.recheckAfter,
4365
- cachePolicy: probe.cachePolicy,
4366
- rateLimited: probe.rateLimited,
4367
- rateLimitScope: probe.rateLimitScope,
4368
- },
4369
- finalConversation: {
4370
- tier:
4371
- classification === PROBE_ACCEPT_CLASSIFICATION
4372
- ? PRO_ANSWER_TIER
4373
- : DEFAULT_ANSWER_TIER,
4374
- temporary: false,
4375
- },
4376
- tier: finalTier,
4377
- result: {
4378
- ...result,
4379
- webSearch: search,
4380
- pageRefreshedBeforeSend: refreshResult.refreshed,
4381
- },
4382
- };
4383
- }
4384
-
4385
- async historyLinks() {
4386
- const page = await this.page();
4387
- const locator = page.locator(SELECTORS.historyLinks.join(", "));
4388
- const items = await locator.evaluateAll((elements) =>
4389
- elements.map((element) => ({
4390
- href: element.getAttribute("href") || "",
4391
- title:
4392
- (element.innerText || element.textContent || "").replace(/\s+/g, " ").trim() ||
4393
- element.getAttribute("title") ||
4394
- element.getAttribute("aria-label") ||
4395
- "",
4396
- })),
4397
- );
4398
- return uniqueBy(
4399
- items
4400
- .filter((item) => /^\/c\//.test(item.href))
4401
- .map((item) => ({
4402
- id: conversationIdFromUrl(item.href),
4403
- title: item.title,
4404
- url: absoluteChatUrl(item.href),
4405
- })),
4406
- (item) => item.id,
4407
- );
4408
- }
4409
-
4410
- async listHistory({ query, limit = 20 } = {}) {
4411
- await this.ensureSignedIn();
4412
- const safeLimit = Math.max(1, Math.min(Number(limit) || 20, MAX_HISTORY_RESULTS));
4413
- let conversations = await this.historyLinks();
4414
-
4415
- if (query) {
4416
- const matches = rankTextMatch(conversations, query, (item) => item.title);
4417
- conversations = matches.map((entry) => entry.item);
4418
- }
4419
- return {
4420
- conversations: conversations.slice(0, safeLimit),
4421
- returned: Math.min(conversations.length, safeLimit),
4422
- note:
4423
- conversations.length === 0
4424
- ? "当前侧栏没有匹配项。可以使用 conversationId 或完整 /c/... URL 精确打开历史对话。"
4425
- : undefined,
4426
- };
4427
- }
4428
-
4429
- async searchHistory({ query, limit = 20 } = {}) {
4430
- await this.ensureSignedIn();
4431
- const page = await this.page();
4432
- const safeLimit = Math.max(1, Math.min(Number(limit) || 20, MAX_HISTORY_RESULTS));
4433
- const searchButton = await this.firstVisible(SELECTORS.historySearchButtons, {
4434
- timeout: 1_000,
4435
- });
4436
-
4437
- if (!searchButton) {
4438
- // Some layouts hide search until the sidebar is expanded.
4439
- const openSidebar = page.locator("button[aria-label='Open sidebar'], button[aria-label='打开边栏']").first();
4440
- if (await openSidebar.isVisible().catch(() => false)) {
4441
- await this.siteAction("open-history-sidebar");
4442
- await this.click(openSidebar, "open-history-sidebar-click");
4443
- await page.waitForTimeout(300);
4444
- }
4445
- }
4446
-
4447
- const resolvedButton =
4448
- searchButton ||
4449
- (await this.firstVisible(SELECTORS.historySearchButtons, { timeout: 1_000 }));
4450
- if (!resolvedButton) {
4451
- throw new ChatGPTWebError("没有找到 ChatGPT 的“搜索聊天”控件。", { url: page.url() });
4452
- }
4453
- await this.siteAction("open-history-search");
4454
- await this.click(resolvedButton, "open-history-search-click");
4455
- try {
4456
- const input = await this.firstVisible(SELECTORS.historySearchInputs, { timeout: 2_000 });
4457
- if (!input) throw new ChatGPTWebError("搜索聊天窗口已打开,但没有找到搜索输入框。");
4458
- await this.siteAction("search-history");
4459
- await this.fill(input, query, "fill-history-search");
4460
- await page.waitForTimeout(800);
4461
-
4462
- const links = page.locator(
4463
- "[role='dialog'] a[href^='/c/'], [role='dialog'] [data-href^='/c/'], a[href^='/c/']:visible",
4464
- );
4465
- const raw = await links.evaluateAll((elements) =>
4466
- elements.map((element) => ({
4467
- href: element.getAttribute("href") || element.getAttribute("data-href") || "",
4468
- title:
4469
- (element.innerText || element.textContent || "").replace(/\s+/g, " ").trim() ||
4470
- element.getAttribute("title") ||
4471
- element.getAttribute("aria-label") ||
4472
- "",
4473
- })),
4474
- );
4475
- const conversations = uniqueBy(
4476
- raw
4477
- .filter((item) => /^\/c\//.test(item.href))
4478
- .map((item) => ({
4479
- id: conversationIdFromUrl(item.href),
4480
- title: item.title,
4481
- url: absoluteChatUrl(item.href),
4482
- })),
4483
- (item) => item.id,
4484
- ).slice(0, safeLimit);
4485
-
4486
- return { query, conversations, returned: conversations.length };
4487
- } finally {
4488
- // Also close the modal on selector/timeouts so later send/status calls
4489
- // cannot be blocked by a stale global-search dialog.
4490
- await this.keyboardPress(page, "Escape", "close-history-search").catch(() => {});
4491
- }
4492
- }
4493
-
4494
- async selectHistory({ conversationId, url, title } = {}) {
4495
- await this.ensureSignedIn();
4496
- const page = await this.page();
4497
- let destination = null;
4498
- let matched = null;
4499
-
4500
- if (url) {
4501
- const parsed = new URL(url, CHATGPT_URL);
4502
- if (parsed.hostname !== new URL(CHATGPT_URL).hostname || !/^\/c\//.test(parsed.pathname)) {
4503
- throw new ChatGPTWebError("历史对话 URL 必须是 chatgpt.com/c/... 地址。", { url });
4504
- }
4505
- destination = parsed.toString();
4506
- } else if (conversationId) {
4507
- if (!/^[a-zA-Z0-9-]+$/.test(conversationId)) {
4508
- throw new ChatGPTWebError("conversationId 格式无效。", { conversationId });
4509
- }
4510
- destination = new URL(`/c/${conversationId}`, CHATGPT_URL).toString();
4511
- } else if (title) {
4512
- let conversations = await this.historyLinks();
4513
- const matches = rankTextMatch(conversations, title, (item) => item.title);
4514
- let ranked = matches;
4515
- if (!ranked.length) {
4516
- const searched = await this.searchHistory({ query: title, limit: 30 });
4517
- conversations = searched.conversations;
4518
- ranked = rankTextMatch(conversations, title, (item) => item.title);
4519
- }
4520
- if (!ranked.length) {
4521
- throw new ChatGPTWebError("侧栏中没有找到匹配的历史对话。", {
4522
- requested: title,
4523
- visibleTitles: conversations.slice(0, 30).map((item) => item.title),
4524
- });
4525
- }
4526
- const best = ranked[0];
4527
- const tied = ranked.filter((entry) => entry.score === best.score);
4528
- if (best.score < 100 && tied.length > 1) {
4529
- throw new ChatGPTWebError("历史对话标题匹配到多个结果,请改用 conversationId。", {
4530
- matches: tied.map((entry) => entry.item),
4531
- });
4532
- }
4533
- matched = best.item;
4534
- destination = best.item.url;
4535
- } else {
4536
- throw new ChatGPTWebError("请选择 conversationId、url 或 title 中的一项。");
4537
- }
4538
-
4539
- await this.assertComposerEmpty("select-history");
4540
- await this.siteAction("select-history");
4541
- await navigate(page, destination, { waitUntil: "domcontentloaded" }, this.signal());
4542
- const composer = await this.composer();
4543
- if (!composer || !conversationIdFromUrl(page.url())) {
4544
- throw new ChatGPTWebError("历史对话打开后未通过页面校验,可能已删除或无权访问。", {
4545
- requested: destination,
4546
- observed: page.url(),
4547
- });
4548
- }
4549
-
4550
- this.#settingsCache = null;
4551
- const latest = await this.getLatestResponse();
4552
- return {
4553
- selected: true,
4554
- matched,
4555
- ...latest,
4556
- };
4557
- }
4558
-
4559
- async getLatestResponse({ includeSettings = false, includeTranscript = true } = {}) {
4560
- const page = await this.page();
4561
- const body = await page.locator("body").innerText().catch(() => "");
4562
- const rateLimit = classifyRateLimitText(body);
4563
- const lengthLimit = classifyConversationLengthText(body);
4564
- if (rateLimit.limited) await this.tripCircuitBreaker(rateLimit.scope, "page-text-read");
4565
- const assistant = this.assistantLocator();
4566
- const user = this.userLocator();
4567
- const renderedAssistantCount = await assistant.count();
4568
- const renderedUserCount = await user.count();
4569
- const runtime = await readRuntimeState();
4570
- const stop = await this.firstVisible(SELECTORS.stopButton, { timeout: 100 });
4571
- const lastAssistant = renderedAssistantCount ? assistant.last() : null;
4572
- const lastAssistantText = lastAssistant
4573
- ? await lastAssistant.innerText().catch(() => "")
4574
- : "";
4575
- const streaming = lastAssistant
4576
- ? await lastAssistant
4577
- .locator(
4578
- "[data-is-streaming='true'], .result-streaming, [class*='loading-shimmer'], [data-testid*='thinking']",
4579
- )
4580
- .count()
4581
- .then((value) => value > 0)
4582
- .catch(() => false)
4583
- : false;
4584
- // A completed response can leave an empty assistant placeholder after
4585
- // streaming finishes. Preserve the PR's node-count/change completion rule.
4586
- const generationComplete = Boolean(
4587
- runtime.activeGeneration?.active &&
4588
- !stop &&
4589
- !streaming &&
4590
- (runtime.activeGeneration.assistantBefore == null
4591
- ? renderedAssistantCount > 0
4592
- : renderedAssistantCount > Number(runtime.activeGeneration.assistantBefore) ||
4593
- lastAssistantText.trim() !==
4594
- String(runtime.activeGeneration.baselineResponse || "").trim()),
4595
- );
4596
- const staleGeneration = generationIsStale(runtime);
4597
- if (generationComplete || staleGeneration) {
4598
- await updateRuntimeState({
4599
- activeGeneration: null,
4600
- ...(generationComplete
4601
- ? { lastGenerationCompletedAt: Date.now() }
4602
- : { lastGenerationInterruptedAt: Date.now() }),
4603
- });
4604
- }
4605
- const generationUnconfirmed =
4606
- runtime.activeGeneration?.active && !generationComplete && !staleGeneration;
4607
- let settings = this.cachedSettings();
4608
- let settingsWarning = null;
4609
- if (includeSettings && !runtime.circuitBreaker?.active && !generationUnconfirmed) {
4610
- try {
4611
- settings = await this.advancedSettings();
4612
- } catch (error) {
4613
- settingsWarning = { message: error instanceof Error ? error.message : String(error) };
4614
- }
4615
- }
4616
- const transcript = includeTranscript && !stop && !streaming &&
4617
- !rateLimit.limited && !runtime.circuitBreaker?.active && !generationUnconfirmed
4618
- ? await this.loadCompleteTranscript()
4619
- : null;
4620
- const userCount = transcript?.userMessageCount ?? renderedUserCount;
4621
- const assistantCount = transcript?.assistantMessageCount ?? renderedAssistantCount;
4622
- const latestUserText = transcript
4623
- ? transcript.messages.findLast((message) => message.author === "user")?.text.trim() || null
4624
- : renderedUserCount
4625
- ? (await user.last().innerText()).trim()
4626
- : null;
4627
- const latestAssistantText = transcript
4628
- ? transcript.messages.findLast((message) => message.author === "assistant")?.text.trim() || null
4629
- : renderedAssistantCount
4630
- ? lastAssistantText.trim()
4631
- : null;
4632
- const conversationState = conversationTurnLimitState(
4633
- {
4634
- userMessageCount: userCount,
4635
- assistantMessageCount: assistantCount,
4636
- lengthLimitDetected: lengthLimit.limited,
4637
- },
4638
- MAX_CONVERSATION_TURNS,
4639
- );
4640
- return {
4641
- url: page.url(),
4642
- conversationId: conversationIdFromUrl(page.url()),
4643
- lastUserMessage: latestUserText,
4644
- userMessageCount: userCount,
4645
- response: latestAssistantText,
4646
- assistantMessageCount: assistantCount,
4647
- generating: Boolean(stop || streaming),
4648
- activeGeneration:
4649
- generationComplete || staleGeneration ? null : runtime.activeGeneration || null,
4650
- rateLimited: rateLimit.limited,
4651
- rateLimitScope: rateLimit.scope,
4652
- conversationTurnCount: conversationState.turnCount,
4653
- maxConversationTurns: MAX_CONVERSATION_TURNS,
4654
- conversationRotationRequired: conversationState.shouldRotate,
4655
- conversationLengthLimitDetected: lengthLimit.limited,
4656
- transcriptMessageCount: transcript?.messageCount ?? null,
4657
- transcriptLoaded: transcript?.complete ?? false,
4658
- transcriptLoadPasses: transcript?.passes ?? 0,
4659
- transcriptSource: transcript?.source || null,
4660
- circuitBreaker: rateLimit.limited
4661
- ? (await readRuntimeState()).circuitBreaker || null
4662
- : runtime.circuitBreaker || null,
4663
- model: settings.model,
4664
- thinkingLevel: settings.thinkingLevel,
4665
- settingsWarning,
4666
- mode: await this.currentMode(),
4667
- temporary: await this.temporaryState(),
4668
- };
4669
- }
4670
- }