dsh-github-copilot 0.4.0-alpha.66 → 0.4.0-alpha.69

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.
@@ -0,0 +1,15 @@
1
+ //#region lib/types/copilot-identity.js
2
+ /** Native OAuth ownership and the sole plugin-owned, account-discovered route. */
3
+ const GITHUB_COPILOT_CREDENTIAL_KEY = "llm-pi-ai/github-copilot";
4
+ const GITHUB_COPILOT_PROVIDER_ID = "github-copilot";
5
+ const GITHUB_COPILOT_PREVIEW_PROVIDER_ID = "github-copilot-preview";
6
+ const GITHUB_COPILOT_AUTO_MODEL_ID = "auto";
7
+ const GITHUB_COPILOT_AUTO_EFFICIENCY_MODEL_ID = "auto-efficiency";
8
+ const GITHUB_COPILOT_AUTO_INTELLIGENCE_MODEL_ID = "auto-intelligence";
9
+ function autoModelPreference(model) {
10
+ if (model === "auto") return "balance";
11
+ if (model === "auto-efficiency") return "efficiency";
12
+ if (model === "auto-intelligence") return "intelligence";
13
+ }
14
+ //#endregion
15
+ export { GITHUB_COPILOT_PREVIEW_PROVIDER_ID as a, GITHUB_COPILOT_CREDENTIAL_KEY as i, GITHUB_COPILOT_AUTO_INTELLIGENCE_MODEL_ID as n, GITHUB_COPILOT_PROVIDER_ID as o, GITHUB_COPILOT_AUTO_MODEL_ID as r, autoModelPreference as s, GITHUB_COPILOT_AUTO_EFFICIENCY_MODEL_ID as t };
package/lib/index.js CHANGED
@@ -1,4 +1,6 @@
1
- import { A as GITHUB_COPILOT_AUTO_EFFICIENCY_MODEL_ID, C as currentSearchInitiator, D as readSettingsNamespace, E as readConfigValue, F as GITHUB_COPILOT_PROVIDER_ID, I as autoModelPreference, M as GITHUB_COPILOT_AUTO_MODEL_ID, N as GITHUB_COPILOT_CREDENTIAL_KEY, O as isPluginPreviewProvider, P as GITHUB_COPILOT_PREVIEW_PROVIDER_ID, 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_AUTO_INTELLIGENCE_MODEL_ID, k as readCopilotCatalog, 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-BhrTbF-V.js";
1
+ import { a as GITHUB_COPILOT_PREVIEW_PROVIDER_ID, i as GITHUB_COPILOT_CREDENTIAL_KEY, n as GITHUB_COPILOT_AUTO_INTELLIGENCE_MODEL_ID, o as GITHUB_COPILOT_PROVIDER_ID, r as GITHUB_COPILOT_AUTO_MODEL_ID, s as autoModelPreference, t as GITHUB_COPILOT_AUTO_EFFICIENCY_MODEL_ID } from "./copilot-identity-DRZY_d2X.js";
2
+ import { C as currentSearchInitiator, D as readSettingsNamespace, E as readConfigValue, O as isPluginPreviewProvider, 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, k as readCopilotCatalog, 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-jzNYveyK.js";
3
+ import { a as selectCompactionReasoning, i as resolveRequestBudgetPolicy, n as assessRequestBudget, r as calculateRequestBudget, t as DEFAULT_REQUEST_BUDGET_POLICY } from "./request-budget-DLY_aRq0.js";
2
4
  import AuthorizationService from "@deepseek-ai/dsh-authorization";
3
5
  import { createHash, randomUUID } from "node:crypto";
4
6
  import * as dshScope from "@deepseek-ai/dsh-scope";
@@ -1309,7 +1311,7 @@ var UsageFailure = class extends Error {
1309
1311
  this.diagnostic = diagnostic;
1310
1312
  }
1311
1313
  };
1312
- function failure$3(diagnostic) {
1314
+ function failure$2(diagnostic) {
1313
1315
  throw new UsageFailure(diagnostic);
1314
1316
  }
1315
1317
  function certificateFailure(error) {
@@ -1321,9 +1323,9 @@ async function readBody(response, signal) {
1321
1323
  const length = response.headers.get("content-length");
1322
1324
  if (length !== null && (!/^\d+$/u.test(length) || Number(length) > MAX_BODY_BYTES)) {
1323
1325
  response.body?.cancel().catch(() => void 0);
1324
- failure$3("COPILOT_USAGE_BODY_TOO_LARGE");
1326
+ failure$2("COPILOT_USAGE_BODY_TOO_LARGE");
1325
1327
  }
1326
- if (!response.body) failure$3("COPILOT_USAGE_INVALID_RESPONSE");
1328
+ if (!response.body) failure$2("COPILOT_USAGE_INVALID_RESPONSE");
1327
1329
  const reader = response.body.getReader(), chunks = [];
1328
1330
  const cancel = () => {
1329
1331
  reader.cancel().catch(() => void 0);
@@ -1338,7 +1340,7 @@ async function readBody(response, signal) {
1338
1340
  size += next.value.byteLength;
1339
1341
  if (size > MAX_BODY_BYTES) {
1340
1342
  reader.cancel().catch(() => void 0);
1341
- failure$3("COPILOT_USAGE_BODY_TOO_LARGE");
1343
+ failure$2("COPILOT_USAGE_BODY_TOO_LARGE");
1342
1344
  }
1343
1345
  chunks.push(next.value);
1344
1346
  }
@@ -1355,7 +1357,7 @@ async function readBody(response, signal) {
1355
1357
  try {
1356
1358
  return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1357
1359
  } catch {
1358
- failure$3("COPILOT_USAGE_INVALID_RESPONSE");
1360
+ failure$2("COPILOT_USAGE_INVALID_RESPONSE");
1359
1361
  }
1360
1362
  }
1361
1363
  /** One Host-owned, memory-only account cache. No auth renewal, persistence or model transport. */
@@ -1401,8 +1403,8 @@ var CopilotUsageSource = class {
1401
1403
  return this.load(true);
1402
1404
  }
1403
1405
  active(generation) {
1404
- if (this.disposed) failure$3("COPILOT_USAGE_DISPOSED");
1405
- if (generation !== this.generation) failure$3("COPILOT_USAGE_ACCOUNT_CHANGED");
1406
+ if (this.disposed) failure$2("COPILOT_USAGE_DISPOSED");
1407
+ if (generation !== this.generation) failure$2("COPILOT_USAGE_ACCOUNT_CHANGED");
1406
1408
  }
1407
1409
  async readAuth(generation) {
1408
1410
  this.active(generation);
@@ -1411,24 +1413,24 @@ var CopilotUsageSource = class {
1411
1413
  stored = await this.dependencies.readCredential();
1412
1414
  } catch {
1413
1415
  this.active(generation);
1414
- failure$3("COPILOT_USAGE_CREDENTIALS_UNAVAILABLE");
1416
+ failure$2("COPILOT_USAGE_CREDENTIALS_UNAVAILABLE");
1415
1417
  }
1416
1418
  this.active(generation);
1417
- if (stored === void 0) failure$3("COPILOT_USAGE_SIGNED_OUT");
1419
+ if (stored === void 0) failure$2("COPILOT_USAGE_SIGNED_OUT");
1418
1420
  let grant;
1419
1421
  try {
1420
1422
  grant = normalizeGitHubCopilotOAuthCredential(stored);
1421
1423
  } catch {
1422
- failure$3("COPILOT_USAGE_INVALID_GRANT");
1424
+ failure$2("COPILOT_USAGE_INVALID_GRANT");
1423
1425
  }
1424
- if (grant.enterpriseUrl !== void 0) failure$3("COPILOT_USAGE_ENTERPRISE_UNSUPPORTED");
1426
+ if (grant.enterpriseUrl !== void 0) failure$2("COPILOT_USAGE_ENTERPRISE_UNSUPPORTED");
1425
1427
  return {
1426
1428
  grant,
1427
1429
  key: copilotAccountKey(grant)
1428
1430
  };
1429
1431
  }
1430
1432
  async assertCurrent(key, generation) {
1431
- if ((await this.readAuth(generation)).key !== key) failure$3("COPILOT_USAGE_ACCOUNT_CHANGED");
1433
+ if ((await this.readAuth(generation)).key !== key) failure$2("COPILOT_USAGE_ACCOUNT_CHANGED");
1432
1434
  }
1433
1435
  diagnostic(error) {
1434
1436
  return error instanceof UsageFailure ? error.diagnostic : "COPILOT_USAGE_NETWORK";
@@ -1439,16 +1441,16 @@ var CopilotUsageSource = class {
1439
1441
  const certificates = this.dependencies.getCACertificates ?? getCACertificates;
1440
1442
  const defaults = certificates("default");
1441
1443
  const system = certificates("system");
1442
- if (!Array.isArray(defaults) || !Array.isArray(system) || system.length === 0 || [...defaults, ...system].some((ca) => typeof ca !== "string" || ca.length === 0)) failure$3("COPILOT_USAGE_TRUST_UNAVAILABLE");
1444
+ if (!Array.isArray(defaults) || !Array.isArray(system) || system.length === 0 || [...defaults, ...system].some((ca) => typeof ca !== "string" || ca.length === 0)) failure$2("COPILOT_USAGE_TRUST_UNAVAILABLE");
1443
1445
  const ca = [.../* @__PURE__ */ new Set([...defaults, ...system])];
1444
1446
  this.dispatcher = (this.dependencies.createDispatcher ?? ((options) => new Agent(options)))({ connect: {
1445
1447
  ca,
1446
1448
  rejectUnauthorized: true
1447
1449
  } });
1448
- if (!this.dispatcher) failure$3("COPILOT_USAGE_TRUST_UNAVAILABLE");
1450
+ if (!this.dispatcher) failure$2("COPILOT_USAGE_TRUST_UNAVAILABLE");
1449
1451
  return this.dispatcher;
1450
1452
  } catch {
1451
- failure$3("COPILOT_USAGE_TRUST_UNAVAILABLE");
1453
+ failure$2("COPILOT_USAGE_TRUST_UNAVAILABLE");
1452
1454
  }
1453
1455
  }
1454
1456
  async load(force) {
@@ -1504,18 +1506,18 @@ var CopilotUsageSource = class {
1504
1506
  ...!this.dependencies.fetch && { dispatcher: this.quotaDispatcher() }
1505
1507
  });
1506
1508
  } catch (error) {
1507
- if (certificateFailure(error)) failure$3("COPILOT_USAGE_TLS");
1509
+ if (certificateFailure(error)) failure$2("COPILOT_USAGE_TLS");
1508
1510
  throw error;
1509
1511
  }
1510
1512
  if (response.redirected || response.status >= 300 && response.status < 400) {
1511
1513
  response.body?.cancel().catch(() => void 0);
1512
- failure$3("COPILOT_USAGE_REDIRECT");
1514
+ failure$2("COPILOT_USAGE_REDIRECT");
1513
1515
  }
1514
1516
  if (!response.ok) {
1515
1517
  response.body?.cancel().catch(() => void 0);
1516
- if (response.status === 401 || response.status === 403) failure$3("COPILOT_USAGE_AUTH_REJECTED");
1517
- if (response.status === 429) failure$3("COPILOT_USAGE_RATE_LIMITED");
1518
- failure$3("COPILOT_USAGE_HTTP_ERROR");
1518
+ if (response.status === 401 || response.status === 403) failure$2("COPILOT_USAGE_AUTH_REJECTED");
1519
+ if (response.status === 429) failure$2("COPILOT_USAGE_RATE_LIMITED");
1520
+ failure$2("COPILOT_USAGE_HTTP_ERROR");
1519
1521
  }
1520
1522
  return readBody(response, abort.signal);
1521
1523
  }
@@ -1646,7 +1648,7 @@ let GitHubCopilotUsageController = (() => {
1646
1648
  //#endregion
1647
1649
  //#region package.json
1648
1650
  var name$1 = "dsh-github-copilot";
1649
- var version = "0.4.0-alpha.66";
1651
+ var version = "0.4.0-alpha.69";
1650
1652
  //#endregion
1651
1653
  //#region lib/types/probe.js
1652
1654
  /**
@@ -1948,92 +1950,6 @@ async function probeAnthropic(candidate, apiKey, signal) {
1948
1950
  };
1949
1951
  }
1950
1952
  //#endregion
1951
- //#region lib/types/request-budget.js
1952
- /** The safety allowance matches the pinned native SDK; pressure is a separate opt-in check. */
1953
- const DEFAULT_REQUEST_BUDGET_POLICY = Object.freeze({
1954
- safetyTokens: 4096,
1955
- pressureRatio: .9,
1956
- compactionReasoning: "prefer-low"
1957
- });
1958
- /** Validate deployment policy before applying defaults; unknown keys fail rather than silently drift. */
1959
- function resolveRequestBudgetPolicy(config = {}) {
1960
- const keys = /* @__PURE__ */ new Set([
1961
- "safetyTokens",
1962
- "pressureRatio",
1963
- "compactionReasoning"
1964
- ]);
1965
- for (const key of Object.keys(config)) if (!keys.has(key)) throw new Error(`COPILOT_REQUEST_BUDGET_POLICY_INVALID: unknown setting ${key}`);
1966
- const safetyTokens = config.safetyTokens === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens : config.safetyTokens;
1967
- const pressureRatio = config.pressureRatio === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio : config.pressureRatio;
1968
- const compactionReasoning = config.compactionReasoning === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning : config.compactionReasoning;
1969
- if (!Number.isSafeInteger(safetyTokens) || safetyTokens < 0) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: safetyTokens must be a non-negative safe integer");
1970
- if (!Number.isFinite(pressureRatio) || pressureRatio <= 0 || pressureRatio > 1) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: pressureRatio must be greater than zero and at most one");
1971
- if (compactionReasoning !== "prefer-low" && compactionReasoning !== "preserve") throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: unsupported compactionReasoning");
1972
- return Object.freeze({
1973
- safetyTokens,
1974
- pressureRatio,
1975
- compactionReasoning
1976
- });
1977
- }
1978
- function failure$2(code, message) {
1979
- return Object.freeze({
1980
- ok: false,
1981
- code,
1982
- message: `${code}: ${message}`
1983
- });
1984
- }
1985
- function positiveInteger$1(value) {
1986
- return Number.isSafeInteger(value) && value > 0;
1987
- }
1988
- /**
1989
- * Reserve output under the combined context and independently enforce the prompt ceiling.
1990
- * `policy` must come from resolveRequestBudgetPolicy; no caller cap or catalog object is changed.
1991
- */
1992
- function calculateRequestBudget(limits, requestedMaxTokens, policy = DEFAULT_REQUEST_BUDGET_POLICY) {
1993
- const { contextWindow, maxInputTokens, maxTokens } = limits;
1994
- 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");
1995
- if (requestedMaxTokens !== void 0 && !positiveInteger$1(requestedMaxTokens)) return failure$2("COPILOT_REQUEST_INVALID_OUTPUT_LIMIT", "request output cap must be a positive safe integer");
1996
- const outputReservation = requestedMaxTokens ?? maxTokens;
1997
- if (outputReservation > maxTokens) return failure$2("COPILOT_REQUEST_OUTPUT_LIMIT_EXCEEDED", `request output cap ${outputReservation} exceeds model output capacity ${maxTokens}`);
1998
- const contextInputLimit = contextWindow - outputReservation;
1999
- const limitingFactor = maxInputTokens !== void 0 && maxInputTokens <= contextInputLimit ? "prompt" : "context";
2000
- const hardInputLimit = Math.min(maxInputTokens ?? contextInputLimit, contextInputLimit) - policy.safetyTokens;
2001
- if (hardInputLimit <= 0) return failure$2("COPILOT_REQUEST_NO_INPUT_HEADROOM", "output reservation and safety allowance leave no positive input budget");
2002
- return Object.freeze({
2003
- ok: true,
2004
- budget: Object.freeze({
2005
- contextWindow,
2006
- ...maxInputTokens === void 0 ? {} : { maxInputTokens },
2007
- maxOutputTokens: maxTokens,
2008
- outputReservation,
2009
- hardInputLimit,
2010
- pressureInputLimit: Math.floor(hardInputLimit * policy.pressureRatio),
2011
- limitingFactor
2012
- })
2013
- });
2014
- }
2015
- /**
2016
- * Check an estimated full prompt; estimates are not provider-exact token counts.
2017
- * Enable pressure only for an owned ordinary loop call with a compaction recovery path.
2018
- * Auxiliary and agentless calls use hard admission, including compaction itself.
2019
- */
2020
- function assessRequestBudget(estimatedInput, budget, pressure = false) {
2021
- 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");
2022
- const input = Math.ceil(estimatedInput);
2023
- 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}`);
2024
- if (pressure && input > budget.pressureInputLimit) return failure$2("COPILOT_REQUEST_PRESSURE_EXCEEDED", `estimated input ${input} exceeds proactive compaction budget ${budget.pressureInputLimit}`);
2025
- return Object.freeze({ ok: true });
2026
- }
2027
- /**
2028
- * Select a low-cost supported effort only for a caller-confirmed compaction request.
2029
- * A supplied effort, including a materialized provider default, wins unchanged; native validation
2030
- * remains authoritative. Unsupported low-cost controls preserve the provider default, never off/none.
2031
- */
2032
- function selectCompactionReasoning(supportedEfforts, requestedEffort, mode = DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning) {
2033
- if (requestedEffort !== void 0 || mode === "preserve") return requestedEffort;
2034
- return supportedEfforts.find((effort) => effort === "minimal") ?? supportedEfforts.find((effort) => effort === "low");
2035
- }
2036
- //#endregion
2037
1953
  //#region lib/types/search-routing-policy.js
2038
1954
  /** Resolve old and new settings without guessing registered providers or dropping unknown ids. */
2039
1955
  function normalizeWebSearchRouting(config) {
@@ -2076,6 +1992,7 @@ function readInlineConfig(config) {
2076
1992
  childSessionId: binding.childSessionId,
2077
1993
  parentSessionId: binding.parentSessionId
2078
1994
  })),
1995
+ followParentModel: readConfigValue(config.followParentModel),
2079
1996
  searchModel: readConfigValue(config.searchModel),
2080
1997
  searchRouting: readConfigValue(config.searchRouting),
2081
1998
  temporaryRouteBackup: readConfigValue(config.temporaryRouteBackup)
@@ -2095,10 +2012,11 @@ const Config = z.object({
2095
2012
  accountModelTtlMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(864e5),
2096
2013
  accountModelFailureCooldownMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(3e5),
2097
2014
  excludedModelIds: z.array(z.string()).default([]).hidden().volatile(),
2015
+ followParentModel: z.boolean().default(false).volatile(),
2098
2016
  parentModelFollow: z.array(z.object({
2099
2017
  childSessionId: z.string().min(1),
2100
2018
  parentSessionId: z.string().min(1)
2101
- })).default([]).volatile(),
2019
+ })).default([]).hidden().volatile(),
2102
2020
  requestBudgetSafetyTokens: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens),
2103
2021
  requestBudgetPressureRatio: z.number().step(.01).min(.01).max(1).default(DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio),
2104
2022
  compactionReasoning: z.union(["prefer-low", "preserve"]).default(DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning),
@@ -6808,16 +6726,20 @@ var ParentModelFollowError = class extends Error {
6808
6726
  this.name = "ParentModelFollowError";
6809
6727
  }
6810
6728
  };
6729
+ function supportsParentFollowing(subject) {
6730
+ return !subject.state.blocked && subject.state.descriptor && subject.origin === "subagent";
6731
+ }
6811
6732
  /** Resolve a new turn's intent without changing any Session, setting or descriptor. */
6812
- function resolveParentModel(child, bindings, lookup) {
6733
+ function resolveParentModel(child, bindings, lookup, followAll = false) {
6813
6734
  const matches = bindings.filter((binding) => binding.childSessionId === child.id);
6814
- if (matches.length === 0) return void 0;
6735
+ const automatic = matches.length === 0;
6736
+ if (automatic && (!followAll || !supportsParentFollowing(child))) return void 0;
6815
6737
  const fail = (code) => {
6816
6738
  throw new ParentModelFollowError(`COPILOT_PARENT_MODEL_${code}`);
6817
6739
  };
6818
- if (matches.length !== 1) fail("BINDING_INVALID");
6819
- if (child.state.blocked || !child.state.descriptor || child.origin !== "subagent") fail("CHILD_UNSUPPORTED");
6820
- if (!child.parentId || child.parentId !== matches[0]?.parentSessionId) fail("LINEAGE_INVALID");
6740
+ if (!automatic && matches.length !== 1) fail("BINDING_INVALID");
6741
+ if (!supportsParentFollowing(child)) fail("CHILD_UNSUPPORTED");
6742
+ if (!child.parentId || !automatic && child.parentId !== matches[0]?.parentSessionId) fail("LINEAGE_INVALID");
6821
6743
  if (child.state.explicit !== null) return void 0;
6822
6744
  const seen = /* @__PURE__ */ new Set([child.id]);
6823
6745
  let current = child;
@@ -6827,17 +6749,23 @@ function resolveParentModel(child, bindings, lookup) {
6827
6749
  seen.add(parentId);
6828
6750
  const parent = lookup(parentId);
6829
6751
  if (!parent) return fail("PARENT_UNAVAILABLE");
6830
- if (parent.state.blocked) fail("PARENT_UNSUPPORTED");
6752
+ if (parent.state.blocked) {
6753
+ if (automatic) return void 0;
6754
+ fail("PARENT_UNSUPPORTED");
6755
+ }
6831
6756
  const parentBindings = bindings.filter((binding) => binding.childSessionId === parent.id);
6832
6757
  if (parentBindings.length > 1) fail("BINDING_INVALID");
6833
- if (parentBindings.length === 1 && parent.state.explicit === null) {
6834
- if (!parent.state.descriptor || parent.origin !== "subagent" || parent.parentId !== parentBindings[0]?.parentSessionId) fail("LINEAGE_INVALID");
6758
+ if ((parentBindings.length === 1 || followAll && supportsParentFollowing(parent)) && parent.state.explicit === null) {
6759
+ if (!parent.state.descriptor || parent.origin !== "subagent" || parentBindings.length === 1 && parent.parentId !== parentBindings[0]?.parentSessionId) fail("LINEAGE_INVALID");
6835
6760
  current = parent;
6836
6761
  continue;
6837
6762
  }
6838
6763
  const selection = parent.pending ?? parent.recorded;
6839
6764
  if (!selection) return fail("SELECTION_UNAVAILABLE");
6840
- if (selection.provider !== "github-copilot-preview") fail("PROVIDER_UNSUPPORTED");
6765
+ if (selection.provider !== "github-copilot-preview") {
6766
+ if (automatic) return void 0;
6767
+ fail("PROVIDER_UNSUPPORTED");
6768
+ }
6841
6769
  return { ...selection };
6842
6770
  }
6843
6771
  }
@@ -6948,7 +6876,8 @@ function installAutoModelRouting(ctx, dependencies) {
6948
6876
  if (state.data.turn === previous.turn) return previous.selection;
6949
6877
  }
6950
6878
  const bindings = dependencies.parentModelBindings?.() ?? [];
6951
- if (!bindings.some((binding) => binding.childSessionId === agent.session.id)) return void 0;
6879
+ const followAll = dependencies.followParentModel?.() === true;
6880
+ if (!bindings.some((binding) => binding.childSessionId === agent.session.id) && (!followAll || agent.session.header.origin !== "subagent")) return void 0;
6952
6881
  const projections = ctx.get("sessionProjections");
6953
6882
  if (!record(projections) || typeof projections.register !== "function" || typeof projections.stateOf !== "function") throw failure$1("COPILOT_PARENT_MODEL_PROJECTIONS_UNAVAILABLE");
6954
6883
  const stateOf = projections.stateOf;
@@ -6998,7 +6927,7 @@ function installAutoModelRouting(ctx, dependencies) {
6998
6927
  const selection = resolveParentModel(child, bindings, (id) => {
6999
6928
  if (!record(agents) || typeof agents.get !== "function") return void 0;
7000
6929
  return readSubject(agents.get(id));
7001
- });
6930
+ }, followAll);
7002
6931
  followed.set(agent, {
7003
6932
  turn: child.state.turn,
7004
6933
  selection
@@ -7569,7 +7498,8 @@ var PreviewAdapter = class extends PiAiAdapter {
7569
7498
  throw requestFailure;
7570
7499
  }
7571
7500
  const fresh = context.messages.reduce((tokens, message) => tokens + estimateMessageTokens(message), 0);
7572
- const admitted = assessRequestBudget(Math.max(estimateContextTokens(context).tokens, fresh), calculated.budget);
7501
+ const estimate = Math.max(estimateContextTokens(context).tokens, fresh);
7502
+ const admitted = assessRequestBudget(estimate, calculated.budget);
7573
7503
  if (!admitted.ok) {
7574
7504
  requestFailure = budgetFailure(admitted);
7575
7505
  throw requestFailure;
@@ -7880,7 +7810,8 @@ function apply$1(ctx, config = {}) {
7880
7810
  return (await discoverSnapshot({ signal })).models.filter((model) => !excluded.has(model.id));
7881
7811
  },
7882
7812
  budgetPolicy: () => budgetSettings(),
7883
- parentModelBindings: () => cacheSettings().parentModelFollow ?? []
7813
+ parentModelBindings: () => cacheSettings().parentModelFollow ?? [],
7814
+ followParentModel: () => cacheSettings().followParentModel === true
7884
7815
  });
7885
7816
  const registration = ctx.llm.registerAdapter([GITHUB_COPILOT_PREVIEW_PROVIDER_ID], new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings));
7886
7817
  let exclusionSignature = JSON.stringify([...excludedModels()]);
@@ -7915,6 +7846,25 @@ function apply$1(ctx, config = {}) {
7915
7846
  ctx.provide("githubCopilotPreview", {
7916
7847
  getView,
7917
7848
  refresh,
7849
+ recoveryLimits(modelId) {
7850
+ const snapshot = source.readSnapshot();
7851
+ if (snapshot === void 0 || proofFor(snapshot) === void 0 || !getView().available || excludedModels().has(modelId)) return void 0;
7852
+ const descriptor = snapshot.models.find((model) => model.id === modelId);
7853
+ if (descriptor === void 0) return void 0;
7854
+ const revision = lifetime.revision;
7855
+ const proof = snapshotProof;
7856
+ return Object.freeze({
7857
+ limits: Object.freeze({
7858
+ contextWindow: descriptor.contextWindow,
7859
+ maxTokens: descriptor.maxTokens,
7860
+ ...descriptor.maxInputTokens === void 0 ? {} : { maxInputTokens: descriptor.maxInputTokens }
7861
+ }),
7862
+ policy: Object.freeze({ ...budgetSettings() }),
7863
+ assertCurrent: () => {
7864
+ if (!lifetime.isCurrent(revision) || snapshotProof !== proof || proofFor(snapshot) === void 0 || source.readSnapshot() !== snapshot || excludedModels().has(modelId)) throw new Error("COPILOT_MANUAL_RECOVERY_ACCOUNT_PROOF_CHANGED");
7865
+ }
7866
+ });
7867
+ },
7918
7868
  captureSearchProof() {
7919
7869
  const revision = lifetime.revision;
7920
7870
  const captured = snapshotProof;
@@ -0,0 +1,159 @@
1
+ import "./copilot-identity-DRZY_d2X.js";
2
+ import { i as resolveRequestBudgetPolicy, r as calculateRequestBudget } from "./request-budget-DLY_aRq0.js";
3
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
4
+ import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
5
+ //#region lib/types/manual-compaction-recovery.js
6
+ function recoverError(code) {
7
+ return /* @__PURE__ */ new Error(`COPILOT_MANUAL_RECOVERY_${code}`);
8
+ }
9
+ function sumUsage(usages) {
10
+ const required = (key) => usages.reduce((sum, usage) => sum + usage[key], 0);
11
+ const optional = (key) => usages.every((usage) => usage[key] !== void 0) ? { [key]: usages.reduce((sum, usage) => sum + usage[key], 0) } : {};
12
+ return {
13
+ inputTokens: required("inputTokens"),
14
+ outputTokens: required("outputTokens"),
15
+ ...optional("totalTokens"),
16
+ ...optional("cacheReadTokens"),
17
+ ...optional("cacheWriteTokens"),
18
+ ...optional("reasoningTokens")
19
+ };
20
+ }
21
+ /**
22
+ * Bounded, explicit manual-only map/fold. The native engine still owns the only
23
+ * durable transaction, source-stability check, shrink check and cancellation.
24
+ */
25
+ async function summarizeOversizedManualInput(options) {
26
+ const { input, signal, estimate, summarize, makeCheckpoint, assertCurrent } = options;
27
+ const maxCalls = options.maxCalls ?? 16;
28
+ if (!Number.isSafeInteger(maxCalls) || maxCalls < 2 || maxCalls > 32 || !Number.isSafeInteger(options.inputLimit) || options.inputLimit <= 0) throw recoverError("INVALID_POLICY");
29
+ const prefix = input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : [];
30
+ const messages = input.messages.slice(prefix.length);
31
+ if (messages.length === 0) throw recoverError("NO_HISTORY");
32
+ const pending = /* @__PURE__ */ new Set();
33
+ const safeBoundaries = /* @__PURE__ */ new Set([0]);
34
+ for (let index = 0; index < messages.length; index++) {
35
+ const message = messages[index];
36
+ if (message.role === "assistant") {
37
+ for (const block of message.content) if (block.type === "tool-call") {
38
+ if (!block.id || pending.has(block.id)) throw recoverError("UNBALANCED");
39
+ pending.add(block.id);
40
+ }
41
+ }
42
+ if (message.role === "tool") {
43
+ if (!message.toolCallId || !pending.delete(message.toolCallId)) throw recoverError("UNBALANCED");
44
+ }
45
+ if (pending.size === 0) safeBoundaries.add(index + 1);
46
+ }
47
+ if (pending.size !== 0) throw recoverError("UNBALANCED");
48
+ let previous;
49
+ let offset = 0;
50
+ let calls = 0;
51
+ const usages = [];
52
+ while (offset < messages.length) {
53
+ signal.throwIfAborted();
54
+ assertCurrent?.();
55
+ const carry = previous === void 0 ? [] : [makeCheckpoint(previous.summary)];
56
+ const head = [...prefix, ...carry];
57
+ if (estimate({
58
+ tools: input.tools,
59
+ messages: head
60
+ }) >= options.inputLimit) throw recoverError("FIXED_PREFIX");
61
+ let end = offset;
62
+ for (let index = offset + 1; index <= messages.length; index++) {
63
+ if (estimate({
64
+ tools: input.tools,
65
+ messages: [...head, ...messages.slice(offset, index)]
66
+ }) > options.inputLimit) break;
67
+ if (safeBoundaries.has(index)) end = index;
68
+ }
69
+ if (end === offset) throw recoverError("INDIVISIBLE");
70
+ if (++calls > maxCalls) throw recoverError("CALL_LIMIT");
71
+ const result = await summarize({
72
+ tools: input.tools,
73
+ messages: [...head, ...messages.slice(offset, end)]
74
+ });
75
+ signal.throwIfAborted();
76
+ assertCurrent?.();
77
+ if (previous !== void 0 && (result.provider !== previous.provider || result.model !== previous.model || result.maxTokens !== previous.maxTokens)) throw recoverError("ROUTE_CHANGED");
78
+ if (result.summary.length === 0 || result.summary.some((block) => block.type !== "text") || !result.summary.some((block) => block.type === "text" && block.text.trim())) throw recoverError("EMPTY_SUMMARY");
79
+ if (result.usage !== void 0) usages.push(result.usage);
80
+ previous = result;
81
+ offset = end;
82
+ }
83
+ if (previous === void 0) throw recoverError("NO_HISTORY");
84
+ return {
85
+ summary: [...previous.summary],
86
+ provider: previous.provider,
87
+ model: previous.model,
88
+ ...previous.maxTokens === void 0 ? {} : { maxTokens: previous.maxTokens },
89
+ ...usages.length === calls ? { usage: sumUsage(usages) } : {}
90
+ };
91
+ }
92
+ /**
93
+ * Deployment-selected alternative to stock BasicCompactionEngine. Do not
94
+ * mount both: Cordis compaction is a singleton, not an overridable service.
95
+ */
96
+ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine {
97
+ manual = /* @__PURE__ */ new WeakMap();
98
+ async compactNow(agent, signal, sourceCommandId) {
99
+ this.manual.set(agent, (this.manual.get(agent) ?? 0) + 1);
100
+ try {
101
+ return await super.compactNow(agent, signal, sourceCommandId);
102
+ } finally {
103
+ const remaining = this.manual.get(agent) - 1;
104
+ if (remaining === 0) this.manual.delete(agent);
105
+ else this.manual.set(agent, remaining);
106
+ }
107
+ }
108
+ async summarize(input, agent, signal) {
109
+ const routed = agent.session.requestHeader()?.config;
110
+ const policy = this.config.modelPolicies.find((item) => item.provider === routed?.provider && item.model === routed.model);
111
+ const configuredProvider = policy?.summarizationProvider ?? this.config.summarizationProvider;
112
+ const configuredModel = policy?.summarizationModel ?? this.config.summarizationModel;
113
+ const selected = configuredProvider.length > 0 ? {
114
+ provider: configuredProvider,
115
+ model: configuredModel
116
+ } : routed?.provider && routed.model ? routed : {
117
+ provider: agent.options.provider,
118
+ model: agent.options.model
119
+ };
120
+ const summaryProvider = selected.provider;
121
+ const summaryModel = selected.model;
122
+ if (!this.manual.has(agent) || summaryProvider !== "github-copilot-preview" || !summaryModel) return super.summarize(input, agent, signal);
123
+ const lease = this.ctx.get("githubCopilotPreview")?.recoveryLimits(summaryModel);
124
+ if (lease === void 0) throw recoverError("ACCOUNT_PROOF_UNAVAILABLE");
125
+ const maxTokens = policy?.maxTokens ?? this.config.maxTokens;
126
+ const budget = calculateRequestBudget(lease.limits, maxTokens, resolveRequestBudgetPolicy(lease.policy));
127
+ if (!budget.ok) throw recoverError(budget.code);
128
+ const toolHistoryBytes = Buffer.byteLength(JSON.stringify(agent.session.toolHistory()), "utf8");
129
+ const inputLimit = budget.budget.hardInputLimit - 4096 - toolHistoryBytes;
130
+ if (inputLimit <= 0) throw recoverError("FIXED_PREFIX");
131
+ const operationSignal = signal ?? new AbortController().signal;
132
+ const estimate = (candidate) => Buffer.byteLength(JSON.stringify(candidate), "utf8");
133
+ if (estimate(input) <= inputLimit) return super.summarize(input, agent, signal);
134
+ return summarizeOversizedManualInput({
135
+ input,
136
+ inputLimit,
137
+ signal: operationSignal,
138
+ estimate,
139
+ assertCurrent: lease.assertCurrent,
140
+ makeCheckpoint: (summary) => createUserMessage({
141
+ source: { kind: "user" },
142
+ content: [
143
+ {
144
+ type: "text",
145
+ text: "Prior intermediate checkpoint (merge with newer context):\n<compacted-summary>"
146
+ },
147
+ ...summary,
148
+ {
149
+ type: "text",
150
+ text: "</compacted-summary>"
151
+ }
152
+ ]
153
+ }),
154
+ summarize: (candidate) => super.summarize(candidate, agent, signal)
155
+ });
156
+ }
157
+ };
158
+ //#endregion
159
+ export { CopilotManualRecoveryCompactionEngine, CopilotManualRecoveryCompactionEngine as default, summarizeOversizedManualInput };
@@ -0,0 +1,87 @@
1
+ //#region lib/types/request-budget.js
2
+ /** The safety allowance matches the pinned native SDK; pressure is a separate opt-in check. */
3
+ const DEFAULT_REQUEST_BUDGET_POLICY = Object.freeze({
4
+ safetyTokens: 4096,
5
+ pressureRatio: .9,
6
+ compactionReasoning: "prefer-low"
7
+ });
8
+ /** Validate deployment policy before applying defaults; unknown keys fail rather than silently drift. */
9
+ function resolveRequestBudgetPolicy(config = {}) {
10
+ const keys = /* @__PURE__ */ new Set([
11
+ "safetyTokens",
12
+ "pressureRatio",
13
+ "compactionReasoning"
14
+ ]);
15
+ for (const key of Object.keys(config)) if (!keys.has(key)) throw new Error(`COPILOT_REQUEST_BUDGET_POLICY_INVALID: unknown setting ${key}`);
16
+ const safetyTokens = config.safetyTokens === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens : config.safetyTokens;
17
+ const pressureRatio = config.pressureRatio === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio : config.pressureRatio;
18
+ const compactionReasoning = config.compactionReasoning === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning : config.compactionReasoning;
19
+ if (!Number.isSafeInteger(safetyTokens) || safetyTokens < 0) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: safetyTokens must be a non-negative safe integer");
20
+ if (!Number.isFinite(pressureRatio) || pressureRatio <= 0 || pressureRatio > 1) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: pressureRatio must be greater than zero and at most one");
21
+ if (compactionReasoning !== "prefer-low" && compactionReasoning !== "preserve") throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: unsupported compactionReasoning");
22
+ return Object.freeze({
23
+ safetyTokens,
24
+ pressureRatio,
25
+ compactionReasoning
26
+ });
27
+ }
28
+ function failure(code, message) {
29
+ return Object.freeze({
30
+ ok: false,
31
+ code,
32
+ message: `${code}: ${message}`
33
+ });
34
+ }
35
+ function positiveInteger(value) {
36
+ return Number.isSafeInteger(value) && value > 0;
37
+ }
38
+ /**
39
+ * Reserve output under the combined context and independently enforce the prompt ceiling.
40
+ * `policy` must come from resolveRequestBudgetPolicy; no caller cap or catalog object is changed.
41
+ */
42
+ function calculateRequestBudget(limits, requestedMaxTokens, policy = DEFAULT_REQUEST_BUDGET_POLICY) {
43
+ const { contextWindow, maxInputTokens, maxTokens } = limits;
44
+ if (!positiveInteger(contextWindow) || !positiveInteger(maxTokens) || maxInputTokens !== void 0 && !positiveInteger(maxInputTokens)) return failure("COPILOT_REQUEST_INVALID_LIMITS", "model token capacities must be positive safe integers");
45
+ if (requestedMaxTokens !== void 0 && !positiveInteger(requestedMaxTokens)) return failure("COPILOT_REQUEST_INVALID_OUTPUT_LIMIT", "request output cap must be a positive safe integer");
46
+ const outputReservation = requestedMaxTokens ?? maxTokens;
47
+ if (outputReservation > maxTokens) return failure("COPILOT_REQUEST_OUTPUT_LIMIT_EXCEEDED", `request output cap ${outputReservation} exceeds model output capacity ${maxTokens}`);
48
+ const contextInputLimit = contextWindow - outputReservation;
49
+ const limitingFactor = maxInputTokens !== void 0 && maxInputTokens <= contextInputLimit ? "prompt" : "context";
50
+ const hardInputLimit = Math.min(maxInputTokens ?? contextInputLimit, contextInputLimit) - policy.safetyTokens;
51
+ if (hardInputLimit <= 0) return failure("COPILOT_REQUEST_NO_INPUT_HEADROOM", "output reservation and safety allowance leave no positive input budget");
52
+ return Object.freeze({
53
+ ok: true,
54
+ budget: Object.freeze({
55
+ contextWindow,
56
+ ...maxInputTokens === void 0 ? {} : { maxInputTokens },
57
+ maxOutputTokens: maxTokens,
58
+ outputReservation,
59
+ hardInputLimit,
60
+ pressureInputLimit: Math.floor(hardInputLimit * policy.pressureRatio),
61
+ limitingFactor
62
+ })
63
+ });
64
+ }
65
+ /**
66
+ * Check an estimated full prompt; estimates are not provider-exact token counts.
67
+ * Enable pressure only for an owned ordinary loop call with a compaction recovery path.
68
+ * Auxiliary and agentless calls use hard admission, including compaction itself.
69
+ */
70
+ function assessRequestBudget(estimatedInput, budget, pressure = false) {
71
+ if (!Number.isFinite(estimatedInput) || estimatedInput < 0 || estimatedInput > Number.MAX_SAFE_INTEGER) return failure("COPILOT_REQUEST_INVALID_ESTIMATE", "estimated input must be finite, non-negative, and safely representable");
72
+ const input = Math.ceil(estimatedInput);
73
+ if (input > budget.hardInputLimit) return failure(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}`);
74
+ if (pressure && input > budget.pressureInputLimit) return failure("COPILOT_REQUEST_PRESSURE_EXCEEDED", `estimated input ${input} exceeds proactive compaction budget ${budget.pressureInputLimit}`);
75
+ return Object.freeze({ ok: true });
76
+ }
77
+ /**
78
+ * Select a low-cost supported effort only for a caller-confirmed compaction request.
79
+ * A supplied effort, including a materialized provider default, wins unchanged; native validation
80
+ * remains authoritative. Unsupported low-cost controls preserve the provider default, never off/none.
81
+ */
82
+ function selectCompactionReasoning(supportedEfforts, requestedEffort, mode = DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning) {
83
+ if (requestedEffort !== void 0 || mode === "preserve") return requestedEffort;
84
+ return supportedEfforts.find((effort) => effort === "minimal") ?? supportedEfforts.find((effort) => effort === "low");
85
+ }
86
+ //#endregion
87
+ export { selectCompactionReasoning as a, resolveRequestBudgetPolicy as i, assessRequestBudget as n, calculateRequestBudget as r, DEFAULT_REQUEST_BUDGET_POLICY as t };
package/lib/routed-web.js CHANGED
@@ -1,4 +1,5 @@
1
- import { C as currentSearchInitiator, O as isPluginPreviewProvider, t as isCopilotSearchSelection, w as currentSearchSelection } from "./search-routing-BhrTbF-V.js";
1
+ import "./copilot-identity-DRZY_d2X.js";
2
+ import { C as currentSearchInitiator, O as isPluginPreviewProvider, t as isCopilotSearchSelection, w as currentSearchSelection } from "./search-routing-jzNYveyK.js";
2
3
  import { WebError, WebRuntime } from "@deepseek-ai/dsh-web";
3
4
  //#region lib/types/routed-web.js
4
5
  /**