@nick3/copilot-api 1.5.9 → 1.6.1

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 (28) hide show
  1. package/README.md +33 -30
  2. package/README.zh-CN.md +953 -0
  3. package/dist/{account-CbYMFuS4.js → account-B2tSWtVS.js} +2 -2
  4. package/dist/{account-CbYMFuS4.js.map → account-B2tSWtVS.js.map} +1 -1
  5. package/dist/{accounts-manager-BKG9aZEL.js → accounts-manager-CAyZJSn8.js} +144 -111
  6. package/dist/accounts-manager-CAyZJSn8.js.map +1 -0
  7. package/dist/admin/assets/index-BESw8Vvd.css +1 -0
  8. package/dist/admin/assets/index-Ddo9RHg-.js +101 -0
  9. package/dist/admin/index.html +2 -2
  10. package/dist/{auth-Ckj1wD43.js → auth-BXCeDjRG.js} +3 -3
  11. package/dist/{auth-Ckj1wD43.js.map → auth-BXCeDjRG.js.map} +1 -1
  12. package/dist/{check-usage-bIbj_1Q_.js → check-usage-CQxXYfUx.js} +3 -3
  13. package/dist/{check-usage-bIbj_1Q_.js.map → check-usage-CQxXYfUx.js.map} +1 -1
  14. package/dist/{get-copilot-token-MAZsr5Vu.js → get-copilot-token-p17sJyPU.js} +2 -2
  15. package/dist/{get-copilot-token-MAZsr5Vu.js.map → get-copilot-token-p17sJyPU.js.map} +1 -1
  16. package/dist/main.js +3 -3
  17. package/dist/{poll-access-token-DiwBJNtK.js → poll-access-token-Bc6VwWab.js} +49 -9
  18. package/dist/poll-access-token-Bc6VwWab.js.map +1 -0
  19. package/dist/{server-DAxpfPde.js → server-BAlLdlCl.js} +112 -61
  20. package/dist/server-BAlLdlCl.js.map +1 -0
  21. package/dist/{start-8dkfsQqd.js → start-eFWi3mS4.js} +6 -6
  22. package/dist/{start-8dkfsQqd.js.map → start-eFWi3mS4.js.map} +1 -1
  23. package/package.json +1 -1
  24. package/dist/accounts-manager-BKG9aZEL.js.map +0 -1
  25. package/dist/admin/assets/index-BFN8rXmt.css +0 -1
  26. package/dist/admin/assets/index-HnEqzcKv.js +0 -101
  27. package/dist/poll-access-token-DiwBJNtK.js.map +0 -1
  28. package/dist/server-DAxpfPde.js.map +0 -1
@@ -1,8 +1,8 @@
1
- import { A as requestContext, D as prepareMessageProxyHeaders, E as prepareInteractionHeaders, O as accountFromState, T as prepareForCompact, _ as HTTPError, b as copilotHeaders, c as getUUID, d as parseUserIdMetadata, f as resolveAffinityKey, g as getCopilotUsage, h as getDeviceCode, j as resolveTraceId, k as state, l as isNullish, m as getGitHubUser, o as generateRequestIdFromPayload, p as sleep, s as getRootSessionId, t as pollAccessToken, u as normalizeStableSessionId, v as forwardError, w as normalizeDomain, y as copilotBaseUrl } from "./poll-access-token-DiwBJNtK.js";
2
- import { _ as DEFAULT_IDENTITY_ENTERPRISE_DOMAIN, a as getAccountClientIdentityByLoginAndApp, b as getCurrentIdentityEnvironment, d as loadRegistry, g as saveRegistry, h as saveAccountToken, l as listAccountsFromRegistry, m as removeAccountToken, p as removeAccountFromRegistry, r as addAccountToRegistry, t as isAccountType } from "./account-CbYMFuS4.js";
1
+ import { A as captureOutboundHeadersSnapshot, D as prepareMessageProxyHeaders, E as prepareInteractionHeaders, M as requestContext, N as resolveTraceId, O as accountFromState, T as prepareForCompact, _ as HTTPError, b as copilotHeaders, c as getUUID, d as parseUserIdMetadata, f as resolveAffinityKey, g as getCopilotUsage, h as getDeviceCode, k as state, l as isNullish, m as getGitHubUser, o as generateRequestIdFromPayload, p as sleep, s as getRootSessionId, t as pollAccessToken, u as normalizeStableSessionId, v as forwardError, w as normalizeDomain, y as copilotBaseUrl } from "./poll-access-token-Bc6VwWab.js";
2
+ import { _ as DEFAULT_IDENTITY_ENTERPRISE_DOMAIN, a as getAccountClientIdentityByLoginAndApp, b as getCurrentIdentityEnvironment, d as loadRegistry, g as saveRegistry, h as saveAccountToken, l as listAccountsFromRegistry, m as removeAccountToken, p as removeAccountFromRegistry, r as addAccountToRegistry, t as isAccountType } from "./account-B2tSWtVS.js";
3
3
  import { r as ensurePaths, t as PATHS } from "./paths-DGlr310R.js";
4
- import "./get-copilot-token-MAZsr5Vu.js";
5
- import { A as isResponsesApiWebSearchEnabled, C as getReasoningEffortForModel, D as isMessageStartInputTokensFallbackEnabled, E as isForceAgentEnabled, M as resolveModelAlias, N as shouldCompactUseSmallModel, O as isMessagesApiEnabled, S as getProviderConfig, T as isAccountAffinityEnabled, _ as getExtraPromptForModel, a as getClientIpInfo, b as getModelAliasesInfo, c as normalizeChatCompletionsUsage, d as toLocalDateString, f as PROVIDER_TYPE_ANTHROPIC, g as getConfig, h as getClaudeTokenMultiplier, i as extractResponsesUsageFromStreamEvent, j as mergeConfigWithDefaults, k as isResponsesApiContextManagementModel, l as normalizeEmbeddingsUsage, m as getAnthropicApiKey, n as applySharedSessionAffinityRetention, o as getRequestHistoryStore, p as getAliasTargetSet, r as extractResponsesUsageFromResult, s as getStatsStore, t as accountsManager, u as normalizeMessagesUsage, v as getLogLevel, w as getSmallModel, x as getModelRefreshIntervalMs, y as getModelAliases } from "./accounts-manager-BKG9aZEL.js";
4
+ import "./get-copilot-token-p17sJyPU.js";
5
+ import { A as isResponsesApiWebSearchEnabled, C as getReasoningEffortForModel, D as isMessageStartInputTokensFallbackEnabled, E as isForceAgentEnabled, M as resolveModelAlias, N as shouldCompactUseSmallModel, O as isMessagesApiEnabled, S as getProviderConfig, T as isAccountAffinityEnabled, _ as getExtraPromptForModel, a as getClientIpInfo, b as getModelAliasesInfo, c as normalizeChatCompletionsUsage, d as toLocalDateString, f as PROVIDER_TYPE_ANTHROPIC, g as getConfig, h as getClaudeTokenMultiplier, i as extractResponsesUsageFromStreamEvent, j as mergeConfigWithDefaults, k as isResponsesApiContextManagementModel, l as normalizeEmbeddingsUsage, m as getAnthropicApiKey, n as applySharedSessionAffinityRetention, o as getRequestHistoryStore, p as getAliasTargetSet, r as extractResponsesUsageFromResult, s as getStatsStore, t as accountsManager, u as normalizeMessagesUsage, v as getLogLevel, w as getSmallModel, x as getModelRefreshIntervalMs, y as getModelAliases } from "./accounts-manager-CAyZJSn8.js";
6
6
  import consola from "consola";
7
7
  import fs, { readFile } from "node:fs/promises";
8
8
  import { randomUUID, timingSafeEqual } from "node:crypto";
@@ -1181,18 +1181,16 @@ adminApiRoutes.get("/stats/premium-daily", (c) => {
1181
1181
  const granularity = p.get("granularity") === "hour" ? "hour" : "day";
1182
1182
  const now = /* @__PURE__ */ new Date();
1183
1183
  const todayStr = toLocalDateString(now.getTime());
1184
- const resolvedFrom = from || toLocalDateString(now.getTime() - 10080 * 60 * 1e3);
1184
+ const resolvedFrom = from || toLocalDateString(new Date(now.getFullYear(), now.getMonth(), now.getDate() - 6).getTime());
1185
1185
  const resolvedTo = to || todayStr;
1186
1186
  function parseLocalDate(dateStr) {
1187
1187
  const [y, m, d] = dateStr.split("-").map(Number);
1188
1188
  return new Date(y, m - 1, d);
1189
1189
  }
1190
- if (granularity === "hour") {
1191
- const fromDate = parseLocalDate(resolvedFrom);
1192
- if (parseLocalDate(resolvedTo).getTime() - fromDate.getTime() + 1440 * 60 * 1e3 > 2880 * 60 * 1e3) return jsonError(c, 400, {
1193
- message: "Hourly granularity is only supported for ranges up to 48 hours.",
1194
- type: "bad_request"
1195
- });
1190
+ /** DST-safe end-of-day: next local midnight minus 1 ms. */
1191
+ function localDateEndMs(dateStr) {
1192
+ const [y, m, d] = dateStr.split("-").map(Number);
1193
+ return new Date(y, m - 1, d + 1).getTime() - 1;
1196
1194
  }
1197
1195
  const statsStore = getStatsStore();
1198
1196
  if (!statsStore) return c.json({
@@ -1205,8 +1203,21 @@ adminApiRoutes.get("/stats/premium-daily", (c) => {
1205
1203
  }
1206
1204
  });
1207
1205
  if (granularity === "hour") {
1208
- const fromMs = parseLocalDate(resolvedFrom).getTime();
1209
- const toMs = parseLocalDate(resolvedTo).getTime() + 86399999;
1206
+ const clientFromMs = parseFiniteNumber(p.get("from_ms"));
1207
+ const clientToMs = parseFiniteNumber(p.get("to_ms"));
1208
+ let fromMs;
1209
+ let toMs;
1210
+ if (clientFromMs !== void 0 && clientToMs !== void 0) {
1211
+ fromMs = clientFromMs;
1212
+ toMs = clientToMs;
1213
+ } else {
1214
+ fromMs = parseLocalDate(resolvedFrom).getTime();
1215
+ toMs = localDateEndMs(resolvedTo);
1216
+ }
1217
+ if (toMs - fromMs > 840 * 60 * 60 * 1e3) return jsonError(c, 400, {
1218
+ message: "Hourly granularity is only supported for ranges up to 35 days.",
1219
+ type: "bad_request"
1220
+ });
1210
1221
  const result$1 = statsStore.getHourlyPremiumStats({
1211
1222
  fromMs,
1212
1223
  toMs,
@@ -2453,7 +2464,7 @@ const createChatCompletions = async (payload, account, options) => {
2453
2464
  if (!ctx.copilotToken) throw new Error("Copilot token not found");
2454
2465
  const enableVision = payload.messages.some((x) => typeof x.content !== "string" && x.content?.some((x$1) => x$1.type === "image_url"));
2455
2466
  const effectiveInitiator = resolveEffectiveInitiator(options?.initiator ?? getChatInitiator(payload.messages), {
2456
- isCompact: options?.isCompact,
2467
+ isCompact: Boolean(options?.compactType),
2457
2468
  isSubagent: Boolean(options?.subagentMarker)
2458
2469
  });
2459
2470
  const headers = {
@@ -2462,7 +2473,8 @@ const createChatCompletions = async (payload, account, options) => {
2462
2473
  };
2463
2474
  prepareInteractionHeaders(options?.sessionId, Boolean(options?.subagentMarker), headers);
2464
2475
  const upstreamPayload = applyDefaultReasoningEffort(payload);
2465
- prepareForCompact(headers, options?.isCompact);
2476
+ prepareForCompact(headers, options?.compactType);
2477
+ captureOutboundHeadersSnapshot(headers);
2466
2478
  const response = await fetch(`${copilotBaseUrl(ctx)}/chat/completions`, {
2467
2479
  method: "POST",
2468
2480
  headers,
@@ -3056,9 +3068,11 @@ completionRoutes.post("/", async (c) => {
3056
3068
  const createEmbeddings = async (payload, account) => {
3057
3069
  const ctx = account ?? accountFromState();
3058
3070
  if (!ctx.copilotToken) throw new Error("Copilot token not found");
3071
+ const headers = copilotHeaders(ctx);
3072
+ captureOutboundHeadersSnapshot(headers);
3059
3073
  const response = await fetch(`${copilotBaseUrl(ctx)}/embeddings`, {
3060
3074
  method: "POST",
3061
- headers: copilotHeaders(ctx),
3075
+ headers,
3062
3076
  body: JSON.stringify(payload)
3063
3077
  });
3064
3078
  if (!response.ok) throw new HTTPError("Failed to create embeddings", response);
@@ -3268,18 +3282,23 @@ const _normalizeSdkModelId = (sdkModelId) => {
3268
3282
  };
3269
3283
 
3270
3284
  //#endregion
3271
- //#region src/routes/messages/preprocess.ts
3285
+ //#region src/lib/compact.ts
3286
+ const COMPACT_REQUEST = 1;
3287
+ const COMPACT_AUTO_CONTINUE = 2;
3272
3288
  const compactSystemPromptStart = "You are a helpful AI assistant tasked with summarizing conversations";
3273
3289
  const compactTextOnlyGuard = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.";
3274
3290
  const compactSummaryPromptStart = "Your task is to create a detailed summary of the conversation so far";
3291
+ const compactAutoContinueClaudeCodePromptStart = "This session is being continued from a previous conversation that ran out of context. The summary below covers the earlier portion of the conversation.";
3292
+ const compactAutoContinueOpenCodePromptStart = "Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed.";
3293
+ const compactAutoContinuePromptStarts = [compactAutoContinueClaudeCodePromptStart, compactAutoContinueOpenCodePromptStart];
3275
3294
  const compactMessageSections = ["Pending Tasks:", "Current Work:"];
3295
+
3296
+ //#endregion
3297
+ //#region src/routes/messages/preprocess.ts
3276
3298
  const TOOL_REFERENCE_TURN_BOUNDARY = "Tool loaded.";
3277
- const getAnthropicEffortForModel = (model) => {
3278
- const reasoningEffort = getReasoningEffortForModel(model);
3279
- if (reasoningEffort === "xhigh") return "max";
3280
- if (reasoningEffort === "none" || reasoningEffort === "minimal") return "low";
3281
- return reasoningEffort;
3282
- };
3299
+ const IDE_EXECUTE_CODE_TOOL = "mcp__ide__executeCode";
3300
+ const IDE_GET_DIAGNOSTICS_TOOL = "mcp__ide__getDiagnostics";
3301
+ const IDE_GET_DIAGNOSTICS_DESCRIPTION = "Get language diagnostics from VS Code. Returns errors, warnings, information, and hints for files in the workspace.";
3283
3302
  const getCompactCandidateText = (message) => {
3284
3303
  if (message.role !== "user") return "";
3285
3304
  if (typeof message.content === "string") return message.content;
@@ -3290,13 +3309,19 @@ const isCompactMessage = (lastMessage) => {
3290
3309
  if (!text) return false;
3291
3310
  return text.includes(compactTextOnlyGuard) && text.includes(compactSummaryPromptStart) && compactMessageSections.some((section) => text.includes(section));
3292
3311
  };
3293
- const isCompactRequest = (anthropicPayload) => {
3312
+ const isCompactAutoContinueMessage = (lastMessage) => {
3313
+ const text = getCompactCandidateText(lastMessage);
3314
+ return Boolean(text) && compactAutoContinuePromptStarts.some((promptStart) => text.startsWith(promptStart));
3315
+ };
3316
+ const getCompactType = (anthropicPayload) => {
3294
3317
  const lastMessage = anthropicPayload.messages.at(-1);
3295
- if (lastMessage && isCompactMessage(lastMessage)) return true;
3318
+ if (lastMessage && isCompactMessage(lastMessage)) return COMPACT_REQUEST;
3319
+ if (lastMessage && isCompactAutoContinueMessage(lastMessage)) return COMPACT_AUTO_CONTINUE;
3296
3320
  const system = anthropicPayload.system;
3297
- if (typeof system === "string") return system.startsWith(compactSystemPromptStart);
3298
- if (!Array.isArray(system)) return false;
3299
- return system.some((msg) => typeof msg.text === "string" && msg.text.startsWith(compactSystemPromptStart));
3321
+ if (typeof system === "string") return system.startsWith(compactSystemPromptStart) ? COMPACT_REQUEST : 0;
3322
+ if (!Array.isArray(system)) return 0;
3323
+ if (system.some((msg) => typeof msg.text === "string" && msg.text.startsWith(compactSystemPromptStart))) return COMPACT_REQUEST;
3324
+ return 0;
3300
3325
  };
3301
3326
  const mergeContentWithText = (tr, textBlock) => {
3302
3327
  if (typeof tr.content === "string") return {
@@ -3335,8 +3360,10 @@ const stripToolReferenceTurnBoundary = (anthropicPayload) => {
3335
3360
  msg.content = msg.content.filter((block) => block.type !== "text" || block.text.trim() !== TOOL_REFERENCE_TURN_BOUNDARY);
3336
3361
  }
3337
3362
  };
3338
- const mergeToolResultForClaude = (anthropicPayload) => {
3339
- for (const msg of anthropicPayload.messages) {
3363
+ const mergeToolResultForClaude = (anthropicPayload, options) => {
3364
+ const lastMessageIndex = anthropicPayload.messages.length - 1;
3365
+ for (const [index, msg] of anthropicPayload.messages.entries()) {
3366
+ if (options?.skipLastMessage && index === lastMessageIndex) continue;
3340
3367
  if (msg.role !== "user" || !Array.isArray(msg.content)) continue;
3341
3368
  const toolResults = [];
3342
3369
  const textBlocks = [];
@@ -3351,6 +3378,17 @@ const mergeToolResultForClaude = (anthropicPayload) => {
3351
3378
  msg.content = mergeToolResult(toolResults, textBlocks);
3352
3379
  }
3353
3380
  };
3381
+ const sanitizeIdeTools = (payload) => {
3382
+ if (!payload.tools || payload.tools.length === 0) return;
3383
+ payload.tools = payload.tools.flatMap((tool) => {
3384
+ if (tool.name === IDE_EXECUTE_CODE_TOOL) return [];
3385
+ if (tool.name === IDE_GET_DIAGNOSTICS_TOOL) return [{
3386
+ ...tool,
3387
+ description: IDE_GET_DIAGNOSTICS_DESCRIPTION
3388
+ }];
3389
+ return [tool];
3390
+ });
3391
+ };
3354
3392
  const hasToolRef = (block) => {
3355
3393
  return Array.isArray(block.content) && block.content.some((c) => c.type === "tool_reference");
3356
3394
  };
@@ -3389,11 +3427,18 @@ const filterAssistantThinkingBlocks = (payload) => {
3389
3427
  const prepareMessagesApiPayload = (payload, selectedModel) => {
3390
3428
  stripCacheControl(payload);
3391
3429
  filterAssistantThinkingBlocks(payload);
3430
+ const hasThinking = Boolean(payload.thinking);
3392
3431
  const toolChoice = payload.tool_choice;
3393
3432
  const disableThink = toolChoice?.type === "any" || toolChoice?.type === "tool";
3394
3433
  if (selectedModel?.capabilities.supports.adaptive_thinking && !disableThink) {
3395
3434
  payload.thinking = { type: "adaptive" };
3396
- payload.output_config = { effort: getAnthropicEffortForModel(payload.model) };
3435
+ if (!hasThinking) payload.thinking.display = "summarized";
3436
+ if (payload.model === "claude-opus-4.7") payload.thinking.display = "summarized";
3437
+ let effort = getReasoningEffortForModel(payload.model);
3438
+ if (effort === "none" || effort === "minimal") effort = "low";
3439
+ const reasoningEffort = selectedModel.capabilities.supports.reasoning_effort;
3440
+ if (reasoningEffort && !reasoningEffort.includes(effort)) effort = reasoningEffort.at(-1);
3441
+ payload.output_config = { effort };
3397
3442
  }
3398
3443
  };
3399
3444
 
@@ -3775,11 +3820,11 @@ async function handleCountTokens(c) {
3775
3820
 
3776
3821
  //#endregion
3777
3822
  //#region src/services/copilot/create-responses.ts
3778
- const createResponses = async (payload, { vision, initiator, upstreamRequestId, subagentMarker, sessionId, isCompact }, account) => {
3823
+ const createResponses = async (payload, { vision, initiator, upstreamRequestId, subagentMarker, sessionId, compactType }, account) => {
3779
3824
  const ctx = account ?? accountFromState();
3780
3825
  if (!ctx.copilotToken) throw new Error("Copilot token not found");
3781
3826
  const effectiveInitiator = resolveEffectiveInitiator(initiator, {
3782
- isCompact,
3827
+ isCompact: Boolean(compactType),
3783
3828
  isSubagent: Boolean(subagentMarker)
3784
3829
  });
3785
3830
  const headers = {
@@ -3787,8 +3832,9 @@ const createResponses = async (payload, { vision, initiator, upstreamRequestId,
3787
3832
  "x-initiator": effectiveInitiator
3788
3833
  };
3789
3834
  prepareInteractionHeaders(sessionId, Boolean(subagentMarker), headers);
3790
- prepareForCompact(headers, isCompact);
3835
+ prepareForCompact(headers, compactType);
3791
3836
  payload.service_tier = null;
3837
+ captureOutboundHeadersSnapshot(headers);
3792
3838
  const response = await fetch(`${copilotBaseUrl(ctx)}/responses`, {
3793
3839
  method: "POST",
3794
3840
  headers,
@@ -4774,18 +4820,18 @@ const getMessagesInitiator = (payload) => {
4774
4820
  return lastMessage.content.some((block) => block.type !== "tool_result") ? "user" : "agent";
4775
4821
  };
4776
4822
  const INTERLEAVED_THINKING_BETA = "interleaved-thinking-2025-05-14";
4823
+ const ADVANCED_TOOL_USE_BETA = "advanced-tool-use-2025-11-20";
4777
4824
  const allowedAnthropicBetas = new Set([
4778
4825
  INTERLEAVED_THINKING_BETA,
4779
4826
  "context-management-2025-06-27",
4780
- "advanced-tool-use-2025-11-20"
4827
+ ADVANCED_TOOL_USE_BETA
4781
4828
  ]);
4782
4829
  const buildAnthropicBetaHeader = (anthropicBetaHeader, thinking) => {
4783
4830
  const isAdaptiveThinking = thinking?.type === "adaptive";
4784
4831
  if (anthropicBetaHeader) {
4785
- const filteredBeta = anthropicBetaHeader.split(",").map((item) => item.trim()).filter((item) => item.length > 0).filter((item) => allowedAnthropicBetas.has(item));
4786
- const uniqueFilteredBetas = [...new Set(filteredBeta)];
4787
- const finalFilteredBetas = isAdaptiveThinking ? uniqueFilteredBetas.filter((item) => item !== INTERLEAVED_THINKING_BETA) : uniqueFilteredBetas;
4788
- if (finalFilteredBetas.length > 0) return finalFilteredBetas.join(",");
4832
+ const filteredBeta = anthropicBetaHeader.split(",").map((item) => item.trim()).filter((item) => item.length > 0).filter((item) => allowedAnthropicBetas.has(item)).filter((item) => !isAdaptiveThinking || item !== INTERLEAVED_THINKING_BETA);
4833
+ const uniqueFilteredBetas = [...new Set([ADVANCED_TOOL_USE_BETA, ...filteredBeta])];
4834
+ if (uniqueFilteredBetas.length > 0) return uniqueFilteredBetas.join(",");
4789
4835
  return;
4790
4836
  }
4791
4837
  if (thinking?.budget_tokens && !isAdaptiveThinking) return INTERLEAVED_THINKING_BETA;
@@ -4797,7 +4843,7 @@ const shouldUseMessageProxyHeaders = (payload) => {
4797
4843
  };
4798
4844
  const buildMessagesHeaders = ({ ctx, enableVision, initiator, options, payload }) => {
4799
4845
  const effectiveInitiator = resolveEffectiveInitiator(initiator, {
4800
- isCompact: options?.isCompact,
4846
+ isCompact: Boolean(options?.compactType),
4801
4847
  isSubagent: Boolean(options?.subagentMarker)
4802
4848
  });
4803
4849
  const headers = {
@@ -4805,7 +4851,7 @@ const buildMessagesHeaders = ({ ctx, enableVision, initiator, options, payload }
4805
4851
  "x-initiator": effectiveInitiator
4806
4852
  };
4807
4853
  prepareInteractionHeaders(options?.sessionId, Boolean(options?.subagentMarker), headers);
4808
- prepareForCompact(headers, options?.isCompact);
4854
+ prepareForCompact(headers, options?.compactType);
4809
4855
  if (shouldUseMessageProxyHeaders(payload)) prepareMessageProxyHeaders(headers);
4810
4856
  const anthropicBeta = buildAnthropicBetaHeader(options?.anthropicBetaHeader, payload.thinking);
4811
4857
  if (anthropicBeta) headers["anthropic-beta"] = anthropicBeta;
@@ -4821,6 +4867,7 @@ const createMessages = async (payload, account, options) => {
4821
4867
  options,
4822
4868
  payload
4823
4869
  });
4870
+ captureOutboundHeadersSnapshot(headers);
4824
4871
  const response = await fetch(`${copilotBaseUrl(ctx)}/v1/messages`, {
4825
4872
  method: "POST",
4826
4873
  headers,
@@ -5092,8 +5139,11 @@ function closeThinkingBlockIfOpen(state$1, events$1) {
5092
5139
  }
5093
5140
 
5094
5141
  //#endregion
5095
- //#region src/routes/messages/subagent-marker.ts
5142
+ //#region src/lib/subagent.ts
5096
5143
  const subagentMarkerPrefix = "__SUBAGENT_MARKER__";
5144
+
5145
+ //#endregion
5146
+ //#region src/routes/messages/subagent-marker.ts
5097
5147
  const subagentStartContextPrefix = "SubagentStart hook additional context:";
5098
5148
  const REMINDER_RE = /<system-reminder>([\s\S]*?)<\/system-reminder>/g;
5099
5149
  const NONE_INSPECTION = {
@@ -5127,7 +5177,7 @@ const extractMarkerPayloadFromReminderLine = (line) => {
5127
5177
  let markerLine = trimmedLine;
5128
5178
  if (markerLine.startsWith(subagentStartContextPrefix)) markerLine = markerLine.slice(38).trimStart();
5129
5179
  if (!markerLine.startsWith(subagentMarkerPrefix)) return null;
5130
- return markerLine.slice(19).trimStart();
5180
+ return markerLine.slice(subagentMarkerPrefix.length).trimStart();
5131
5181
  };
5132
5182
  const inspectSubagentMarkerFromSystemReminder = (text) => {
5133
5183
  let sawInvalidMarker = false;
@@ -5213,6 +5263,7 @@ async function handleCompletion(c) {
5213
5263
  const { ip: clientIp, source: clientIpSource } = getClientIpInfo(c);
5214
5264
  const userAgent = c.req.header("user-agent") ?? void 0;
5215
5265
  const anthropicPayload = await c.req.json();
5266
+ sanitizeIdeTools(anthropicPayload);
5216
5267
  debugJson(logger$5, "Anthropic request payload:", anthropicPayload);
5217
5268
  const markerInspection = inspectSubagentMarkerFromFirstUser(anthropicPayload);
5218
5269
  const subagentMarker = markerInspection.kind === "valid" ? markerInspection.marker : null;
@@ -5224,13 +5275,13 @@ async function handleCompletion(c) {
5224
5275
  const ownershipLookupSessionId = markerInspection.kind === "valid" ? normalizeStableSessionId(markerInspection.marker.session_id) : void 0;
5225
5276
  const ownershipWriteSessionId = markerInspection.kind === "none" ? sessionId : void 0;
5226
5277
  const anthropicBeta = c.req.header("anthropic-beta");
5227
- const isCompact = isCompactRequest(anthropicPayload);
5278
+ const compactType = getCompactType(anthropicPayload);
5279
+ const isCompact = compactType !== 0;
5228
5280
  const originalRequestModel = anthropicPayload.model;
5229
5281
  if (anthropicBeta && isWarmupProbeRequest(anthropicPayload)) anthropicPayload.model = getSmallModel();
5230
- if (isCompact) {
5231
- logger$5.debug("Is compact request:", isCompact);
5232
- if (shouldCompactUseSmallModel()) anthropicPayload.model = getSmallModel();
5233
- } else {
5282
+ if (compactType !== 0) logger$5.debug("Compact request type:", compactType);
5283
+ if (compactType === COMPACT_REQUEST && shouldCompactUseSmallModel()) anthropicPayload.model = getSmallModel();
5284
+ if (compactType === 0) {
5234
5285
  stripToolReferenceTurnBoundary(anthropicPayload);
5235
5286
  mergeToolResultForClaude(anthropicPayload);
5236
5287
  }
@@ -5362,7 +5413,7 @@ async function handleCompletion(c) {
5362
5413
  sessionId,
5363
5414
  instr,
5364
5415
  selectedModel,
5365
- isCompact
5416
+ compactType
5366
5417
  });
5367
5418
  if (endpoint === RESPONSES_ENDPOINT$1) return await handleWithResponsesApi({
5368
5419
  c,
@@ -5372,7 +5423,7 @@ async function handleCompletion(c) {
5372
5423
  sessionId,
5373
5424
  selectedModel,
5374
5425
  instr,
5375
- isCompact
5426
+ compactType
5376
5427
  });
5377
5428
  return await handleWithChatCompletions({
5378
5429
  c,
@@ -5381,15 +5432,15 @@ async function handleCompletion(c) {
5381
5432
  sessionId,
5382
5433
  selectedModel,
5383
5434
  instr,
5384
- isCompact
5435
+ compactType
5385
5436
  });
5386
5437
  }
5387
5438
  const handleWithChatCompletions = async (params) => {
5388
- const { c, openAIPayload, subagentMarker, sessionId, selectedModel, instr, isCompact } = params;
5439
+ const { c, openAIPayload, subagentMarker, sessionId, selectedModel, instr, compactType } = params;
5389
5440
  debugJson(logger$5, "Translated OpenAI request payload:", openAIPayload);
5390
5441
  const ctx = toAccountContext(instr.account);
5391
5442
  const effectiveInitiator = resolveEffectiveInitiator(getChatInitiator(openAIPayload.messages), {
5392
- isCompact,
5443
+ isCompact: compactType !== 0,
5393
5444
  isSubagent: Boolean(subagentMarker)
5394
5445
  });
5395
5446
  instr.initiator = effectiveInitiator;
@@ -5400,7 +5451,7 @@ const handleWithChatCompletions = async (params) => {
5400
5451
  initiator: effectiveInitiator,
5401
5452
  subagentMarker,
5402
5453
  sessionId,
5403
- isCompact
5454
+ compactType
5404
5455
  });
5405
5456
  instr.confirmAffinity?.();
5406
5457
  instr.confirmOwnership?.();
@@ -5433,14 +5484,14 @@ const handleWithChatCompletions = async (params) => {
5433
5484
  }));
5434
5485
  };
5435
5486
  const handleWithResponsesApi = async (params) => {
5436
- const { c, anthropicPayload, openAIPayload, subagentMarker, sessionId, selectedModel, instr, isCompact } = params;
5487
+ const { c, anthropicPayload, openAIPayload, subagentMarker, sessionId, selectedModel, instr, compactType } = params;
5437
5488
  const responsesPayload = translateAnthropicMessagesToResponsesPayload(anthropicPayload, selectedModel.id);
5438
5489
  applyResponsesApiContextManagement(responsesPayload, selectedModel.capabilities.limits.max_prompt_tokens);
5439
5490
  compactInputByLatestCompaction(responsesPayload);
5440
5491
  debugJson(logger$5, "Translated Responses payload:", responsesPayload);
5441
5492
  const { vision, initiator } = getResponsesRequestOptions(responsesPayload);
5442
5493
  const effectiveInitiator = resolveEffectiveInitiator(initiator, {
5443
- isCompact,
5494
+ isCompact: compactType !== 0,
5444
5495
  isSubagent: Boolean(subagentMarker)
5445
5496
  });
5446
5497
  const ctx = toAccountContext(instr.account);
@@ -5453,7 +5504,7 @@ const handleWithResponsesApi = async (params) => {
5453
5504
  upstreamRequestId: instr.upstreamRequestId,
5454
5505
  subagentMarker,
5455
5506
  sessionId,
5456
- isCompact
5507
+ compactType
5457
5508
  }, ctx);
5458
5509
  instr.confirmAffinity?.();
5459
5510
  instr.confirmOwnership?.();
@@ -5946,12 +5997,12 @@ async function streamMessagesAndLog(params) {
5946
5997
  }
5947
5998
  }
5948
5999
  const handleWithMessagesApi = async (params) => {
5949
- const { c, anthropicPayload, anthropicBetaHeader, subagentMarker, sessionId, instr, selectedModel, isCompact } = params;
6000
+ const { c, anthropicPayload, anthropicBetaHeader, subagentMarker, sessionId, instr, selectedModel, compactType } = params;
5950
6001
  prepareMessagesApiPayload(anthropicPayload, selectedModel);
5951
6002
  debugJson(logger$5, "Translated Messages payload:", anthropicPayload);
5952
6003
  const ctx = toAccountContext(instr.account);
5953
6004
  const effectiveInitiator = resolveEffectiveInitiator(getMessagesInitiator(anthropicPayload), {
5954
- isCompact,
6005
+ isCompact: compactType !== 0,
5955
6006
  isSubagent: Boolean(subagentMarker)
5956
6007
  });
5957
6008
  instr.initiator = effectiveInitiator;
@@ -5963,7 +6014,7 @@ const handleWithMessagesApi = async (params) => {
5963
6014
  initiator: effectiveInitiator,
5964
6015
  subagentMarker,
5965
6016
  sessionId,
5966
- isCompact
6017
+ compactType
5967
6018
  });
5968
6019
  instr.confirmAffinity?.();
5969
6020
  instr.confirmOwnership?.();
@@ -6866,4 +6917,4 @@ server.route("/:provider/v1/models", providerModelRoutes);
6866
6917
 
6867
6918
  //#endregion
6868
6919
  export { server };
6869
- //# sourceMappingURL=server-DAxpfPde.js.map
6920
+ //# sourceMappingURL=server-BAlLdlCl.js.map