dsh-github-copilot 0.4.0-alpha.114 → 0.4.0-alpha.116

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 (36) hide show
  1. package/AGENTS.md +13 -4
  2. package/CHANGELOG.md +15 -0
  3. package/CONTRIBUTING.md +9 -0
  4. package/README.md +24 -7
  5. package/README.zh.md +19 -7
  6. package/deployment-baseline.json +29 -3
  7. package/docs/auto-high-cost.md +132 -0
  8. package/docs/auto-iteration-review.json +22 -0
  9. package/docs/auto-task-routing.md +8 -6
  10. package/docs/automatic-model-routing.md +4 -1
  11. package/docs/copilot-compaction.md +2 -2
  12. package/docs/evidence-driven-iteration.md +86 -0
  13. package/docs/manual-compaction-recovery.md +20 -6
  14. package/lib/client.js +239 -75
  15. package/lib/client.js.map +1 -1
  16. package/lib/index.js +261 -18
  17. package/lib/manual-compaction-recovery.js +39 -10
  18. package/lib/remote.js +125 -40
  19. package/lib/types/authorization-controller.d.ts +2 -0
  20. package/lib/types/auto-allocation-card.d.ts +9 -0
  21. package/lib/types/auto-allocation-evidence.d.ts +38 -0
  22. package/lib/types/auto-allocation.d.ts +24 -0
  23. package/lib/types/auto-model-host.d.ts +2 -0
  24. package/lib/types/auto-model-routing.d.ts +6 -2
  25. package/lib/types/auto-task-classifier.d.ts +1 -1
  26. package/lib/types/config.d.ts +8 -2
  27. package/lib/types/manual-compaction-recovery.d.ts +16 -3
  28. package/lib/types/model-preferences-card.d.ts +1 -1
  29. package/lib/types/preview-route.d.ts +4 -3
  30. package/lib/types/remote.d.ts +3 -0
  31. package/lib/types/turn-selection-card.d.ts +2 -1
  32. package/lib/types/turn-selection-host.d.ts +21 -0
  33. package/lib/types/turn-selection-remote.d.ts +2 -0
  34. package/lib/types/turn-selection.d.ts +15 -0
  35. package/package.json +5 -1
  36. package/scripts/iteration-review.mjs +53 -0
package/lib/index.js CHANGED
@@ -2998,7 +2998,7 @@ function createAccountProvider(descriptors, guard, baseURL) {
2998
2998
  var package_default = {
2999
2999
  name: "dsh-github-copilot",
3000
3000
  description: "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
3001
- version: "0.4.0-alpha.114",
3001
+ version: "0.4.0-alpha.116",
3002
3002
  publishConfig: {
3003
3003
  "access": "public",
3004
3004
  "registry": "https://registry.npmjs.org/",
@@ -3070,6 +3070,10 @@ var package_default = {
3070
3070
  "docs/mockups/copilot-account-dropdown.html",
3071
3071
  "docs/automatic-model-routing.md",
3072
3072
  "docs/auto-task-routing.md",
3073
+ "docs/auto-high-cost.md",
3074
+ "docs/evidence-driven-iteration.md",
3075
+ "docs/auto-iteration-review.json",
3076
+ "scripts/iteration-review.mjs",
3073
3077
  "docs/image-input-compatibility.md",
3074
3078
  "output/auto-model-mockup/index.html",
3075
3079
  "docs/images/dual-model-provenance.json",
@@ -5799,6 +5803,7 @@ const WebSearchRoutingConfigSchema = z.object({
5799
5803
  /** Keep native live references at the boundary; request code consumes plain snapshots. */
5800
5804
  function readInlineConfig(config) {
5801
5805
  const exclusions = readConfigValue(config.excludedModelIds);
5806
+ const highCost = readConfigValue(config.highCostModelIds);
5802
5807
  const bindings = readConfigValue(config.parentModelFollow);
5803
5808
  const accounts = readConfigValue(config.sessionAccounts);
5804
5809
  const continuation = readConfigValue(config.sessionContinuation);
@@ -5821,6 +5826,7 @@ function readInlineConfig(config) {
5821
5826
  accountId: account.accountId
5822
5827
  })),
5823
5828
  excludedModelIds: exclusions === void 0 ? void 0 : Array.from(exclusions),
5829
+ highCostModelIds: highCost === void 0 ? void 0 : Array.from(highCost),
5824
5830
  parentModelFollow: bindings === void 0 ? void 0 : Array.from(bindings, (binding) => ({
5825
5831
  childSessionId: binding.childSessionId,
5826
5832
  parentSessionId: binding.parentSessionId
@@ -5848,6 +5854,7 @@ const Config = z.object({
5848
5854
  accountModelTtlMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(864e5),
5849
5855
  accountModelFailureCooldownMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(3e5),
5850
5856
  excludedModelIds: z.array(z.string()).default([]).hidden().volatile(),
5857
+ highCostModelIds: z.array(z.string()).default([]).hidden().volatile(),
5851
5858
  activeAccountId: z.string().hidden().volatile(),
5852
5859
  sessionAccounts: z.array(z.object({
5853
5860
  sessionId: z.string().min(1).max(256),
@@ -5865,6 +5872,7 @@ const Config = z.object({
5865
5872
  })).default([]).hidden().volatile(),
5866
5873
  followParentModel: z.boolean().default(false).volatile(),
5867
5874
  autoSemanticAssessment: z.boolean().default(true),
5875
+ autoAllocationEvidence: z.boolean().default(true),
5868
5876
  parentModelFollow: z.array(z.object({
5869
5877
  childSessionId: z.string().min(1),
5870
5878
  parentSessionId: z.string().min(1)
@@ -7898,6 +7906,66 @@ function excludedModelSet(value) {
7898
7906
  return new Set(normalizeExcludedModelIds(value));
7899
7907
  }
7900
7908
  //#endregion
7909
+ //#region lib/types/auto-allocation.js
7910
+ const AUTO_ALLOCATION_POLICY = "high-cost-v1";
7911
+ const AutoAllocationSchema = z$1.object({
7912
+ policyVersion: z$1.literal(AUTO_ALLOCATION_POLICY),
7913
+ selectedModelId: z$1.string().min(1).max(512),
7914
+ candidates: z$1.array(z$1.object({
7915
+ modelId: z$1.string().min(1).max(512),
7916
+ highCost: z$1.boolean(),
7917
+ previous: z$1.boolean(),
7918
+ weight: z$1.number().positive().max(1.5),
7919
+ expectedShare: z$1.number().positive().max(1)
7920
+ }).strict()).min(1).max(512)
7921
+ }).strict().refine((value) => {
7922
+ const total = value.candidates.reduce((sum, row) => sum + row.weight, 0);
7923
+ return new Set(value.candidates.map((row) => row.modelId)).size === value.candidates.length && value.candidates.some((row) => row.modelId === value.selectedModelId) && value.candidates.filter((row) => row.previous).length <= 1 && value.candidates.every((row) => row.weight === (row.highCost ? 2 : 10) * (row.previous ? 1.5 : 1) / 10 && Math.abs(row.expectedShare - row.weight / total) <= 1e-12);
7924
+ }, { message: "Invalid allocation policy evidence" });
7925
+ function normalizeHighCostModelIds(value) {
7926
+ try {
7927
+ return normalizeExcludedModelIds(value);
7928
+ } catch (cause) {
7929
+ if (cause instanceof Error && cause.message === "COPILOT_MODEL_EXCLUSIONS_INVALID") throw new Error("COPILOT_HIGH_COST_MODELS_INVALID");
7930
+ throw cause;
7931
+ }
7932
+ }
7933
+ /** Integer policy units avoid cumulative decimal drift; avalanche sequential turn seeds. */
7934
+ function allocateAutoModel(pool, highCostModelIds, previousModelId, seed) {
7935
+ if (!Number.isSafeInteger(seed) || pool.length === 0 || pool.length > 512 || normalizeExcludedModelIds(pool.map((model) => model.id)).length !== pool.length) throw new Error("COPILOT_AUTO_ALLOCATION_INVALID");
7936
+ const marked = new Set(normalizeHighCostModelIds(highCostModelIds));
7937
+ const rows = pool.map((model) => {
7938
+ const highCost = marked.has(model.id);
7939
+ const previous = model.id === previousModelId;
7940
+ const units = (highCost ? 2 : 10) * (previous ? 1.5 : 1);
7941
+ return {
7942
+ modelId: model.id,
7943
+ highCost,
7944
+ previous,
7945
+ units
7946
+ };
7947
+ });
7948
+ const total = rows.reduce((sum, row) => sum + row.units, 0);
7949
+ let hash = seed >>> 0;
7950
+ hash = Math.imul(hash ^ hash >>> 16, 2246822507);
7951
+ hash = Math.imul(hash ^ hash >>> 13, 3266489909);
7952
+ const point = ((hash ^ hash >>> 16) >>> 0) / 4294967296 * total;
7953
+ let boundary = 0;
7954
+ const selected = rows.find((row) => {
7955
+ boundary += row.units;
7956
+ return point < boundary;
7957
+ });
7958
+ return Object.freeze({
7959
+ policyVersion: AUTO_ALLOCATION_POLICY,
7960
+ selectedModelId: selected.modelId,
7961
+ candidates: Object.freeze(rows.map(({ units, ...row }) => Object.freeze({
7962
+ ...row,
7963
+ weight: units / 10,
7964
+ expectedShare: units / total
7965
+ })))
7966
+ });
7967
+ }
7968
+ //#endregion
7901
7969
  //#region lib/types/authorization-controller.js
7902
7970
  /**
7903
7971
  * Host-side bridge between the Models-page companion UI and DSH's neutral
@@ -8042,10 +8110,12 @@ function modelPreferencesView(ctx, accountModels, error) {
8042
8110
  if (descriptor === void 0) return unavailable("COPILOT_MODEL_SETTINGS_UNAVAILABLE");
8043
8111
  if (!Number.isSafeInteger(descriptor.revision) || descriptor.revision < 0) return unavailable("COPILOT_MODEL_SETTINGS_INVALID");
8044
8112
  let excludedModelIds;
8113
+ let highCostModelIds;
8045
8114
  try {
8046
8115
  const raw = object$3(descriptor.value);
8047
8116
  if (raw === void 0) return unavailable("COPILOT_MODEL_SETTINGS_INVALID");
8048
8117
  excludedModelIds = normalizeExcludedModelIds(raw.excludedModelIds);
8118
+ highCostModelIds = normalizeHighCostModelIds(raw.highCostModelIds);
8049
8119
  } catch {
8050
8120
  return unavailable("COPILOT_MODEL_SETTINGS_INVALID");
8051
8121
  }
@@ -8056,6 +8126,7 @@ function modelPreferencesView(ctx, accountModels, error) {
8056
8126
  writable: true,
8057
8127
  revision: descriptor.revision,
8058
8128
  excludedModelIds,
8129
+ highCostModelIds,
8059
8130
  lockedModelIds: [],
8060
8131
  unavailableExcludedModelIds: excludedModelIds.filter((id) => !available.has(id)),
8061
8132
  ...diagnostic === void 0 ? {} : { error: diagnostic }
@@ -8218,6 +8289,7 @@ let GitHubCopilotAuthorizationController = (() => {
8218
8289
  let _excludeModel_decorators;
8219
8290
  let _restoreModel_decorators;
8220
8291
  let _setModelExcluded_decorators;
8292
+ let _setModelHighCost_decorators;
8221
8293
  let _discoverModels_decorators;
8222
8294
  let _ensureModels_decorators;
8223
8295
  let _reconcile_decorators;
@@ -8232,6 +8304,7 @@ let GitHubCopilotAuthorizationController = (() => {
8232
8304
  _excludeModel_decorators = [Remote];
8233
8305
  _restoreModel_decorators = [Remote];
8234
8306
  _setModelExcluded_decorators = [Remote];
8307
+ _setModelHighCost_decorators = [Remote];
8235
8308
  _discoverModels_decorators = [Remote];
8236
8309
  _ensureModels_decorators = [Remote];
8237
8310
  _reconcile_decorators = [Remote];
@@ -8293,6 +8366,17 @@ let GitHubCopilotAuthorizationController = (() => {
8293
8366
  },
8294
8367
  metadata: _metadata
8295
8368
  }, null, _instanceExtraInitializers);
8369
+ __esDecorate$3(this, null, _setModelHighCost_decorators, {
8370
+ kind: "method",
8371
+ name: "setModelHighCost",
8372
+ static: false,
8373
+ private: false,
8374
+ access: {
8375
+ has: (obj) => "setModelHighCost" in obj,
8376
+ get: (obj) => obj.setModelHighCost
8377
+ },
8378
+ metadata: _metadata
8379
+ }, null, _instanceExtraInitializers);
8296
8380
  __esDecorate$3(this, null, _discoverModels_decorators, {
8297
8381
  kind: "method",
8298
8382
  name: "discoverModels",
@@ -8463,6 +8547,9 @@ let GitHubCopilotAuthorizationController = (() => {
8463
8547
  async setModelExcluded(modelId, excluded) {
8464
8548
  return this.updateModelExclusion(modelId, excluded);
8465
8549
  }
8550
+ async setModelHighCost(modelId, highCost) {
8551
+ return this.updateModelExclusion(modelId, highCost, "highCostModelIds");
8552
+ }
8466
8553
  /** Explicit model discovery: may refresh OAuth and GET the account catalog, never changes selection. */
8467
8554
  async discoverModels() {
8468
8555
  return this.loadAccountModels(true);
@@ -8612,7 +8699,7 @@ let GitHubCopilotAuthorizationController = (() => {
8612
8699
  this.authorizationMilestone = void 0;
8613
8700
  return this.status();
8614
8701
  }
8615
- async updateModelExclusion(modelId, exclude) {
8702
+ async updateModelExclusion(modelId, exclude, field = "excludedModelIds") {
8616
8703
  const view = () => modelPreferencesView(this.ctx, accountModelsView(this.ctx), this.modelPreferenceFailure);
8617
8704
  let normalized;
8618
8705
  try {
@@ -8626,21 +8713,25 @@ let GitHubCopilotAuthorizationController = (() => {
8626
8713
  this.modelPreferenceFailure = "COPILOT_MODEL_PREFERENCES_UNAVAILABLE";
8627
8714
  return view();
8628
8715
  }
8629
- const ids = new Set(current.excludedModelIds);
8716
+ const original = field === "excludedModelIds" ? current.excludedModelIds : current.highCostModelIds ?? [];
8717
+ const ids = new Set(original);
8630
8718
  if (exclude) ids.add(normalized);
8631
8719
  else ids.delete(normalized);
8632
8720
  const next = normalizeExcludedModelIds([...ids]);
8633
- if (next.length === current.excludedModelIds.length && next.every((id, index) => id === current.excludedModelIds[index])) {
8721
+ if (next.length === original.length && next.every((id, index) => id === original[index])) {
8634
8722
  this.modelPreferenceFailure = void 0;
8635
8723
  return current;
8636
8724
  }
8637
8725
  try {
8638
8726
  await service(this.ctx, "settings", ["describe", "mutate"]).mutate(GITHUB_COPILOT_SETTINGS_NAMESPACE$1, [{
8639
8727
  op: "set",
8640
- path: ["excludedModelIds"],
8728
+ path: [field],
8641
8729
  value: next
8642
8730
  }], current.revision);
8643
8731
  this.modelPreferenceFailure = void 0;
8732
+ const saved = view();
8733
+ const readback = field === "excludedModelIds" ? saved.excludedModelIds : saved.highCostModelIds;
8734
+ if (!saved.writable || readback === void 0 || readback.length !== next.length || readback.some((id, index) => id !== next[index])) this.modelPreferenceFailure = "COPILOT_MODEL_EXCLUSION_SAVE_FAILED";
8644
8735
  } catch (cause) {
8645
8736
  const record = object$3(cause);
8646
8737
  this.modelPreferenceFailure = record?.code === "SETTINGS_CONFLICT" || cause instanceof Error && /conflict/i.test(cause.message) ? "COPILOT_MODEL_EXCLUSION_CONFLICT" : "COPILOT_MODEL_EXCLUSION_SAVE_FAILED";
@@ -10168,7 +10259,7 @@ function targetCategory(assessment, preference) {
10168
10259
  }
10169
10260
  /**
10170
10261
  * Filter input headroom before task-aware supplier categories.
10171
- * Preserve suitable continuity; distribute only equally classified candidates.
10262
+ * Apply finite continuity and positive cost weights within the fitting category.
10172
10263
  * Preserves Core compaction ownership if no candidate currently fits.
10173
10264
  */
10174
10265
  function selectAutoModel(models, messages, preference = "balance", context) {
@@ -10210,15 +10301,16 @@ function selectAutoModel(models, messages, preference = "balance", context) {
10210
10301
  if (fitting.length > 0) {
10211
10302
  const selectedCategory = order.find((category) => fitting.some((model) => (model.category ?? "unknown") === category));
10212
10303
  const pool = fitting.filter((model) => (model.category ?? "unknown") === selectedCategory);
10213
- const previous = pool.find((model) => model.id === context?.previousModelId);
10214
- selectedModel = previous ?? pool[seed % pool.length];
10304
+ const allocation = allocateAutoModel(pool, context?.highCostModelIds, context?.previousModelId, seed);
10305
+ selectedModel = pool.find((model) => model.id === allocation.selectedModelId);
10215
10306
  explanation = {
10216
10307
  assessment,
10217
10308
  targetCategory: target,
10218
10309
  selectedCategory,
10219
10310
  categoryCandidateCount: pool.length,
10220
- method: previous ? "continuity" : pool.length === 1 ? "only-candidate" : "equal-distribution",
10221
- fallback: selectedCategory !== target
10311
+ method: pool.length === 1 ? "only-candidate" : "weighted-distribution",
10312
+ fallback: selectedCategory !== target,
10313
+ ...context?.collectAllocationEvidence === false ? {} : { allocation }
10222
10314
  };
10223
10315
  selectedInputBudget = candidateInputLimit(selectedModel, requestedMaxTokens, policy);
10224
10316
  inputFitDiagnostic = "fitting-candidate-selected";
@@ -10271,6 +10363,92 @@ function autoModelInputModalities(models) {
10271
10363
  return models.filter((model) => autoModelPreference(model.id) === void 0 && model.input.includes("text")).some((model) => model.input.includes("image")) ? ["text", "image"] : ["text"];
10272
10364
  }
10273
10365
  //#endregion
10366
+ //#region lib/types/auto-allocation-evidence.js
10367
+ const AutoAllocationSummarySchema = z$1.object({
10368
+ policyVersion: z$1.literal(AUTO_ALLOCATION_POLICY),
10369
+ scope: z$1.literal("viewed-session-host-lifetime"),
10370
+ status: z$1.enum(["observed", "not-collected"]),
10371
+ retainedDecisions: z$1.number().int().nonnegative().max(128),
10372
+ noFitDecisions: z$1.number().int().nonnegative().max(128),
10373
+ rowsTruncated: z$1.boolean(),
10374
+ completeHistory: z$1.literal(false),
10375
+ observationStart: z$1.number().int().nonnegative().nullable(),
10376
+ observationEnd: z$1.number().int().nonnegative().nullable(),
10377
+ rows: z$1.array(z$1.object({
10378
+ modelId: z$1.string().min(1).max(512),
10379
+ category: z$1.enum([
10380
+ "powerful",
10381
+ "versatile",
10382
+ "lightweight",
10383
+ "unknown"
10384
+ ]),
10385
+ highCost: z$1.boolean(),
10386
+ previous: z$1.boolean(),
10387
+ weight: z$1.number().positive().max(1.5),
10388
+ opportunities: z$1.number().int().positive().max(128),
10389
+ expectedSelections: z$1.number().nonnegative().max(128),
10390
+ selections: z$1.number().int().nonnegative().max(128)
10391
+ }).strict()).max(512)
10392
+ }).strict();
10393
+ /** Recompute only from captured bounded decisions, never today's settings or history content. */
10394
+ function summarizeAutoAllocations(explanations, window) {
10395
+ const rows = /* @__PURE__ */ new Map();
10396
+ let noFitDecisions = 0;
10397
+ let retainedDecisions = 0;
10398
+ let rowsTruncated = false;
10399
+ for (const explanation of explanations) {
10400
+ if (explanation.method === "no-fit") {
10401
+ noFitDecisions++;
10402
+ continue;
10403
+ }
10404
+ const allocation = explanation.allocation;
10405
+ if (allocation?.policyVersion !== "high-cost-v1") continue;
10406
+ retainedDecisions++;
10407
+ for (const row of allocation.candidates) {
10408
+ const key = JSON.stringify([
10409
+ row.modelId,
10410
+ explanation.selectedCategory,
10411
+ row.highCost,
10412
+ row.previous,
10413
+ row.weight
10414
+ ]);
10415
+ let aggregate = rows.get(key);
10416
+ if (aggregate === void 0) {
10417
+ if (rows.size === 512) {
10418
+ rowsTruncated = true;
10419
+ continue;
10420
+ }
10421
+ aggregate = {
10422
+ modelId: row.modelId,
10423
+ category: explanation.selectedCategory,
10424
+ highCost: row.highCost,
10425
+ previous: row.previous,
10426
+ weight: row.weight,
10427
+ opportunities: 0,
10428
+ expectedSelections: 0,
10429
+ selections: 0
10430
+ };
10431
+ rows.set(key, aggregate);
10432
+ }
10433
+ aggregate.opportunities++;
10434
+ aggregate.expectedSelections += row.expectedShare;
10435
+ if (allocation.selectedModelId === row.modelId) aggregate.selections++;
10436
+ }
10437
+ }
10438
+ return AutoAllocationSummarySchema.parse({
10439
+ policyVersion: AUTO_ALLOCATION_POLICY,
10440
+ scope: "viewed-session-host-lifetime",
10441
+ status: retainedDecisions + noFitDecisions === 0 ? "not-collected" : "observed",
10442
+ retainedDecisions,
10443
+ noFitDecisions,
10444
+ rowsTruncated,
10445
+ completeHistory: false,
10446
+ rows: [...rows.values()],
10447
+ observationStart: window?.start ?? null,
10448
+ observationEnd: window?.end ?? null
10449
+ });
10450
+ }
10451
+ //#endregion
10274
10452
  //#region lib/types/turn-selection.js
10275
10453
  const ExplanationSchema = z$1.object({
10276
10454
  assessment: TaskAssessmentSchema.extend({
@@ -10300,10 +10478,12 @@ const ExplanationSchema = z$1.object({
10300
10478
  method: z$1.enum([
10301
10479
  "continuity",
10302
10480
  "equal-distribution",
10481
+ "weighted-distribution",
10303
10482
  "only-candidate",
10304
10483
  "no-fit"
10305
10484
  ]),
10306
- fallback: z$1.boolean()
10485
+ fallback: z$1.boolean(),
10486
+ allocation: AutoAllocationSchema.optional()
10307
10487
  }).strict();
10308
10488
  z$1.discriminatedUnion("mode", [
10309
10489
  z$1.object({ mode: z$1.literal("unknown") }).strict(),
@@ -10329,20 +10509,31 @@ z$1.discriminatedUnion("mode", [
10329
10509
  /** Ephemeral decision evidence only; never session content, model usage or credentials. */
10330
10510
  var TurnSelectionStore = class {
10331
10511
  agents = /* @__PURE__ */ new Map();
10512
+ timestamps = /* @__PURE__ */ new WeakMap();
10332
10513
  record(agent, turn, selection) {
10333
10514
  if (!Number.isSafeInteger(turn) || turn < 0) throw new Error("COPILOT_TURN_SELECTION_INVALID_TURN");
10334
10515
  let turns = this.agents.get(agent);
10335
10516
  if (!turns) {
10336
10517
  turns = /* @__PURE__ */ new Map();
10518
+ this.timestamps.set(agent, /* @__PURE__ */ new Map());
10337
10519
  this.agents.set(agent, turns);
10338
- if (this.agents.size > 64) this.agents.delete(this.agents.keys().next().value);
10520
+ if (this.agents.size > 64) {
10521
+ const oldest = this.agents.keys().next().value;
10522
+ this.agents.delete(oldest);
10523
+ this.timestamps.delete(oldest);
10524
+ }
10339
10525
  }
10340
10526
  if (!turns.has(turn)) {
10527
+ this.timestamps.get(agent).set(turn, Date.now());
10341
10528
  const explanation = selection.mode === "auto" ? selection.explanation : void 0;
10342
10529
  turns.set(turn, Object.freeze({
10343
10530
  ...selection,
10344
10531
  ...explanation === void 0 ? {} : { explanation: Object.freeze({
10345
10532
  ...explanation,
10533
+ ...explanation.allocation === void 0 ? {} : { allocation: Object.freeze({
10534
+ ...explanation.allocation,
10535
+ candidates: Object.freeze(explanation.allocation.candidates.map((row) => Object.freeze({ ...row })))
10536
+ }) },
10346
10537
  assessment: Object.freeze({
10347
10538
  ...explanation.assessment,
10348
10539
  signals: Object.freeze([...explanation.assessment.signals]),
@@ -10351,17 +10542,34 @@ var TurnSelectionStore = class {
10351
10542
  }) }
10352
10543
  }));
10353
10544
  }
10354
- if (turns.size > 128) turns.delete(turns.keys().next().value);
10545
+ if (turns.size > 128) {
10546
+ const oldest = turns.keys().next().value;
10547
+ turns.delete(oldest);
10548
+ this.timestamps.get(agent).delete(oldest);
10549
+ }
10355
10550
  }
10356
10551
  get(agent, turn) {
10357
10552
  if (!Number.isSafeInteger(turn) || turn < 0) throw new Error("COPILOT_TURN_SELECTION_INVALID_TURN");
10358
10553
  return this.agents.get(agent)?.get(turn) ?? { mode: "unknown" };
10359
10554
  }
10555
+ allocationSummary(agent) {
10556
+ const explanations = [...this.agents.get(agent)?.values() ?? []].flatMap((selection) => selection.mode === "auto" && selection.explanation !== void 0 ? [selection.explanation] : []);
10557
+ const times = [...this.timestamps.get(agent)?.entries() ?? []].flatMap(([turn, time]) => {
10558
+ const selection = this.agents.get(agent)?.get(turn);
10559
+ return selection?.mode === "auto" && selection.explanation !== void 0 && (selection.explanation.allocation !== void 0 || selection.explanation.method === "no-fit") ? [time] : [];
10560
+ });
10561
+ return summarizeAutoAllocations(explanations, times.length ? {
10562
+ start: Math.min(...times),
10563
+ end: Math.max(...times)
10564
+ } : void 0);
10565
+ }
10360
10566
  remove(agent) {
10361
10567
  this.agents.delete(agent);
10568
+ this.timestamps.delete(agent);
10362
10569
  }
10363
10570
  clear() {
10364
10571
  this.agents.clear();
10572
+ this.timestamps = /* @__PURE__ */ new WeakMap();
10365
10573
  }
10366
10574
  };
10367
10575
  //#endregion
@@ -10546,11 +10754,13 @@ let TurnSelectionController = (() => {
10546
10754
  let _classSuper = TypertRemoteService;
10547
10755
  let _instanceExtraInitializers = [];
10548
10756
  let _get_decorators;
10757
+ let _allocationSummary_decorators;
10549
10758
  let _requestedModels_decorators;
10550
10759
  return class TurnSelectionController extends _classSuper {
10551
10760
  static {
10552
10761
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
10553
10762
  _get_decorators = [Remote];
10763
+ _allocationSummary_decorators = [Remote];
10554
10764
  _requestedModels_decorators = [Remote];
10555
10765
  __esDecorate(this, null, _get_decorators, {
10556
10766
  kind: "method",
@@ -10563,6 +10773,17 @@ let TurnSelectionController = (() => {
10563
10773
  },
10564
10774
  metadata: _metadata
10565
10775
  }, null, _instanceExtraInitializers);
10776
+ __esDecorate(this, null, _allocationSummary_decorators, {
10777
+ kind: "method",
10778
+ name: "allocationSummary",
10779
+ static: false,
10780
+ private: false,
10781
+ access: {
10782
+ has: (obj) => "allocationSummary" in obj,
10783
+ get: (obj) => obj.allocationSummary
10784
+ },
10785
+ metadata: _metadata
10786
+ }, null, _instanceExtraInitializers);
10566
10787
  __esDecorate(this, null, _requestedModels_decorators, {
10567
10788
  kind: "method",
10568
10789
  name: "requestedModels",
@@ -10590,6 +10811,9 @@ let TurnSelectionController = (() => {
10590
10811
  get(agent, turn) {
10591
10812
  return this.selections.get(agent, turn);
10592
10813
  }
10814
+ allocationSummary(agent) {
10815
+ return this.selections.allocationSummary(agent);
10816
+ }
10593
10817
  requestedModels(agent, turn) {
10594
10818
  if (!Number.isSafeInteger(turn) || turn < 0) throw new Error("COPILOT_TURN_SELECTION_INVALID_TURN");
10595
10819
  const registry = this.ctx.get("sessionProjections");
@@ -10794,7 +11018,9 @@ async function decide(dependencies, signal, messages, preference, context) {
10794
11018
  if (signal.aborted) throw signal.reason;
10795
11019
  return selectAutoModel(await dependencies.loadModels(signal), messages, preference, {
10796
11020
  ...context,
10797
- assessment
11021
+ assessment,
11022
+ highCostModelIds: dependencies.highCostModelIds?.(),
11023
+ collectAllocationEvidence: dependencies.allocationEvidence?.() !== false
10798
11024
  });
10799
11025
  } catch (cause) {
10800
11026
  if (cause instanceof AutoModelRoutingError) throw failure$1(cause.code);
@@ -11211,8 +11437,9 @@ function installAutoModelRouting(ctx, dependencies) {
11211
11437
  selections.clear();
11212
11438
  };
11213
11439
  }
11214
- function taskClassifierModel(models) {
11215
- return models.filter((model) => model.category === "lightweight" && model.input.includes("text")).toSorted((left, right) => Number(right.reasoning.advertisedEfforts.includes("off")) - Number(left.reasoning.advertisedEfforts.includes("off")) || left.id.localeCompare(right.id, "en")).find((model) => {
11440
+ function taskClassifierModel(models, highCostModelIds) {
11441
+ const highCost = new Set(normalizeHighCostModelIds(highCostModelIds));
11442
+ return models.filter((model) => model.category === "lightweight" && model.input.includes("text")).toSorted((left, right) => Number(highCost.has(left.id)) - Number(highCost.has(right.id)) || Number(right.reasoning.advertisedEfforts.includes("off")) - Number(left.reasoning.advertisedEfforts.includes("off")) || left.id.localeCompare(right.id, "en")).find((model) => {
11216
11443
  const budget = calculateRequestBudget(model, 128);
11217
11444
  return budget.ok && budget.budget.hardInputLimit >= 12e3;
11218
11445
  });
@@ -12185,13 +12412,14 @@ function createAccountRuntime(ctx, config, binding, exclusionTurns, replayRecove
12185
12412
  parentModelBindings: () => cacheSettings().parentModelFollow ?? [],
12186
12413
  followParentModel: () => cacheSettings().followParentModel === true,
12187
12414
  semanticAssessment: () => cacheSettings().autoSemanticAssessment ?? true,
12415
+ highCostModelIds: () => normalizeHighCostModelIds(cacheSettings().highCostModelIds),
12188
12416
  assessmentDiagnostic: (code) => ctx.logger.warn(code),
12189
12417
  async classifyTask(...args) {
12190
12418
  const [input, signal, observe, checkpoint] = args;
12191
12419
  checkpoint?.();
12192
12420
  const snapshot = await discoverSnapshot({ signal });
12193
12421
  checkpoint?.();
12194
- const model = taskClassifierModel(snapshot.models.filter((model) => !excludedModels().has(model.id)));
12422
+ const model = taskClassifierModel(snapshot.models.filter((model) => !excludedModels().has(model.id)), normalizeHighCostModelIds(cacheSettings().highCostModelIds));
12195
12423
  if (model === void 0) throw failure("COPILOT_AUTO_CLASSIFIER_UNAVAILABLE");
12196
12424
  observe?.({
12197
12425
  stage: "model-selected",
@@ -12328,6 +12556,8 @@ function apply$1(ctx, config = {}) {
12328
12556
  parentModelBindings: () => currentRuntime().auto.parentModelBindings(),
12329
12557
  followParentModel: () => currentRuntime().auto.followParentModel(),
12330
12558
  semanticAssessment: () => currentRuntime().auto.semanticAssessment(),
12559
+ highCostModelIds: () => normalizeHighCostModelIds(config.accountModelSettings?.().highCostModelIds),
12560
+ allocationEvidence: () => config.accountModelSettings?.().autoAllocationEvidence !== false,
12331
12561
  assessmentDiagnostic: (code) => ctx.logger.warn(code),
12332
12562
  admitModel: (agent, turn, model, signal) => currentRuntime(signal).auto.admitModel(agent, turn, model, signal)
12333
12563
  });
@@ -12338,7 +12568,20 @@ function apply$1(ctx, config = {}) {
12338
12568
  getView: () => disposed ? initial.preview.getView() : currentRuntime().preview.getView(),
12339
12569
  refresh: async () => currentRuntime().preview.refresh(),
12340
12570
  discover: (options) => currentRuntime(options?.signal).preview.discover(options),
12341
- recoveryLimits: (model) => currentRuntime().preview.recoveryLimits(model),
12571
+ recoveryLimits: (model, agent) => {
12572
+ const accounts = ctx.get("githubCopilotSessionAccounts");
12573
+ const binding = agent !== void 0 && accounts !== void 0 ? accounts.bindingForAccount((accounts.turns.current(agent.session) ?? accounts.selected(agent)).accountId) : requestBinding();
12574
+ const lease = runtimeFor(binding).preview.recoveryLimits(model);
12575
+ if (lease === void 0) return void 0;
12576
+ return {
12577
+ ...lease,
12578
+ assertCurrent: () => {
12579
+ binding?.assertCurrent();
12580
+ if (agent !== void 0 && accounts !== void 0 && (accounts.turns.current(agent.session) ?? accounts.selected(agent)).accountId !== binding?.accountId) throw new Error("COPILOT_MANUAL_RECOVERY_ACCOUNT_PROOF_CHANGED");
12581
+ lease.assertCurrent();
12582
+ }
12583
+ };
12584
+ },
12342
12585
  routeFacts: (model) => currentRuntime().preview.routeFacts(model),
12343
12586
  captureSearchProof: () => currentRuntime().preview.captureSearchProof(),
12344
12587
  resolveRequestAuth: (model, signal) => currentRuntime(signal).preview.resolveRequestAuth(model, signal)
@@ -1,6 +1,7 @@
1
1
  import "./copilot-identity-DRZY_d2X.js";
2
2
  import { i as resolveRequestBudgetPolicy, r as calculateRequestBudget } from "./request-budget-DLY_aRq0.js";
3
- import { createUserMessage } from "@deepseek-ai/dsh-llm";
3
+ import z from "@deepseek-ai/schemastery";
4
+ import { LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
4
5
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
5
6
  import { CommandDefinitionId } from "@deepseek-ai/dsh-commands/brand";
6
7
  //#region lib/types/background-compaction.js
@@ -169,7 +170,7 @@ function sumUsage(usages) {
169
170
  };
170
171
  }
171
172
  /**
172
- * Bounded, explicit manual-only map/fold. The native engine still owns the only
173
+ * Bounded map/fold. The native engine still owns the only
173
174
  * durable transaction, source-stability check, shrink check and cancellation.
174
175
  */
175
176
  async function summarizeOversizedManualInput(options) {
@@ -244,9 +245,14 @@ async function summarizeOversizedManualInput(options) {
244
245
  * mount both: Cordis compaction is a singleton, not an overridable service.
245
246
  */
246
247
  var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine {
248
+ static Config = z.intersect([BasicCompactionEngine.Config, z.object({ automaticRecovery: z.boolean().default(true) })]);
247
249
  manual = /* @__PURE__ */ new WeakMap();
250
+ automaticRecovery;
248
251
  constructor(ctx, config = {}) {
249
- super(ctx, config);
252
+ const { automaticRecovery = true, ...nativeConfig } = config;
253
+ if (typeof automaticRecovery !== "boolean") throw recoverError("INVALID_POLICY");
254
+ super(ctx, nativeConfig);
255
+ this.automaticRecovery = automaticRecovery;
250
256
  ctx.inject(["commands", "jobs"], (scope) => {
251
257
  installBackgroundCompaction(scope, (agent, signal) => this.compactNow(agent, signal));
252
258
  });
@@ -263,7 +269,8 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
263
269
  }
264
270
  async summarize(input, agent, signal) {
265
271
  const routed = agent.session.requestHeader()?.config;
266
- const policy = this.config.modelPolicies.find((item) => item.provider === routed?.provider && item.model === routed.model);
272
+ const target = routed?.provider && routed.model ? routed : agent.options;
273
+ const policy = this.config.modelPolicies.find((item) => item.provider === target.provider && item.model === target.model);
267
274
  const configuredProvider = policy?.summarizationProvider ?? this.config.summarizationProvider;
268
275
  const configuredModel = policy?.summarizationModel ?? this.config.summarizationModel;
269
276
  const selected = configuredProvider.length > 0 ? {
@@ -275,23 +282,40 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
275
282
  };
276
283
  const summaryProvider = selected.provider;
277
284
  const summaryModel = selected.model;
278
- if (!this.manual.has(agent) || summaryProvider !== "github-copilot-preview" || !summaryModel) return super.summarize(input, agent, signal);
279
- const lease = this.ctx.get("githubCopilotPreview")?.recoveryLimits(summaryModel);
285
+ if (!this.manual.has(agent) && !this.automaticRecovery || summaryProvider !== "github-copilot-preview" || !summaryModel) return super.summarize(input, agent, signal);
286
+ const lease = this.ctx.get("githubCopilotPreview")?.recoveryLimits(summaryModel, agent);
280
287
  if (lease === void 0) throw recoverError("ACCOUNT_PROOF_UNAVAILABLE");
288
+ const agents = this.ctx.get("agents");
289
+ if (this.ctx.get("githubCopilotSessionAccounts") !== void 0 && agents === void 0) throw recoverError("INITIATOR_UNAVAILABLE");
290
+ const summarize = (candidate) => agents === void 0 ? super.summarize(candidate, agent, signal) : agents.withInitiator(agent, () => super.summarize(candidate, agent, signal));
281
291
  const maxTokens = policy?.maxTokens ?? this.config.maxTokens;
282
292
  const budget = calculateRequestBudget(lease.limits, maxTokens, resolveRequestBudgetPolicy(lease.policy));
283
293
  if (!budget.ok) throw recoverError(budget.code);
284
294
  const toolHistoryBytes = Buffer.byteLength(JSON.stringify(agent.session.toolHistory()), "utf8");
285
- const inputLimit = budget.budget.hardInputLimit - 4096 - toolHistoryBytes;
295
+ let inputLimit = budget.budget.hardInputLimit - 4096 - toolHistoryBytes;
286
296
  if (inputLimit <= 0) throw recoverError("FIXED_PREFIX");
287
297
  const operationSignal = signal ?? new AbortController().signal;
288
298
  const estimate = (candidate) => Buffer.byteLength(JSON.stringify(candidate), "utf8");
289
- if (estimate(input) <= inputLimit) return super.summarize(input, agent, signal);
290
- return summarizeOversizedManualInput({
299
+ operationSignal.throwIfAborted();
300
+ lease.assertCurrent();
301
+ const originalSize = estimate(input);
302
+ let failedAttempt = false;
303
+ if (originalSize <= inputLimit) try {
304
+ return await summarize(input);
305
+ } catch (error) {
306
+ operationSignal.throwIfAborted();
307
+ if (!(error instanceof LlmError) || error.code !== "CONTEXT_WINDOW_EXCEEDED") throw error;
308
+ lease.assertCurrent();
309
+ inputLimit = Math.min(inputLimit, Math.floor(originalSize / 2));
310
+ failedAttempt = true;
311
+ }
312
+ this.ctx.logger.info("[github-copilot] Segmented compaction recovery started; up to %d additional model calls.", failedAttempt ? 15 : 16);
313
+ const result = await summarizeOversizedManualInput({
291
314
  input,
292
315
  inputLimit,
293
316
  signal: operationSignal,
294
317
  estimate,
318
+ maxCalls: failedAttempt ? 15 : 16,
295
319
  assertCurrent: lease.assertCurrent,
296
320
  makeCheckpoint: (summary) => createUserMessage({
297
321
  source: { kind: "user" },
@@ -307,8 +331,13 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
307
331
  }
308
332
  ]
309
333
  }),
310
- summarize: (candidate) => super.summarize(candidate, agent, signal)
334
+ summarize
311
335
  });
336
+ if (failedAttempt) {
337
+ const { usage: _usage, ...unaccounted } = result;
338
+ return unaccounted;
339
+ }
340
+ return result;
312
341
  }
313
342
  };
314
343
  //#endregion