@jeffreycao/copilot-api 2.2.0 → 2.2.2

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 (35) hide show
  1. package/README.md +177 -206
  2. package/README.zh-CN.md +196 -221
  3. package/dist/{auth-HR8NHHhJ.js → auth-Bb1k-ECx.js} +4 -4
  4. package/dist/{auth-HR8NHHhJ.js.map → auth-Bb1k-ECx.js.map} +1 -1
  5. package/dist/auth-Rglf5pV9.js +2 -0
  6. package/dist/{config-CHzejzwY.js → config-D0EIG26T.js} +48 -7
  7. package/dist/config-D0EIG26T.js.map +1 -0
  8. package/dist/{debug-ChC85ySp.js → debug-DdGqmvyk.js} +2 -2
  9. package/dist/{debug-ChC85ySp.js.map → debug-DdGqmvyk.js.map} +1 -1
  10. package/dist/{electron-fetch-DPhDE6JE.js → electron-fetch-BRX-ug5E.js} +1 -1
  11. package/dist/{electron-fetch-DPhDE6JE.js.map → electron-fetch-BRX-ug5E.js.map} +1 -1
  12. package/dist/fast-path-BoMnZCVC.js +11 -0
  13. package/dist/fast-path-BoMnZCVC.js.map +1 -0
  14. package/dist/main.js +45 -39
  15. package/dist/main.js.map +1 -1
  16. package/dist/mcp-fpSlKZxK.js +16 -0
  17. package/dist/mcp-fpSlKZxK.js.map +1 -0
  18. package/dist/{mcp-BG6fpi6q.js → mcp-server-BeNu_Edl.js} +3 -13
  19. package/dist/mcp-server-BeNu_Edl.js.map +1 -0
  20. package/dist/mcp-server-DQ4r-fAy.js +2 -0
  21. package/dist/{models-CJuY4JZ5.js → models-CgxSOPld.js} +2 -2
  22. package/dist/{models-CJuY4JZ5.js.map → models-CgxSOPld.js.map} +1 -1
  23. package/dist/{server-DN95QRWA.js → server-ooE0nEgj.js} +77 -40
  24. package/dist/server-ooE0nEgj.js.map +1 -0
  25. package/dist/{start-BL3AiN3r.js → start-CoFNjnwH.js} +8 -8
  26. package/dist/{start-BL3AiN3r.js.map → start-CoFNjnwH.js.map} +1 -1
  27. package/dist/{tls-BmWaOfKV.js → tls-Aq1Dd8E2.js} +1 -1
  28. package/dist/{tls-BmWaOfKV.js.map → tls-Aq1Dd8E2.js.map} +1 -1
  29. package/dist/{token-Ctj6sfG4.js → token-Drm4iN8n.js} +3 -3
  30. package/dist/{token-Ctj6sfG4.js.map → token-Drm4iN8n.js.map} +1 -1
  31. package/package.json +4 -3
  32. package/dist/auth-PIo0IPSc.js +0 -2
  33. package/dist/config-CHzejzwY.js.map +0 -1
  34. package/dist/mcp-BG6fpi6q.js.map +0 -1
  35. package/dist/server-DN95QRWA.js.map +0 -1
@@ -1,12 +1,12 @@
1
- import { A as isResponsesApiWebSocketEnabled, C as getClaudeTokenMultiplier, D as isAlphaSearchCodexPriorityEnabled, E as getResponsesTransportConfig, M as PATHS, O as isMessagesApiEnabled, S as getClaudeAutoModel, T as getMessageApiWebSearchModel, _ as resolveMappedModel, b as getAlphaSearchModel, d as getModelResponsesApiCompactThreshold$1, f as getReasoningEffortForModel, g as isGpt56OrAbove, h as isContextManagementEnabledForResponses, i as listEnabledProviders, k as isResponsesApiWebSearchEnabled, l as getExtraPromptForModel, m as isContextManagementEnabledForMessages, n as getRawProviderConfig, o as resolveEffectiveProviderType, p as getSmallModel, s as resolveProviderAuthType, t as getProviderConfig, u as getModelMappings, v as setModelMappings, w as getConfig, x as getAnthropicApiKey } from "./config-CHzejzwY.js";
2
- import { A as buildCodexRequestHeaders, B as createPooledWebSocketStream, C as compactAutoContinuePromptStarts, D as compactTextOnlyGuard, E as compactSystemPromptStarts, F as createResponsesHttpEventStream, H as state, I as fetchResponsesWithLifecycle, L as createResponsesSafeStream, M as generateTraceId, N as requestContext, P as resolveTraceId$1, R as encodePoolKeyPart, U as HTTPError, V as createWebSocketUrl, W as forwardError, b as prepareInteractionHeaders, c as getUUID, d as isResponsesStream, f as parseUserIdMetadata, g as copilotHeaders, h as copilotBaseUrl, j as forwardCodexResponses, k as CODEX_API_BASE_URL, l as isAsyncIterable, o as generateRequestIdFromPayload, p as getCopilotUsage, r as setupCodexToken, s as getRootSessionId, u as isNullish, v as copilotWebSocketHeaders, w as compactMessageSections, x as prepareMessageProxyHeaders, y as prepareForCompact, z as isTerminalResponsesStreamChunk } from "./token-Ctj6sfG4.js";
1
+ import { A as isResponsesApiWebSocketEnabled, C as getClaudeTokenMultiplier, D as isAlphaSearchCodexPriorityEnabled, E as getResponsesTransportConfig, M as PATHS, O as isMessagesApiEnabled, S as getClaudeAutoModel, T as getMessageApiWebSearchModel, _ as resolveMappedModel, b as getAlphaSearchModel, d as getModelResponsesApiCompactThreshold$1, f as getReasoningEffortForModel, g as isGpt56OrAbove, h as isContextManagementEnabledForResponses, i as listEnabledProviders, k as isResponsesApiWebSearchEnabled, l as getExtraPromptForModel, m as isContextManagementEnabledForMessages, n as getRawProviderConfig, o as resolveEffectiveProviderType, p as getSmallModel, s as resolveProviderAuthType, t as getProviderConfig, u as getModelMappings, v as setModelMappings, w as getConfig, x as getAnthropicApiKey } from "./config-D0EIG26T.js";
2
+ import { A as buildCodexRequestHeaders, B as createPooledWebSocketStream, C as compactAutoContinuePromptStarts, D as compactTextOnlyGuard, E as compactSystemPromptStarts, F as createResponsesHttpEventStream, H as state, I as fetchResponsesWithLifecycle, L as createResponsesSafeStream, M as generateTraceId, N as requestContext, P as resolveTraceId$1, R as encodePoolKeyPart, U as HTTPError, V as createWebSocketUrl, W as forwardError, b as prepareInteractionHeaders, c as getUUID, d as isResponsesStream, f as parseUserIdMetadata, g as copilotHeaders, h as copilotBaseUrl, j as forwardCodexResponses, k as CODEX_API_BASE_URL, l as isAsyncIterable, o as generateRequestIdFromPayload, p as getCopilotUsage, r as setupCodexToken, s as getRootSessionId, u as isNullish, v as copilotWebSocketHeaders, w as compactMessageSections, x as prepareMessageProxyHeaders, y as prepareForCompact, z as isTerminalResponsesStreamChunk } from "./token-Drm4iN8n.js";
3
3
  import { a as isDeferredToolName, c as parseMcpToolSearchSentinel, d as shouldEnableResponsesToolSearch, i as isBridgeToolSearchName, l as resolveBridgeToolSearchName, o as listDeferredToolNames, r as formatToolSearchBridgeArguments, s as normalizeToolSearchBridgeArguments, t as BRIDGE_TOOL_SEARCH_NAME, u as selectDeferredToolsByNames } from "./tool-search-Ds1vbmGG.js";
4
- import { i as toClientModelId, r as normalizeSdkModelId, t as findEndpointModel } from "./models-CJuY4JZ5.js";
4
+ import { i as toClientModelId, r as normalizeSdkModelId, t as findEndpointModel } from "./models-CgxSOPld.js";
5
5
  import consola from "consola";
6
6
  import { createHash } from "node:crypto";
7
7
  import fs, { readFileSync } from "node:fs";
8
- import fs$1 from "node:fs/promises";
9
8
  import path from "node:path";
9
+ import fs$1 from "node:fs/promises";
10
10
  import { fetch as fetch$1, getGlobalDispatcher } from "undici";
11
11
  import { events } from "fetch-event-stream";
12
12
  import { z } from "zod";
@@ -203,30 +203,11 @@ const logBuffers = /* @__PURE__ */ new Map();
203
203
  let runtimeInitialized = false;
204
204
  let flushInterval;
205
205
  let cleanupInterval;
206
+ let currentLogDateKey;
206
207
  const ensureLogDirectory = () => {
207
208
  const logDir = getLogDir();
208
209
  if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
209
210
  };
210
- const cleanupOldLogs = () => {
211
- const logDir = getLogDir();
212
- if (!fs.existsSync(logDir)) return;
213
- const now = Date.now();
214
- for (const entry of fs.readdirSync(logDir)) {
215
- const filePath = path.join(logDir, entry);
216
- let stats;
217
- try {
218
- stats = fs.statSync(filePath);
219
- } catch {
220
- continue;
221
- }
222
- if (!stats.isFile()) continue;
223
- if (now - stats.mtimeMs > LOG_RETENTION_MS) try {
224
- fs.rmSync(filePath);
225
- } catch {
226
- continue;
227
- }
228
- }
229
- };
230
211
  const formatArgs = (args) => args.map((arg) => typeof arg === "string" ? arg : util.inspect(arg, {
231
212
  depth: null,
232
213
  colors: false
@@ -240,22 +221,78 @@ const maybeUnref = (timer) => {
240
221
  };
241
222
  const flushBuffer = (filePath) => {
242
223
  const buffer = logBuffers.get(filePath);
243
- if (!buffer || buffer.length === 0) return;
224
+ if (!buffer) return;
225
+ logBuffers.delete(filePath);
226
+ if (buffer.length === 0) return;
244
227
  const stream = getLogStream(filePath);
245
228
  const content = buffer.join("\n") + "\n";
246
229
  stream.write(content, (error) => {
247
230
  if (error) console.warn("Failed to write handler log", error);
248
231
  });
249
- logBuffers.set(filePath, []);
250
232
  };
251
233
  const flushAllBuffers = () => {
252
234
  for (const filePath of logBuffers.keys()) flushBuffer(filePath);
253
235
  };
236
+ const closeLogFile = async (filePath) => {
237
+ flushBuffer(filePath);
238
+ const stream = logStreams.get(filePath);
239
+ logStreams.delete(filePath);
240
+ logBuffers.delete(filePath);
241
+ if (!stream || stream.closed) return;
242
+ await new Promise((resolve) => {
243
+ stream.once("close", resolve);
244
+ stream.end();
245
+ });
246
+ };
247
+ const closePreviousDateLogFiles = (dateKey) => {
248
+ if (currentLogDateKey === void 0) {
249
+ currentLogDateKey = dateKey;
250
+ return;
251
+ }
252
+ if (currentLogDateKey === dateKey) return;
253
+ const filePaths = new Set([...logBuffers.keys(), ...logStreams.keys()]);
254
+ currentLogDateKey = dateKey;
255
+ for (const filePath of filePaths) closeLogFile(filePath).catch((error) => {
256
+ console.warn("Failed to rotate handler log", error);
257
+ });
258
+ };
259
+ const cleanupOldLogs = async () => {
260
+ const logDir = getLogDir();
261
+ if (!fs.existsSync(logDir)) return;
262
+ const now = Date.now();
263
+ for (const entry of fs.readdirSync(logDir)) {
264
+ const filePath = path.join(logDir, entry);
265
+ let stats;
266
+ try {
267
+ stats = fs.statSync(filePath);
268
+ } catch {
269
+ continue;
270
+ }
271
+ if (!stats.isFile() || now - stats.mtimeMs <= LOG_RETENTION_MS) continue;
272
+ try {
273
+ await closeLogFile(filePath);
274
+ } catch (error) {
275
+ console.warn(`Failed to close old handler log: ${filePath}`, error);
276
+ continue;
277
+ }
278
+ try {
279
+ fs.rmSync(filePath);
280
+ } catch (error) {
281
+ console.warn(`Failed to remove old handler log: ${filePath}`, error);
282
+ }
283
+ }
284
+ };
285
+ const scheduleLogCleanup = () => {
286
+ cleanupOldLogs().catch((error) => {
287
+ console.warn("Failed to clean up handler logs", error);
288
+ });
289
+ };
254
290
  const flushAndCloseLogStreams = () => {
255
291
  flushAllBuffers();
256
292
  for (const stream of logStreams.values()) stream.end();
257
293
  logStreams.clear();
258
294
  logBuffers.clear();
295
+ currentLogDateKey = void 0;
259
296
  };
260
297
  const shutdownLoggerRuntime = () => {
261
298
  if (flushInterval) {
@@ -273,10 +310,10 @@ const initializeLoggerRuntime = () => {
273
310
  if (runtimeInitialized) return;
274
311
  runtimeInitialized = true;
275
312
  ensureLogDirectory();
276
- cleanupOldLogs();
313
+ scheduleLogCleanup();
277
314
  flushInterval = setInterval(flushAllBuffers, FLUSH_INTERVAL_MS);
278
315
  maybeUnref(flushInterval);
279
- cleanupInterval = setInterval(cleanupOldLogs, CLEANUP_INTERVAL_MS);
316
+ cleanupInterval = setInterval(scheduleLogCleanup, CLEANUP_INTERVAL_MS);
280
317
  maybeUnref(cleanupInterval);
281
318
  registerProcessCleanup(shutdownLoggerRuntime);
282
319
  };
@@ -284,11 +321,12 @@ const getLogStream = (filePath) => {
284
321
  initializeLoggerRuntime();
285
322
  let stream = logStreams.get(filePath);
286
323
  if (!stream || stream.destroyed) {
287
- stream = fs.createWriteStream(filePath, { flags: "a" });
288
- logStreams.set(filePath, stream);
289
- stream.on("error", (error) => {
324
+ const createdStream = fs.createWriteStream(filePath, { flags: "a" });
325
+ stream = createdStream;
326
+ logStreams.set(filePath, createdStream);
327
+ createdStream.on("error", (error) => {
290
328
  console.warn("Log stream error", error);
291
- logStreams.delete(filePath);
329
+ if (logStreams.get(filePath) === createdStream) logStreams.delete(filePath);
292
330
  });
293
331
  }
294
332
  return stream;
@@ -330,7 +368,9 @@ const createHandlerLogger = (name) => {
330
368
  const filePath = path.join(getLogDir(), `${sanitizedName}-${dateKey}.log`);
331
369
  const message = formatArgs(logObj.args);
332
370
  const traceIdStr = traceId ? ` [${traceId}]` : "";
333
- appendLine(filePath, `[${timestamp}] [${logObj.type}] [${logObj.tag || name}]${traceIdStr}${message ? ` ${message}` : ""}`);
371
+ const line = `[${timestamp}] [${logObj.type}] [${logObj.tag || name}]${traceIdStr}${message ? ` ${message}` : ""}`;
372
+ closePreviousDateLogFiles(dateKey);
373
+ appendLine(filePath, line);
334
374
  } });
335
375
  return instance;
336
376
  };
@@ -8481,7 +8521,7 @@ var ResponsesMessagesTranslationError = class extends Error {
8481
8521
  }
8482
8522
  };
8483
8523
  function translateResponsesToMessages(payload, options) {
8484
- const registry = createToolRegistry(payload, options.provider);
8524
+ const registry = createToolRegistry(payload);
8485
8525
  const normalized = normalizeResponsesInput(payload.input);
8486
8526
  const { messages, system } = translateInputToAnthropic(normalized.input, registry, payload.instructions, payload.input);
8487
8527
  if (normalized.compaction) messages.push({
@@ -8634,11 +8674,10 @@ function normalizeResponsesInput(input) {
8634
8674
  }, ...withoutTrigger.slice(latestCompactionIndex + 1)]
8635
8675
  };
8636
8676
  }
8637
- function createToolRegistry(payload, provider) {
8677
+ function createToolRegistry(payload) {
8638
8678
  const registry = {
8639
8679
  byAlias: /* @__PURE__ */ new Map(),
8640
8680
  byOriginal: /* @__PURE__ */ new Map(),
8641
- provider,
8642
8681
  tools: []
8643
8682
  };
8644
8683
  for (const tool of payload.tools ?? []) registerTool(tool, registry);
@@ -8689,7 +8728,7 @@ function registerMessagesTool(registration, registry) {
8689
8728
  type: "object",
8690
8729
  properties: {}
8691
8730
  },
8692
- ...registration.kind === "custom" && registry.provider !== "kimi" ? { strict: true } : {}
8731
+ ...registration.kind === "custom" ? { strict: true } : {}
8693
8732
  });
8694
8733
  return descriptor;
8695
8734
  }
@@ -9950,7 +9989,6 @@ async function handleResponsesViaMessages(c, options) {
9950
9989
  model: options.publicModel
9951
9990
  }, {
9952
9991
  model: options.targetModel,
9953
- provider: options.provider,
9954
9992
  publicModel: options.publicModel
9955
9993
  });
9956
9994
  const context = translation;
@@ -10026,7 +10064,6 @@ async function handleProviderResponsesForProvider(c, options) {
10026
10064
  normalizeProviderResponsesReasoningEffort(payload, providerConfig);
10027
10065
  if (shouldFallbackToMessages$1(c, payload.model, effectiveType)) return await handleResponsesViaMessages(c, {
10028
10066
  payload,
10029
- provider: providerConfig.name,
10030
10067
  publicModel: options.publicModel ?? payload.model,
10031
10068
  targetModel: `${provider}/${payload.model}`
10032
10069
  });
@@ -10526,4 +10563,4 @@ server.route("/:provider/images", providerImageRoutes);
10526
10563
  //#endregion
10527
10564
  export { server };
10528
10565
 
10529
- //# sourceMappingURL=server-DN95QRWA.js.map
10566
+ //# sourceMappingURL=server-ooE0nEgj.js.map