dsh-github-copilot 0.4.0 → 0.4.2-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { c as DiagnosticsViewSchema, d as diagnosticsReason, i as DIAGNOSTICS_RETENTION_MS, l as diagnosticsBucket, o as DiagnosticsRowSchema, s as DiagnosticsSnapshotSchema, u as diagnosticsOutcome } from "./diagnostics-types-FVf6zjob.js";
2
- import { C as providerErrorMessage, D as onSettingsNamespaceUpdated, E as readCopilotCatalog, O as readConfigValue, S as isAbortError, T as isPluginPreviewProvider, _ as sameCandidates, a as COPILOT_HOSTED_SEARCH_PROVIDER_ID, b as currentSearchSelection, c as applyRequestAuth, d as ANTHROPIC_WEB_SEARCH_TOOL_TYPE, f as GITHUB_COPILOT_CREDENTIAL_KEY$1, g as candidatesForRoute, h as WEB_SEARCH_TOOL_TYPE, i as describeSearchBackend, k as readSettingsNamespace, l as normalizeRequestAuth, m as SearchPlan, n as routeSessionSearch, o as GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID, p as RESPONSES_WEB_SEARCH_TOOL_TYPE, r as DescribedSearchFallbackError, s as createTraditionalSearchProvider, t as isCopilotSearchSelection, u as providerRequestHeaders, v as currentChatRoute, w as readBounded, x as abortable$1, y as currentSearchInitiator } from "./search-routing-CV2hs8as.js";
3
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 { _ as normalizeHighCostModelIds, b as normalizeExcludedModelIds, c as DiagnosticsViewSchema, d as diagnosticsReason, f as AutoAllocationDiagnosticsCollector, g as allocateAutoModel, h as AutoAllocationSchema, i as DIAGNOSTICS_RETENTION_MS, l as diagnosticsBucket, m as AUTO_ALLOCATION_POLICY, o as DiagnosticsRowSchema, p as emptyAutoAllocationDiagnostics, s as DiagnosticsSnapshotSchema, u as diagnosticsOutcome, v as ModelExclusionTurns, y as excludedModelSet } from "./diagnostics-types-Bl3QCfR0.js";
3
+ import { C as providerErrorMessage, D as onSettingsNamespaceUpdated, E as readCopilotCatalog, O as readConfigValue, S as isAbortError, T as isPluginPreviewProvider, _ as sameCandidates, a as COPILOT_HOSTED_SEARCH_PROVIDER_ID, b as currentSearchSelection, c as applyRequestAuth, d as ANTHROPIC_WEB_SEARCH_TOOL_TYPE, f as GITHUB_COPILOT_CREDENTIAL_KEY$1, g as candidatesForRoute, h as WEB_SEARCH_TOOL_TYPE, i as describeSearchBackend, k as readSettingsNamespace, l as normalizeRequestAuth, m as SearchPlan, n as routeSessionSearch, o as GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID, p as RESPONSES_WEB_SEARCH_TOOL_TYPE, r as DescribedSearchFallbackError, s as createTraditionalSearchProvider, t as isCopilotSearchSelection, u as providerRequestHeaders, v as currentChatRoute, w as readBounded, x as abortable$1, y as currentSearchInitiator } from "./search-routing-CV2hs8as.js";
4
4
  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";
5
5
  import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
6
6
  import { z } from "zod";
@@ -37,6 +37,7 @@ function emptyDiagnostics() {
37
37
  updatedAt: 0,
38
38
  rows: [],
39
39
  pending: [],
40
+ autoAllocation: emptyAutoAllocationDiagnostics(),
40
41
  dropped: 0,
41
42
  clientDropped: 0,
42
43
  clientUnconfirmed: 0,
@@ -55,16 +56,21 @@ var DiagnosticsCollector = class {
55
56
  data = emptyDiagnostics();
56
57
  live = /* @__PURE__ */ new Set();
57
58
  enabled = false;
59
+ autoAllocationEnabled = false;
58
60
  lastWall = 0;
61
+ autoAllocation;
59
62
  constructor(version, layer, changed = () => {}, wall = Date.now, mono = () => performance.now()) {
60
63
  this.version = version;
61
64
  this.layer = layer;
62
65
  this.changed = changed;
63
66
  this.wall = wall;
64
67
  this.mono = mono;
68
+ this.autoAllocation = new AutoAllocationDiagnosticsCollector(version, changed, wall);
65
69
  }
66
70
  restore(snapshot) {
67
71
  this.data = DiagnosticsSnapshotSchema.parse(snapshot);
72
+ this.autoAllocation.restore(this.data.autoAllocation ?? emptyAutoAllocationDiagnostics());
73
+ this.data.autoAllocation = this.autoAllocation.snapshot();
68
74
  this.lastWall = this.data.updatedAt;
69
75
  for (const pending of this.data.pending) {
70
76
  this.add(pending.operation, pending.stage, "interrupted", "unknown", pending.bucket, pending.count, pending.version);
@@ -97,6 +103,7 @@ var DiagnosticsCollector = class {
97
103
  const epoch = this.data.epoch + 1;
98
104
  if (!Number.isSafeInteger(epoch)) throw new Error("COPILOT_DIAGNOSTICS_EPOCH_LIMIT");
99
105
  this.live.clear();
106
+ this.autoAllocation.clear();
100
107
  this.data = {
101
108
  ...emptyDiagnostics(),
102
109
  epoch
@@ -204,12 +211,14 @@ var DiagnosticsCollector = class {
204
211
  }
205
212
  return DiagnosticsSnapshotSchema.parse({
206
213
  ...this.data,
214
+ autoAllocation: this.autoAllocation.snapshot(),
207
215
  updatedAt: this.wall(),
208
216
  pending
209
217
  });
210
218
  }
211
219
  close() {
212
220
  this.setEnabled(false);
221
+ this.setAutoAllocationEnabled(false);
213
222
  }
214
223
  noteDropped() {
215
224
  if (this.enabled) {
@@ -223,6 +232,30 @@ var DiagnosticsCollector = class {
223
232
  this.increment("clientUnconfirmed", unconfirmed);
224
233
  if (dropped || unconfirmed) this.changed();
225
234
  }
235
+ recordAutoAllocation(explanation) {
236
+ if (!this.autoAllocationEnabled) return;
237
+ if (explanation.method !== "no-fit" && explanation.method !== "weighted-distribution" && explanation.method !== "only-candidate") return;
238
+ if (explanation.method !== "no-fit" && explanation.allocation === void 0) return;
239
+ const before = this.autoAllocation.snapshot();
240
+ this.autoAllocation.record(explanation);
241
+ const next = this.autoAllocation.snapshot();
242
+ const candidate = {
243
+ ...this.data,
244
+ autoAllocation: next
245
+ };
246
+ if (!DiagnosticsSnapshotSchema.safeParse(candidate).success) {
247
+ this.autoAllocation.restore(before, false);
248
+ this.autoAllocation.setEnabled(this.enabled);
249
+ this.data.saturated = Math.min(Number.MAX_SAFE_INTEGER, this.data.saturated + 1);
250
+ this.changed();
251
+ return;
252
+ }
253
+ this.data.autoAllocation = next;
254
+ }
255
+ setAutoAllocationEnabled(enabled) {
256
+ this.autoAllocationEnabled = enabled;
257
+ this.autoAllocation.setEnabled(enabled);
258
+ }
226
259
  mergeClient(rows) {
227
260
  if (!this.enabled) return;
228
261
  const now = this.wall();
@@ -289,6 +322,15 @@ const result$1 = strictRemoteCodec("dsh-github-copilot#DiagnosticsView", Diagnos
289
322
  codec: strictRemoteCodec("dsh-github-copilot#DiagnosticsEnabled", z.boolean())
290
323
  }]
291
324
  },
325
+ {
326
+ method: "setAutoAllocationEnabled",
327
+ parameters: [{
328
+ name: "enabled",
329
+ wire: "enabled",
330
+ source: "json",
331
+ codec: strictRemoteCodec("dsh-github-copilot#AutoAllocationDiagnosticsEnabled", z.boolean())
332
+ }]
333
+ },
292
334
  {
293
335
  method: "recordClient",
294
336
  parameters: [{
@@ -311,11 +353,12 @@ const result$1 = strictRemoteCodec("dsh-github-copilot#DiagnosticsView", Diagnos
311
353
  var package_default = {
312
354
  name: "dsh-github-copilot",
313
355
  description: "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
314
- version: "0.4.0",
356
+ version: "0.4.2-alpha.2",
357
+ releaseNotes: "CHANGELOG.md",
315
358
  publishConfig: {
316
359
  "access": "public",
317
360
  "registry": "https://registry.npmjs.org/",
318
- "tag": "latest"
361
+ "tag": "alpha"
319
362
  },
320
363
  packageManager: "pnpm@11.7.0",
321
364
  repository: {
@@ -443,20 +486,20 @@ var package_default = {
443
486
  "@deepseek-ai/cordis": "^4.0.4",
444
487
  "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
445
488
  "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
446
- "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
447
- "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
448
- "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
449
489
  "@deepseek-ai/dsh-api-remotes": "0.2.0-rc.2",
450
490
  "@deepseek-ai/dsh-authorization": "0.2.0-rc.2",
451
491
  "@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
452
492
  "@deepseek-ai/dsh-client-ui-settings-models": "0.2.0-rc.2",
453
493
  "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
494
+ "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
495
+ "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
496
+ "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
454
497
  "@deepseek-ai/dsh-credentials": "0.2.0-rc.2",
455
498
  "@deepseek-ai/dsh-launch-environment": "0.2.0-rc.2",
456
499
  "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
457
500
  "@deepseek-ai/dsh-llm-pi-ai": "0.2.0-rc.2",
458
- "@deepseek-ai/dsh-session": "0.2.0-rc.2",
459
501
  "@deepseek-ai/dsh-scope": "0.2.0-rc.2",
502
+ "@deepseek-ai/dsh-session": "0.2.0-rc.2",
460
503
  "@deepseek-ai/dsh-settings": "0.2.0-rc.2",
461
504
  "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
462
505
  "@deepseek-ai/dsh-web": "0.2.0-rc.2",
@@ -481,22 +524,22 @@ var package_default = {
481
524
  "@deepseek-ai/cordis": "~4.0.4",
482
525
  "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
483
526
  "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
484
- "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
485
- "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
486
- "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
487
- "@deepseek-ai/dsh-jobs": "0.2.0-rc.2",
488
527
  "@deepseek-ai/dsh-api-gateway": "0.2.0-rc.2",
489
528
  "@deepseek-ai/dsh-api-remotes": "0.2.0-rc.2",
490
529
  "@deepseek-ai/dsh-app-boot": "0.2.0-rc.2",
491
- "@deepseek-ai/dsh-config-editor": "0.2.0-rc.2",
492
530
  "@deepseek-ai/dsh-attachment": "0.2.0-rc.2",
493
531
  "@deepseek-ai/dsh-authorization": "0.2.0-rc.2",
494
532
  "@deepseek-ai/dsh-client-connection": "0.2.0-rc.2",
495
533
  "@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
496
534
  "@deepseek-ai/dsh-client-ui-settings-models": "0.2.0-rc.2",
497
535
  "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
536
+ "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
537
+ "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
538
+ "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
539
+ "@deepseek-ai/dsh-config-editor": "0.2.0-rc.2",
498
540
  "@deepseek-ai/dsh-credentials": "0.2.0-rc.2",
499
541
  "@deepseek-ai/dsh-fs": "0.2.0-rc.2",
542
+ "@deepseek-ai/dsh-jobs": "0.2.0-rc.2",
500
543
  "@deepseek-ai/dsh-launch-environment": "0.2.0-rc.2",
501
544
  "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
502
545
  "@deepseek-ai/dsh-llm-pi-ai": "0.2.0-rc.2",
@@ -606,6 +649,7 @@ let DiagnosticsController = (() => {
606
649
  let _instanceExtraInitializers = [];
607
650
  let _get_decorators;
608
651
  let _setEnabled_decorators;
652
+ let _setAutoAllocationEnabled_decorators;
609
653
  let _clear_decorators;
610
654
  let _recordClient_decorators;
611
655
  return class DiagnosticsController extends _classSuper {
@@ -613,6 +657,7 @@ let DiagnosticsController = (() => {
613
657
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
614
658
  _get_decorators = [Remote];
615
659
  _setEnabled_decorators = [Remote];
660
+ _setAutoAllocationEnabled_decorators = [Remote];
616
661
  _clear_decorators = [Remote];
617
662
  _recordClient_decorators = [Remote];
618
663
  __esDecorate$9(this, null, _get_decorators, {
@@ -637,6 +682,17 @@ let DiagnosticsController = (() => {
637
682
  },
638
683
  metadata: _metadata
639
684
  }, null, _instanceExtraInitializers);
685
+ __esDecorate$9(this, null, _setAutoAllocationEnabled_decorators, {
686
+ kind: "method",
687
+ name: "setAutoAllocationEnabled",
688
+ static: false,
689
+ private: false,
690
+ access: {
691
+ has: (obj) => "setAutoAllocationEnabled" in obj,
692
+ get: (obj) => obj.setAutoAllocationEnabled
693
+ },
694
+ metadata: _metadata
695
+ }, null, _instanceExtraInitializers);
640
696
  __esDecorate$9(this, null, _clear_decorators, {
641
697
  kind: "method",
642
698
  name: "clear",
@@ -671,6 +727,7 @@ let DiagnosticsController = (() => {
671
727
  state = "unavailable";
672
728
  problem = "storage-unavailable";
673
729
  enabled = false;
730
+ autoAllocationEnabled = false;
674
731
  dirty = false;
675
732
  persistedAt;
676
733
  revision = 0;
@@ -687,7 +744,9 @@ let DiagnosticsController = (() => {
687
744
  const readEnabled = () => {
688
745
  const value = ctx.get("settings")?.describe({ redactSecrets: true }).find((row) => row.ns === "github-copilot")?.value;
689
746
  this.enabled = typeof value === "object" && value !== null && "diagnosticsEnabled" in value && value.diagnosticsEnabled === true;
747
+ this.autoAllocationEnabled = typeof value === "object" && value !== null && "autoAllocationDiagnosticsEnabled" in value && value.autoAllocationDiagnosticsEnabled === true;
690
748
  this.collector.setEnabled(this.enabled && this.state === "ready");
749
+ this.collector.setAutoAllocationEnabled(this.autoAllocationEnabled && this.state === "ready");
691
750
  if (!this.enabled) this.brackets.clear();
692
751
  };
693
752
  ctx.inject(["settings"], (scope) => {
@@ -717,6 +776,7 @@ let DiagnosticsController = (() => {
717
776
  this.state = "error";
718
777
  this.problem = error instanceof Error && error.message === "COPILOT_DIAGNOSTICS_PROFILE_UNAVAILABLE" ? "profile-unavailable" : typeof error === "object" && error !== null && "code" in error && (error.code === "invalid-record" || error.code === "malformed-medium" || error.code === "version-mismatch") ? "storage-invalid" : "storage-unavailable";
719
778
  this.collector.setEnabled(false);
779
+ this.collector.setAutoAllocationEnabled(false);
720
780
  ctx.logger.warn("[github-copilot] COPILOT_DIAGNOSTICS_STORAGE_UNAVAILABLE");
721
781
  }
722
782
  if (this.closed) return;
@@ -813,6 +873,7 @@ let DiagnosticsController = (() => {
813
873
  get() {
814
874
  return {
815
875
  enabled: this.enabled,
876
+ autoAllocationEnabled: this.autoAllocationEnabled,
816
877
  state: this.state,
817
878
  diagnostic: this.problem,
818
879
  ...this.persistedAt === void 0 ? {} : { persistedAt: this.persistedAt },
@@ -845,6 +906,30 @@ let DiagnosticsController = (() => {
845
906
  this.settingsBusy = false;
846
907
  }
847
908
  }
909
+ async setAutoAllocationEnabled(enabled) {
910
+ if (typeof enabled !== "boolean") throw new Error("COPILOT_DIAGNOSTICS_INVALID_CONTROL");
911
+ if (this.settingsBusy) throw new Error("COPILOT_DIAGNOSTICS_CONTROL_BUSY");
912
+ if (enabled && !this.domain) throw new Error("COPILOT_DIAGNOSTICS_STORAGE_UNAVAILABLE");
913
+ this.settingsBusy = true;
914
+ try {
915
+ const settings = this.ctx.get("settings");
916
+ const row = settings?.describe({ redactSecrets: true }).find((item) => item.ns === "github-copilot");
917
+ if (!settings || !row) throw new Error("COPILOT_DIAGNOSTICS_SETTINGS_UNAVAILABLE");
918
+ await settings.mutate("github-copilot", [{
919
+ op: "set",
920
+ path: ["autoAllocationDiagnosticsEnabled"],
921
+ value: enabled
922
+ }], row.revision);
923
+ const saved = settings.describe({ redactSecrets: true }).find((item) => item.ns === "github-copilot")?.value;
924
+ if (typeof saved !== "object" || saved === null || !("autoAllocationDiagnosticsEnabled" in saved) || saved.autoAllocationDiagnosticsEnabled !== enabled) throw new Error("COPILOT_DIAGNOSTICS_SETTINGS_COMMIT_UNCERTAIN");
925
+ this.autoAllocationEnabled = enabled;
926
+ this.collector.setAutoAllocationEnabled(enabled && this.state === "ready");
927
+ await this.flush();
928
+ return this.get();
929
+ } finally {
930
+ this.settingsBusy = false;
931
+ }
932
+ }
848
933
  async clear() {
849
934
  if (!this.domain) throw new Error("COPILOT_DIAGNOSTICS_STORAGE_UNAVAILABLE");
850
935
  this.collector.clear();
@@ -1714,6 +1799,28 @@ function normalizeGitHubCopilotOAuthCredential(credential) {
1714
1799
  * Provider-side GitHub Copilot auth resolution over the same credential record
1715
1800
  * that DSH's built-in llm-pi-ai adapter owns.
1716
1801
  */
1802
+ const nativeRefreshResults = /* @__PURE__ */ new WeakSet();
1803
+ const refreshWrites = /* @__PURE__ */ new WeakMap();
1804
+ /** Only a validated native OAuth refresh may certify its exact returned object. */
1805
+ async function certifyCopilotNativeRefresh(previous, result, derive, signal) {
1806
+ const ids = (grant) => grant.availableModelIds === void 0 ? void 0 : JSON.stringify([...grant.availableModelIds].sort());
1807
+ if (previous.refresh !== result.refresh || previous.enterpriseUrl !== result.enterpriseUrl || ids(previous) !== ids(result) || result.expires <= Date.now()) return;
1808
+ const before = await derive(previous);
1809
+ const after = await derive(result);
1810
+ signal?.throwIfAborted();
1811
+ if (before.apiKey === previous.access && after.apiKey === result.access && trustedGitHubCopilotBaseUrl(before.baseUrl, previous) === trustedGitHubCopilotBaseUrl(after.baseUrl, result)) nativeRefreshResults.add(result);
1812
+ }
1813
+ /** Consume exactly one notification from the serialized, certified write. */
1814
+ function observeCopilotNativeRefresh(ctx, key) {
1815
+ const service = ctx.get("credentials");
1816
+ const write = service === void 0 ? void 0 : refreshWrites.get(service)?.get(key);
1817
+ if (!write) return void 0;
1818
+ if (++write.notifications !== 1) {
1819
+ write.settle(false);
1820
+ return;
1821
+ }
1822
+ return write.committed;
1823
+ }
1717
1824
  function captureActiveGitHubCopilotBinding(ctx) {
1718
1825
  const accounts = ctx.get("githubCopilotAccounts");
1719
1826
  if (accounts) return accounts.host.capture();
@@ -1778,12 +1885,45 @@ function createGitHubCopilotCredentialStore(ctx, logicalProviderId = GITHUB_COPI
1778
1885
  modify: async (providerId, mutate) => {
1779
1886
  assertProvider(providerId);
1780
1887
  binding?.assertCurrent();
1781
- return toCredential(await credentialService(ctx).modifyRecord(key, async (current) => {
1782
- binding?.assertCurrent();
1783
- const next = await mutate(toCredential(current));
1888
+ const service = credentialService(ctx);
1889
+ let pending;
1890
+ let expected;
1891
+ let writes = refreshWrites.get(service);
1892
+ if (!writes) {
1893
+ writes = /* @__PURE__ */ new Map();
1894
+ refreshWrites.set(service, writes);
1895
+ }
1896
+ try {
1897
+ const stored = await service.modifyRecord(key, async (current) => {
1898
+ binding?.assertCurrent();
1899
+ const next = await mutate(toCredential(current));
1900
+ binding?.assertCurrent();
1901
+ const record = next === void 0 ? void 0 : toRecord(next);
1902
+ if (next !== void 0 && nativeRefreshResults.delete(next)) {
1903
+ expected = record;
1904
+ let settle;
1905
+ const committed = new Promise((resolve) => {
1906
+ settle = resolve;
1907
+ });
1908
+ pending = {
1909
+ notifications: 0,
1910
+ settle,
1911
+ committed
1912
+ };
1913
+ if (writes.has(key)) {
1914
+ writes.get(key)?.settle(false);
1915
+ pending.settle(false);
1916
+ } else writes.set(key, pending);
1917
+ }
1918
+ return record;
1919
+ });
1784
1920
  binding?.assertCurrent();
1785
- return next === void 0 ? void 0 : toRecord(next);
1786
- }));
1921
+ pending?.settle(pending.notifications === 1 && stored?.kind === "grant" && expected?.kind === "grant" && JSON.stringify(normalizeGitHubCopilotOAuthCredential(stored.payload)) === JSON.stringify(normalizeGitHubCopilotOAuthCredential(expected.payload)));
1922
+ return toCredential(stored);
1923
+ } finally {
1924
+ pending?.settle(false);
1925
+ if (writes.get(key) === pending) writes.delete(key);
1926
+ }
1787
1927
  },
1788
1928
  delete: async (providerId) => {
1789
1929
  assertProvider(providerId);
@@ -1800,9 +1940,18 @@ function createGitHubCopilotTokenResolver(ctx, onCredentialChanged) {
1800
1940
  const models = createModels({ credentials: createGitHubCopilotCredentialStore(ctx) });
1801
1941
  const provider = githubCopilotProvider();
1802
1942
  if (provider.auth.oauth === void 0) throw new Error("github-copilot: native OAuth method is unavailable");
1943
+ const oauth = provider.auth.oauth;
1803
1944
  models.setProvider({
1804
1945
  ...provider,
1805
- auth: { oauth: provider.auth.oauth }
1946
+ auth: { oauth: {
1947
+ ...oauth,
1948
+ async refresh(credential, signal) {
1949
+ const previous = normalizeGitHubCopilotOAuthCredential(credential);
1950
+ const result = normalizeGitHubCopilotOAuthCredential(await oauth.refresh(credential, signal));
1951
+ await certifyCopilotNativeRefresh(previous, result, oauth.toAuth, signal);
1952
+ return result;
1953
+ }
1954
+ } }
1806
1955
  });
1807
1956
  return async (modelId) => {
1808
1957
  const binding = captureActiveGitHubCopilotBinding(ctx);
@@ -1945,10 +2094,13 @@ function createAccountModelAuth(credentials, renewRejectedCredential) {
1945
2094
  },
1946
2095
  async refresh(credential, requestSignal) {
1947
2096
  active(signal);
1948
- matches(normalizeGitHubCopilotOAuthCredential(credential), key);
2097
+ const previous = normalizeGitHubCopilotOAuthCredential(credential);
2098
+ matches(previous, key);
1949
2099
  const result = normalizeGitHubCopilotOAuthCredential(await oauth.refresh(credential, requestSignal === void 0 ? signal : AbortSignal.any([signal, requestSignal])));
1950
2100
  active(signal);
1951
2101
  matches(result, key);
2102
+ await certifyCopilotNativeRefresh(previous, result, oauth.toAuth, signal);
2103
+ active(signal);
1952
2104
  return result;
1953
2105
  },
1954
2106
  async toAuth(credential) {
@@ -3756,6 +3908,8 @@ function createAccountProvider(descriptors, guard, baseURL) {
3756
3908
  guard.assertActive();
3757
3909
  const result = normalizeGitHubCopilotOAuthCredential(fresh);
3758
3910
  guard.assertAccount(result);
3911
+ await certifyCopilotNativeRefresh(current, result, oauth.toAuth, operationSignal);
3912
+ guard.assertActive();
3759
3913
  return result;
3760
3914
  },
3761
3915
  toAuth: async (credential) => {
@@ -3888,6 +4042,7 @@ function createAccountProvider(descriptors, guard, baseURL) {
3888
4042
  dispatchInit = prepared.init;
3889
4043
  compression = prepared.evidence;
3890
4044
  }
4045
+ lease.dispatch?.();
3891
4046
  liveness?.beginRequest(originalBody);
3892
4047
  let response;
3893
4048
  const upload = guard.onRequestBodyTimeout === void 0 ? void 0 : createRequestUploadObserver();
@@ -6828,6 +6983,7 @@ function readInlineConfig(config) {
6828
6983
  return {
6829
6984
  ...config,
6830
6985
  diagnosticsEnabled: readConfigValue(config.diagnosticsEnabled),
6986
+ autoAllocationDiagnosticsEnabled: readConfigValue(config.autoAllocationDiagnosticsEnabled),
6831
6987
  continuationDefaultHistory: defaults === void 0 ? void 0 : Array.from(defaults, (row) => ({
6832
6988
  enabled: row.enabled,
6833
6989
  changedAt: row.changedAt
@@ -6860,6 +7016,7 @@ const MAX_TIMEOUT_MS = 2147483647;
6860
7016
  /** Schema of the plugin's settings section. */
6861
7017
  const Config = z$1.object({
6862
7018
  diagnosticsEnabled: z$1.boolean().default(false).hidden().volatile(),
7019
+ autoAllocationDiagnosticsEnabled: z$1.boolean().default(false).hidden().volatile(),
6863
7020
  enabled: z$1.boolean().default(true),
6864
7021
  providers: z$1.array(z$1.string()).default([]),
6865
7022
  includeSources: z$1.boolean().default(true),
@@ -8880,112 +9037,6 @@ function wholeProfileOwned(snapshot, backup) {
8880
9037
  ...Object.keys(backup.ownedHeaders).length === 0 ? {} : { headers: backup.ownedHeaders }
8881
9038
  });
8882
9039
  }
8883
- const MAX_MODEL_ID_LENGTH = 512;
8884
- /** Admission is bound to the native turn and its request signal, not the global picker. */
8885
- var ModelExclusionTurns = class {
8886
- turns = /* @__PURE__ */ new WeakMap();
8887
- signals = /* @__PURE__ */ new WeakMap();
8888
- admit(owner, turn, model, signal, excluded) {
8889
- const previous = this.turns.get(owner);
8890
- if (signal.aborted || excluded.has(model) && (previous?.turn !== turn || previous.model !== model)) {
8891
- if (previous?.turn !== turn) this.turns.delete(owner);
8892
- return false;
8893
- }
8894
- this.turns.set(owner, {
8895
- turn,
8896
- model
8897
- });
8898
- this.signals.set(signal, {
8899
- owner,
8900
- turn,
8901
- model
8902
- });
8903
- return true;
8904
- }
8905
- permits(signal, model) {
8906
- if (signal === void 0 || signal.aborted) return false;
8907
- const admitted = this.signals.get(signal);
8908
- if (admitted?.model !== model) return false;
8909
- const current = this.turns.get(admitted.owner);
8910
- return current?.turn === admitted.turn && current.model === model;
8911
- }
8912
- end(owner) {
8913
- this.turns.delete(owner);
8914
- }
8915
- };
8916
- function normalizeExcludedModelIds(value) {
8917
- if (value === void 0) return [];
8918
- if (!Array.isArray(value) || value.length > 512) throw new Error("COPILOT_MODEL_EXCLUSIONS_INVALID");
8919
- const ids = /* @__PURE__ */ new Set();
8920
- for (const candidate of value) {
8921
- if (typeof candidate !== "string" || candidate.length === 0 || candidate.length > MAX_MODEL_ID_LENGTH || candidate.trim() !== candidate || autoModelPreference(candidate) !== void 0) throw new Error("COPILOT_MODEL_EXCLUSIONS_INVALID");
8922
- ids.add(candidate);
8923
- }
8924
- return [...ids].toSorted();
8925
- }
8926
- function excludedModelSet(value) {
8927
- return new Set(normalizeExcludedModelIds(value));
8928
- }
8929
- //#endregion
8930
- //#region lib/types/auto-allocation.js
8931
- const AUTO_ALLOCATION_POLICY = "high-cost-v1";
8932
- const AutoAllocationSchema = z.object({
8933
- policyVersion: z.literal(AUTO_ALLOCATION_POLICY),
8934
- selectedModelId: z.string().min(1).max(512),
8935
- candidates: z.array(z.object({
8936
- modelId: z.string().min(1).max(512),
8937
- highCost: z.boolean(),
8938
- previous: z.boolean(),
8939
- weight: z.number().positive().max(1.5),
8940
- expectedShare: z.number().positive().max(1)
8941
- }).strict()).min(1).max(512)
8942
- }).strict().refine((value) => {
8943
- const total = value.candidates.reduce((sum, row) => sum + row.weight, 0);
8944
- 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);
8945
- }, { message: "Invalid allocation policy evidence" });
8946
- function normalizeHighCostModelIds(value) {
8947
- try {
8948
- return normalizeExcludedModelIds(value);
8949
- } catch (cause) {
8950
- if (cause instanceof Error && cause.message === "COPILOT_MODEL_EXCLUSIONS_INVALID") throw new Error("COPILOT_HIGH_COST_MODELS_INVALID");
8951
- throw cause;
8952
- }
8953
- }
8954
- /** Integer policy units avoid cumulative decimal drift; avalanche sequential turn seeds. */
8955
- function allocateAutoModel(pool, highCostModelIds, previousModelId, seed) {
8956
- 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");
8957
- const marked = new Set(normalizeHighCostModelIds(highCostModelIds));
8958
- const rows = pool.map((model) => {
8959
- const highCost = marked.has(model.id);
8960
- const previous = model.id === previousModelId;
8961
- const units = (highCost ? 2 : 10) * (previous ? 1.5 : 1);
8962
- return {
8963
- modelId: model.id,
8964
- highCost,
8965
- previous,
8966
- units
8967
- };
8968
- });
8969
- const total = rows.reduce((sum, row) => sum + row.units, 0);
8970
- let hash = seed >>> 0;
8971
- hash = Math.imul(hash ^ hash >>> 16, 2246822507);
8972
- hash = Math.imul(hash ^ hash >>> 13, 3266489909);
8973
- const point = ((hash ^ hash >>> 16) >>> 0) / 4294967296 * total;
8974
- let boundary = 0;
8975
- const selected = rows.find((row) => {
8976
- boundary += row.units;
8977
- return point < boundary;
8978
- });
8979
- return Object.freeze({
8980
- policyVersion: AUTO_ALLOCATION_POLICY,
8981
- selectedModelId: selected.modelId,
8982
- candidates: Object.freeze(rows.map(({ units, ...row }) => Object.freeze({
8983
- ...row,
8984
- weight: units / 10,
8985
- expectedShare: units / total
8986
- })))
8987
- });
8988
- }
8989
9040
  //#endregion
8990
9041
  //#region lib/types/authorization-controller.js
8991
9042
  /**
@@ -11725,8 +11776,12 @@ z.discriminatedUnion("mode", [
11725
11776
  ]);
11726
11777
  /** Ephemeral decision evidence only; never session content, model usage or credentials. */
11727
11778
  var TurnSelectionStore = class {
11779
+ onAutoDecision;
11728
11780
  agents = /* @__PURE__ */ new Map();
11729
11781
  timestamps = /* @__PURE__ */ new WeakMap();
11782
+ constructor(onAutoDecision) {
11783
+ this.onAutoDecision = onAutoDecision;
11784
+ }
11730
11785
  record(agent, turn, selection) {
11731
11786
  if (!Number.isSafeInteger(turn) || turn < 0) throw new Error("COPILOT_TURN_SELECTION_INVALID_TURN");
11732
11787
  let turns = this.agents.get(agent);
@@ -11758,6 +11813,7 @@ var TurnSelectionStore = class {
11758
11813
  })
11759
11814
  }) }
11760
11815
  }));
11816
+ if (explanation !== void 0) this.onAutoDecision?.(explanation);
11761
11817
  }
11762
11818
  if (turns.size > 128) {
11763
11819
  const oldest = turns.keys().next().value;
@@ -12303,7 +12359,13 @@ function actualNotice(agent, model) {
12303
12359
  }
12304
12360
  /** Resolve virtual Auto once per Core turn before request/header persistence. */
12305
12361
  function installAutoModelRouting(ctx, dependencies) {
12306
- const selections = new TurnSelectionStore();
12362
+ const selections = new TurnSelectionStore((explanation) => {
12363
+ try {
12364
+ ctx.get("githubCopilotDiagnostics")?.collector.recordAutoAllocation(explanation);
12365
+ } catch {
12366
+ ctx.logger.warn("[github-copilot] COPILOT_AUTO_ALLOCATION_DIAGNOSTICS_UNAVAILABLE");
12367
+ }
12368
+ });
12307
12369
  new TurnSelectionController(ctx, selections);
12308
12370
  const captured = /* @__PURE__ */ new WeakMap();
12309
12371
  const routed = /* @__PURE__ */ new WeakMap();
@@ -12760,7 +12822,7 @@ var PreviewLifetime = class {
12760
12822
  turns;
12761
12823
  acquire;
12762
12824
  controller = new AbortController();
12763
- wires = /* @__PURE__ */ new Set();
12825
+ wires = /* @__PURE__ */ new Map();
12764
12826
  retryEntries = /* @__PURE__ */ new Map();
12765
12827
  revision = 0;
12766
12828
  active = true;
@@ -12814,12 +12876,12 @@ var PreviewLifetime = class {
12814
12876
  });
12815
12877
  return replay;
12816
12878
  }
12817
- change() {
12879
+ change(preserveDispatched = false) {
12818
12880
  this.assertActive();
12819
12881
  this.revision++;
12820
12882
  this.clearRetries();
12821
12883
  this.source.invalidate();
12822
- for (const wire of this.wires) wire.abort(new ManagedWireAbortError("COPILOT_PREVIEW_CREDENTIAL_CHANGED"));
12884
+ for (const [wire, state] of this.wires) if (!preserveDispatched || !state.dispatched) wire.abort(new ManagedWireAbortError("COPILOT_PREVIEW_CREDENTIAL_CHANGED"));
12823
12885
  }
12824
12886
  dispose() {
12825
12887
  if (!this.active) return;
@@ -12827,7 +12889,7 @@ var PreviewLifetime = class {
12827
12889
  this.clearRetries();
12828
12890
  this.source.dispose();
12829
12891
  this.controller.abort(new ManagedWireAbortError("COPILOT_PREVIEW_DISPOSED"));
12830
- for (const wire of this.wires) wire.abort();
12892
+ for (const wire of this.wires.keys()) wire.abort();
12831
12893
  this.wires.clear();
12832
12894
  }
12833
12895
  async read(signal = this.controller.signal, ticket) {
@@ -12943,9 +13005,14 @@ var PreviewLifetime = class {
12943
13005
  if (options?.apiKey !== grant.access) throw failure("COPILOT_PREVIEW_CREDENTIAL_CHANGED");
12944
13006
  if (trustedGitHubCopilotBaseUrl(model.baseUrl, grant) !== lease.proof.baseURL) throw failure("COPILOT_PREVIEW_CREDENTIAL_CHANGED");
12945
13007
  const controller = new AbortController();
12946
- this.wires.add(controller);
13008
+ const state = { dispatched: false };
13009
+ this.wires.set(controller, state);
12947
13010
  return {
12948
13011
  signal: AbortSignal.any([signal, controller.signal]),
13012
+ dispatch: () => {
13013
+ if (!this.isCurrent(lease.revision)) throw failure("COPILOT_PREVIEW_PREPARED_CALL_INVALIDATED", "ABORTED");
13014
+ state.dispatched = true;
13015
+ },
12949
13016
  release: () => {
12950
13017
  this.wires.delete(controller);
12951
13018
  controller.abort();
@@ -13675,8 +13742,8 @@ function createAccountRuntime(ctx, config, binding, exclusionTurns, replayRecove
13675
13742
  if (snapshotProof === void 0 || snapshotProof.expires <= Date.now()) return void 0;
13676
13743
  return `${binding?.accountId ?? "canonical"}:${lifetime.revision}:${snapshotProof.accountKey}:${snapshotProof.tokenFingerprint}`;
13677
13744
  },
13678
- invalidate() {
13679
- lifetime.change();
13745
+ invalidate(preserveDispatched = false) {
13746
+ lifetime.change(preserveDispatched);
13680
13747
  provenSnapshot = void 0;
13681
13748
  snapshotProof = void 0;
13682
13749
  lastValidatedProof = void 0;
@@ -13813,7 +13880,13 @@ function apply$1(ctx, config = {}) {
13813
13880
  if (event.type === "turn/end") exclusionTurns.end(session);
13814
13881
  });
13815
13882
  const removeListener = ctx.on("credentials/record-updated", (key) => {
13816
- for (const [accountId, runtime] of runtimes) if ((accountId === "canonical" ? "llm-pi-ai/github-copilot" : `github-copilot/account-${accountId}`) === key) runtime.invalidate();
13883
+ const refresh = observeCopilotNativeRefresh(ctx, key);
13884
+ for (const [accountId, runtime] of runtimes) if ((accountId === "canonical" ? "llm-pi-ai/github-copilot" : `github-copilot/account-${accountId}`) === key) {
13885
+ runtime.invalidate(refresh !== void 0);
13886
+ if (refresh !== void 0) refresh.then((committed) => {
13887
+ if (!committed && !disposed) runtime.invalidate();
13888
+ });
13889
+ }
13817
13890
  });
13818
13891
  const removeAccountListener = ctx.get("githubCopilotAccounts")?.host.onChanged(() => {
13819
13892
  publishedDirectory = "";
@@ -1,5 +1,5 @@
1
- import { d as diagnosticsReason, u as diagnosticsOutcome } from "./diagnostics-types-FVf6zjob.js";
2
1
  import "./copilot-identity-DRZY_d2X.js";
2
+ import { d as diagnosticsReason, u as diagnosticsOutcome } from "./diagnostics-types-Bl3QCfR0.js";
3
3
  import { i as resolveRequestBudgetPolicy, r as calculateRequestBudget } from "./request-budget-DLY_aRq0.js";
4
4
  import z from "@deepseek-ai/schemastery";
5
5
  import { LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";