@zqagent/core 0.2.20 → 0.3.6

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 (238) hide show
  1. package/README.md +1 -1
  2. package/README.oss.en.md +3 -3
  3. package/README.oss.md +8 -3
  4. package/README.oss.zh-TW.md +3 -3
  5. package/dist/McpClient-CEQBUPuC.d.cts +145 -0
  6. package/dist/McpClient-CEQBUPuC.d.ts +145 -0
  7. package/dist/{ToolRegistry-C3pTFiaJ.d.cts → ToolRegistry-Cy0fQxrb.d.ts} +2 -111
  8. package/dist/{ToolRegistry-C3pTFiaJ.d.ts → ToolRegistry-DouDvn9E.d.cts} +2 -111
  9. package/dist/{explore-RtZtb-V6.d.ts → TurnEngine-BPKhWuSI.d.cts} +108 -73
  10. package/dist/{explore-BgRhj6SP.d.cts → TurnEngine-DtGEuVLT.d.ts} +108 -73
  11. package/dist/conflictGuard-BBOOIxxK.d.cts +42 -0
  12. package/dist/conflictGuard-BBOOIxxK.d.ts +42 -0
  13. package/dist/index.cjs +5418 -1096
  14. package/dist/index.cjs.map +1 -1
  15. package/dist/index.d.cts +577 -195
  16. package/dist/index.d.ts +577 -195
  17. package/dist/index.js +5299 -1011
  18. package/dist/index.js.map +1 -1
  19. package/dist/internal/crypto/secrets.cjs +25 -0
  20. package/dist/internal/crypto/secrets.cjs.map +1 -0
  21. package/dist/internal/crypto/secrets.d.cts +2 -0
  22. package/dist/internal/crypto/secrets.d.ts +2 -0
  23. package/dist/internal/crypto/secrets.js +3 -0
  24. package/dist/internal/crypto/secrets.js.map +1 -0
  25. package/dist/internal/engine/FileLogHook.cjs +179 -0
  26. package/dist/internal/engine/FileLogHook.cjs.map +1 -0
  27. package/dist/internal/engine/FileLogHook.d.cts +67 -0
  28. package/dist/internal/engine/FileLogHook.d.ts +67 -0
  29. package/dist/internal/engine/FileLogHook.js +144 -0
  30. package/dist/internal/engine/FileLogHook.js.map +1 -0
  31. package/dist/internal/engine/approvalView.cjs +25 -0
  32. package/dist/internal/engine/approvalView.cjs.map +1 -0
  33. package/dist/internal/engine/approvalView.d.cts +1 -0
  34. package/dist/internal/engine/approvalView.d.ts +1 -0
  35. package/dist/internal/engine/approvalView.js +3 -0
  36. package/dist/internal/engine/approvalView.js.map +1 -0
  37. package/dist/internal/engine/limits.cjs +59 -0
  38. package/dist/internal/engine/limits.cjs.map +1 -0
  39. package/dist/internal/engine/limits.d.cts +32 -0
  40. package/dist/internal/engine/limits.d.ts +32 -0
  41. package/dist/internal/engine/limits.js +31 -0
  42. package/dist/internal/engine/limits.js.map +1 -0
  43. package/dist/internal/engine/sessionNaming.cjs +47 -0
  44. package/dist/internal/engine/sessionNaming.cjs.map +1 -0
  45. package/dist/internal/engine/sessionNaming.d.cts +25 -0
  46. package/dist/internal/engine/sessionNaming.d.ts +25 -0
  47. package/dist/internal/engine/sessionNaming.js +20 -0
  48. package/dist/internal/engine/sessionNaming.js.map +1 -0
  49. package/dist/internal/llmConfig.cjs +561 -0
  50. package/dist/internal/llmConfig.cjs.map +1 -0
  51. package/dist/internal/llmConfig.d.cts +75 -0
  52. package/dist/internal/llmConfig.d.ts +75 -0
  53. package/dist/internal/llmConfig.js +535 -0
  54. package/dist/internal/llmConfig.js.map +1 -0
  55. package/dist/internal/mcp/builtin/index.cjs +685 -0
  56. package/dist/internal/mcp/builtin/index.cjs.map +1 -0
  57. package/dist/internal/mcp/builtin/index.d.cts +21 -0
  58. package/dist/internal/mcp/builtin/index.d.ts +21 -0
  59. package/dist/internal/mcp/builtin/index.js +652 -0
  60. package/dist/internal/mcp/builtin/index.js.map +1 -0
  61. package/dist/internal/mcp/config.cjs +278 -0
  62. package/dist/internal/mcp/config.cjs.map +1 -0
  63. package/dist/internal/mcp/config.d.cts +61 -0
  64. package/dist/internal/mcp/config.d.ts +61 -0
  65. package/dist/internal/mcp/config.js +235 -0
  66. package/dist/internal/mcp/config.js.map +1 -0
  67. package/dist/internal/mcp/presets.cjs +184 -0
  68. package/dist/internal/mcp/presets.cjs.map +1 -0
  69. package/dist/internal/mcp/presets.d.cts +39 -0
  70. package/dist/internal/mcp/presets.d.ts +39 -0
  71. package/dist/internal/mcp/presets.js +158 -0
  72. package/dist/internal/mcp/presets.js.map +1 -0
  73. package/dist/internal/node-name.cjs +45 -0
  74. package/dist/internal/node-name.cjs.map +1 -0
  75. package/dist/internal/node-name.d.cts +3 -0
  76. package/dist/internal/node-name.d.ts +3 -0
  77. package/dist/internal/node-name.js +10 -0
  78. package/dist/internal/node-name.js.map +1 -0
  79. package/dist/internal/paths.cjs +63 -0
  80. package/dist/internal/paths.cjs.map +1 -0
  81. package/dist/internal/paths.d.cts +17 -0
  82. package/dist/internal/paths.d.ts +17 -0
  83. package/dist/internal/paths.js +25 -0
  84. package/dist/internal/paths.js.map +1 -0
  85. package/dist/internal/providers/diagnostics.cjs +288 -0
  86. package/dist/internal/providers/diagnostics.cjs.map +1 -0
  87. package/dist/internal/providers/diagnostics.d.cts +103 -0
  88. package/dist/internal/providers/diagnostics.d.ts +103 -0
  89. package/dist/internal/providers/diagnostics.js +250 -0
  90. package/dist/internal/providers/diagnostics.js.map +1 -0
  91. package/dist/internal/providers/models.cjs +699 -0
  92. package/dist/internal/providers/models.cjs.map +1 -0
  93. package/dist/internal/providers/models.d.cts +136 -0
  94. package/dist/internal/providers/models.d.ts +136 -0
  95. package/dist/internal/providers/models.js +654 -0
  96. package/dist/internal/providers/models.js.map +1 -0
  97. package/dist/internal/terminal.cjs +161 -0
  98. package/dist/internal/terminal.cjs.map +1 -0
  99. package/dist/internal/terminal.d.cts +58 -0
  100. package/dist/internal/terminal.d.ts +58 -0
  101. package/dist/internal/terminal.js +128 -0
  102. package/dist/internal/terminal.js.map +1 -0
  103. package/dist/internal/tools/execAsync.cjs +187 -0
  104. package/dist/internal/tools/execAsync.cjs.map +1 -0
  105. package/dist/internal/tools/execAsync.d.cts +30 -0
  106. package/dist/internal/tools/execAsync.d.ts +30 -0
  107. package/dist/internal/tools/execAsync.js +162 -0
  108. package/dist/internal/tools/execAsync.js.map +1 -0
  109. package/dist/internal/tools/git.cjs +935 -0
  110. package/dist/internal/tools/git.cjs.map +1 -0
  111. package/dist/internal/tools/git.d.cts +206 -0
  112. package/dist/internal/tools/git.d.ts +206 -0
  113. package/dist/internal/tools/git.js +883 -0
  114. package/dist/internal/tools/git.js.map +1 -0
  115. package/dist/internal/tools/pathSafety.cjs +99 -0
  116. package/dist/internal/tools/pathSafety.cjs.map +1 -0
  117. package/dist/internal/tools/pathSafety.d.cts +44 -0
  118. package/dist/internal/tools/pathSafety.d.ts +44 -0
  119. package/dist/internal/tools/pathSafety.js +61 -0
  120. package/dist/internal/tools/pathSafety.js.map +1 -0
  121. package/dist/internal/tools/plan.cjs +146 -0
  122. package/dist/internal/tools/plan.cjs.map +1 -0
  123. package/dist/internal/tools/plan.d.cts +48 -0
  124. package/dist/internal/tools/plan.d.ts +48 -0
  125. package/dist/internal/tools/plan.js +117 -0
  126. package/dist/internal/tools/plan.js.map +1 -0
  127. package/dist/internal/tools/ripgrep.cjs +118 -0
  128. package/dist/internal/tools/ripgrep.cjs.map +1 -0
  129. package/dist/internal/tools/ripgrep.d.cts +6 -0
  130. package/dist/internal/tools/ripgrep.d.ts +6 -0
  131. package/dist/internal/tools/ripgrep.js +89 -0
  132. package/dist/internal/tools/ripgrep.js.map +1 -0
  133. package/dist/internal/tools/sandbox.cjs +253 -0
  134. package/dist/internal/tools/sandbox.cjs.map +1 -0
  135. package/dist/internal/tools/sandbox.d.cts +67 -0
  136. package/dist/internal/tools/sandbox.d.ts +67 -0
  137. package/dist/internal/tools/sandbox.js +213 -0
  138. package/dist/internal/tools/sandbox.js.map +1 -0
  139. package/dist/internal/tools/shell.cjs +771 -0
  140. package/dist/internal/tools/shell.cjs.map +1 -0
  141. package/dist/internal/tools/shell.d.cts +47 -0
  142. package/dist/internal/tools/shell.d.ts +47 -0
  143. package/dist/internal/tools/shell.js +731 -0
  144. package/dist/internal/tools/shell.js.map +1 -0
  145. package/dist/internal/tools/shellRuntime.cjs +220 -0
  146. package/dist/internal/tools/shellRuntime.cjs.map +1 -0
  147. package/dist/internal/tools/shellRuntime.d.cts +67 -0
  148. package/dist/internal/tools/shellRuntime.d.ts +67 -0
  149. package/dist/internal/tools/shellRuntime.js +181 -0
  150. package/dist/internal/tools/shellRuntime.js.map +1 -0
  151. package/dist/internal/update/controller.cjs +1035 -0
  152. package/dist/internal/update/controller.cjs.map +1 -0
  153. package/dist/internal/update/controller.d.cts +150 -0
  154. package/dist/internal/update/controller.d.ts +150 -0
  155. package/dist/internal/update/controller.js +991 -0
  156. package/dist/internal/update/controller.js.map +1 -0
  157. package/dist/internal/update/platform.cjs +234 -0
  158. package/dist/internal/update/platform.cjs.map +1 -0
  159. package/dist/internal/update/platform.d.cts +77 -0
  160. package/dist/internal/update/platform.d.ts +77 -0
  161. package/dist/internal/update/platform.js +184 -0
  162. package/dist/internal/update/platform.js.map +1 -0
  163. package/dist/tools/ask.d.cts +3 -1
  164. package/dist/tools/ask.d.ts +3 -1
  165. package/dist/tools/diff.cjs +17 -6
  166. package/dist/tools/diff.cjs.map +1 -1
  167. package/dist/tools/diff.d.cts +5 -2
  168. package/dist/tools/diff.d.ts +5 -2
  169. package/dist/tools/diff.js +17 -6
  170. package/dist/tools/diff.js.map +1 -1
  171. package/dist/tools/directories.d.cts +3 -1
  172. package/dist/tools/directories.d.ts +3 -1
  173. package/dist/tools/explore.cjs +1778 -204
  174. package/dist/tools/explore.cjs.map +1 -1
  175. package/dist/tools/explore.d.cts +82 -2
  176. package/dist/tools/explore.d.ts +82 -2
  177. package/dist/tools/explore.js +1780 -204
  178. package/dist/tools/explore.js.map +1 -1
  179. package/dist/tools/files.cjs +56 -21
  180. package/dist/tools/files.cjs.map +1 -1
  181. package/dist/tools/files.d.cts +6 -3
  182. package/dist/tools/files.d.ts +6 -3
  183. package/dist/tools/files.js +56 -21
  184. package/dist/tools/files.js.map +1 -1
  185. package/dist/tools/git.cjs +34 -25
  186. package/dist/tools/git.cjs.map +1 -1
  187. package/dist/tools/git.d.cts +4 -204
  188. package/dist/tools/git.d.ts +4 -204
  189. package/dist/tools/git.js +34 -25
  190. package/dist/tools/git.js.map +1 -1
  191. package/dist/tools/media.cjs +280 -3
  192. package/dist/tools/media.cjs.map +1 -1
  193. package/dist/tools/media.d.cts +3 -1
  194. package/dist/tools/media.d.ts +3 -1
  195. package/dist/tools/media.js +278 -1
  196. package/dist/tools/media.js.map +1 -1
  197. package/dist/tools/plan.cjs +62 -0
  198. package/dist/tools/plan.cjs.map +1 -1
  199. package/dist/tools/plan.d.cts +4 -17
  200. package/dist/tools/plan.d.ts +4 -17
  201. package/dist/tools/plan.js +59 -0
  202. package/dist/tools/plan.js.map +1 -1
  203. package/dist/tools/search.cjs +3 -0
  204. package/dist/tools/search.cjs.map +1 -1
  205. package/dist/tools/search.d.cts +3 -1
  206. package/dist/tools/search.d.ts +3 -1
  207. package/dist/tools/search.js +3 -0
  208. package/dist/tools/search.js.map +1 -1
  209. package/dist/tools/shell.cjs +76 -11
  210. package/dist/tools/shell.cjs.map +1 -1
  211. package/dist/tools/shell.d.cts +5 -39
  212. package/dist/tools/shell.d.ts +5 -39
  213. package/dist/tools/shell.js +75 -11
  214. package/dist/tools/shell.js.map +1 -1
  215. package/dist/tools/todo.d.cts +3 -1
  216. package/dist/tools/todo.d.ts +3 -1
  217. package/dist/tools/web.cjs +279 -5
  218. package/dist/tools/web.cjs.map +1 -1
  219. package/dist/tools/web.d.cts +3 -1
  220. package/dist/tools/web.d.ts +3 -1
  221. package/dist/tools/web.js +275 -3
  222. package/dist/tools/web.js.map +1 -1
  223. package/dist/types-BYyXWWPW.d.cts +237 -0
  224. package/dist/types-BYyXWWPW.d.ts +237 -0
  225. package/package.json +26 -37
  226. package/bin/zqagent +0 -2
  227. package/dist/cli/index.cjs +0 -25218
  228. package/dist/cli/index.cjs.map +0 -1
  229. package/dist/cli/index.d.cts +0 -2
  230. package/dist/cli/index.d.ts +0 -2
  231. package/dist/cli/index.js +0 -25201
  232. package/dist/cli/index.js.map +0 -1
  233. package/dist/server/index.cjs +0 -20510
  234. package/dist/server/index.cjs.map +0 -1
  235. package/dist/server/index.d.cts +0 -2
  236. package/dist/server/index.d.ts +0 -2
  237. package/dist/server/index.js +0 -20493
  238. package/dist/server/index.js.map +0 -1
@@ -0,0 +1,654 @@
1
+ // src/providers/proxy.ts
2
+ import nodeFetch from "node-fetch";
3
+
4
+ // ../../node_modules/.pnpm/socks-proxy-agent@9.0.0_supports-color@7.2.0/node_modules/socks-proxy-agent/dist/index.js
5
+ import { SocksClient } from "socks";
6
+
7
+ // ../../node_modules/.pnpm/agent-base@8.0.0/node_modules/agent-base/dist/index.js
8
+ import * as net from "net";
9
+ import * as http from "http";
10
+ import { Agent as HttpsAgent } from "https";
11
+ var INTERNAL = /* @__PURE__ */ Symbol("AgentBaseInternalState");
12
+ var Agent2 = class extends http.Agent {
13
+ constructor(opts) {
14
+ super(opts);
15
+ this[INTERNAL] = {};
16
+ }
17
+ /**
18
+ * Determine whether this is an `http` or `https` request.
19
+ */
20
+ isSecureEndpoint(options) {
21
+ if (options) {
22
+ if (typeof options.secureEndpoint === "boolean") {
23
+ return options.secureEndpoint;
24
+ }
25
+ if (typeof options.protocol === "string") {
26
+ return options.protocol === "https:";
27
+ }
28
+ }
29
+ const { stack } = new Error();
30
+ if (typeof stack !== "string")
31
+ return false;
32
+ return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
33
+ }
34
+ // In order to support async signatures in `connect()` and Node's native
35
+ // connection pooling in `http.Agent`, the array of sockets for each origin
36
+ // has to be updated synchronously. This is so the length of the array is
37
+ // accurate when `addRequest()` is next called. We achieve this by creating a
38
+ // fake socket and adding it to `sockets[origin]` and incrementing
39
+ // `totalSocketCount`.
40
+ incrementSockets(name) {
41
+ if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
42
+ return null;
43
+ }
44
+ if (!this.sockets[name]) {
45
+ this.sockets[name] = [];
46
+ }
47
+ const fakeSocket = new net.Socket({ writable: false });
48
+ this.sockets[name].push(fakeSocket);
49
+ this.totalSocketCount++;
50
+ return fakeSocket;
51
+ }
52
+ decrementSockets(name, socket) {
53
+ if (!this.sockets[name] || socket === null) {
54
+ return;
55
+ }
56
+ const sockets = this.sockets[name];
57
+ const index = sockets.indexOf(socket);
58
+ if (index !== -1) {
59
+ sockets.splice(index, 1);
60
+ this.totalSocketCount--;
61
+ if (sockets.length === 0) {
62
+ delete this.sockets[name];
63
+ }
64
+ }
65
+ }
66
+ // In order to properly update the socket pool, we need to call `getName()` on
67
+ // the core `https.Agent` if it is a secureEndpoint.
68
+ getName(options) {
69
+ const secureEndpoint = this.isSecureEndpoint(options);
70
+ if (secureEndpoint) {
71
+ return HttpsAgent.prototype.getName.call(this, options);
72
+ }
73
+ return super.getName(options);
74
+ }
75
+ createSocket(req, options, cb) {
76
+ const connectOpts = {
77
+ ...options,
78
+ secureEndpoint: this.isSecureEndpoint(options)
79
+ };
80
+ const name = this.getName(connectOpts);
81
+ const fakeSocket = this.incrementSockets(name);
82
+ Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
83
+ this.decrementSockets(name, fakeSocket);
84
+ if (socket instanceof http.Agent) {
85
+ try {
86
+ return socket.addRequest(req, connectOpts);
87
+ } catch (err) {
88
+ return cb(err);
89
+ }
90
+ }
91
+ this[INTERNAL].currentSocket = socket;
92
+ super.createSocket(req, options, cb);
93
+ }, (err) => {
94
+ this.decrementSockets(name, fakeSocket);
95
+ cb(err);
96
+ });
97
+ }
98
+ createConnection() {
99
+ const socket = this[INTERNAL].currentSocket;
100
+ this[INTERNAL].currentSocket = void 0;
101
+ if (!socket) {
102
+ throw new Error("No socket was returned in the `connect()` function");
103
+ }
104
+ return socket;
105
+ }
106
+ get defaultPort() {
107
+ return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
108
+ }
109
+ set defaultPort(v) {
110
+ if (this[INTERNAL]) {
111
+ this[INTERNAL].defaultPort = v;
112
+ }
113
+ }
114
+ get protocol() {
115
+ return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
116
+ }
117
+ set protocol(v) {
118
+ if (this[INTERNAL]) {
119
+ this[INTERNAL].protocol = v;
120
+ }
121
+ }
122
+ };
123
+
124
+ // ../../node_modules/.pnpm/socks-proxy-agent@9.0.0_supports-color@7.2.0/node_modules/socks-proxy-agent/dist/index.js
125
+ import createDebug from "debug";
126
+ import * as dns from "dns";
127
+ import * as net2 from "net";
128
+ import * as tls from "tls";
129
+ import { URL } from "url";
130
+ var debug = createDebug("socks-proxy-agent");
131
+ var setServernameFromNonIpHost = (options) => {
132
+ if (options.servername === void 0 && options.host && !net2.isIP(options.host)) {
133
+ return {
134
+ ...options,
135
+ servername: options.host
136
+ };
137
+ }
138
+ return options;
139
+ };
140
+ function parseSocksURL(url) {
141
+ let lookup2 = false;
142
+ let type = 5;
143
+ const host = url.hostname;
144
+ const port = parseInt(url.port, 10) || 1080;
145
+ switch (url.protocol.replace(":", "")) {
146
+ case "socks4":
147
+ lookup2 = true;
148
+ type = 4;
149
+ break;
150
+ // pass through
151
+ case "socks4a":
152
+ type = 4;
153
+ break;
154
+ case "socks5":
155
+ lookup2 = true;
156
+ type = 5;
157
+ break;
158
+ // pass through
159
+ case "socks":
160
+ type = 5;
161
+ break;
162
+ case "socks5h":
163
+ type = 5;
164
+ break;
165
+ default:
166
+ throw new TypeError(`A "socks" protocol must be specified! Got: ${String(url.protocol)}`);
167
+ }
168
+ const proxy = {
169
+ host,
170
+ port,
171
+ type
172
+ };
173
+ if (url.username) {
174
+ Object.defineProperty(proxy, "userId", {
175
+ value: decodeURIComponent(url.username),
176
+ enumerable: false
177
+ });
178
+ }
179
+ if (url.password != null) {
180
+ Object.defineProperty(proxy, "password", {
181
+ value: decodeURIComponent(url.password),
182
+ enumerable: false
183
+ });
184
+ }
185
+ return { lookup: lookup2, proxy };
186
+ }
187
+ var SocksProxyAgent = class extends Agent2 {
188
+ constructor(uri, opts) {
189
+ super(opts);
190
+ const url = typeof uri === "string" ? new URL(uri) : uri;
191
+ const { proxy, lookup: lookup2 } = parseSocksURL(url);
192
+ this.shouldLookup = lookup2;
193
+ this.proxy = proxy;
194
+ this.timeout = opts?.timeout ?? null;
195
+ this.socketOptions = opts?.socketOptions ?? null;
196
+ }
197
+ /**
198
+ * Initiates a SOCKS connection to the specified SOCKS proxy server,
199
+ * which in turn connects to the specified remote host and port.
200
+ */
201
+ async connect(req, opts) {
202
+ const { shouldLookup, proxy, timeout } = this;
203
+ if (!opts.host) {
204
+ throw new Error("No `host` defined!");
205
+ }
206
+ let { host } = opts;
207
+ const { port, lookup: lookupFn = dns.lookup } = opts;
208
+ if (shouldLookup) {
209
+ host = await new Promise((resolve, reject) => {
210
+ lookupFn(host, {}, (err, address) => {
211
+ if (err) {
212
+ reject(err);
213
+ } else {
214
+ resolve(typeof address === "string" ? address : address[0].address);
215
+ }
216
+ });
217
+ });
218
+ }
219
+ const socksOpts = {
220
+ proxy,
221
+ destination: {
222
+ host,
223
+ port: typeof port === "number" ? port : parseInt(port, 10)
224
+ },
225
+ command: "connect",
226
+ timeout: timeout ?? void 0,
227
+ // @ts-expect-error the type supplied by socks for socket_options is wider
228
+ // than necessary since socks will always override the host and port
229
+ socket_options: this.socketOptions ?? void 0
230
+ };
231
+ const cleanup = (tlsSocket) => {
232
+ req.destroy();
233
+ socket.destroy();
234
+ if (tlsSocket)
235
+ tlsSocket.destroy();
236
+ };
237
+ debug("Creating socks proxy connection: %o", socksOpts);
238
+ const { socket } = await SocksClient.createConnection(socksOpts);
239
+ debug("Successfully created socks proxy connection");
240
+ if (timeout !== null) {
241
+ socket.setTimeout(timeout);
242
+ socket.on("timeout", () => cleanup());
243
+ }
244
+ if (opts.secureEndpoint) {
245
+ debug("Upgrading socket connection to TLS");
246
+ const tlsSocket = tls.connect({
247
+ ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"),
248
+ socket
249
+ });
250
+ tlsSocket.once("error", (error) => {
251
+ debug("Socket TLS error", error.message);
252
+ cleanup(tlsSocket);
253
+ });
254
+ return tlsSocket;
255
+ }
256
+ return socket;
257
+ }
258
+ };
259
+ SocksProxyAgent.protocols = [
260
+ "socks",
261
+ "socks4",
262
+ "socks4a",
263
+ "socks5",
264
+ "socks5h"
265
+ ];
266
+ function omit(obj, ...keys) {
267
+ const ret = {};
268
+ let key;
269
+ for (key in obj) {
270
+ if (!keys.includes(key)) {
271
+ ret[key] = obj[key];
272
+ }
273
+ }
274
+ return ret;
275
+ }
276
+
277
+ // src/providers/proxy.ts
278
+ function socksProxyUrl() {
279
+ const raw = (process.env.SOCKS5_PROXY ?? "").trim();
280
+ return raw || null;
281
+ }
282
+ function isSocks(raw) {
283
+ return /^socks/i.test(raw);
284
+ }
285
+ var cached = null;
286
+ function socksAgent() {
287
+ const url = socksProxyUrl();
288
+ if (!url) return null;
289
+ if (cached?.url === url) return cached.agent;
290
+ let agent = null;
291
+ if (isSocks(url)) {
292
+ try {
293
+ agent = new SocksProxyAgent(url);
294
+ } catch {
295
+ try {
296
+ agent = new SocksProxyAgent(url.replace(/^socks5h:\/\//, "socks5://"));
297
+ } catch {
298
+ agent = null;
299
+ }
300
+ }
301
+ }
302
+ cached = { url, agent };
303
+ return agent;
304
+ }
305
+ function makeSocksFetch(agent) {
306
+ return ((url, init) => nodeFetch(String(url), { ...init, agent }));
307
+ }
308
+
309
+ // src/providers/diagnostics.ts
310
+ function cleanLlmValue(v) {
311
+ if (v == null) return void 0;
312
+ let s = String(v).replace(/^\uFEFF/, "");
313
+ s = s.replace(/[\r\n\t]/g, "").trim();
314
+ if (s.length >= 2 && (s.startsWith('"') && s.endsWith('"') || s.startsWith("'") && s.endsWith("'"))) {
315
+ s = s.slice(1, -1).trim();
316
+ }
317
+ return s || void 0;
318
+ }
319
+ function normalizeBaseURL(raw) {
320
+ let s = cleanLlmValue(raw);
321
+ if (!s) return void 0;
322
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) s = `https://${s}`;
323
+ s = s.replace(/\/+$/, "");
324
+ s = s.replace(/\/(chat\/completions|completions|responses|models)$/i, "");
325
+ return s.replace(/\/+$/, "") || void 0;
326
+ }
327
+ function isReasoningModel(model) {
328
+ return /^(o\d|gpt-5)/i.test(model);
329
+ }
330
+
331
+ // src/providers/models.ts
332
+ import {
333
+ capabilitiesOf,
334
+ normalizeCapabilities
335
+ } from "@zqagent/shared/model-capabilities";
336
+ async function doFetch(url, init) {
337
+ const agent = socksAgent();
338
+ if (agent) {
339
+ const f = makeSocksFetch(agent);
340
+ return f(url, init);
341
+ }
342
+ return globalThis.fetch(url, init);
343
+ }
344
+ function normalizeModelMeta(v) {
345
+ if (!Array.isArray(v)) return void 0;
346
+ const out = [];
347
+ const seen = /* @__PURE__ */ new Set();
348
+ for (const x of v) {
349
+ if (!x || typeof x !== "object") continue;
350
+ const rec = x;
351
+ const id = String(rec.id ?? "").trim();
352
+ if (!id || seen.has(id)) continue;
353
+ seen.add(id);
354
+ const ctx = Number(rec.contextWindow);
355
+ const capabilities = normalizeCapabilities(rec.capabilities);
356
+ out.push({
357
+ id,
358
+ ...Number.isFinite(ctx) && ctx > 0 ? { contextWindow: ctx } : {},
359
+ ...capabilities ? { capabilities } : {}
360
+ });
361
+ if (out.length >= 500) break;
362
+ }
363
+ return out;
364
+ }
365
+ function modelCapabilities(meta, model) {
366
+ return capabilitiesOf(meta, model);
367
+ }
368
+ function mergeModelMeta(base, patch) {
369
+ if (!base?.length) return patch;
370
+ if (!patch?.length) return base;
371
+ const byId = /* @__PURE__ */ new Map();
372
+ for (const m of base) byId.set(m.id, { ...m });
373
+ for (const m of patch) {
374
+ const prev = byId.get(m.id);
375
+ byId.set(m.id, {
376
+ ...prev,
377
+ ...m,
378
+ ...prev?.capabilities?.length ? { capabilities: prev.capabilities } : {}
379
+ });
380
+ }
381
+ return [...byId.values()];
382
+ }
383
+ function modelContextWindow(meta, model) {
384
+ if (!model || !meta?.length) return void 0;
385
+ const exact = meta.find((m) => m.id === model && m.contextWindow);
386
+ if (exact?.contextWindow) return exact.contextWindow;
387
+ const prefix = meta.find((m) => m.contextWindow && model.startsWith(m.id));
388
+ return prefix?.contextWindow;
389
+ }
390
+ var NON_CHAT_PATTERNS = [
391
+ /embedding/i,
392
+ /rerank/i,
393
+ /(^|[-_/.])(asr|tts)([-_/.]|$)/i,
394
+ /speech|voice|unisound|audio-?coding/i,
395
+ /realtime|livetranslate|(^|[-_])s2s([-_]|$)/i,
396
+ /image|wan\d|z-image|paint|draw|flux|kolors|cogview/i,
397
+ /deep-research|search-planning/i,
398
+ /(^|[-_])cmaas[-_]|confidential/i,
399
+ /(^|[-_])test[-_]|auto-handle|gpu-auto/i
400
+ ];
401
+ function isChatModel(modelId) {
402
+ return !NON_CHAT_PATTERNS.some((re) => re.test(modelId));
403
+ }
404
+ function rankModels(models) {
405
+ const chat = [];
406
+ const nonChat = [];
407
+ for (const m of models) (isChatModel(m) ? chat : nonChat).push(m);
408
+ return { ordered: [...chat, ...nonChat], nonChat };
409
+ }
410
+ function parseModelList(body) {
411
+ if (!body || typeof body !== "object") return { models: [], meta: [] };
412
+ const data = body.data;
413
+ if (!Array.isArray(data)) return { models: [], meta: [] };
414
+ const models = [];
415
+ const meta = [];
416
+ for (const item of data) {
417
+ if (!item || typeof item !== "object") continue;
418
+ const rec = item;
419
+ const id = rec.id;
420
+ if (typeof id !== "string" || !id.trim()) continue;
421
+ models.push(id);
422
+ const ctx = rec.context_length ?? rec.context_window ?? rec.max_context_length ?? rec.max_input_tokens ?? rec.max_model_len;
423
+ if (typeof ctx === "number" && ctx > 0) {
424
+ meta.push({ id, contextWindow: ctx });
425
+ }
426
+ }
427
+ return { models, meta };
428
+ }
429
+ function modelListCandidates(baseURL) {
430
+ const base = baseURL.replace(/\/+$/, "");
431
+ if (!base) return [];
432
+ const out = [];
433
+ const add = (u) => {
434
+ if (u && !out.includes(u)) out.push(u);
435
+ };
436
+ add(`${base}/models`);
437
+ if (!/\/v\d+[a-z0-9]*$/i.test(base)) add(`${base}/v1/models`);
438
+ const root = stripVersionSuffix(base);
439
+ if (root !== base) {
440
+ add(`${root}/models`);
441
+ add(`${root}/v1/models`);
442
+ }
443
+ add(`${root}/api/v1/models`);
444
+ add(`${root}/api/models`);
445
+ return out.slice(0, 6);
446
+ }
447
+ function stripVersionSuffix(base) {
448
+ const s = base.replace(/\/+$/, "");
449
+ const suffixes = [
450
+ "/compatible-mode/v1",
451
+ "/compatible-mode",
452
+ "/openai/v1",
453
+ "/v1beta",
454
+ "/v1",
455
+ // DeepSeek 的 /beta 只用于前缀补全(FIM),模型列表仍在根路径
456
+ "/beta"
457
+ ];
458
+ for (const suf of suffixes) {
459
+ if (s.toLowerCase().endsWith(suf)) return s.slice(0, -suf.length).replace(/\/+$/, "");
460
+ }
461
+ return s;
462
+ }
463
+ async function errorSnippet(resp) {
464
+ const r = resp;
465
+ if (typeof r.text !== "function") return void 0;
466
+ try {
467
+ const text = (await r.text()).trim();
468
+ if (!text) return void 0;
469
+ try {
470
+ const body = JSON.parse(text);
471
+ const err = body["error"];
472
+ const msg = (err && typeof err === "object" ? String(err["message"] ?? "") : "") || String(body["message"] ?? "");
473
+ if (msg) {
474
+ return msg.replace(/\s*\(request_id:[^)]*\)/gi, "").slice(0, 160);
475
+ }
476
+ } catch {
477
+ }
478
+ return text.replace(/\s+/g, " ").slice(0, 200);
479
+ } catch {
480
+ return void 0;
481
+ }
482
+ }
483
+ async function fetchModelsWithDiagnostics(baseURL, apiKey, preferredModel, opts = {}) {
484
+ const base = normalizeBaseURL(baseURL) ?? baseURL.replace(/\/+$/, "");
485
+ const key = cleanLlmValue(apiKey) ?? "";
486
+ const budgetMs = opts.budgetMs ?? 25e3;
487
+ const timeoutMs = opts.timeoutMs ?? 8e3;
488
+ const started = Date.now();
489
+ const attempts = [];
490
+ const candidates = modelListCandidates(base);
491
+ let authFailed = false;
492
+ for (const url of candidates) {
493
+ const left = budgetMs - (Date.now() - started);
494
+ if (left < 500) {
495
+ attempts.push({ url, error: "\u8D85\u51FA\u91CD\u8BD5\u603B\u9884\u7B97\uFF0C\u672A\u5C1D\u8BD5" });
496
+ continue;
497
+ }
498
+ try {
499
+ const resp = await doFetch(url, {
500
+ method: "GET",
501
+ headers: {
502
+ Authorization: `Bearer ${key}`,
503
+ Accept: "application/json"
504
+ },
505
+ signal: AbortSignal.timeout(Math.min(timeoutMs, left))
506
+ });
507
+ if (!resp.ok) {
508
+ const status = typeof resp.status === "number" ? resp.status : void 0;
509
+ const detail = await errorSnippet(resp);
510
+ attempts.push({ url, ...status !== void 0 ? { status } : {}, ...detail ? { error: detail } : {} });
511
+ if (status === 401 || status === 403) authFailed = true;
512
+ continue;
513
+ }
514
+ const body = await resp.json();
515
+ const { models, meta } = parseModelList(body);
516
+ if (models.length === 0) {
517
+ attempts.push({ url, error: "\u8FD4\u56DE\u7684\u6A21\u578B\u5217\u8868\u4E3A\u7A7A" });
518
+ continue;
519
+ }
520
+ const { ordered, nonChat } = rankModels(models);
521
+ const filled = await fillContextWindow(base, key, ordered, meta, preferredModel, {
522
+ budgetMs: Math.max(1e3, budgetMs - (Date.now() - started))
523
+ });
524
+ return {
525
+ result: {
526
+ models: ordered,
527
+ endpoint: url,
528
+ nonChat,
529
+ ...filled.length > 0 ? { modelMeta: filled } : {}
530
+ },
531
+ attempts,
532
+ authFailed: false
533
+ };
534
+ } catch (e) {
535
+ attempts.push({ url, error: e instanceof Error ? e.message : String(e) });
536
+ }
537
+ }
538
+ return { result: null, attempts, authFailed };
539
+ }
540
+ function describeModelFetchFailure(baseURL, diag) {
541
+ const lines = diag.attempts.map((a) => {
542
+ const why = a.status !== void 0 ? `HTTP ${a.status}` : a.error ?? "\u8BF7\u6C42\u5931\u8D25";
543
+ return ` \xB7 ${a.url} \u2192 ${why}${a.status !== void 0 && a.error ? `\uFF08${a.error}\uFF09` : ""}`;
544
+ });
545
+ if (diag.authFailed) {
546
+ return `\u6A21\u578B\u5217\u8868\u5237\u65B0\u5931\u8D25\uFF1AAPI Key \u65E0\u6548\u6216\u65E0\u6743\u9650\uFF08Base URL\uFF1A${baseURL}\uFF09\u3002
547
+ \u5DF2\u5C1D\u8BD5\uFF1A
548
+ ${lines.join("\n")}
549
+ \u8BF7\u68C0\u67E5 Key \u662F\u5426\u586B\u5199\u6B63\u786E\u3001\u662F\u5426\u5DF2\u8FC7\u671F\uFF0C\u6216\u8BE5 Key \u662F\u5426\u6709\u6743\u8BBF\u95EE\u6B64\u7AEF\u70B9\u3002`;
550
+ }
551
+ return `\u6A21\u578B\u5217\u8868\u5237\u65B0\u5931\u8D25\uFF1A\u6240\u6709\u5019\u9009\u7AEF\u70B9\u90FD\u6CA1\u6709\u8FD4\u56DE\u53EF\u7528\u6A21\u578B\uFF08Base URL\uFF1A${baseURL}\uFF09\u3002
552
+ \u5DF2\u5C1D\u8BD5\uFF1A
553
+ ${lines.join("\n")}
554
+ \u8BF7\u786E\u8BA4 Base URL \u662F\u5426\u6B63\u786E\uFF08\u4E00\u822C\u586B\u5230 /v1 \u4E3A\u6B62\uFF0C\u5982 https://api.deepseek.com\uFF09\uFF0C\u4EE5\u53CA\u8BE5\u670D\u52A1\u662F\u5426\u63D0\u4F9B OpenAI \u517C\u5BB9\u7684 GET /models \u63A5\u53E3\u3002`;
555
+ }
556
+ async function fillContextWindow(base, key, models, meta, preferred, opts = {}) {
557
+ if (meta.length > 0) return meta;
558
+ const target = preferred?.trim() || models[0];
559
+ if (!target) return meta;
560
+ const ctx = await fetchModelContext(base, key, target, opts.budgetMs);
561
+ return ctx ? [{ id: target, contextWindow: ctx }] : meta;
562
+ }
563
+ async function fetchModels(baseURL, apiKey, preferredModel) {
564
+ const diag = await fetchModelsWithDiagnostics(baseURL, apiKey, preferredModel);
565
+ return diag.result;
566
+ }
567
+ async function fetchModelContext(baseURL, apiKey, modelId, timeoutMs = 1e4) {
568
+ if (!modelId) return void 0;
569
+ const base = normalizeBaseURL(baseURL) ?? baseURL.replace(/\/+$/, "");
570
+ const key = cleanLlmValue(apiKey) ?? "";
571
+ try {
572
+ const resp = await doFetch(`${base}/models/${encodeURIComponent(modelId)}`, {
573
+ method: "GET",
574
+ headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
575
+ signal: AbortSignal.timeout(Math.max(500, timeoutMs))
576
+ });
577
+ if (!resp.ok) return void 0;
578
+ const body = await resp.json();
579
+ const rec = body ?? {};
580
+ const inner = rec.data && typeof rec.data === "object" && !Array.isArray(rec.data) ? rec.data : rec;
581
+ return parseModelList({ data: [inner] }).meta[0]?.contextWindow;
582
+ } catch {
583
+ return void 0;
584
+ }
585
+ }
586
+ function extractError(body) {
587
+ const b = body ?? {};
588
+ const e = b.error ?? b;
589
+ const message = String(e.message ?? b.message ?? "").trim();
590
+ const code = typeof e.code === "string" ? e.code : typeof b.code === "string" ? b.code : void 0;
591
+ const requestId = typeof b.request_id === "string" ? b.request_id : void 0;
592
+ return {
593
+ message: message || "\u672A\u77E5\u9519\u8BEF",
594
+ code: code ? `${code}${requestId ? ` (request_id=${requestId})` : ""}` : void 0
595
+ };
596
+ }
597
+ async function probeModel(baseURL, apiKey, model) {
598
+ const base = normalizeBaseURL(baseURL) ?? baseURL.replace(/\/+$/, "");
599
+ const key = cleanLlmValue(apiKey) ?? "";
600
+ const started = Date.now();
601
+ try {
602
+ const resp = await doFetch(`${base}/chat/completions`, {
603
+ method: "POST",
604
+ headers: {
605
+ "Content-Type": "application/json",
606
+ Authorization: `Bearer ${key}`
607
+ },
608
+ body: JSON.stringify({
609
+ model,
610
+ messages: [{ role: "user", content: "ping" }],
611
+ // 与 Provider 共用 isReasoningModel:o 系列 / gpt-5 只接受
612
+ // max_completion_tokens,传 max_tokens 会 400,把可用模型误判成不可用
613
+ ...isReasoningModel(model) ? { max_completion_tokens: 8 } : { max_tokens: 8 },
614
+ stream: false
615
+ }),
616
+ signal: AbortSignal.timeout(2e4)
617
+ });
618
+ const latencyMs = Date.now() - started;
619
+ if (resp.ok) return { ok: true, latencyMs };
620
+ let body = null;
621
+ try {
622
+ body = await resp.json();
623
+ } catch {
624
+ }
625
+ const { message, code } = extractError(body);
626
+ return {
627
+ ok: false,
628
+ error: `HTTP ${resp.status} ${message}`,
629
+ ...code ? { code } : {},
630
+ latencyMs
631
+ };
632
+ } catch (err) {
633
+ return {
634
+ ok: false,
635
+ error: err instanceof Error ? err.message : String(err),
636
+ latencyMs: Date.now() - started
637
+ };
638
+ }
639
+ }
640
+ export {
641
+ describeModelFetchFailure,
642
+ fetchModelContext,
643
+ fetchModels,
644
+ fetchModelsWithDiagnostics,
645
+ isChatModel,
646
+ mergeModelMeta,
647
+ modelCapabilities,
648
+ modelContextWindow,
649
+ modelListCandidates,
650
+ normalizeModelMeta,
651
+ probeModel,
652
+ stripVersionSuffix
653
+ };
654
+ //# sourceMappingURL=models.js.map