dsh-github-copilot 0.4.0-alpha.59 → 0.4.0-alpha.61

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
@@ -1646,7 +1646,7 @@ let GitHubCopilotUsageController = (() => {
1646
1646
  //#endregion
1647
1647
  //#region package.json
1648
1648
  var name$1 = "dsh-github-copilot";
1649
- var version = "0.4.0-alpha.59";
1649
+ var version = "0.4.0-alpha.61";
1650
1650
  //#endregion
1651
1651
  //#region lib/types/probe.js
1652
1652
  /**
@@ -2087,6 +2087,7 @@ const Config = z.object({
2087
2087
  probeTimeoutMs: z.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e4),
2088
2088
  accountModelTtlMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(864e5),
2089
2089
  accountModelFailureCooldownMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(3e5),
2090
+ excludedModelIds: z.array(z.string()).default([]).hidden(),
2090
2091
  requestBudgetSafetyTokens: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens),
2091
2092
  requestBudgetPressureRatio: z.number().step(.01).min(.01).max(1).default(DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio),
2092
2093
  compactionReasoning: z.union(["prefer-low", "preserve"]).default(DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning),
@@ -4235,6 +4236,20 @@ function migrationStatus(ctx) {
4235
4236
  result.complete.routes = result.routes.nativeConfigured !== null && result.routes.nativeRegistered !== null && result.routes.managedRegistered !== null;
4236
4237
  return result;
4237
4238
  }
4239
+ const MAX_MODEL_ID_LENGTH = 512;
4240
+ function normalizeExcludedModelIds(value) {
4241
+ if (value === void 0) return [];
4242
+ if (!Array.isArray(value) || value.length > 512) throw new Error("COPILOT_MODEL_EXCLUSIONS_INVALID");
4243
+ const ids = /* @__PURE__ */ new Set();
4244
+ for (const candidate of value) {
4245
+ 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");
4246
+ ids.add(candidate);
4247
+ }
4248
+ return [...ids].toSorted();
4249
+ }
4250
+ function excludedModelSet(value) {
4251
+ return new Set(normalizeExcludedModelIds(value));
4252
+ }
4238
4253
  //#endregion
4239
4254
  //#region lib/types/authorization-controller.js
4240
4255
  /**
@@ -4360,6 +4375,77 @@ function accountModelsView(ctx) {
4360
4375
  return empty;
4361
4376
  }
4362
4377
  }
4378
+ function modelSelection(value) {
4379
+ const selection = object$3(value);
4380
+ const provider = selection?.provider;
4381
+ const model = selection?.model;
4382
+ return typeof provider === "string" && provider.length > 0 && typeof model === "string" && model.length > 0 ? {
4383
+ provider,
4384
+ model
4385
+ } : void 0;
4386
+ }
4387
+ function fixedPreviewModel(value) {
4388
+ const selection = modelSelection(value);
4389
+ return selection?.provider === "github-copilot-preview" && autoModelPreference(selection.model) === void 0 ? selection.model : void 0;
4390
+ }
4391
+ function selectedFixedModelIds(ctx) {
4392
+ try {
4393
+ const defaults = service(ctx, "agentDefaultModel", ["currentSelection"]);
4394
+ const agents = service(ctx, "agents", ["list"]);
4395
+ const projections = service(ctx, "sessionProjections", ["stateOf"]);
4396
+ const locked = /* @__PURE__ */ new Set();
4397
+ const currentSelection = Reflect.get(defaults, "currentSelection");
4398
+ const defaultValue = typeof currentSelection === "function" ? Reflect.apply(currentSelection, defaults, []) : void 0;
4399
+ if (defaultValue !== null && defaultValue !== void 0 && modelSelection(defaultValue) === void 0) return void 0;
4400
+ const defaultSelection = fixedPreviewModel(defaultValue);
4401
+ if (defaultSelection !== void 0) locked.add(defaultSelection);
4402
+ const list = Reflect.get(agents, "list");
4403
+ const rows = typeof list === "function" ? Reflect.apply(list, agents, []) : void 0;
4404
+ if (!Array.isArray(rows) || rows.length > 1024) return void 0;
4405
+ const stateOf = Reflect.get(projections, "stateOf");
4406
+ if (typeof stateOf !== "function") return void 0;
4407
+ for (const candidate of rows) {
4408
+ const session = object$3(object$3(candidate)?.session);
4409
+ if (session === void 0) return void 0;
4410
+ const state = object$3(Reflect.apply(stateOf, projections, [session, "modelSelection"]));
4411
+ if (state === void 0 || !("pending" in state)) return void 0;
4412
+ const pending = state.pending;
4413
+ if (pending !== null && modelSelection(pending) === void 0) return void 0;
4414
+ let selected = pending === null ? void 0 : fixedPreviewModel(pending);
4415
+ if (pending === null) {
4416
+ const requestHeader = session.requestHeader;
4417
+ const header = typeof requestHeader === "function" ? object$3(Reflect.apply(requestHeader, session, [])) : void 0;
4418
+ if (header?.config !== void 0 && modelSelection(header.config) === void 0) return void 0;
4419
+ selected = fixedPreviewModel(header?.config);
4420
+ }
4421
+ if (selected !== void 0) locked.add(selected);
4422
+ }
4423
+ return [...locked].toSorted();
4424
+ } catch {
4425
+ return;
4426
+ }
4427
+ }
4428
+ function modelPreferencesView(ctx, accountModels, error) {
4429
+ try {
4430
+ const descriptor = service(ctx, "settings", ["describe", "mutate"]).describe({ redactSecrets: true }).find((item) => item.ns === GITHUB_COPILOT_SETTINGS_NAMESPACE$1);
4431
+ if (descriptor === void 0 || !Number.isSafeInteger(descriptor.revision) || descriptor.revision < 0) return void 0;
4432
+ const excludedModelIds = normalizeExcludedModelIds(object$3(descriptor.value)?.excludedModelIds);
4433
+ const lockedModelIds = selectedFixedModelIds(ctx);
4434
+ if (lockedModelIds === void 0) return void 0;
4435
+ const available = new Set(accountModels?.models.map((model) => model.id) ?? []);
4436
+ return {
4437
+ state: error === void 0 ? "ready" : "error",
4438
+ writable: true,
4439
+ revision: descriptor.revision,
4440
+ excludedModelIds,
4441
+ lockedModelIds,
4442
+ unavailableExcludedModelIds: excludedModelIds.filter((id) => !available.has(id)),
4443
+ ...error === void 0 ? {} : { error }
4444
+ };
4445
+ } catch {
4446
+ return;
4447
+ }
4448
+ }
4363
4449
  function validateGrant(record) {
4364
4450
  if (record.kind !== "grant") throw new Error("github-copilot: the configured credential is not an OAuth grant");
4365
4451
  normalizeGitHubCopilotOAuthCredential(record.payload);
@@ -4514,6 +4600,8 @@ let GitHubCopilotAuthorizationController = (() => {
4514
4600
  let _instanceExtraInitializers = [];
4515
4601
  let _migrationStatus_decorators;
4516
4602
  let _status_decorators;
4603
+ let _excludeModel_decorators;
4604
+ let _restoreModel_decorators;
4517
4605
  let _discoverModels_decorators;
4518
4606
  let _ensureModels_decorators;
4519
4607
  let _reconcile_decorators;
@@ -4525,6 +4613,8 @@ let GitHubCopilotAuthorizationController = (() => {
4525
4613
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
4526
4614
  _migrationStatus_decorators = [Remote];
4527
4615
  _status_decorators = [Remote];
4616
+ _excludeModel_decorators = [Remote];
4617
+ _restoreModel_decorators = [Remote];
4528
4618
  _discoverModels_decorators = [Remote];
4529
4619
  _ensureModels_decorators = [Remote];
4530
4620
  _reconcile_decorators = [Remote];
@@ -4553,6 +4643,28 @@ let GitHubCopilotAuthorizationController = (() => {
4553
4643
  },
4554
4644
  metadata: _metadata
4555
4645
  }, null, _instanceExtraInitializers);
4646
+ __esDecorate(this, null, _excludeModel_decorators, {
4647
+ kind: "method",
4648
+ name: "excludeModel",
4649
+ static: false,
4650
+ private: false,
4651
+ access: {
4652
+ has: (obj) => "excludeModel" in obj,
4653
+ get: (obj) => obj.excludeModel
4654
+ },
4655
+ metadata: _metadata
4656
+ }, null, _instanceExtraInitializers);
4657
+ __esDecorate(this, null, _restoreModel_decorators, {
4658
+ kind: "method",
4659
+ name: "restoreModel",
4660
+ static: false,
4661
+ private: false,
4662
+ access: {
4663
+ has: (obj) => "restoreModel" in obj,
4664
+ get: (obj) => obj.restoreModel
4665
+ },
4666
+ metadata: _metadata
4667
+ }, null, _instanceExtraInitializers);
4556
4668
  __esDecorate(this, null, _discoverModels_decorators, {
4557
4669
  kind: "method",
4558
4670
  name: "discoverModels",
@@ -4631,6 +4743,7 @@ let GitHubCopilotAuthorizationController = (() => {
4631
4743
  reconciliationFailed = false;
4632
4744
  attempt;
4633
4745
  authorizationMilestone;
4746
+ modelPreferenceFailure;
4634
4747
  constructor(ctx) {
4635
4748
  super(ctx, "githubCopilotAuthorization", { namespace: "githubCopilot" });
4636
4749
  }
@@ -4664,6 +4777,7 @@ let GitHubCopilotAuthorizationController = (() => {
4664
4777
  }
4665
4778
  const inFlight = authorization.describe("llm-pi-ai/github-copilot")?.inFlight === true || this.attempt !== void 0;
4666
4779
  const discovered = accountModelsView(this.ctx);
4780
+ const modelPreferences = modelPreferencesView(this.ctx, discovered, this.modelPreferenceFailure);
4667
4781
  return {
4668
4782
  phase: inFlight ? "authorizing" : this.failure !== void 0 ? "error" : record.configured ? "signed-in" : "signed-out",
4669
4783
  configured: record.configured,
@@ -4673,10 +4787,17 @@ let GitHubCopilotAuthorizationController = (() => {
4673
4787
  route,
4674
4788
  ...catalog === void 0 ? {} : { catalog },
4675
4789
  ...discovered === void 0 ? {} : { accountModels: discovered },
4790
+ ...modelPreferences === void 0 ? {} : { modelPreferences },
4676
4791
  ...this.failure === void 0 ? {} : { error: this.failure },
4677
4792
  ...this.authorizationMilestone === void 0 ? {} : { authorizationMilestone: this.authorizationMilestone }
4678
4793
  };
4679
4794
  }
4795
+ async excludeModel(modelId) {
4796
+ return this.updateModelExclusion(modelId, true);
4797
+ }
4798
+ async restoreModel(modelId) {
4799
+ return this.updateModelExclusion(modelId, false);
4800
+ }
4680
4801
  /** Explicit model discovery: may refresh OAuth and GET the account catalog, never changes selection. */
4681
4802
  async discoverModels() {
4682
4803
  return this.loadAccountModels(true);
@@ -4802,6 +4923,44 @@ let GitHubCopilotAuthorizationController = (() => {
4802
4923
  this.authorizationMilestone = void 0;
4803
4924
  return this.status();
4804
4925
  }
4926
+ async updateModelExclusion(modelId, exclude) {
4927
+ let normalized;
4928
+ try {
4929
+ [normalized] = normalizeExcludedModelIds([modelId]);
4930
+ } catch {
4931
+ this.modelPreferenceFailure = "COPILOT_MODEL_EXCLUSION_SAVE_FAILED";
4932
+ return this.status();
4933
+ }
4934
+ const current = modelPreferencesView(this.ctx, accountModelsView(this.ctx));
4935
+ if (current === void 0 || current.revision === void 0) {
4936
+ this.modelPreferenceFailure = "COPILOT_MODEL_PREFERENCES_UNAVAILABLE";
4937
+ return this.status();
4938
+ }
4939
+ if (exclude && current.lockedModelIds.includes(normalized)) {
4940
+ this.modelPreferenceFailure = "COPILOT_MODEL_EXCLUSION_SELECTED";
4941
+ return this.status();
4942
+ }
4943
+ const ids = new Set(current.excludedModelIds);
4944
+ if (exclude) ids.add(normalized);
4945
+ else ids.delete(normalized);
4946
+ const next = normalizeExcludedModelIds([...ids]);
4947
+ if (next.length === current.excludedModelIds.length && next.every((id, index) => id === current.excludedModelIds[index])) {
4948
+ this.modelPreferenceFailure = void 0;
4949
+ return this.status();
4950
+ }
4951
+ try {
4952
+ await service(this.ctx, "settings", ["describe", "mutate"]).mutate(GITHUB_COPILOT_SETTINGS_NAMESPACE$1, [{
4953
+ op: "set",
4954
+ path: ["excludedModelIds"],
4955
+ value: next
4956
+ }], current.revision);
4957
+ this.modelPreferenceFailure = void 0;
4958
+ } catch (cause) {
4959
+ const record = object$3(cause);
4960
+ this.modelPreferenceFailure = record?.code === "SETTINGS_CONFLICT" || cause instanceof Error && /conflict/i.test(cause.message) ? "COPILOT_MODEL_EXCLUSION_CONFLICT" : "COPILOT_MODEL_EXCLUSION_SAVE_FAILED";
4961
+ }
4962
+ return this.status();
4963
+ }
4805
4964
  async ensureProviderProfile() {
4806
4965
  try {
4807
4966
  await ensureGitHubCopilotProviderProfile(this.ctx);
@@ -5048,6 +5207,112 @@ function normalizeCopilotResponsesPayload(payload) {
5048
5207
  throw new CopilotResponsesReplayError("invalid-payload");
5049
5208
  }
5050
5209
  }
5210
+ const retryLifetimeMs = 6e4;
5211
+ const maxRetryBytes = 2097152;
5212
+ function cacheBytes(value) {
5213
+ let json;
5214
+ try {
5215
+ json = JSON.stringify(value);
5216
+ } catch {
5217
+ return;
5218
+ }
5219
+ if (json === void 0 || Buffer.byteLength(json, "utf8") > maxRetryBytes) return void 0;
5220
+ return json;
5221
+ }
5222
+ /** A single lease can admit one HTTP-verified retry at a time; it never reads durable history. */
5223
+ var ResponsesRetryReplay = class {
5224
+ snapshot;
5225
+ active = 0;
5226
+ disposed = false;
5227
+ dispose() {
5228
+ this.disposed = true;
5229
+ this.snapshot = void 0;
5230
+ }
5231
+ belongsTo(sessionId) {
5232
+ return this.snapshot?.sessionId === sessionId;
5233
+ }
5234
+ begin(context, signal, sessionId, modelId) {
5235
+ const contextBytes = cacheBytes(context);
5236
+ const overlapping = this.active++ !== 0;
5237
+ if (overlapping) this.snapshot = void 0;
5238
+ const previous = this.snapshot;
5239
+ if (previous !== void 0 && (signal !== previous.signal || signal?.aborted || previous.sessionId !== sessionId || previous.modelId !== modelId || previous.context !== contextBytes || Date.now() - previous.at >= retryLifetimeMs)) this.snapshot = void 0;
5240
+ const eligible = contextBytes !== void 0 && !overlapping && !this.disposed && !signal?.aborted && this.snapshot;
5241
+ let candidate;
5242
+ let payloadBytes;
5243
+ let finished = false;
5244
+ let observed = false;
5245
+ return {
5246
+ normalize: (payload) => {
5247
+ if (this.disposed || signal?.aborted) throw new CopilotResponsesReplayError();
5248
+ const rawBytes = cacheBytes(payload);
5249
+ let normalized;
5250
+ let reused = false;
5251
+ try {
5252
+ normalized = normalizeCopilotResponsesPayload(payload);
5253
+ } catch (error) {
5254
+ if (!(error instanceof CopilotResponsesReplayError) || !eligible || !isRecord$1(payload) || !Array.isArray(payload.input) || !isRecord$1(eligible.raw) || !Array.isArray(eligible.raw.input)) {
5255
+ this.snapshot = void 0;
5256
+ throw error;
5257
+ }
5258
+ try {
5259
+ const prior = eligible.raw.input;
5260
+ if (payload.input.length !== prior.length) throw error;
5261
+ let references = 0;
5262
+ const restored = payload.input.map((item, index) => {
5263
+ if (!isRecord$1(item) || !Object.hasOwn(item, "id")) return item;
5264
+ const original = prior[index];
5265
+ if (!isRecord$1(original) || !nonemptyString(item.id) || original.id !== item.id || ![
5266
+ "reasoning",
5267
+ "message",
5268
+ "function_call"
5269
+ ].includes(String(original.type)) || normalizeItem(original) === original) throw error;
5270
+ if (item.type === "item_reference") {
5271
+ if (Object.keys(item).length !== 2) throw error;
5272
+ } else if (item.type !== original.type || Object.keys(item).length >= Object.keys(original).length || Object.entries(item).some(([key, value]) => !Object.hasOwn(original, key) || cacheBytes(value) !== cacheBytes(original[key]))) throw error;
5273
+ references++;
5274
+ return original;
5275
+ });
5276
+ if (references === 0 || cacheBytes({
5277
+ ...payload,
5278
+ input: restored
5279
+ }) !== cacheBytes(eligible.raw)) throw error;
5280
+ } catch {
5281
+ this.snapshot = void 0;
5282
+ throw error;
5283
+ }
5284
+ normalized = JSON.parse(eligible.normalized);
5285
+ reused = true;
5286
+ }
5287
+ payloadBytes = cacheBytes(normalized);
5288
+ candidate = signal === void 0 || !sessionId || !modelId || contextBytes === void 0 || rawBytes === void 0 || payloadBytes === void 0 ? void 0 : {
5289
+ raw: JSON.parse(rawBytes),
5290
+ normalized: payloadBytes,
5291
+ context: contextBytes,
5292
+ signal,
5293
+ sessionId,
5294
+ modelId,
5295
+ at: Date.now()
5296
+ };
5297
+ if (reused && eligible) candidate = {
5298
+ ...eligible,
5299
+ at: Date.now()
5300
+ };
5301
+ return normalized;
5302
+ },
5303
+ observe: (body, status) => {
5304
+ observed = true;
5305
+ this.snapshot = !this.disposed && !signal?.aborted && this.active === 1 && !overlapping && status === 408 && candidate !== void 0 && body === payloadBytes ? candidate : void 0;
5306
+ },
5307
+ finish: () => {
5308
+ if (finished) return;
5309
+ finished = true;
5310
+ this.active--;
5311
+ if (!observed || signal?.aborted || this.disposed || overlapping) this.snapshot = void 0;
5312
+ }
5313
+ };
5314
+ }
5315
+ };
5051
5316
  const scopeMessages = /* @__PURE__ */ new Set(["input item ID does not belong to this connection", "input item does not belong to this connection"]);
5052
5317
  const maxErrorBytes = 8192;
5053
5318
  const errorReadTimeoutMs = 250;
@@ -5299,6 +5564,13 @@ function createAccountProvider(descriptors, guard, baseURL) {
5299
5564
  headers["x-api-key"] = null;
5300
5565
  let unauthorized = false;
5301
5566
  const responses = model.api === "openai-responses";
5567
+ let retry;
5568
+ try {
5569
+ retry = responses ? guard.retryReplay?.begin(context, guard.retrySignal, options?.sessionId, model.id) : void 0;
5570
+ } catch (error) {
5571
+ lease.release();
5572
+ throw error;
5573
+ }
5302
5574
  const reportReplayFailure = (error) => {
5303
5575
  if (lease.signal.aborted || options.signal?.aborted) return;
5304
5576
  try {
@@ -5309,7 +5581,8 @@ function createAccountProvider(descriptors, guard, baseURL) {
5309
5581
  const replacement = await options.onPayload?.(payload, selectedModel);
5310
5582
  if (lease.signal.aborted || options.signal?.aborted) throw new Error("COPILOT_MANAGED_ABORTED");
5311
5583
  try {
5312
- return normalizeCopilotResponsesPayload(replacement === void 0 ? payload : replacement);
5584
+ const effective = replacement === void 0 ? payload : replacement;
5585
+ return retry === void 0 ? normalizeCopilotResponsesPayload(effective) : retry.normalize(effective);
5313
5586
  } catch (error) {
5314
5587
  if (error instanceof CopilotResponsesReplayError) reportReplayFailure(error);
5315
5588
  throw error;
@@ -5317,7 +5590,14 @@ function createAccountProvider(descriptors, guard, baseURL) {
5317
5590
  } : options.onPayload;
5318
5591
  const fetch = options.fetch ?? globalThis.fetch;
5319
5592
  const observeResponse = async (input, init) => {
5320
- const response = await fetch(input, init);
5593
+ let response;
5594
+ try {
5595
+ response = await fetch(input, init);
5596
+ } catch (error) {
5597
+ retry?.observe(void 0, 0);
5598
+ throw error;
5599
+ }
5600
+ retry?.observe(typeof init?.body === "string" ? init.body : void 0, response.status);
5321
5601
  if (response.status === 401) {
5322
5602
  if (responses && await isCopilotInputItemScopeError(response, lease.signal)) reportReplayFailure(new CopilotResponsesReplayError("scope-mismatch"));
5323
5603
  else unauthorized = true;
@@ -5338,6 +5618,7 @@ function createAccountProvider(descriptors, guard, baseURL) {
5338
5618
  onPayload
5339
5619
  };
5340
5620
  if (!hasApi(model, "openai-responses") && !hasApi(model, "openai-completions") && !hasApi(model, "anthropic-messages")) {
5621
+ retry?.finish();
5341
5622
  lease.release();
5342
5623
  throw new Error("COPILOT_MANAGED_PROTOCOL_UNSUPPORTED");
5343
5624
  }
@@ -5348,6 +5629,8 @@ function createAccountProvider(descriptors, guard, baseURL) {
5348
5629
  yield event;
5349
5630
  }
5350
5631
  } finally {
5632
+ if (lease.signal.aborted || options.signal?.aborted) retry?.observe(void 0, 0);
5633
+ retry?.finish();
5351
5634
  lease.release();
5352
5635
  if (unauthorized && !guard.signal.aborted && !options.signal?.aborted) try {
5353
5636
  guard.onUnauthorized?.();
@@ -6652,15 +6935,18 @@ var PreviewLifetime = class {
6652
6935
  source;
6653
6936
  proofFor;
6654
6937
  displayProofFor;
6938
+ excluded;
6655
6939
  controller = new AbortController();
6656
6940
  wires = /* @__PURE__ */ new Set();
6941
+ retryEntries = /* @__PURE__ */ new Map();
6657
6942
  revision = 0;
6658
6943
  active = true;
6659
- constructor(credentials, source, proofFor, displayProofFor) {
6944
+ constructor(credentials, source, proofFor, displayProofFor, excluded) {
6660
6945
  this.credentials = credentials;
6661
6946
  this.source = source;
6662
6947
  this.proofFor = proofFor;
6663
6948
  this.displayProofFor = displayProofFor;
6949
+ this.excluded = excluded;
6664
6950
  }
6665
6951
  assertActive() {
6666
6952
  if (!this.active) throw failure("COPILOT_PREVIEW_DISPOSED", "ABORTED");
@@ -6668,15 +6954,52 @@ var PreviewLifetime = class {
6668
6954
  isCurrent(revision) {
6669
6955
  return this.active && revision === this.revision;
6670
6956
  }
6957
+ removeRetry(signal) {
6958
+ const entry = this.retryEntries.get(signal);
6959
+ if (entry === void 0) return;
6960
+ signal.removeEventListener("abort", entry.onAbort);
6961
+ entry.replay.dispose();
6962
+ this.retryEntries.delete(signal);
6963
+ }
6964
+ clearRetries() {
6965
+ for (const signal of this.retryEntries.keys()) this.removeRetry(signal);
6966
+ }
6967
+ clearSessionRetries(sessionId) {
6968
+ for (const [signal, entry] of this.retryEntries) if (entry.replay.belongsTo(sessionId)) this.removeRetry(signal);
6969
+ }
6970
+ retryFor(signal, snapshot, proof, model) {
6971
+ let entry = this.retryEntries.get(signal);
6972
+ if (entry !== void 0 && (entry.snapshot !== snapshot || entry.proof !== proof || entry.model !== model || entry.revision !== this.revision || Date.now() - entry.at >= 6e4)) {
6973
+ this.removeRetry(signal);
6974
+ entry = void 0;
6975
+ }
6976
+ if (entry !== void 0) return entry.replay;
6977
+ if (this.retryEntries.size >= 16) this.removeRetry(this.retryEntries.keys().next().value);
6978
+ const replay = new ResponsesRetryReplay();
6979
+ const onAbort = () => this.removeRetry(signal);
6980
+ signal.addEventListener("abort", onAbort, { once: true });
6981
+ this.retryEntries.set(signal, {
6982
+ replay,
6983
+ snapshot,
6984
+ proof,
6985
+ model,
6986
+ revision: this.revision,
6987
+ at: Date.now(),
6988
+ onAbort
6989
+ });
6990
+ return replay;
6991
+ }
6671
6992
  change() {
6672
6993
  this.assertActive();
6673
6994
  this.revision++;
6995
+ this.clearRetries();
6674
6996
  this.source.invalidate();
6675
6997
  for (const wire of this.wires) wire.abort(new ManagedWireAbortError("COPILOT_PREVIEW_CREDENTIAL_CHANGED"));
6676
6998
  }
6677
6999
  dispose() {
6678
7000
  if (!this.active) return;
6679
7001
  this.active = false;
7002
+ this.clearRetries();
6680
7003
  this.source.dispose();
6681
7004
  this.controller.abort(new ManagedWireAbortError("COPILOT_PREVIEW_DISPOSED"));
6682
7005
  for (const wire of this.wires) wire.abort();
@@ -6725,6 +7048,7 @@ var PreviewLifetime = class {
6725
7048
  const combined = signal === void 0 ? this.controller.signal : AbortSignal.any([signal, this.controller.signal]);
6726
7049
  const grant = await this.read(combined);
6727
7050
  if (grant === void 0) throw failure("COPILOT_PREVIEW_OAUTH_REQUIRED");
7051
+ if (this.excluded(model)) throw failure("COPILOT_PREVIEW_MODEL_EXCLUDED", "INVALID_REQUEST");
6728
7052
  const descriptor = snapshot.models.find((item) => item.id === model);
6729
7053
  if (descriptor === void 0) throw failure("COPILOT_PREVIEW_MODEL_NOT_ENTITLED", "UNKNOWN_MODEL");
6730
7054
  const proof = this.proofFor(snapshot);
@@ -6738,6 +7062,11 @@ var PreviewLifetime = class {
6738
7062
  started: false
6739
7063
  };
6740
7064
  this.entitled(lease, grant, model);
7065
+ if (signal !== void 0 && !signal.aborted) return {
7066
+ ...lease,
7067
+ retrySignal: signal,
7068
+ retryReplay: this.retryFor(signal, snapshot, proof, model)
7069
+ };
6741
7070
  return lease;
6742
7071
  }
6743
7072
  account(lease, grant) {
@@ -6746,6 +7075,7 @@ var PreviewLifetime = class {
6746
7075
  }
6747
7076
  entitled(lease, grant, model) {
6748
7077
  this.account(lease, grant);
7078
+ if (this.excluded(model)) throw failure("COPILOT_PREVIEW_MODEL_EXCLUDED", "INVALID_REQUEST");
6749
7079
  if (lease.descriptor.id !== model) throw failure("COPILOT_PREVIEW_MODEL_MISMATCH", "UNKNOWN_MODEL");
6750
7080
  if (this.source.readSnapshot() !== lease.snapshot || this.proofFor(lease.snapshot) !== lease.proof) throw failure("COPILOT_PREVIEW_METADATA_STALE");
6751
7081
  if (tokenFingerprint(grant.access) !== lease.proof.tokenFingerprint || copilotEntitlementKey(grant) !== lease.proof.entitlementKey || grant.expires <= Date.now()) {
@@ -6762,7 +7092,11 @@ var PreviewLifetime = class {
6762
7092
  guard(lease) {
6763
7093
  return {
6764
7094
  signal: lease?.signal ?? this.controller.signal,
6765
- ...lease === void 0 ? {} : { selectedModelId: lease.descriptor.id },
7095
+ ...lease === void 0 ? {} : {
7096
+ selectedModelId: lease.descriptor.id,
7097
+ retryReplay: lease.retryReplay,
7098
+ retrySignal: lease.retrySignal
7099
+ },
6766
7100
  assertActive: () => this.assertActive(),
6767
7101
  assertAccount: (grant) => this.account(lease, grant),
6768
7102
  assertEntitled: (grant, model) => this.entitled(lease, grant, model),
@@ -6842,13 +7176,15 @@ var PreviewAdapter = class extends PiAiAdapter {
6842
7176
  discoverSnapshot;
6843
7177
  refreshRejected;
6844
7178
  requestBudgetSettings;
6845
- constructor(lifetime, optionsFor, discoverSnapshot, refreshRejected, requestBudgetSettings) {
7179
+ accountModelSettings;
7180
+ constructor(lifetime, optionsFor, discoverSnapshot, refreshRejected, requestBudgetSettings, accountModelSettings) {
6846
7181
  super(optionsFor());
6847
7182
  this.lifetime = lifetime;
6848
7183
  this.optionsFor = optionsFor;
6849
7184
  this.discoverSnapshot = discoverSnapshot;
6850
7185
  this.refreshRejected = refreshRejected;
6851
7186
  this.requestBudgetSettings = requestBudgetSettings;
7187
+ this.accountModelSettings = accountModelSettings;
6852
7188
  }
6853
7189
  async listModels(provider) {
6854
7190
  owned(provider);
@@ -6858,7 +7194,8 @@ var PreviewAdapter = class extends PiAiAdapter {
6858
7194
  if (grant === void 0 || snapshot.accountKey !== copilotAccountKey(grant)) return [];
6859
7195
  const proof = this.lifetime.proofFor(snapshot);
6860
7196
  if (proof === void 0 || tokenFingerprint(grant.access) !== proof.tokenFingerprint || grant.expires <= Date.now()) return [];
6861
- const models = snapshot.models.filter((model) => autoModelPreference(model.id) === void 0 && model.input.includes("text"));
7197
+ const excluded = this.excludedModels();
7198
+ const models = snapshot.models.filter((model) => autoModelPreference(model.id) === void 0 && !excluded.has(model.id) && model.input.includes("text"));
6862
7199
  if (models.length === 0) return [];
6863
7200
  return [
6864
7201
  {
@@ -6895,7 +7232,8 @@ var PreviewAdapter = class extends PiAiAdapter {
6895
7232
  const cached = this.lifetime.source.readSnapshot();
6896
7233
  const snapshot = await this.discoverSnapshot({ signal });
6897
7234
  if (autoModelPreference(model) !== void 0) {
6898
- const models = snapshot.models.filter((candidate) => autoModelPreference(candidate.id) === void 0 && candidate.input.includes("text"));
7235
+ const excluded = this.excludedModels();
7236
+ const models = snapshot.models.filter((candidate) => autoModelPreference(candidate.id) === void 0 && !excluded.has(candidate.id) && candidate.input.includes("text"));
6899
7237
  if (models.length === 0) throw failure("COPILOT_AUTO_NO_ELIGIBLE_MODEL", "UNKNOWN_MODEL");
6900
7238
  return {
6901
7239
  provider,
@@ -7013,15 +7351,20 @@ var PreviewAdapter = class extends PiAiAdapter {
7013
7351
  }
7014
7352
  })();
7015
7353
  }
7354
+ excludedModels() {
7355
+ return excludedModelSet(this.accountModelSettings().excludedModelIds);
7356
+ }
7016
7357
  };
7017
7358
  /** Register one stable account route; attach/status remain network-free. */
7018
7359
  function apply$1(ctx, config = {}) {
7019
7360
  const { accountModelTtlMs, accountModelFailureCooldownMs, accountModelSettings, requestBudget, requestBudgetSettings, ...requestConfig } = config;
7020
7361
  const cacheSettings = accountModelSettings ?? (() => ({
7021
7362
  accountModelTtlMs,
7022
- accountModelFailureCooldownMs
7363
+ accountModelFailureCooldownMs,
7364
+ excludedModelIds: []
7023
7365
  }));
7024
7366
  const budgetSettings = requestBudgetSettings ?? (() => requestBudget ?? {});
7367
+ const excludedModels = () => excludedModelSet(cacheSettings().excludedModelIds);
7025
7368
  resolveRequestBudgetPolicy(budgetSettings());
7026
7369
  const store = createGitHubCopilotCredentialStore(ctx, GITHUB_COPILOT_PREVIEW_PROVIDER_ID);
7027
7370
  let rejectedAuth;
@@ -7082,7 +7425,10 @@ function apply$1(ctx, config = {}) {
7082
7425
  });
7083
7426
  const displayProofFor = (snapshot) => source.readDisplaySnapshot() === snapshot && provenSnapshot === snapshot && snapshotProof?.accountKey === snapshot.accountKey ? snapshotProof : void 0;
7084
7427
  const proofFor = (snapshot) => source.readSnapshot() === snapshot && snapshotProof !== void 0 && snapshotProof.expires > Date.now() ? displayProofFor(snapshot) : void 0;
7085
- const lifetime = new PreviewLifetime(store, source, proofFor, displayProofFor);
7428
+ const lifetime = new PreviewLifetime(store, source, proofFor, displayProofFor, (modelId) => excludedModels().has(modelId));
7429
+ const removeStepListener = ctx.on("session/event", (session, event) => {
7430
+ if (event.type === "step/start" || event.type === "turn/end") lifetime.clearSessionRetries(session.id);
7431
+ });
7086
7432
  const template = resolvedProfile(createAccountProvider([], lifetime.guard(), "https://api.individual.githubcopilot.com").provider, requestConfig);
7087
7433
  let configured = false;
7088
7434
  let readError;
@@ -7268,14 +7614,25 @@ function apply$1(ctx, config = {}) {
7268
7614
  };
7269
7615
  const removeAutoRoute = installAutoModelRouting(ctx, {
7270
7616
  async loadModels(signal) {
7271
- return (await discoverSnapshot({ signal })).models;
7617
+ const excluded = excludedModels();
7618
+ return (await discoverSnapshot({ signal })).models.filter((model) => !excluded.has(model.id));
7272
7619
  },
7273
7620
  budgetPolicy: () => budgetSettings()
7274
7621
  });
7275
- const registration = ctx.llm.registerAdapter([GITHUB_COPILOT_PREVIEW_PROVIDER_ID], new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings));
7622
+ const registration = ctx.llm.registerAdapter([GITHUB_COPILOT_PREVIEW_PROVIDER_ID], new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings));
7623
+ let exclusionSignature = JSON.stringify([...excludedModels()]);
7624
+ const removeSettings = onSettingsNamespaceUpdated(ctx, (namespace) => {
7625
+ if (namespace !== "github-copilot") return;
7626
+ const next = JSON.stringify([...excludedModels()]);
7627
+ if (next === exclusionSignature) return;
7628
+ exclusionSignature = next;
7629
+ publishedDirectory = "";
7630
+ registration.replace([GITHUB_COPILOT_PREVIEW_PROVIDER_ID]);
7631
+ });
7276
7632
  installCopilotCompactionPressure(ctx, { resolve(request) {
7277
7633
  const snapshot = source.readSnapshot();
7278
7634
  if (snapshot === void 0 || proofFor(snapshot) === void 0) return void 0;
7635
+ if (excludedModels().has(request.model)) return void 0;
7279
7636
  const descriptor = snapshot.models.find((model) => model.id === request.model);
7280
7637
  if (descriptor === void 0) return void 0;
7281
7638
  const result = calculateRequestBudget(descriptor, request.maxTokens, resolveRequestBudgetPolicy(budgetSettings()));
@@ -7302,6 +7659,7 @@ function apply$1(ctx, config = {}) {
7302
7659
  return () => lifetime.isCurrent(revision) && (expires === void 0 || expires > Date.now()) && (snapshotProof === captured || snapshotProof === void 0 || snapshotProof.expires > Date.now());
7303
7660
  },
7304
7661
  routeFacts(modelId) {
7662
+ if (excludedModels().has(modelId)) return void 0;
7305
7663
  const snapshot = source.readSnapshot();
7306
7664
  const proof = snapshot === void 0 ? void 0 : proofFor(snapshot);
7307
7665
  const descriptor = snapshot?.models.find((model) => model.id === modelId);
@@ -7345,7 +7703,9 @@ function apply$1(ctx, config = {}) {
7345
7703
  });
7346
7704
  ctx.effect(() => () => {
7347
7705
  lifetime.dispose();
7706
+ removeStepListener();
7348
7707
  removeListener();
7708
+ removeSettings();
7349
7709
  removeAutoRoute();
7350
7710
  registration();
7351
7711
  });
package/lib/remote.js CHANGED
@@ -305,6 +305,20 @@ const GitHubCopilotAuthorizationViewSchema = z.object({
305
305
  discoveredAt: z.number().int().nonnegative().optional(),
306
306
  error: z.string().optional()
307
307
  }).strict().optional(),
308
+ modelPreferences: z.object({
309
+ state: z.enum(["ready", "error"]),
310
+ writable: z.boolean(),
311
+ revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
312
+ excludedModelIds: z.array(z.string().min(1).max(512)).max(512),
313
+ lockedModelIds: z.array(z.string().min(1).max(512)).max(512),
314
+ unavailableExcludedModelIds: z.array(z.string().min(1).max(512)).max(512),
315
+ error: z.enum([
316
+ "COPILOT_MODEL_PREFERENCES_UNAVAILABLE",
317
+ "COPILOT_MODEL_EXCLUSION_SELECTED",
318
+ "COPILOT_MODEL_EXCLUSION_CONFLICT",
319
+ "COPILOT_MODEL_EXCLUSION_SAVE_FAILED"
320
+ ]).optional()
321
+ }).strict().optional(),
308
322
  route: z.object({
309
323
  state: z.enum([
310
324
  "ready",
@@ -393,6 +407,20 @@ const contribution = {
393
407
  parameters: [],
394
408
  result
395
409
  })),
410
+ ...["excludeModel", "restoreModel"].map((method) => ({
411
+ id: `dsh-github-copilot:githubCopilot.${method}`,
412
+ service: "githubCopilotAuthorization",
413
+ namespace: "githubCopilot",
414
+ method,
415
+ invocation: direct,
416
+ parameters: [{
417
+ name: "modelId",
418
+ wire: "modelId",
419
+ source: "json",
420
+ codec: strictRemoteCodec("dsh-github-copilot#GitHubCopilotModelId", z.string().min(1).max(512))
421
+ }],
422
+ result
423
+ })),
396
424
  {
397
425
  id: "dsh-github-copilot:githubCopilot.migrationStatus",
398
426
  service: "githubCopilotAuthorization",