dsh-github-copilot 0.4.2-alpha.7 → 0.4.2-alpha.9

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.
@@ -1,4 +1,4 @@
1
- import { a as DiagnosticsPendingSchema, c as DiagnosticsViewSchema, n as DIAGNOSTICS_OPERATIONS, r as DIAGNOSTICS_REASONS, s as DiagnosticsSnapshotSchema } from "./diagnostics-types-BDIc78T4.js";
1
+ import { a as DiagnosticsPendingSchema, c as DiagnosticsViewSchema, n as DIAGNOSTICS_OPERATIONS, r as DIAGNOSTICS_REASONS, s as DiagnosticsSnapshotSchema } from "./diagnostics-types-C1BD6ayS.js";
2
2
  import { z } from "zod";
3
3
  //#region lib/types/diagnostics-analysis.js
4
4
  const RETENTION_MS = 12096e5;
@@ -386,6 +386,32 @@ const upload = z.discriminatedUnion("state", [
386
386
  }).strict()
387
387
  ]);
388
388
  const REQUEST_DIAGNOSTICS_RETENTION_MS = 864e5;
389
+ const CredentialChangeReasonSchema = z.enum([
390
+ "qualified",
391
+ "unknown-source",
392
+ "account-changed",
393
+ "endpoint-changed",
394
+ "entitlements-changed",
395
+ "expired",
396
+ "auth-mismatch",
397
+ "duplicate-notification",
398
+ "missing-notification",
399
+ "commit-mismatch",
400
+ "write-failed",
401
+ "write-conflict"
402
+ ]);
403
+ const CredentialChangeSchema = z.object({
404
+ changeId: z.string().uuid(),
405
+ observedAt: integer$1,
406
+ version: z.string().max(64).regex(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/),
407
+ phase: z.enum(["notification", "commit"]),
408
+ reason: CredentialChangeReasonSchema,
409
+ preparing: integer$1,
410
+ dispatched: integer$1,
411
+ alreadyAborted: integer$1,
412
+ preserved: integer$1,
413
+ revoked: integer$1
414
+ }).strict();
389
415
  const RequestDiagnosticSchema = z.object({
390
416
  streamId: z.string().uuid(),
391
417
  dispatchIndex: integer$1.min(1),
@@ -432,7 +458,14 @@ const RequestDiagnosticsSchema = z.object({
432
458
  dropped: integer$1,
433
459
  evicted: integer$1,
434
460
  pending: integer$1.max(128).optional(),
435
- interruptedOnReopen: integer$1.optional()
461
+ interruptedOnReopen: integer$1.optional(),
462
+ credentialChanges: z.object({
463
+ rows: z.array(CredentialChangeSchema).max(128),
464
+ dropped: integer$1,
465
+ evicted: integer$1,
466
+ pending: integer$1.max(128).optional(),
467
+ interruptedOnReopen: integer$1.optional()
468
+ }).strict().optional()
436
469
  }).strict();
437
470
  //#endregion
438
471
  //#region lib/types/diagnostics-types.js
@@ -619,4 +652,4 @@ function diagnosticsOutcome(reason) {
619
652
  return "failed";
620
653
  }
621
654
  //#endregion
622
- export { normalizeExcludedModelIds as S, AutoAllocationSchema as _, DiagnosticsPendingSchema as a, ModelExclusionTurns as b, DiagnosticsViewSchema as c, diagnosticsReason as d, REQUEST_DIAGNOSTICS_RETENTION_MS as f, AUTO_ALLOCATION_POLICY as g, emptyAutoAllocationDiagnostics as h, DIAGNOSTICS_RETENTION_MS as i, diagnosticsBucket as l, AutoAllocationDiagnosticsCollector as m, DIAGNOSTICS_OPERATIONS as n, DiagnosticsRowSchema as o, RequestDiagnosticSchema as p, DIAGNOSTICS_REASONS as r, DiagnosticsSnapshotSchema as s, DIAGNOSTICS_MAX_ROWS as t, diagnosticsOutcome as u, allocateAutoModel as v, excludedModelSet as x, normalizeHighCostModelIds as y };
655
+ export { normalizeExcludedModelIds as C, excludedModelSet as S, AUTO_ALLOCATION_POLICY as _, DiagnosticsPendingSchema as a, normalizeHighCostModelIds as b, DiagnosticsViewSchema as c, diagnosticsReason as d, CredentialChangeSchema as f, emptyAutoAllocationDiagnostics as g, AutoAllocationDiagnosticsCollector as h, DIAGNOSTICS_RETENTION_MS as i, diagnosticsBucket as l, RequestDiagnosticSchema as m, DIAGNOSTICS_OPERATIONS as n, DiagnosticsRowSchema as o, REQUEST_DIAGNOSTICS_RETENTION_MS as p, DIAGNOSTICS_REASONS as r, DiagnosticsSnapshotSchema as s, DIAGNOSTICS_MAX_ROWS as t, diagnosticsOutcome as u, AutoAllocationSchema as v, ModelExclusionTurns as x, allocateAutoModel as y };
package/lib/index.js CHANGED
@@ -1,5 +1,5 @@
1
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 { S as normalizeExcludedModelIds, _ as AutoAllocationSchema, b as ModelExclusionTurns, c as DiagnosticsViewSchema, d as diagnosticsReason, f as REQUEST_DIAGNOSTICS_RETENTION_MS, g as AUTO_ALLOCATION_POLICY, h as emptyAutoAllocationDiagnostics, i as DIAGNOSTICS_RETENTION_MS, l as diagnosticsBucket, m as AutoAllocationDiagnosticsCollector, o as DiagnosticsRowSchema, p as RequestDiagnosticSchema, s as DiagnosticsSnapshotSchema, u as diagnosticsOutcome, v as allocateAutoModel, x as excludedModelSet, y as normalizeHighCostModelIds } from "./diagnostics-types-BDIc78T4.js";
2
+ import { C as normalizeExcludedModelIds, S as excludedModelSet, _ as AUTO_ALLOCATION_POLICY, b as normalizeHighCostModelIds, c as DiagnosticsViewSchema, d as diagnosticsReason, f as CredentialChangeSchema, g as emptyAutoAllocationDiagnostics, h as AutoAllocationDiagnosticsCollector, i as DIAGNOSTICS_RETENTION_MS, l as diagnosticsBucket, m as RequestDiagnosticSchema, o as DiagnosticsRowSchema, p as REQUEST_DIAGNOSTICS_RETENTION_MS, s as DiagnosticsSnapshotSchema, u as diagnosticsOutcome, v as AutoAllocationSchema, x as ModelExclusionTurns, y as allocateAutoModel } from "./diagnostics-types-C1BD6ayS.js";
3
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";
@@ -59,6 +59,7 @@ var DiagnosticsCollector = class {
59
59
  autoAllocationEnabled = false;
60
60
  requestEnabled = false;
61
61
  requestHandles = /* @__PURE__ */ new Set();
62
+ credentialHandles = /* @__PURE__ */ new Map();
62
63
  requestGeneration = 0;
63
64
  lastWall = 0;
64
65
  autoAllocation;
@@ -84,6 +85,11 @@ var DiagnosticsCollector = class {
84
85
  const requests = this.data.requests;
85
86
  requests.interruptedOnReopen = Math.min(Number.MAX_SAFE_INTEGER, (requests.interruptedOnReopen ?? 0) + (requests.pending ?? 0));
86
87
  requests.pending = 0;
88
+ if (requests.credentialChanges) {
89
+ const credentials = requests.credentialChanges;
90
+ credentials.interruptedOnReopen = Math.min(Number.MAX_SAFE_INTEGER, (credentials.interruptedOnReopen ?? 0) + (credentials.pending ?? 0));
91
+ credentials.pending = 0;
92
+ }
87
93
  this.changed();
88
94
  }
89
95
  this.expire();
@@ -113,6 +119,7 @@ var DiagnosticsCollector = class {
113
119
  if (!Number.isSafeInteger(epoch)) throw new Error("COPILOT_DIAGNOSTICS_EPOCH_LIMIT");
114
120
  this.live.clear();
115
121
  this.requestHandles.clear();
122
+ this.credentialHandles.clear();
116
123
  this.requestGeneration++;
117
124
  this.autoAllocation.clear();
118
125
  this.data = {
@@ -159,6 +166,7 @@ var DiagnosticsCollector = class {
159
166
  }
160
167
  expire() {
161
168
  const now = this.wall();
169
+ for (const [handle, startedAt] of this.credentialHandles) if (startedAt <= now - 864e5) this.credentialHandles.delete(handle);
162
170
  const oldest = Math.floor((now - DIAGNOSTICS_RETENTION_MS) / 36e5) * 36e5;
163
171
  const kept = this.data.rows.filter((row) => row.hour > oldest);
164
172
  this.increment("evicted", this.data.rows.length - kept.length);
@@ -170,6 +178,13 @@ var DiagnosticsCollector = class {
170
178
  requests.evicted = Math.min(Number.MAX_SAFE_INTEGER, requests.evicted + requests.rows.length - retained.length);
171
179
  if (retained.length !== requests.rows.length) this.changed();
172
180
  requests.rows = retained;
181
+ const credentials = requests.credentialChanges;
182
+ if (credentials) {
183
+ const kept = credentials.rows.filter((row) => row.observedAt > now - REQUEST_DIAGNOSTICS_RETENTION_MS);
184
+ credentials.evicted = Math.min(Number.MAX_SAFE_INTEGER, credentials.evicted + credentials.rows.length - kept.length);
185
+ if (kept.length !== credentials.rows.length) this.changed();
186
+ credentials.rows = kept;
187
+ }
173
188
  }
174
189
  }
175
190
  add(operation, stage, metric, reason, bucket, count = 1, version = this.version) {
@@ -231,7 +246,11 @@ var DiagnosticsCollector = class {
231
246
  ...this.data,
232
247
  ...this.data.requests ? { requests: {
233
248
  ...this.data.requests,
234
- pending: this.requestHandles.size
249
+ pending: this.requestHandles.size,
250
+ ...this.data.requests.credentialChanges ? { credentialChanges: {
251
+ ...this.data.requests.credentialChanges,
252
+ pending: this.credentialHandles.size
253
+ } } : {}
235
254
  } } : {},
236
255
  autoAllocation: this.autoAllocation.snapshot(),
237
256
  updatedAt: this.wall(),
@@ -245,9 +264,78 @@ var DiagnosticsCollector = class {
245
264
  }
246
265
  setRequestEnabled(enabled) {
247
266
  if (this.requestEnabled !== enabled) this.requestGeneration++;
267
+ if (this.requestEnabled !== enabled) this.credentialHandles.clear();
248
268
  if (this.requestEnabled && !enabled) for (const handle of this.requestHandles) handle.finish("interrupted", "unknown");
249
269
  this.requestEnabled = enabled;
250
270
  }
271
+ beginCredentialChange() {
272
+ if (!this.requestEnabled || this.layer !== "host") return void 0;
273
+ this.expire();
274
+ const requests = this.data.requests ??= {
275
+ rows: [],
276
+ dropped: 0,
277
+ evicted: 0
278
+ };
279
+ const credentials = requests.credentialChanges ??= {
280
+ rows: [],
281
+ dropped: 0,
282
+ evicted: 0
283
+ };
284
+ if (this.credentialHandles.size >= 128) {
285
+ credentials.dropped = Math.min(Number.MAX_SAFE_INTEGER, credentials.dropped + 1);
286
+ this.changed();
287
+ return;
288
+ }
289
+ const changeId = crypto.randomUUID(), generation = this.requestGeneration, startedAt = this.wall();
290
+ const phases = /* @__PURE__ */ new Set();
291
+ let cancelled = false;
292
+ const handle = {
293
+ cancel: () => {
294
+ cancelled = true;
295
+ this.credentialHandles.delete(handle);
296
+ this.changed();
297
+ },
298
+ record: (evidence) => {
299
+ if (cancelled || !this.requestEnabled || generation !== this.requestGeneration || startedAt <= this.wall() - 864e5 || phases.has(evidence.phase)) return;
300
+ phases.add(evidence.phase);
301
+ if (evidence.phase === "commit" || evidence.reason !== "qualified") this.credentialHandles.delete(handle);
302
+ this.expire();
303
+ const current = this.data.requests?.credentialChanges;
304
+ if (!current) return;
305
+ const parsed = CredentialChangeSchema.safeParse({
306
+ ...evidence,
307
+ changeId,
308
+ observedAt: this.wall(),
309
+ version: this.version
310
+ });
311
+ if (!parsed.success) {
312
+ current.dropped = Math.min(Number.MAX_SAFE_INTEGER, current.dropped + 1);
313
+ this.changed();
314
+ return;
315
+ }
316
+ const rows = [...current.rows, parsed.data];
317
+ const evicted = rows.length > 128 ? 1 : 0;
318
+ if (evicted) rows.shift();
319
+ const candidate = {
320
+ ...this.data,
321
+ requests: {
322
+ ...this.data.requests,
323
+ credentialChanges: {
324
+ ...current,
325
+ rows,
326
+ evicted: Math.min(Number.MAX_SAFE_INTEGER, current.evicted + evicted)
327
+ }
328
+ }
329
+ };
330
+ if (DiagnosticsSnapshotSchema.safeParse(candidate).success) this.data = candidate;
331
+ else current.dropped = Math.min(Number.MAX_SAFE_INTEGER, current.dropped + 1);
332
+ this.changed();
333
+ }
334
+ };
335
+ this.credentialHandles.set(handle, startedAt);
336
+ this.changed();
337
+ return handle;
338
+ }
251
339
  beginRequest(start) {
252
340
  if (!this.requestEnabled) return void 0;
253
341
  const requests = this.data.requests ??= {
@@ -493,7 +581,7 @@ const result$1 = strictRemoteCodec("dsh-github-copilot#DiagnosticsView", Diagnos
493
581
  var package_default = {
494
582
  name: "dsh-github-copilot",
495
583
  description: "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
496
- version: "0.4.2-alpha.7",
584
+ version: "0.4.2-alpha.9",
497
585
  releaseNotes: "CHANGELOG.md",
498
586
  publishConfig: {
499
587
  "access": "public",
@@ -1982,25 +2070,41 @@ function normalizeGitHubCopilotOAuthCredential(credential) {
1982
2070
  * that DSH's built-in llm-pi-ai adapter owns.
1983
2071
  */
1984
2072
  const nativeRefreshResults = /* @__PURE__ */ new WeakSet();
2073
+ const nativeRefreshRejections = /* @__PURE__ */ new WeakMap();
1985
2074
  const refreshWrites = /* @__PURE__ */ new WeakMap();
1986
2075
  /** Only a validated native OAuth refresh may certify its exact returned object. */
1987
2076
  async function certifyCopilotNativeRefresh(previous, result, derive, signal) {
1988
2077
  const ids = (grant) => grant.availableModelIds === void 0 ? void 0 : JSON.stringify([...grant.availableModelIds].sort());
1989
- if (previous.refresh !== result.refresh || previous.enterpriseUrl !== result.enterpriseUrl || ids(previous) !== ids(result) || result.expires <= Date.now()) return;
2078
+ const reject = (reason) => {
2079
+ nativeRefreshRejections.set(result, reason);
2080
+ };
2081
+ if (previous.refresh !== result.refresh) return reject("account-changed");
2082
+ if (previous.enterpriseUrl !== result.enterpriseUrl) return reject("endpoint-changed");
2083
+ if (ids(previous) !== ids(result)) return reject("entitlements-changed");
2084
+ if (result.expires <= Date.now()) return reject("expired");
1990
2085
  const before = await derive(previous);
1991
2086
  const after = await derive(result);
1992
2087
  signal?.throwIfAborted();
1993
2088
  if (before.apiKey === previous.access && after.apiKey === result.access && trustedGitHubCopilotBaseUrl(before.baseUrl, previous) === trustedGitHubCopilotBaseUrl(after.baseUrl, result)) nativeRefreshResults.add(result);
2089
+ else reject(before.apiKey !== previous.access || after.apiKey !== result.access ? "auth-mismatch" : "endpoint-changed");
1994
2090
  }
1995
2091
  /** Consume exactly one notification from the serialized, certified write. */
1996
- function observeCopilotNativeRefresh(ctx, key) {
2092
+ function observeCopilotNativeRefresh(ctx, key, diagnostic) {
1997
2093
  const service = ctx.get("credentials");
1998
2094
  const write = service === void 0 ? void 0 : refreshWrites.get(service)?.get(key);
1999
- if (!write) return void 0;
2095
+ if (!write) {
2096
+ diagnostic?.("notification", "unknown-source");
2097
+ return;
2098
+ }
2000
2099
  if (++write.notifications !== 1) {
2100
+ write.reason = "duplicate-notification";
2001
2101
  write.settle(false);
2102
+ diagnostic?.("notification", write.reason);
2002
2103
  return;
2003
2104
  }
2105
+ diagnostic?.("notification", write.qualification);
2106
+ if (write.qualification !== "qualified") return void 0;
2107
+ if (diagnostic) write.committed.then(() => diagnostic("commit", write.reason));
2004
2108
  return write.committed;
2005
2109
  }
2006
2110
  function captureActiveGitHubCopilotBinding(ctx) {
@@ -2081,7 +2185,10 @@ function createGitHubCopilotCredentialStore(ctx, logicalProviderId = GITHUB_COPI
2081
2185
  const next = await mutate(toCredential(current));
2082
2186
  binding?.assertCurrent();
2083
2187
  const record = next === void 0 ? void 0 : toRecord(next);
2084
- if (next !== void 0 && nativeRefreshResults.delete(next)) {
2188
+ const qualified = next !== void 0 && nativeRefreshResults.delete(next);
2189
+ const rejected = next === void 0 ? void 0 : nativeRefreshRejections.get(next);
2190
+ if (next !== void 0) nativeRefreshRejections.delete(next);
2191
+ if (qualified || rejected !== void 0 && !writes.has(key)) {
2085
2192
  expected = record;
2086
2193
  let settle;
2087
2194
  const committed = new Promise((resolve) => {
@@ -2090,17 +2197,24 @@ function createGitHubCopilotCredentialStore(ctx, logicalProviderId = GITHUB_COPI
2090
2197
  pending = {
2091
2198
  notifications: 0,
2092
2199
  settle,
2093
- committed
2200
+ committed,
2201
+ qualification: qualified ? "qualified" : rejected,
2202
+ reason: "write-failed"
2094
2203
  };
2095
2204
  if (writes.has(key)) {
2096
- writes.get(key)?.settle(false);
2205
+ const previous = writes.get(key);
2206
+ previous.reason = "write-conflict";
2207
+ previous.settle(false);
2208
+ pending.reason = "write-conflict";
2097
2209
  pending.settle(false);
2098
2210
  } else writes.set(key, pending);
2099
2211
  }
2100
2212
  return record;
2101
2213
  });
2102
2214
  binding?.assertCurrent();
2103
- pending?.settle(pending.notifications === 1 && stored?.kind === "grant" && expected?.kind === "grant" && JSON.stringify(normalizeGitHubCopilotOAuthCredential(stored.payload)) === JSON.stringify(normalizeGitHubCopilotOAuthCredential(expected.payload)));
2215
+ const committed = pending?.qualification === "qualified" && pending.notifications === 1 && stored?.kind === "grant" && expected?.kind === "grant" && JSON.stringify(normalizeGitHubCopilotOAuthCredential(stored.payload)) === JSON.stringify(normalizeGitHubCopilotOAuthCredential(expected.payload));
2216
+ if (pending && pending.reason === "write-failed") pending.reason = committed ? "qualified" : pending.notifications === 0 ? "missing-notification" : "commit-mismatch";
2217
+ pending?.settle(committed);
2104
2218
  return toCredential(stored);
2105
2219
  } finally {
2106
2220
  pending?.settle(false);
@@ -4259,7 +4373,7 @@ function accountBaseURL(value) {
4259
4373
  return url.origin;
4260
4374
  }
4261
4375
  /** Materialize advertised capabilities only; model names and the local static catalog never select the API. */
4262
- function accountModelFromDescriptor(descriptor, baseURL) {
4376
+ function accountModelFromDescriptor(descriptor, baseURL, classifierReasoningOff = false) {
4263
4377
  const map = {
4264
4378
  off: null,
4265
4379
  minimal: null,
@@ -4270,9 +4384,11 @@ function accountModelFromDescriptor(descriptor, baseURL) {
4270
4384
  max: null
4271
4385
  };
4272
4386
  const advertised = new Set(descriptor.reasoning.advertisedEfforts);
4387
+ if (classifierReasoningOff && advertised.has("off")) map.off = "none";
4273
4388
  const supported = enabledLevels.filter((level) => advertised.has(level) && (descriptor.api !== "anthropic-messages" || descriptor.reasoning.adaptiveThinking === true && level !== "minimal"));
4274
4389
  for (const level of supported) map[level] = level;
4275
4390
  const mapped = new Set(supported);
4391
+ if (map.off !== null) mapped.add("off");
4276
4392
  const unmapped = [.../* @__PURE__ */ new Set([...descriptor.reasoning.unmappedEfforts, ...descriptor.reasoning.advertisedEfforts.filter((level) => !mapped.has(level))])].sort();
4277
4393
  const model = {
4278
4394
  id: descriptor.id,
@@ -4284,7 +4400,7 @@ function accountModelFromDescriptor(descriptor, baseURL) {
4284
4400
  maxTokens: descriptor.maxTokens,
4285
4401
  ...descriptor.maxInputTokens === void 0 ? {} : { maxInputTokens: descriptor.maxInputTokens },
4286
4402
  input: [...descriptor.input],
4287
- reasoning: supported.length > 0,
4403
+ reasoning: supported.length > 0 || map.off !== null,
4288
4404
  thinkingLevelMap: Object.freeze(map),
4289
4405
  unmappedReasoningEfforts: Object.freeze(unmapped),
4290
4406
  ...descriptor.reasoning.minThinkingBudget === void 0 ? {} : { minThinkingBudget: descriptor.reasoning.minThinkingBudget },
@@ -4311,11 +4427,11 @@ function accountModelFromDescriptor(descriptor, baseURL) {
4311
4427
  return Object.freeze(model);
4312
4428
  }
4313
4429
  /** Create a descriptor-driven, OAuth-only provider using native SDK serialization for all supported endpoints. */
4314
- function createAccountProvider(descriptors, guard, baseURL) {
4430
+ function createAccountProvider(descriptors, guard, baseURL, classifierReasoningOff = false) {
4315
4431
  const native = githubCopilotProvider();
4316
4432
  const oauth = native.auth.oauth;
4317
4433
  if (oauth === void 0) throw new Error("COPILOT_MANAGED_OAUTH_UNAVAILABLE");
4318
- const models = Object.freeze(descriptors.map((descriptor) => accountModelFromDescriptor(descriptor, baseURL)));
4434
+ const models = Object.freeze(descriptors.map((descriptor) => accountModelFromDescriptor(descriptor, baseURL, classifierReasoningOff)));
4319
4435
  const table = new Map(models.map((model) => [model.id, model]));
4320
4436
  if (table.size !== models.length) throw new Error("COPILOT_MANAGED_DUPLICATE_MODEL");
4321
4437
  const selected = () => {
@@ -13238,7 +13354,7 @@ function installAutoModelRouting(ctx, dependencies) {
13238
13354
  }
13239
13355
  function taskClassifierModel(models, highCostModelIds, modelId = "") {
13240
13356
  const highCost = new Set(normalizeHighCostModelIds(highCostModelIds));
13241
- return models.filter((model) => (modelId !== "" ? model.id === modelId : 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) => {
13357
+ return models.filter((model) => (modelId !== "" ? model.id === modelId : model.category === "lightweight") && model.input.includes("text") && model.reasoning.advertisedEfforts.includes("off")).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) => {
13242
13358
  const budget = calculateRequestBudget(model, 128);
13243
13359
  return budget.ok && budget.budget.hardInputLimit >= 12e3;
13244
13360
  });
@@ -13247,6 +13363,7 @@ function taskClassifierModel(models, highCostModelIds, modelId = "") {
13247
13363
  async function classifyTaskWithAdapter(model, input, signal, stream, observe, reasoningOffSupported = false, checkpoint) {
13248
13364
  checkpoint?.();
13249
13365
  if (signal.aborted) throw signal.reason;
13366
+ if (!model.reasoning.advertisedEfforts.includes("off") || !reasoningOffSupported) throw new Error("COPILOT_AUTO_CLASSIFIER_UNAVAILABLE");
13250
13367
  let output = "";
13251
13368
  let finished = false;
13252
13369
  observe?.({ stage: "adapter-started" });
@@ -13266,7 +13383,7 @@ async function classifyTaskWithAdapter(model, input, signal, stream, observe, re
13266
13383
  }]
13267
13384
  })],
13268
13385
  maxTokens: 128,
13269
- ...reasoningOffSupported && model.reasoning.advertisedEfforts.includes("off") ? { reasoningEffort: ReasoningEffortId("off") } : {}
13386
+ reasoningEffort: ReasoningEffortId("off")
13270
13387
  })) {
13271
13388
  checkpoint?.();
13272
13389
  checkpoint?.();
@@ -13403,6 +13520,26 @@ var PreviewLifetime = class {
13403
13520
  this.source.invalidate();
13404
13521
  for (const [wire, state] of this.wires) if (!preserveDispatched || !state.dispatched) wire.abort(new ManagedWireAbortError("COPILOT_PREVIEW_CREDENTIAL_CHANGED"));
13405
13522
  }
13523
+ credentialChangeCounts(preserveDispatched) {
13524
+ let preparing = 0, dispatched = 0, alreadyAborted = 0, preserved = 0, revoked = 0;
13525
+ for (const [wire, state] of this.wires) {
13526
+ if (wire.signal.aborted) {
13527
+ alreadyAborted++;
13528
+ continue;
13529
+ }
13530
+ if (state.dispatched) dispatched++;
13531
+ else preparing++;
13532
+ if (preserveDispatched && state.dispatched) preserved++;
13533
+ else revoked++;
13534
+ }
13535
+ return {
13536
+ preparing,
13537
+ dispatched,
13538
+ alreadyAborted,
13539
+ preserved,
13540
+ revoked
13541
+ };
13542
+ }
13406
13543
  dispose() {
13407
13544
  if (!this.active) return;
13408
13545
  this.active = false;
@@ -13592,10 +13729,11 @@ var PreviewAdapter = class extends PiAiAdapter {
13592
13729
  refreshRejected;
13593
13730
  requestBudgetSettings;
13594
13731
  accountModelSettings;
13732
+ classifierReasoningOff;
13595
13733
  replayRecovery;
13596
13734
  requestCheckpoint;
13597
13735
  captureRequest;
13598
- constructor(lifetime, optionsFor, discoverSnapshot, refreshRejected, requestBudgetSettings, accountModelSettings, replayRecovery, requestCheckpoint, captureRequest = () => void 0) {
13736
+ constructor(lifetime, optionsFor, discoverSnapshot, refreshRejected, requestBudgetSettings, accountModelSettings, classifierReasoningOff = false, replayRecovery, requestCheckpoint, captureRequest = () => void 0) {
13599
13737
  super(optionsFor());
13600
13738
  this.lifetime = lifetime;
13601
13739
  this.optionsFor = optionsFor;
@@ -13603,6 +13741,7 @@ var PreviewAdapter = class extends PiAiAdapter {
13603
13741
  this.refreshRejected = refreshRejected;
13604
13742
  this.requestBudgetSettings = requestBudgetSettings;
13605
13743
  this.accountModelSettings = accountModelSettings;
13744
+ this.classifierReasoningOff = classifierReasoningOff;
13606
13745
  this.replayRecovery = replayRecovery;
13607
13746
  this.requestCheckpoint = requestCheckpoint;
13608
13747
  this.captureRequest = captureRequest;
@@ -13757,7 +13896,7 @@ var PreviewAdapter = class extends PiAiAdapter {
13757
13896
  const signal = AbortSignal.any([lease.signal, ...options.signal === void 0 ? [] : [options.signal]]);
13758
13897
  if (signal.aborted) throw abortFailure(signal);
13759
13898
  const policy = resolveRequestBudgetPolicy(owner.requestBudgetSettings());
13760
- const model = accountModelFromDescriptor(lease.descriptor, lease.proof.baseURL);
13899
+ const model = accountModelFromDescriptor(lease.descriptor, lease.proof.baseURL, owner.classifierReasoningOff);
13761
13900
  if (options.reasoningEffort !== void 0) {
13762
13901
  const mapping = Object.entries(model.thinkingLevelMap ?? {}).find(([level]) => level === options.reasoningEffort)?.[1];
13763
13902
  if (typeof mapping !== "string" || mapping.length === 0) throw failure("COPILOT_PREVIEW_REASONING_UNSUPPORTED", "INVALID_REQUEST");
@@ -14126,7 +14265,7 @@ function createAccountRuntime(ctx, config, binding, exclusionTurns, replayRecove
14126
14265
  lastValidatedProof = void 0;
14127
14266
  }
14128
14267
  };
14129
- const { provider } = createAccountProvider(lease?.snapshot.models ?? [], guard, lease?.proof.baseURL ?? "https://api.individual.githubcopilot.com");
14268
+ const { provider } = createAccountProvider(lease?.snapshot.models ?? [], guard, lease?.proof.baseURL ?? "https://api.individual.githubcopilot.com", classifier);
14130
14269
  const profile = resolvedProfile(provider, {
14131
14270
  ...requestConfig,
14132
14271
  ...classifier ? { reasoning: void 0 } : {},
@@ -14151,7 +14290,7 @@ function createAccountRuntime(ctx, config, binding, exclusionTurns, replayRecove
14151
14290
  };
14152
14291
  };
14153
14292
  return {
14154
- adapter: new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings, replayRecovery, void 0, (signal) => ctx.get("githubCopilotSessionAccounts")?.recordRequest(signal)),
14293
+ adapter: new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings, false, replayRecovery, void 0, (signal) => ctx.get("githubCopilotSessionAccounts")?.recordRequest(signal)),
14155
14294
  preview: {
14156
14295
  getView,
14157
14296
  refresh,
@@ -14247,7 +14386,7 @@ function createAccountRuntime(ctx, config, binding, exclusionTurns, replayRecove
14247
14386
  });
14248
14387
  const revision = lifetime.revision;
14249
14388
  const classifierOptionsFor = (lease, hooks) => optionsFor(lease, hooks, true);
14250
- const adapter = new PreviewAdapter(lifetime, classifierOptionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings, void 0, checkpoint);
14389
+ const adapter = new PreviewAdapter(lifetime, classifierOptionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings, true, void 0, checkpoint);
14251
14390
  try {
14252
14391
  const prepared = await adapter.prepareCall(GITHUB_COPILOT_PREVIEW_PROVIDER_ID, model.id, signal);
14253
14392
  checkpoint?.();
@@ -14415,11 +14554,47 @@ function apply$1(ctx, config = {}) {
14415
14554
  if (event.type === "turn/end") exclusionTurns.end(session);
14416
14555
  });
14417
14556
  const removeListener = ctx.on("credentials/record-updated", (key) => {
14418
- const refresh = observeCopilotNativeRefresh(ctx, key);
14557
+ let notificationReason = "unknown-source";
14558
+ let commitReason = "write-failed";
14559
+ const refresh = observeCopilotNativeRefresh(ctx, key, (phase, reason) => {
14560
+ if (phase === "notification") notificationReason = reason;
14561
+ else commitReason = reason;
14562
+ });
14419
14563
  for (const [accountId, runtime] of runtimes) if ((accountId === "canonical" ? "llm-pi-ai/github-copilot" : `github-copilot/account-${accountId}`) === key) {
14564
+ let evidence;
14565
+ try {
14566
+ evidence = ctx.get("githubCopilotDiagnostics")?.collector.beginCredentialChange();
14567
+ } catch {
14568
+ ctx.logger.warn("COPILOT_CREDENTIAL_DIAGNOSTICS_CAPTURE_FAILED");
14569
+ }
14570
+ const recordEvidence = (phase, reason, preserve) => {
14571
+ if (!evidence) return;
14572
+ try {
14573
+ const counts = runtime.lifetime.credentialChangeCounts(preserve);
14574
+ evidence.record({
14575
+ phase,
14576
+ reason,
14577
+ ...counts,
14578
+ ...phase === "commit" && preserve ? {
14579
+ preserved: counts.preparing + counts.dispatched,
14580
+ revoked: 0
14581
+ } : {}
14582
+ });
14583
+ } catch {
14584
+ ctx.logger.warn("COPILOT_CREDENTIAL_DIAGNOSTICS_CAPTURE_FAILED");
14585
+ }
14586
+ };
14587
+ recordEvidence("notification", notificationReason, refresh !== void 0);
14420
14588
  runtime.invalidate(refresh !== void 0);
14421
14589
  if (refresh !== void 0) refresh.then((committed) => {
14422
- if (!committed && !disposed) runtime.invalidate();
14590
+ if (!disposed) {
14591
+ recordEvidence("commit", commitReason, committed);
14592
+ if (!committed) runtime.invalidate();
14593
+ } else try {
14594
+ evidence?.cancel();
14595
+ } catch {
14596
+ ctx.logger.warn("COPILOT_CREDENTIAL_DIAGNOSTICS_CAPTURE_FAILED");
14597
+ }
14423
14598
  });
14424
14599
  }
14425
14600
  });
@@ -1,5 +1,5 @@
1
1
  import "./copilot-identity-DRZY_d2X.js";
2
- import { d as diagnosticsReason, u as diagnosticsOutcome } from "./diagnostics-types-BDIc78T4.js";
2
+ import { d as diagnosticsReason, u as diagnosticsOutcome } from "./diagnostics-types-C1BD6ayS.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";
package/lib/remote.js CHANGED
@@ -893,6 +893,32 @@ const upload = z.discriminatedUnion("state", [
893
893
  requestCount: integer$1
894
894
  }).strict()
895
895
  ]);
896
+ const CredentialChangeReasonSchema = z.enum([
897
+ "qualified",
898
+ "unknown-source",
899
+ "account-changed",
900
+ "endpoint-changed",
901
+ "entitlements-changed",
902
+ "expired",
903
+ "auth-mismatch",
904
+ "duplicate-notification",
905
+ "missing-notification",
906
+ "commit-mismatch",
907
+ "write-failed",
908
+ "write-conflict"
909
+ ]);
910
+ const CredentialChangeSchema = z.object({
911
+ changeId: z.string().uuid(),
912
+ observedAt: integer$1,
913
+ version: z.string().max(64).regex(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/),
914
+ phase: z.enum(["notification", "commit"]),
915
+ reason: CredentialChangeReasonSchema,
916
+ preparing: integer$1,
917
+ dispatched: integer$1,
918
+ alreadyAborted: integer$1,
919
+ preserved: integer$1,
920
+ revoked: integer$1
921
+ }).strict();
896
922
  const RequestDiagnosticSchema = z.object({
897
923
  streamId: z.string().uuid(),
898
924
  dispatchIndex: integer$1.min(1),
@@ -939,7 +965,14 @@ const RequestDiagnosticsSchema = z.object({
939
965
  dropped: integer$1,
940
966
  evicted: integer$1,
941
967
  pending: integer$1.max(128).optional(),
942
- interruptedOnReopen: integer$1.optional()
968
+ interruptedOnReopen: integer$1.optional(),
969
+ credentialChanges: z.object({
970
+ rows: z.array(CredentialChangeSchema).max(128),
971
+ dropped: integer$1,
972
+ evicted: integer$1,
973
+ pending: integer$1.max(128).optional(),
974
+ interruptedOnReopen: integer$1.optional()
975
+ }).strict().optional()
943
976
  }).strict();
944
977
  //#endregion
945
978
  //#region lib/types/diagnostics-types.js
@@ -7,11 +7,12 @@ import { type CredentialStore, type OAuthAuth } from '@earendil-works/pi-ai';
7
7
  import { GITHUB_COPILOT_PROVIDER_ID, GITHUB_COPILOT_PREVIEW_PROVIDER_ID } from './copilot-identity.ts';
8
8
  import type { GitHubCopilotOAuthCredential } from './copilot-grant.ts';
9
9
  import type { CopilotAccountBinding } from './copilot-accounts-types.ts';
10
+ import type { CredentialChangeReason } from './request-diagnostics.ts';
10
11
  export { normalizeGitHubCopilotOAuthCredential } from './copilot-grant.ts';
11
12
  /** Only a validated native OAuth refresh may certify its exact returned object. */
12
13
  export declare function certifyCopilotNativeRefresh(previous: GitHubCopilotOAuthCredential, result: GitHubCopilotOAuthCredential, derive: OAuthAuth['toAuth'], signal?: AbortSignal): Promise<void>;
13
14
  /** Consume exactly one notification from the serialized, certified write. */
14
- export declare function observeCopilotNativeRefresh(ctx: Context, key: string): Promise<boolean> | undefined;
15
+ export declare function observeCopilotNativeRefresh(ctx: Context, key: string, diagnostic?: (phase: 'notification' | 'commit', reason: CredentialChangeReason) => void): Promise<boolean> | undefined;
15
16
  export declare function captureActiveGitHubCopilotBinding(ctx: Context): CopilotAccountBinding | undefined;
16
17
  /** Bind exactly one logical route to the canonical Host-owned credential record. */
17
18
  export declare function createGitHubCopilotCredentialStore(ctx: Context, logicalProviderId?: typeof GITHUB_COPILOT_PROVIDER_ID | typeof GITHUB_COPILOT_PREVIEW_PROVIDER_ID, binding?: CopilotAccountBinding): CredentialStore;
@@ -195,6 +195,7 @@ export declare const DiagnosticsAnalysisReportSchema: z.ZodObject<{
195
195
  }>;
196
196
  stage: z.ZodEnum<{
197
197
  ended: "ended";
198
+ dispatched: "dispatched";
198
199
  admitted: "admitted";
199
200
  "rpc-invoked": "rpc-invoked";
200
201
  "host-received": "host-received";
@@ -210,7 +211,6 @@ export declare const DiagnosticsAnalysisReportSchema: z.ZodObject<{
210
211
  "cache-hit": "cache-hit";
211
212
  "joined-flight": "joined-flight";
212
213
  cooldown: "cooldown";
213
- dispatched: "dispatched";
214
214
  }>;
215
215
  bucket: z.ZodNumber;
216
216
  count: z.ZodNumber;
@@ -6,6 +6,7 @@ export declare function DiagnosticsCard({ remote }: {
6
6
  }): import("react").DetailedReactHTMLElement<{
7
7
  'aria-label': string;
8
8
  'data-copilot-native-ui': boolean;
9
+ 'data-copilot-diagnostics': boolean;
9
10
  style: CSSProperties;
10
11
  }, HTMLElement>;
11
12
  //# sourceMappingURL=diagnostics-card.d.ts.map
@@ -1,6 +1,6 @@
1
1
  import type { DiagnosticsOperation, DiagnosticsStage, DiagnosticsOutcome, DiagnosticsReason, DiagnosticsRow, DiagnosticsSnapshot } from './diagnostics-types.ts';
2
2
  import type { AutoSelectionExplanation } from './auto-model-routing.ts';
3
- import type { RequestDiagnosticHandle, RequestDiagnosticStart } from './request-diagnostics.ts';
3
+ import type { RequestDiagnosticHandle, RequestDiagnosticStart, CredentialChangeHandle } from './request-diagnostics.ts';
4
4
  export interface DiagnosticsHandle {
5
5
  stage(stage: DiagnosticsStage): void;
6
6
  finish(outcome: DiagnosticsOutcome, reason?: DiagnosticsReason): void;
@@ -19,6 +19,7 @@ export declare class DiagnosticsCollector {
19
19
  private autoAllocationEnabled;
20
20
  private requestEnabled;
21
21
  private readonly requestHandles;
22
+ private readonly credentialHandles;
22
23
  private requestGeneration;
23
24
  private lastWall;
24
25
  private readonly autoAllocation;
@@ -37,6 +38,7 @@ export declare class DiagnosticsCollector {
37
38
  snapshot(): DiagnosticsSnapshot;
38
39
  close(): void;
39
40
  setRequestEnabled(enabled: boolean): void;
41
+ beginCredentialChange(): CredentialChangeHandle | undefined;
40
42
  beginRequest(start: RequestDiagnosticStart): RequestDiagnosticHandle | undefined;
41
43
  isRequestEnabled(): boolean;
42
44
  noteDropped(): void;