dsh-github-copilot 0.4.0-alpha.40 → 0.4.0-alpha.42

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.
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { A as GITHUB_COPILOT_PREVIEW_PROVIDER_ID, C as currentSearchInitiator, D as isPluginPreviewProvider, E as readSettingsNamespace, O as readCopilotCatalog, S as currentChatRoute, T as onSettingsNamespaceUpdated, _ as RESPONSES_WEB_SEARCH_TOOL_TYPE, a as COPILOT_HOSTED_SEARCH_PROVIDER_ID, b as candidatesForRoute, c as abortable$1, d as readBounded, f as applyRequestAuth, h as ANTHROPIC_WEB_SEARCH_TOOL_TYPE, i as describeSearchBackend, j as GITHUB_COPILOT_PROVIDER_ID, k as GITHUB_COPILOT_CREDENTIAL_KEY, l as isAbortError, m as providerRequestHeaders, n as routeSessionSearch, o as GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID, p as normalizeRequestAuth, r as DescribedSearchFallbackError, s as createTraditionalSearchProvider, t as isCopilotSearchSelection, u as providerErrorMessage, v as SearchPlan, w as currentSearchSelection, x as sameCandidates, y as WEB_SEARCH_TOOL_TYPE } from "./search-routing-C1o895V6.js";
1
+ import { A as GITHUB_COPILOT_CREDENTIAL_KEY, C as currentSearchInitiator, D as isPluginPreviewProvider, E as readSettingsNamespace, M as GITHUB_COPILOT_PROVIDER_ID, O as readCopilotCatalog, S as currentChatRoute, T as onSettingsNamespaceUpdated, _ as RESPONSES_WEB_SEARCH_TOOL_TYPE, a as COPILOT_HOSTED_SEARCH_PROVIDER_ID, b as candidatesForRoute, c as abortable$1, d as readBounded, f as applyRequestAuth, h as ANTHROPIC_WEB_SEARCH_TOOL_TYPE, i as describeSearchBackend, j as GITHUB_COPILOT_PREVIEW_PROVIDER_ID, k as GITHUB_COPILOT_AUTO_MODEL_ID, l as isAbortError, m as providerRequestHeaders, n as routeSessionSearch, o as GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID, p as normalizeRequestAuth, r as DescribedSearchFallbackError, s as createTraditionalSearchProvider, t as isCopilotSearchSelection, u as providerErrorMessage, v as SearchPlan, w as currentSearchSelection, x as sameCandidates, y as WEB_SEARCH_TOOL_TYPE } from "./search-routing-D5tmOCvH.js";
2
2
  import AuthorizationService from "@deepseek-ai/dsh-authorization";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import * as dshScope from "@deepseek-ai/dsh-scope";
@@ -9,7 +9,7 @@ import { createModels, getSupportedThinkingLevels, hasApi, lazyStream } from "@e
9
9
  import { githubCopilotProvider } from "@earendil-works/pi-ai/providers/github-copilot";
10
10
  import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
11
11
  import * as dshLlm from "@deepseek-ai/dsh-llm";
12
- import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, ReasoningEffortId, attributionHeaders, callConfigEquals, contentHasImage, isAgentLoopRequest, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
12
+ import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, ReasoningEffortId, attributionHeaders, boundContextSummary, callConfigEquals, contentHasImage, createUserMessage, isAgentLoopRequest, resolveImageAttachmentAccess, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
13
13
  import { WebError } from "@deepseek-ai/dsh-web";
14
14
  import * as dshSettings from "@deepseek-ai/dsh-settings";
15
15
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
@@ -1300,16 +1300,16 @@ var UsageFailure = class extends Error {
1300
1300
  this.diagnostic = diagnostic;
1301
1301
  }
1302
1302
  };
1303
- function failure$2(diagnostic) {
1303
+ function failure$3(diagnostic) {
1304
1304
  throw new UsageFailure(diagnostic);
1305
1305
  }
1306
1306
  async function readBody(response, signal) {
1307
1307
  const length = response.headers.get("content-length");
1308
1308
  if (length !== null && (!/^\d+$/u.test(length) || Number(length) > MAX_BODY_BYTES)) {
1309
1309
  response.body?.cancel().catch(() => void 0);
1310
- failure$2("COPILOT_USAGE_BODY_TOO_LARGE");
1310
+ failure$3("COPILOT_USAGE_BODY_TOO_LARGE");
1311
1311
  }
1312
- if (!response.body) failure$2("COPILOT_USAGE_INVALID_RESPONSE");
1312
+ if (!response.body) failure$3("COPILOT_USAGE_INVALID_RESPONSE");
1313
1313
  const reader = response.body.getReader(), chunks = [];
1314
1314
  const cancel = () => {
1315
1315
  reader.cancel().catch(() => void 0);
@@ -1324,7 +1324,7 @@ async function readBody(response, signal) {
1324
1324
  size += next.value.byteLength;
1325
1325
  if (size > MAX_BODY_BYTES) {
1326
1326
  reader.cancel().catch(() => void 0);
1327
- failure$2("COPILOT_USAGE_BODY_TOO_LARGE");
1327
+ failure$3("COPILOT_USAGE_BODY_TOO_LARGE");
1328
1328
  }
1329
1329
  chunks.push(next.value);
1330
1330
  }
@@ -1341,7 +1341,7 @@ async function readBody(response, signal) {
1341
1341
  try {
1342
1342
  return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1343
1343
  } catch {
1344
- failure$2("COPILOT_USAGE_INVALID_RESPONSE");
1344
+ failure$3("COPILOT_USAGE_INVALID_RESPONSE");
1345
1345
  }
1346
1346
  }
1347
1347
  /** One Host-owned, memory-only account cache. No auth renewal, persistence or model transport. */
@@ -1383,8 +1383,8 @@ var CopilotUsageSource = class {
1383
1383
  return this.load(true);
1384
1384
  }
1385
1385
  active(generation) {
1386
- if (this.disposed) failure$2("COPILOT_USAGE_DISPOSED");
1387
- if (generation !== this.generation) failure$2("COPILOT_USAGE_ACCOUNT_CHANGED");
1386
+ if (this.disposed) failure$3("COPILOT_USAGE_DISPOSED");
1387
+ if (generation !== this.generation) failure$3("COPILOT_USAGE_ACCOUNT_CHANGED");
1388
1388
  }
1389
1389
  async readAuth(generation) {
1390
1390
  this.active(generation);
@@ -1393,24 +1393,24 @@ var CopilotUsageSource = class {
1393
1393
  stored = await this.dependencies.readCredential();
1394
1394
  } catch {
1395
1395
  this.active(generation);
1396
- failure$2("COPILOT_USAGE_CREDENTIALS_UNAVAILABLE");
1396
+ failure$3("COPILOT_USAGE_CREDENTIALS_UNAVAILABLE");
1397
1397
  }
1398
1398
  this.active(generation);
1399
- if (stored === void 0) failure$2("COPILOT_USAGE_SIGNED_OUT");
1399
+ if (stored === void 0) failure$3("COPILOT_USAGE_SIGNED_OUT");
1400
1400
  let grant;
1401
1401
  try {
1402
1402
  grant = normalizeGitHubCopilotOAuthCredential(stored);
1403
1403
  } catch {
1404
- failure$2("COPILOT_USAGE_INVALID_GRANT");
1404
+ failure$3("COPILOT_USAGE_INVALID_GRANT");
1405
1405
  }
1406
- if (grant.enterpriseUrl !== void 0) failure$2("COPILOT_USAGE_ENTERPRISE_UNSUPPORTED");
1406
+ if (grant.enterpriseUrl !== void 0) failure$3("COPILOT_USAGE_ENTERPRISE_UNSUPPORTED");
1407
1407
  return {
1408
1408
  grant,
1409
1409
  key: copilotAccountKey(grant)
1410
1410
  };
1411
1411
  }
1412
1412
  async assertCurrent(key, generation) {
1413
- if ((await this.readAuth(generation)).key !== key) failure$2("COPILOT_USAGE_ACCOUNT_CHANGED");
1413
+ if ((await this.readAuth(generation)).key !== key) failure$3("COPILOT_USAGE_ACCOUNT_CHANGED");
1414
1414
  }
1415
1415
  diagnostic(error) {
1416
1416
  return error instanceof UsageFailure ? error.diagnostic : "COPILOT_USAGE_NETWORK";
@@ -1466,13 +1466,13 @@ var CopilotUsageSource = class {
1466
1466
  });
1467
1467
  if (response.redirected || response.status >= 300 && response.status < 400) {
1468
1468
  response.body?.cancel().catch(() => void 0);
1469
- failure$2("COPILOT_USAGE_REDIRECT");
1469
+ failure$3("COPILOT_USAGE_REDIRECT");
1470
1470
  }
1471
1471
  if (!response.ok) {
1472
1472
  response.body?.cancel().catch(() => void 0);
1473
- if (response.status === 401 || response.status === 403) failure$2("COPILOT_USAGE_AUTH_REJECTED");
1474
- if (response.status === 429) failure$2("COPILOT_USAGE_RATE_LIMITED");
1475
- failure$2("COPILOT_USAGE_HTTP_ERROR");
1473
+ if (response.status === 401 || response.status === 403) failure$3("COPILOT_USAGE_AUTH_REJECTED");
1474
+ if (response.status === 429) failure$3("COPILOT_USAGE_RATE_LIMITED");
1475
+ failure$3("COPILOT_USAGE_HTTP_ERROR");
1476
1476
  }
1477
1477
  return readBody(response, abort.signal);
1478
1478
  }
@@ -1602,7 +1602,7 @@ let GitHubCopilotUsageController = (() => {
1602
1602
  //#endregion
1603
1603
  //#region package.json
1604
1604
  var name$1 = "dsh-github-copilot";
1605
- var version = "0.4.0-alpha.40";
1605
+ var version = "0.4.0-alpha.42";
1606
1606
  //#endregion
1607
1607
  //#region lib/types/probe.js
1608
1608
  /**
@@ -1931,7 +1931,7 @@ function resolveRequestBudgetPolicy(config = {}) {
1931
1931
  compactionReasoning
1932
1932
  });
1933
1933
  }
1934
- function failure$1(code, message) {
1934
+ function failure$2(code, message) {
1935
1935
  return Object.freeze({
1936
1936
  ok: false,
1937
1937
  code,
@@ -1947,14 +1947,14 @@ function positiveInteger$1(value) {
1947
1947
  */
1948
1948
  function calculateRequestBudget(limits, requestedMaxTokens, policy = DEFAULT_REQUEST_BUDGET_POLICY) {
1949
1949
  const { contextWindow, maxInputTokens, maxTokens } = limits;
1950
- if (!positiveInteger$1(contextWindow) || !positiveInteger$1(maxTokens) || maxInputTokens !== void 0 && !positiveInteger$1(maxInputTokens)) return failure$1("COPILOT_REQUEST_INVALID_LIMITS", "model token capacities must be positive safe integers");
1951
- if (requestedMaxTokens !== void 0 && !positiveInteger$1(requestedMaxTokens)) return failure$1("COPILOT_REQUEST_INVALID_OUTPUT_LIMIT", "request output cap must be a positive safe integer");
1950
+ if (!positiveInteger$1(contextWindow) || !positiveInteger$1(maxTokens) || maxInputTokens !== void 0 && !positiveInteger$1(maxInputTokens)) return failure$2("COPILOT_REQUEST_INVALID_LIMITS", "model token capacities must be positive safe integers");
1951
+ if (requestedMaxTokens !== void 0 && !positiveInteger$1(requestedMaxTokens)) return failure$2("COPILOT_REQUEST_INVALID_OUTPUT_LIMIT", "request output cap must be a positive safe integer");
1952
1952
  const outputReservation = requestedMaxTokens ?? maxTokens;
1953
- if (outputReservation > maxTokens) return failure$1("COPILOT_REQUEST_OUTPUT_LIMIT_EXCEEDED", `request output cap ${outputReservation} exceeds model output capacity ${maxTokens}`);
1953
+ if (outputReservation > maxTokens) return failure$2("COPILOT_REQUEST_OUTPUT_LIMIT_EXCEEDED", `request output cap ${outputReservation} exceeds model output capacity ${maxTokens}`);
1954
1954
  const contextInputLimit = contextWindow - outputReservation;
1955
1955
  const limitingFactor = maxInputTokens !== void 0 && maxInputTokens <= contextInputLimit ? "prompt" : "context";
1956
1956
  const hardInputLimit = Math.min(maxInputTokens ?? contextInputLimit, contextInputLimit) - policy.safetyTokens;
1957
- if (hardInputLimit <= 0) return failure$1("COPILOT_REQUEST_NO_INPUT_HEADROOM", "output reservation and safety allowance leave no positive input budget");
1957
+ if (hardInputLimit <= 0) return failure$2("COPILOT_REQUEST_NO_INPUT_HEADROOM", "output reservation and safety allowance leave no positive input budget");
1958
1958
  return Object.freeze({
1959
1959
  ok: true,
1960
1960
  budget: Object.freeze({
@@ -1974,10 +1974,10 @@ function calculateRequestBudget(limits, requestedMaxTokens, policy = DEFAULT_REQ
1974
1974
  * Auxiliary and agentless calls use hard admission, including compaction itself.
1975
1975
  */
1976
1976
  function assessRequestBudget(estimatedInput, budget, pressure = false) {
1977
- if (!Number.isFinite(estimatedInput) || estimatedInput < 0 || estimatedInput > Number.MAX_SAFE_INTEGER) return failure$1("COPILOT_REQUEST_INVALID_ESTIMATE", "estimated input must be finite, non-negative, and safely representable");
1977
+ if (!Number.isFinite(estimatedInput) || estimatedInput < 0 || estimatedInput > Number.MAX_SAFE_INTEGER) return failure$2("COPILOT_REQUEST_INVALID_ESTIMATE", "estimated input must be finite, non-negative, and safely representable");
1978
1978
  const input = Math.ceil(estimatedInput);
1979
- if (input > budget.hardInputLimit) return failure$1(budget.limitingFactor === "prompt" ? "COPILOT_REQUEST_INPUT_LIMIT_EXCEEDED" : "COPILOT_REQUEST_CONTEXT_LIMIT_EXCEEDED", `estimated input ${input} exceeds input budget ${budget.hardInputLimit} with output reservation ${budget.outputReservation}`);
1980
- if (pressure && input > budget.pressureInputLimit) return failure$1("COPILOT_REQUEST_PRESSURE_EXCEEDED", `estimated input ${input} exceeds proactive compaction budget ${budget.pressureInputLimit}`);
1979
+ if (input > budget.hardInputLimit) return failure$2(budget.limitingFactor === "prompt" ? "COPILOT_REQUEST_INPUT_LIMIT_EXCEEDED" : "COPILOT_REQUEST_CONTEXT_LIMIT_EXCEEDED", `estimated input ${input} exceeds input budget ${budget.hardInputLimit} with output reservation ${budget.outputReservation}`);
1980
+ if (pressure && input > budget.pressureInputLimit) return failure$2("COPILOT_REQUEST_PRESSURE_EXCEEDED", `estimated input ${input} exceeds proactive compaction budget ${budget.pressureInputLimit}`);
1981
1981
  return Object.freeze({ ok: true });
1982
1982
  }
1983
1983
  /**
@@ -2674,7 +2674,7 @@ function buildAnthropicWireBody(request, cfg, model) {
2674
2674
  }
2675
2675
  //#endregion
2676
2676
  //#region lib/types/responses-reasoning-text.js
2677
- function record$1(value) {
2677
+ function record$3(value) {
2678
2678
  return typeof value === "object" && value !== null;
2679
2679
  }
2680
2680
  function responseIndex(value) {
@@ -2732,13 +2732,13 @@ var ResponsesReasoningText = class {
2732
2732
  }
2733
2733
  /** Only recognized public text fields are examined; no copying of the item. */
2734
2734
  snapshot(item) {
2735
- if (!record$1(item) || item.type !== "reasoning") return "";
2735
+ if (!record$3(item) || item.type !== "reasoning") return "";
2736
2736
  let delta = "";
2737
2737
  for (const family of ["summary", "raw"]) {
2738
2738
  const value = family === "summary" ? item.summary : item.content;
2739
2739
  if (!Array.isArray(value)) continue;
2740
2740
  for (const [index, part] of value.entries()) {
2741
- if (!record$1(part) || part.type !== (family === "summary" ? "summary_text" : "reasoning_text")) continue;
2741
+ if (!record$3(part) || part.type !== (family === "summary" ? "summary_text" : "reasoning_text")) continue;
2742
2742
  delta += this.update(family, index, part.text, true);
2743
2743
  }
2744
2744
  }
@@ -5352,7 +5352,7 @@ var Budget = class {
5352
5352
  if (this.consumed > ACCOUNT_MODEL_CATALOG_LIMITS.maxBytes) fail("CATALOG_TOO_LARGE", true);
5353
5353
  }
5354
5354
  };
5355
- function record(value, code) {
5355
+ function record$2(value, code) {
5356
5356
  if (typeof value !== "object" || value === null || Array.isArray(value)) fail(code);
5357
5357
  return value;
5358
5358
  }
@@ -5402,11 +5402,11 @@ function normalizeModel(raw, id, options, budget) {
5402
5402
  if (options.availableModelIds?.has(id) !== true) fail("MISSING_POLICY");
5403
5403
  policySource = "account-available-id";
5404
5404
  } else {
5405
- if (text(field(record(rawPolicy, "INVALID_POLICY"), "state", budget), 64, "INVALID_POLICY", budget) !== "enabled") fail("POLICY_NOT_ENABLED");
5405
+ if (text(field(record$2(rawPolicy, "INVALID_POLICY"), "state", budget), 64, "INVALID_POLICY", budget) !== "enabled") fail("POLICY_NOT_ENABLED");
5406
5406
  policySource = "server-enabled";
5407
5407
  }
5408
- const capabilities = record(field(raw, "capabilities", budget), "INVALID_CAPABILITIES");
5409
- const supports = record(field(capabilities, "supports", budget), "INVALID_SUPPORTS");
5408
+ const capabilities = record$2(field(raw, "capabilities", budget), "INVALID_CAPABILITIES");
5409
+ const supports = record$2(field(capabilities, "supports", budget), "INVALID_SUPPORTS");
5410
5410
  const streaming = field(supports, "streaming", budget);
5411
5411
  if (streaming === false) fail("STREAMING_UNSUPPORTED");
5412
5412
  if (streaming !== true) fail("INVALID_SUPPORTS");
@@ -5427,7 +5427,7 @@ function normalizeModel(raw, id, options, budget) {
5427
5427
  if (selected === void 0) fail(unsupportedEndpointCount === 0 && endpoints.includes("ws:/responses") ? "WEBSOCKET_ONLY" : "UNSUPPORTED_ENDPOINTS");
5428
5428
  const rawLimits = field(capabilities, "limits", budget);
5429
5429
  if (rawLimits === void 0) fail("MISSING_LIMITS");
5430
- const limits = record(rawLimits, "INVALID_LIMITS");
5430
+ const limits = record$2(rawLimits, "INVALID_LIMITS");
5431
5431
  const maxContext = optionalPositive(limits, "max_context_window_tokens", "INVALID_LIMITS", budget);
5432
5432
  const maxInputTokens = optionalPositive(limits, "max_prompt_tokens", "INVALID_LIMITS", budget);
5433
5433
  if (maxContext === void 0 && maxInputTokens === void 0) fail("MISSING_CONTEXT_LIMIT");
@@ -5445,7 +5445,7 @@ function normalizeModel(raw, id, options, budget) {
5445
5445
  if (vision === true) {
5446
5446
  const rawVisionLimits = field(limits, "vision", budget);
5447
5447
  if (rawVisionLimits !== void 0) {
5448
- const rawMediaTypes = field(record(rawVisionLimits, "INVALID_VISION_LIMITS"), "supported_media_types", budget);
5448
+ const rawMediaTypes = field(record$2(rawVisionLimits, "INVALID_VISION_LIMITS"), "supported_media_types", budget);
5449
5449
  if (rawMediaTypes !== void 0) {
5450
5450
  const mediaTypes = stringList(rawMediaTypes, ACCOUNT_MODEL_CATALOG_LIMITS.maxMediaTypes, 128, "INVALID_VISION_LIMITS", budget);
5451
5451
  const mime = /^[a-z0-9][a-z0-9!#$%&'*+.^_`|~-]*\/[a-z0-9][a-z0-9!#$%&'*+.^_`|~-]*$/iu;
@@ -5505,7 +5505,7 @@ function normalizeAccountModelCatalog(raw, options = {}) {
5505
5505
  fail("INVALID_JSON", true);
5506
5506
  }
5507
5507
  }
5508
- const data = field(record(raw, "INVALID_CATALOG"), "data", budget);
5508
+ const data = field(record$2(raw, "INVALID_CATALOG"), "data", budget);
5509
5509
  if (!Array.isArray(data)) fail("INVALID_CATALOG");
5510
5510
  const count = field(data, "length", budget);
5511
5511
  if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) fail("INVALID_CATALOG");
@@ -5528,7 +5528,7 @@ function normalizeAccountModelCatalog(raw, options = {}) {
5528
5528
  for (let index = 0; index < count; index++) {
5529
5529
  let id;
5530
5530
  try {
5531
- const candidate = record(field(data, String(index), budget), "INVALID_MODEL");
5531
+ const candidate = record$2(field(data, String(index), budget), "INVALID_MODEL");
5532
5532
  const candidateId = text(field(candidate, "id", budget), ACCOUNT_MODEL_CATALOG_LIMITS.maxIdLength, "INVALID_ID", budget);
5533
5533
  if (!identifier.test(candidateId)) fail("INVALID_ID");
5534
5534
  id = candidateId;
@@ -6071,6 +6071,234 @@ function installCopilotCompactionPressure(ctx, callbacks) {
6071
6071
  }, { prepend: true });
6072
6072
  }
6073
6073
  //#endregion
6074
+ //#region lib/types/auto-model-routing.js
6075
+ var AutoModelRoutingError = class extends Error {
6076
+ code;
6077
+ constructor(code) {
6078
+ super(code);
6079
+ this.code = code;
6080
+ this.name = "AutoModelRoutingError";
6081
+ }
6082
+ };
6083
+ const effortOrder = /* @__PURE__ */ new Map([
6084
+ ["off", 0],
6085
+ ["minimal", 1],
6086
+ ["low", 2],
6087
+ ["medium", 3],
6088
+ ["high", 4],
6089
+ ["xhigh", 5],
6090
+ ["max", 6]
6091
+ ]);
6092
+ function record$1(value) {
6093
+ return typeof value === "object" && value !== null;
6094
+ }
6095
+ function userMessage(value) {
6096
+ if (!record$1(value)) return false;
6097
+ if (value.role === "user") return true;
6098
+ return record$1(value.source) && value.source.kind === "user";
6099
+ }
6100
+ function latestUserContent(messages) {
6101
+ for (let index = messages.length - 1; index >= 0; index--) {
6102
+ const message = messages[index];
6103
+ if (userMessage(message) && Array.isArray(message.content)) return message.content;
6104
+ }
6105
+ return [];
6106
+ }
6107
+ function classifyAutoModelTurn(messages) {
6108
+ let text = "";
6109
+ let requiresImage = false;
6110
+ for (const block of latestUserContent(messages)) {
6111
+ if (!record$1(block)) continue;
6112
+ if (block.type === "text" && typeof block.text === "string") text += `${block.text}\n`;
6113
+ if (block.type === "image") requiresImage = true;
6114
+ }
6115
+ const codeFenceCount = text.match(/```/gu)?.length ?? 0;
6116
+ const textLength = text.trim().length;
6117
+ return Object.freeze({
6118
+ taskClass: requiresImage ? "balanced" : textLength <= 600 && codeFenceCount <= 2 ? "fast" : textLength > 4e3 || codeFenceCount >= 4 ? "strong" : "balanced",
6119
+ textLength,
6120
+ codeFenceCount,
6121
+ requiresImage
6122
+ });
6123
+ }
6124
+ function maximumEffort(model) {
6125
+ let rank = -1;
6126
+ for (const effort of model.reasoning.advertisedEfforts) rank = Math.max(rank, effortOrder.get(effort) ?? -1);
6127
+ return rank;
6128
+ }
6129
+ function compareCapacity(left, right) {
6130
+ return maximumEffort(left) - maximumEffort(right) || left.contextWindow - right.contextWindow || left.maxTokens - right.maxTokens || left.id.localeCompare(right.id, "en");
6131
+ }
6132
+ function reasonFor(features) {
6133
+ if (features.requiresImage) return "image-capability";
6134
+ if (features.taskClass === "fast") return "short-text-turn";
6135
+ if (features.taskClass === "strong") return "large-structured-turn";
6136
+ return "standard-turn";
6137
+ }
6138
+ /**
6139
+ * MVP policy: filter only by account-verified hard capabilities, then choose a
6140
+ * deterministic capacity tier. Capacity is not a quality, latency or price claim.
6141
+ */
6142
+ function selectAutoModel(models, messages) {
6143
+ const features = classifyAutoModelTurn(messages);
6144
+ const eligible = models.filter((model) => model.id !== "auto" && model.input.includes("text") && (!features.requiresImage || model.input.includes("image"))).toSorted(compareCapacity);
6145
+ if (eligible.length === 0) throw new AutoModelRoutingError("COPILOT_AUTO_NO_ELIGIBLE_MODEL");
6146
+ const index = features.taskClass === "fast" ? 0 : features.taskClass === "strong" ? eligible.length - 1 : Math.floor((eligible.length - 1) / 2);
6147
+ return Object.freeze({
6148
+ model: eligible[index],
6149
+ taskClass: features.taskClass,
6150
+ reason: reasonFor(features),
6151
+ candidateCount: eligible.length
6152
+ });
6153
+ }
6154
+ function autoModelInputModalities(models) {
6155
+ return models.filter((model) => model.id !== "auto" && model.input.includes("text")).some((model) => model.input.includes("image")) ? ["text", "image"] : ["text"];
6156
+ }
6157
+ //#endregion
6158
+ //#region lib/types/auto-model-host.js
6159
+ function failure$1(code) {
6160
+ return new LlmError(code, "INVALID_REQUEST");
6161
+ }
6162
+ async function decide(dependencies, signal, messages) {
6163
+ try {
6164
+ return selectAutoModel(await dependencies.loadModels(signal), messages);
6165
+ } catch (cause) {
6166
+ if (cause instanceof AutoModelRoutingError) throw failure$1(cause.code);
6167
+ throw cause;
6168
+ }
6169
+ }
6170
+ function record(value) {
6171
+ return typeof value === "object" && value !== null;
6172
+ }
6173
+ function autoIntent(ctx, agent) {
6174
+ const candidate = ctx.get("sessionProjections");
6175
+ if (!record(candidate) || typeof candidate.stateOf !== "function") return false;
6176
+ try {
6177
+ const state = candidate.stateOf(agent.session, "modelSelection");
6178
+ if (!record(state) || !record(state.pending)) return false;
6179
+ return state.pending.provider === "github-copilot-preview" && state.pending.model === "auto";
6180
+ } catch {
6181
+ return false;
6182
+ }
6183
+ }
6184
+ function modelSelectionNotice(value) {
6185
+ return record(value) && record(value.source) && value.source.kind === "model-selection";
6186
+ }
6187
+ function routeLabel(provider, model, otherProvider) {
6188
+ return provider === otherProvider ? model : `${provider}/${model}`;
6189
+ }
6190
+ function actualNotice(agent, model) {
6191
+ const previous = agent.session.requestHeader()?.config;
6192
+ if (previous === void 0 || previous.provider === "github-copilot-preview" && previous.model === model) return;
6193
+ const from = routeLabel(previous.provider, previous.model, GITHUB_COPILOT_PREVIEW_PROVIDER_ID);
6194
+ const to = routeLabel(GITHUB_COPILOT_PREVIEW_PROVIDER_ID, model, previous.provider);
6195
+ return createUserMessage({
6196
+ content: [{
6197
+ type: "text",
6198
+ text: `[model changed: assistant turns above this point were generated by ${from}; the session continues with ${to}]`
6199
+ }],
6200
+ source: {
6201
+ kind: "model-selection",
6202
+ form: "notice",
6203
+ summary: boundContextSummary(`${from} → ${to}`)
6204
+ }
6205
+ });
6206
+ }
6207
+ function appendAutoModelDecision(agent, event) {
6208
+ Reflect.apply(agent.session.append, agent.session, ["github-copilot/auto-model-decision", event]);
6209
+ }
6210
+ /** Resolve virtual Auto once per Core turn before request/header persistence. */
6211
+ function installAutoModelRouting(ctx, dependencies) {
6212
+ const captured = /* @__PURE__ */ new WeakMap();
6213
+ const routed = /* @__PURE__ */ new WeakMap();
6214
+ const agentDisposers = /* @__PURE__ */ new WeakMap();
6215
+ const activeDisposers = /* @__PURE__ */ new Set();
6216
+ const installAgent = (agent) => {
6217
+ if (agentDisposers.has(agent)) return;
6218
+ const dispose = agent.ctx.on("agent/pre-step", async ({ messages, turn, step, signal }, next) => {
6219
+ const result = await next();
6220
+ const entered = result.kind === "enter" ? result.messages : messages;
6221
+ captured.set(agent, {
6222
+ turn,
6223
+ messages: entered
6224
+ });
6225
+ if (result.kind !== "enter" || signal.aborted || !autoIntent(ctx, agent)) return result;
6226
+ let state = routed.get(agent);
6227
+ if (state?.turn !== turn) {
6228
+ state = {
6229
+ turn,
6230
+ decision: await decide(dependencies, signal, entered),
6231
+ recorded: false
6232
+ };
6233
+ routed.set(agent, state);
6234
+ }
6235
+ const filtered = result.messages.filter((message) => !modelSelectionNotice(message));
6236
+ const notice = actualNotice(agent, state.decision.model.id);
6237
+ return notice === void 0 ? {
6238
+ ...result,
6239
+ messages: filtered
6240
+ } : {
6241
+ ...result,
6242
+ messages: [...filtered, notice]
6243
+ };
6244
+ }, { prepend: true });
6245
+ agentDisposers.set(agent, dispose);
6246
+ activeDisposers.add(dispose);
6247
+ };
6248
+ const removeCreated = ctx.on("agent/created", ({ agent }) => {
6249
+ installAgent(agent);
6250
+ });
6251
+ const removeDisposed = ctx.on("agent/disposed", ({ agent }) => {
6252
+ const dispose = agentDisposers.get(agent);
6253
+ dispose?.();
6254
+ if (dispose !== void 0) activeDisposers.delete(dispose);
6255
+ agentDisposers.delete(agent);
6256
+ captured.delete(agent);
6257
+ routed.delete(agent);
6258
+ });
6259
+ const removeRequest = ctx.on("agent/request", async ({ agent, turn, step, signal }, next) => {
6260
+ const resolved = await next();
6261
+ if (resolved.provider !== "github-copilot-preview" || resolved.model !== "auto") {
6262
+ routed.delete(agent);
6263
+ return resolved;
6264
+ }
6265
+ let state = routed.get(agent);
6266
+ if (state?.turn !== turn) {
6267
+ const input = captured.get(agent);
6268
+ if (input?.turn !== turn) throw failure$1("COPILOT_AUTO_TURN_CONTEXT_UNAVAILABLE");
6269
+ state = {
6270
+ turn,
6271
+ decision: await decide(dependencies, signal, input.messages),
6272
+ recorded: false
6273
+ };
6274
+ routed.set(agent, state);
6275
+ }
6276
+ if (!state.recorded) {
6277
+ appendAutoModelDecision(agent, {
6278
+ turn,
6279
+ step,
6280
+ provider: GITHUB_COPILOT_PREVIEW_PROVIDER_ID,
6281
+ model: state.decision.model.id,
6282
+ taskClass: state.decision.taskClass,
6283
+ reason: state.decision.reason,
6284
+ candidateCount: state.decision.candidateCount
6285
+ });
6286
+ state.recorded = true;
6287
+ }
6288
+ return {
6289
+ ...resolved,
6290
+ model: state.decision.model.id
6291
+ };
6292
+ }, { prepend: true });
6293
+ return () => {
6294
+ removeCreated();
6295
+ removeDisposed();
6296
+ removeRequest();
6297
+ for (const dispose of activeDisposers) dispose();
6298
+ activeDisposers.clear();
6299
+ };
6300
+ }
6301
+ //#endregion
6074
6302
  //#region lib/types/preview-route.js
6075
6303
  function failure(code, category = "AUTH") {
6076
6304
  return new LlmError(code, category);
@@ -6303,12 +6531,19 @@ var PreviewAdapter = class extends PiAiAdapter {
6303
6531
  if (grant === void 0 || snapshot.accountKey !== copilotAccountKey(grant)) return [];
6304
6532
  const proof = this.lifetime.proofFor(snapshot);
6305
6533
  if (proof === void 0 || tokenFingerprint(grant.access) !== proof.tokenFingerprint || grant.expires <= Date.now()) return [];
6306
- return snapshot.models.map((model) => ({
6534
+ const models = snapshot.models.filter((model) => model.id !== "auto" && model.input.includes("text"));
6535
+ if (models.length === 0) return [];
6536
+ return [{
6537
+ provider,
6538
+ id: GITHUB_COPILOT_AUTO_MODEL_ID,
6539
+ name: "Auto",
6540
+ inputModalities: [...autoModelInputModalities(models)]
6541
+ }, ...models.map((model) => ({
6307
6542
  provider,
6308
6543
  id: model.id,
6309
6544
  name: model.name,
6310
6545
  inputModalities: [...model.input]
6311
- }));
6546
+ }))];
6312
6547
  } catch {
6313
6548
  return [];
6314
6549
  }
@@ -6317,11 +6552,22 @@ var PreviewAdapter = class extends PiAiAdapter {
6317
6552
  owned(provider);
6318
6553
  const cached = this.lifetime.source.readSnapshot();
6319
6554
  const snapshot = await this.discoverSnapshot({ signal });
6555
+ if (model === "auto") {
6556
+ const models = snapshot.models.filter((candidate) => candidate.id !== "auto" && candidate.input.includes("text"));
6557
+ if (models.length === 0) throw failure("COPILOT_AUTO_NO_ELIGIBLE_MODEL", "UNKNOWN_MODEL");
6558
+ return {
6559
+ provider,
6560
+ id: model,
6561
+ name: "Auto",
6562
+ inputModalities: [...autoModelInputModalities(models)]
6563
+ };
6564
+ }
6320
6565
  const lease = await this.lease(snapshot, model, signal, cached === snapshot);
6321
6566
  return this.withRecovery(snapshot, signal, () => new PiAiAdapter(this.optionsFor(lease)).resolveModel(provider, model, signal));
6322
6567
  }
6323
6568
  async prepareCall(provider, model, signal) {
6324
6569
  owned(provider);
6570
+ if (model === "auto") throw failure("COPILOT_AUTO_ROUTE_UNRESOLVED", "INVALID_REQUEST");
6325
6571
  const cached = this.lifetime.source.readSnapshot();
6326
6572
  const snapshot = await this.discoverSnapshot({ signal });
6327
6573
  const lease = await this.lease(snapshot, model, signal, cached === snapshot);
@@ -6334,6 +6580,7 @@ var PreviewAdapter = class extends PiAiAdapter {
6334
6580
  const owner = this;
6335
6581
  return (async function* () {
6336
6582
  owned(options.provider);
6583
+ if (options.model === "auto") throw failure("COPILOT_AUTO_ROUTE_UNRESOLVED", "INVALID_REQUEST");
6337
6584
  const cached = owner.lifetime.source.readSnapshot();
6338
6585
  const snapshot = await owner.discoverSnapshot({ signal: options.signal });
6339
6586
  const lease = await owner.lease(snapshot, options.model, options.signal, cached === snapshot);
@@ -6669,6 +6916,9 @@ function apply$1(ctx, config = {}) {
6669
6916
  resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess(attachments, (hostPath) => ctx.get("fs")?.processPathFromHostPath(hostPath), ref)
6670
6917
  };
6671
6918
  };
6919
+ const removeAutoRoute = installAutoModelRouting(ctx, { async loadModels(signal) {
6920
+ return (await discoverSnapshot({ signal })).models;
6921
+ } });
6672
6922
  const registration = ctx.llm.registerAdapter([GITHUB_COPILOT_PREVIEW_PROVIDER_ID], new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings));
6673
6923
  installCopilotCompactionPressure(ctx, { resolve(request) {
6674
6924
  const snapshot = source.readSnapshot();
@@ -6743,6 +6993,7 @@ function apply$1(ctx, config = {}) {
6743
6993
  ctx.effect(() => () => {
6744
6994
  lifetime.dispose();
6745
6995
  removeListener();
6996
+ removeAutoRoute();
6746
6997
  registration();
6747
6998
  });
6748
6999
  refresh().catch(() => void 0);
package/lib/routed-web.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as currentSearchInitiator, D as isPluginPreviewProvider, t as isCopilotSearchSelection, w as currentSearchSelection } from "./search-routing-C1o895V6.js";
1
+ import { C as currentSearchInitiator, D as isPluginPreviewProvider, t as isCopilotSearchSelection, w as currentSearchSelection } from "./search-routing-D5tmOCvH.js";
2
2
  import { WebError, WebRuntime } from "@deepseek-ai/dsh-web";
3
3
  //#region lib/types/routed-web.js
4
4
  /**
@@ -7,6 +7,7 @@ import { WebError } from "@deepseek-ai/dsh-web";
7
7
  const GITHUB_COPILOT_CREDENTIAL_KEY$1 = "llm-pi-ai/github-copilot";
8
8
  const GITHUB_COPILOT_PROVIDER_ID = "github-copilot";
9
9
  const GITHUB_COPILOT_PREVIEW_PROVIDER_ID = "github-copilot-preview";
10
+ const GITHUB_COPILOT_AUTO_MODEL_ID = "auto";
10
11
  //#endregion
11
12
  //#region lib/types/model-protocol.js
12
13
  /** Project only public leaves and the same pi library's supported wire efforts. */
@@ -787,4 +788,4 @@ async function routeSessionSearch(request, signal, deps) {
787
788
  };
788
789
  }
789
790
  //#endregion
790
- export { GITHUB_COPILOT_PREVIEW_PROVIDER_ID as A, currentSearchInitiator as C, isPluginPreviewProvider as D, readSettingsNamespace as E, readCopilotCatalog as O, currentChatRoute as S, onSettingsNamespaceUpdated as T, RESPONSES_WEB_SEARCH_TOOL_TYPE as _, COPILOT_HOSTED_SEARCH_PROVIDER_ID as a, candidatesForRoute as b, abortable as c, readBounded as d, applyRequestAuth as f, GITHUB_COPILOT_CREDENTIAL_KEY as g, ANTHROPIC_WEB_SEARCH_TOOL_TYPE as h, describeSearchBackend as i, GITHUB_COPILOT_PROVIDER_ID as j, GITHUB_COPILOT_CREDENTIAL_KEY$1 as k, isAbortError as l, providerRequestHeaders as m, routeSessionSearch as n, GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID as o, normalizeRequestAuth as p, DescribedSearchFallbackError as r, createTraditionalSearchProvider as s, isCopilotSearchSelection as t, providerErrorMessage as u, SearchPlan as v, currentSearchSelection as w, sameCandidates as x, WEB_SEARCH_TOOL_TYPE as y };
791
+ export { GITHUB_COPILOT_CREDENTIAL_KEY$1 as A, currentSearchInitiator as C, isPluginPreviewProvider as D, readSettingsNamespace as E, GITHUB_COPILOT_PROVIDER_ID as M, readCopilotCatalog as O, currentChatRoute as S, onSettingsNamespaceUpdated as T, RESPONSES_WEB_SEARCH_TOOL_TYPE as _, COPILOT_HOSTED_SEARCH_PROVIDER_ID as a, candidatesForRoute as b, abortable as c, readBounded as d, applyRequestAuth as f, GITHUB_COPILOT_CREDENTIAL_KEY as g, ANTHROPIC_WEB_SEARCH_TOOL_TYPE as h, describeSearchBackend as i, GITHUB_COPILOT_PREVIEW_PROVIDER_ID as j, GITHUB_COPILOT_AUTO_MODEL_ID as k, isAbortError as l, providerRequestHeaders as m, routeSessionSearch as n, GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID as o, normalizeRequestAuth as p, DescribedSearchFallbackError as r, createTraditionalSearchProvider as s, isCopilotSearchSelection as t, providerErrorMessage as u, SearchPlan as v, currentSearchSelection as w, sameCandidates as x, WEB_SEARCH_TOOL_TYPE as y };
@@ -0,0 +1,8 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { AccountModelDescriptor } from './account-model-catalog.ts';
3
+ export interface AutoModelHostDependencies {
4
+ loadModels(signal: AbortSignal): Promise<readonly AccountModelDescriptor[]>;
5
+ }
6
+ /** Resolve virtual Auto once per Core turn before request/header persistence. */
7
+ export declare function installAutoModelRouting(ctx: Context, dependencies: AutoModelHostDependencies): () => void;
8
+ //# sourceMappingURL=auto-model-host.d.ts.map
@@ -0,0 +1,45 @@
1
+ export declare const AUTO_MODEL_ATTRIBUTION_KEY = "github-copilot-auto-model-attribution";
2
+ type Dispose = () => void;
3
+ export interface AutoModelAttribution {
4
+ readonly provider: string;
5
+ readonly model: string;
6
+ readonly taskClass: 'fast' | 'balanced' | 'strong';
7
+ readonly reason: 'short-text-turn' | 'standard-turn' | 'large-structured-turn' | 'image-capability';
8
+ readonly candidateCount: number;
9
+ }
10
+ interface AttributionState {
11
+ readonly turn: number;
12
+ readonly value: AutoModelAttribution;
13
+ }
14
+ interface Match {
15
+ readonly event: unknown;
16
+ }
17
+ interface Context {
18
+ readonly state?: AttributionState;
19
+ readonly matches: readonly Match[];
20
+ }
21
+ interface LocationData {
22
+ readonly kind: 'turn';
23
+ readonly turn: number;
24
+ readonly key: typeof AUTO_MODEL_ATTRIBUTION_KEY;
25
+ readonly value: AutoModelAttribution;
26
+ }
27
+ export declare const autoModelAttributionDefinition: {
28
+ kind: string;
29
+ match(event: unknown): {
30
+ id: string;
31
+ role: "start";
32
+ } | null;
33
+ start(_context: Context, match: Match): AttributionState;
34
+ update(context: Context & {
35
+ readonly state: AttributionState;
36
+ }): AttributionState;
37
+ buildLocationData(context: Context, scope: string, previous: LocationData | null): LocationData | null;
38
+ };
39
+ export declare function installAutoModelPresentation(capabilities: {
40
+ readonly slots: unknown;
41
+ readonly uiConversation: unknown;
42
+ readonly diagnostic: (code: string) => void;
43
+ }): Dispose;
44
+ export {};
45
+ //# sourceMappingURL=auto-model-presentation.d.ts.map
@@ -0,0 +1,26 @@
1
+ import type { AccountModelDescriptor } from './account-model-catalog.ts';
2
+ export type AutoModelClass = 'fast' | 'balanced' | 'strong';
3
+ export interface AutoModelFeatures {
4
+ readonly taskClass: AutoModelClass;
5
+ readonly textLength: number;
6
+ readonly codeFenceCount: number;
7
+ readonly requiresImage: boolean;
8
+ }
9
+ export interface AutoModelDecision {
10
+ readonly model: AccountModelDescriptor;
11
+ readonly taskClass: AutoModelClass;
12
+ readonly reason: 'short-text-turn' | 'standard-turn' | 'large-structured-turn' | 'image-capability';
13
+ readonly candidateCount: number;
14
+ }
15
+ export declare class AutoModelRoutingError extends Error {
16
+ readonly code: 'COPILOT_AUTO_NO_ELIGIBLE_MODEL';
17
+ constructor(code: 'COPILOT_AUTO_NO_ELIGIBLE_MODEL');
18
+ }
19
+ export declare function classifyAutoModelTurn(messages: readonly unknown[]): AutoModelFeatures;
20
+ /**
21
+ * MVP policy: filter only by account-verified hard capabilities, then choose a
22
+ * deterministic capacity tier. Capacity is not a quality, latency or price claim.
23
+ */
24
+ export declare function selectAutoModel(models: readonly AccountModelDescriptor[], messages: readonly unknown[]): AutoModelDecision;
25
+ export declare function autoModelInputModalities(models: readonly AccountModelDescriptor[]): readonly ('text' | 'image')[];
26
+ //# sourceMappingURL=auto-model-routing.d.ts.map
@@ -3,4 +3,5 @@ export declare const GITHUB_COPILOT_CREDENTIAL_KEY = "llm-pi-ai/github-copilot";
3
3
  export declare const GITHUB_COPILOT_PROVIDER_ID = "github-copilot";
4
4
  export declare const GITHUB_COPILOT_PREVIEW_PROVIDER_ID = "github-copilot-preview";
5
5
  export declare const GITHUB_COPILOT_PREVIEW_MODEL_ID = "gpt-6-astra";
6
+ export declare const GITHUB_COPILOT_AUTO_MODEL_ID = "auto";
6
7
  //# sourceMappingURL=copilot-identity.d.ts.map