dsh-github-copilot 0.4.0-alpha.92 → 0.4.0-alpha.93

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
@@ -21,12 +21,12 @@ import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi
21
21
  import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "@earendil-works/pi-ai/api/github-copilot-headers";
22
22
  //#region lib/types/dual-model-host.js
23
23
  /** Retired planner/executor entry points; retained policies stay enforceable without migration. */
24
- var __runInitializers$4 = function(thisArg, initializers, value) {
24
+ var __runInitializers$5 = function(thisArg, initializers, value) {
25
25
  var useValue = arguments.length > 2;
26
26
  for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
27
27
  return useValue ? value : void 0;
28
28
  };
29
- var __esDecorate$4 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
29
+ var __esDecorate$5 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
30
30
  function accept(f) {
31
31
  if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
32
32
  return f;
@@ -272,7 +272,7 @@ let GitHubCopilotDualModel = (() => {
272
272
  _view_decorators = [Remote];
273
273
  _save_decorators = [Remote];
274
274
  _create_decorators = [Remote];
275
- __esDecorate$4(this, null, _view_decorators, {
275
+ __esDecorate$5(this, null, _view_decorators, {
276
276
  kind: "method",
277
277
  name: "view",
278
278
  static: false,
@@ -283,7 +283,7 @@ let GitHubCopilotDualModel = (() => {
283
283
  },
284
284
  metadata: _metadata
285
285
  }, null, _instanceExtraInitializers);
286
- __esDecorate$4(this, null, _save_decorators, {
286
+ __esDecorate$5(this, null, _save_decorators, {
287
287
  kind: "method",
288
288
  name: "save",
289
289
  static: false,
@@ -294,7 +294,7 @@ let GitHubCopilotDualModel = (() => {
294
294
  },
295
295
  metadata: _metadata
296
296
  }, null, _instanceExtraInitializers);
297
- __esDecorate$4(this, null, _create_decorators, {
297
+ __esDecorate$5(this, null, _create_decorators, {
298
298
  kind: "method",
299
299
  name: "create",
300
300
  static: false,
@@ -312,7 +312,7 @@ let GitHubCopilotDualModel = (() => {
312
312
  value: _metadata
313
313
  });
314
314
  }
315
- owner = __runInitializers$4(this, _instanceExtraInitializers);
315
+ owner = __runInitializers$5(this, _instanceExtraInitializers);
316
316
  lifetime = new AbortController();
317
317
  creates = /* @__PURE__ */ new Map();
318
318
  overlays = /* @__PURE__ */ new Map();
@@ -740,12 +740,12 @@ const SearchProviderCatalogSchema = z$1.object({
740
740
  }).strict();
741
741
  //#endregion
742
742
  //#region lib/types/search-routing-host.js
743
- var __runInitializers$3 = function(thisArg, initializers, value) {
743
+ var __runInitializers$4 = function(thisArg, initializers, value) {
744
744
  var useValue = arguments.length > 2;
745
745
  for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
746
746
  return useValue ? value : void 0;
747
747
  };
748
- var __esDecorate$3 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
748
+ var __esDecorate$4 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
749
749
  function accept(f) {
750
750
  if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
751
751
  return f;
@@ -788,7 +788,7 @@ let SearchRoutingController = (() => {
788
788
  static {
789
789
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
790
790
  _providers_decorators = [Remote];
791
- __esDecorate$3(this, null, _providers_decorators, {
791
+ __esDecorate$4(this, null, _providers_decorators, {
792
792
  kind: "method",
793
793
  name: "providers",
794
794
  static: false,
@@ -808,7 +808,7 @@ let SearchRoutingController = (() => {
808
808
  }
809
809
  constructor(ctx) {
810
810
  super(ctx, "githubCopilotSearchRouting");
811
- __runInitializers$3(this, _instanceExtraInitializers);
811
+ __runInitializers$4(this, _instanceExtraInitializers);
812
812
  }
813
813
  providers() {
814
814
  const unavailable = {
@@ -1250,12 +1250,12 @@ function normalizeCopilotUsage(input, observedAt) {
1250
1250
  }
1251
1251
  //#endregion
1252
1252
  //#region lib/types/copilot-usage-host.js
1253
- var __runInitializers$2 = function(thisArg, initializers, value) {
1253
+ var __runInitializers$3 = function(thisArg, initializers, value) {
1254
1254
  var useValue = arguments.length > 2;
1255
1255
  for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
1256
1256
  return useValue ? value : void 0;
1257
1257
  };
1258
- var __esDecorate$2 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
1258
+ var __esDecorate$3 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
1259
1259
  function accept(f) {
1260
1260
  if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
1261
1261
  return f;
@@ -1595,7 +1595,7 @@ let GitHubCopilotUsageController = (() => {
1595
1595
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
1596
1596
  _get_decorators = [Remote];
1597
1597
  _refresh_decorators = [Remote];
1598
- __esDecorate$2(this, null, _get_decorators, {
1598
+ __esDecorate$3(this, null, _get_decorators, {
1599
1599
  kind: "method",
1600
1600
  name: "get",
1601
1601
  static: false,
@@ -1606,7 +1606,7 @@ let GitHubCopilotUsageController = (() => {
1606
1606
  },
1607
1607
  metadata: _metadata
1608
1608
  }, null, _instanceExtraInitializers);
1609
- __esDecorate$2(this, null, _refresh_decorators, {
1609
+ __esDecorate$3(this, null, _refresh_decorators, {
1610
1610
  kind: "method",
1611
1611
  name: "refresh",
1612
1612
  static: false,
@@ -1624,7 +1624,7 @@ let GitHubCopilotUsageController = (() => {
1624
1624
  value: _metadata
1625
1625
  });
1626
1626
  }
1627
- source = __runInitializers$2(this, _instanceExtraInitializers);
1627
+ source = __runInitializers$3(this, _instanceExtraInitializers);
1628
1628
  constructor(ctx) {
1629
1629
  super(ctx, "githubCopilotUsage");
1630
1630
  const credentials = createGitHubCopilotCredentialStore(ctx);
@@ -1684,7 +1684,7 @@ const usageSchema = z$1.object({
1684
1684
  totalTokens: count.optional(),
1685
1685
  reasoningTokens: count.optional()
1686
1686
  });
1687
- function record$8(value) {
1687
+ function record$9(value) {
1688
1688
  return typeof value === "object" && value !== null && !Array.isArray(value);
1689
1689
  }
1690
1690
  function sameRoute$1(left, right) {
@@ -1703,10 +1703,10 @@ function initialContextEvidence() {
1703
1703
  }
1704
1704
  /** Read only counts and routing leaves; never message content or opaque replay. */
1705
1705
  function foldContextEvidence(state, event) {
1706
- if (!record$8(event) || typeof event.type !== "string" || !record$8(event.data)) return state;
1706
+ if (!record$9(event) || typeof event.type !== "string" || !record$9(event.data)) return state;
1707
1707
  if (event.type === "request/header" || event.type === "model/selection") {
1708
- const raw = event.type === "request/header" ? record$8(event.data.header) ? event.data.header.config : void 0 : event.data;
1709
- if (!record$8(raw)) return {
1708
+ const raw = event.type === "request/header" ? record$9(event.data.header) ? event.data.header.config : void 0 : event.data;
1709
+ if (!record$9(raw)) return {
1710
1710
  ...state,
1711
1711
  route: null,
1712
1712
  sample: null,
@@ -1745,7 +1745,7 @@ function foldContextEvidence(state, event) {
1745
1745
  if (!copilot(state.route)) return state;
1746
1746
  if (event.type === "assistant/message" && event.data.source !== void 0) {
1747
1747
  const source = event.data.source;
1748
- const parsed = routeSchema.safeParse(record$8(source) ? {
1748
+ const parsed = routeSchema.safeParse(record$9(source) ? {
1749
1749
  provider: source.provider,
1750
1750
  model: source.model
1751
1751
  } : source);
@@ -1761,7 +1761,7 @@ function foldContextEvidence(state, event) {
1761
1761
  const settledUsage = usage !== void 0;
1762
1762
  let terminal;
1763
1763
  for (const entry of stream) {
1764
- if (!record$8(entry) || entry.type !== "chunk" || !record$8(entry.chunk)) continue;
1764
+ if (!record$9(entry) || entry.type !== "chunk" || !record$9(entry.chunk)) continue;
1765
1765
  if (!settledUsage && entry.chunk.type === "usage") usage = entry.chunk.usage;
1766
1766
  if (entry.chunk.type === "finish") terminal = entry.chunk.reason;
1767
1767
  }
@@ -1775,7 +1775,7 @@ function foldContextEvidence(state, event) {
1775
1775
  };
1776
1776
  const value = parsed.data;
1777
1777
  const zero = isZeroContextUsage(value);
1778
- const successful = record$8(terminal) && (terminal.kind === "stop" || terminal.kind === "max-tokens" || terminal.kind === "tool-calls");
1778
+ const successful = record$9(terminal) && (terminal.kind === "stop" || terminal.kind === "max-tokens" || terminal.kind === "tool-calls");
1779
1779
  if (zero && !successful) {
1780
1780
  const reason = state.sample !== null || state.reason === "none" ? "failed-zero" : state.reason;
1781
1781
  return {
@@ -1817,7 +1817,7 @@ const contextEvidenceDefinition = {
1817
1817
  function installContextEvidence(ctx) {
1818
1818
  ctx.inject(["sessionProjections"], (scope) => {
1819
1819
  const registry = scope.get("sessionProjections");
1820
- if (!record$8(registry) || typeof registry.register !== "function") {
1820
+ if (!record$9(registry) || typeof registry.register !== "function") {
1821
1821
  scope.logger.warn("[github-copilot] COPILOT_CONTEXT_PROJECTION_UNAVAILABLE");
1822
1822
  return;
1823
1823
  }
@@ -1831,7 +1831,7 @@ function installContextEvidence(ctx) {
1831
1831
  //#endregion
1832
1832
  //#region package.json
1833
1833
  var name$1 = "dsh-github-copilot";
1834
- var version = "0.4.0-alpha.92";
1834
+ var version = "0.4.0-alpha.93";
1835
1835
  //#endregion
1836
1836
  //#region lib/types/probe.js
1837
1837
  /**
@@ -2843,7 +2843,7 @@ function buildAnthropicWireBody(request, cfg, model) {
2843
2843
  }
2844
2844
  //#endregion
2845
2845
  //#region lib/types/responses-reasoning-text.js
2846
- function record$7(value) {
2846
+ function record$8(value) {
2847
2847
  return typeof value === "object" && value !== null;
2848
2848
  }
2849
2849
  function responseIndex(value) {
@@ -2901,13 +2901,13 @@ var ResponsesReasoningText = class {
2901
2901
  }
2902
2902
  /** Only recognized public text fields are examined; no copying of the item. */
2903
2903
  snapshot(item) {
2904
- if (!record$7(item) || item.type !== "reasoning") return "";
2904
+ if (!record$8(item) || item.type !== "reasoning") return "";
2905
2905
  let delta = "";
2906
2906
  for (const family of ["summary", "raw"]) {
2907
2907
  const value = family === "summary" ? item.summary : item.content;
2908
2908
  if (!Array.isArray(value)) continue;
2909
2909
  for (const [index, part] of value.entries()) {
2910
- if (!record$7(part) || part.type !== (family === "summary" ? "summary_text" : "reasoning_text")) continue;
2910
+ if (!record$8(part) || part.type !== (family === "summary" ? "summary_text" : "reasoning_text")) continue;
2911
2911
  delta += this.update(family, index, part.text, true);
2912
2912
  }
2913
2913
  }
@@ -4403,12 +4403,12 @@ function excludedModelSet(value) {
4403
4403
  * Host-side bridge between the Models-page companion UI and DSH's neutral
4404
4404
  * authorization, credential-record, and settings seams.
4405
4405
  */
4406
- var __runInitializers$1 = function(thisArg, initializers, value) {
4406
+ var __runInitializers$2 = function(thisArg, initializers, value) {
4407
4407
  var useValue = arguments.length > 2;
4408
4408
  for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
4409
4409
  return useValue ? value : void 0;
4410
4410
  };
4411
- var __esDecorate$1 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
4411
+ var __esDecorate$2 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
4412
4412
  function accept(f) {
4413
4413
  if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
4414
4414
  return f;
@@ -4738,7 +4738,7 @@ let GitHubCopilotAuthorizationController = (() => {
4738
4738
  _start_decorators = [Remote];
4739
4739
  _cancel_decorators = [Remote];
4740
4740
  _signOut_decorators = [Remote];
4741
- __esDecorate$1(this, null, _migrationStatus_decorators, {
4741
+ __esDecorate$2(this, null, _migrationStatus_decorators, {
4742
4742
  kind: "method",
4743
4743
  name: "migrationStatus",
4744
4744
  static: false,
@@ -4749,7 +4749,7 @@ let GitHubCopilotAuthorizationController = (() => {
4749
4749
  },
4750
4750
  metadata: _metadata
4751
4751
  }, null, _instanceExtraInitializers);
4752
- __esDecorate$1(this, null, _status_decorators, {
4752
+ __esDecorate$2(this, null, _status_decorators, {
4753
4753
  kind: "method",
4754
4754
  name: "status",
4755
4755
  static: false,
@@ -4760,7 +4760,7 @@ let GitHubCopilotAuthorizationController = (() => {
4760
4760
  },
4761
4761
  metadata: _metadata
4762
4762
  }, null, _instanceExtraInitializers);
4763
- __esDecorate$1(this, null, _excludeModel_decorators, {
4763
+ __esDecorate$2(this, null, _excludeModel_decorators, {
4764
4764
  kind: "method",
4765
4765
  name: "excludeModel",
4766
4766
  static: false,
@@ -4771,7 +4771,7 @@ let GitHubCopilotAuthorizationController = (() => {
4771
4771
  },
4772
4772
  metadata: _metadata
4773
4773
  }, null, _instanceExtraInitializers);
4774
- __esDecorate$1(this, null, _restoreModel_decorators, {
4774
+ __esDecorate$2(this, null, _restoreModel_decorators, {
4775
4775
  kind: "method",
4776
4776
  name: "restoreModel",
4777
4777
  static: false,
@@ -4782,7 +4782,7 @@ let GitHubCopilotAuthorizationController = (() => {
4782
4782
  },
4783
4783
  metadata: _metadata
4784
4784
  }, null, _instanceExtraInitializers);
4785
- __esDecorate$1(this, null, _setModelExcluded_decorators, {
4785
+ __esDecorate$2(this, null, _setModelExcluded_decorators, {
4786
4786
  kind: "method",
4787
4787
  name: "setModelExcluded",
4788
4788
  static: false,
@@ -4793,7 +4793,7 @@ let GitHubCopilotAuthorizationController = (() => {
4793
4793
  },
4794
4794
  metadata: _metadata
4795
4795
  }, null, _instanceExtraInitializers);
4796
- __esDecorate$1(this, null, _discoverModels_decorators, {
4796
+ __esDecorate$2(this, null, _discoverModels_decorators, {
4797
4797
  kind: "method",
4798
4798
  name: "discoverModels",
4799
4799
  static: false,
@@ -4804,7 +4804,7 @@ let GitHubCopilotAuthorizationController = (() => {
4804
4804
  },
4805
4805
  metadata: _metadata
4806
4806
  }, null, _instanceExtraInitializers);
4807
- __esDecorate$1(this, null, _ensureModels_decorators, {
4807
+ __esDecorate$2(this, null, _ensureModels_decorators, {
4808
4808
  kind: "method",
4809
4809
  name: "ensureModels",
4810
4810
  static: false,
@@ -4815,7 +4815,7 @@ let GitHubCopilotAuthorizationController = (() => {
4815
4815
  },
4816
4816
  metadata: _metadata
4817
4817
  }, null, _instanceExtraInitializers);
4818
- __esDecorate$1(this, null, _reconcile_decorators, {
4818
+ __esDecorate$2(this, null, _reconcile_decorators, {
4819
4819
  kind: "method",
4820
4820
  name: "reconcile",
4821
4821
  static: false,
@@ -4826,7 +4826,7 @@ let GitHubCopilotAuthorizationController = (() => {
4826
4826
  },
4827
4827
  metadata: _metadata
4828
4828
  }, null, _instanceExtraInitializers);
4829
- __esDecorate$1(this, null, _start_decorators, {
4829
+ __esDecorate$2(this, null, _start_decorators, {
4830
4830
  kind: "method",
4831
4831
  name: "start",
4832
4832
  static: false,
@@ -4837,7 +4837,7 @@ let GitHubCopilotAuthorizationController = (() => {
4837
4837
  },
4838
4838
  metadata: _metadata
4839
4839
  }, null, _instanceExtraInitializers);
4840
- __esDecorate$1(this, null, _cancel_decorators, {
4840
+ __esDecorate$2(this, null, _cancel_decorators, {
4841
4841
  kind: "method",
4842
4842
  name: "cancel",
4843
4843
  static: false,
@@ -4848,7 +4848,7 @@ let GitHubCopilotAuthorizationController = (() => {
4848
4848
  },
4849
4849
  metadata: _metadata
4850
4850
  }, null, _instanceExtraInitializers);
4851
- __esDecorate$1(this, null, _signOut_decorators, {
4851
+ __esDecorate$2(this, null, _signOut_decorators, {
4852
4852
  kind: "method",
4853
4853
  name: "signOut",
4854
4854
  static: false,
@@ -4866,7 +4866,7 @@ let GitHubCopilotAuthorizationController = (() => {
4866
4866
  value: _metadata
4867
4867
  });
4868
4868
  }
4869
- notices = (__runInitializers$1(this, _instanceExtraInitializers), []);
4869
+ notices = (__runInitializers$2(this, _instanceExtraInitializers), []);
4870
4870
  failure;
4871
4871
  reconciliationFailed = false;
4872
4872
  attempt;
@@ -5264,203 +5264,686 @@ function resolveCopilotResponsesReasoning(ctx, request, candidate) {
5264
5264
  throw new Error("COPILOT_RESPONSES_REASONING_CORE_REQUIRED");
5265
5265
  }
5266
5266
  //#endregion
5267
- //#region lib/types/pi-provider-bridge.js
5268
- /** Retain the same stream object after proving its public surface; only SDK-private nominal identity differs. */
5269
- function coreEventStream(stream) {
5270
- return stream;
5271
- }
5272
- /**
5273
- * The published Core adapter consumes streamSimple. Do not pretend its older
5274
- * protocol-specific clients are interchangeable with a newer SDK's clients.
5275
- */
5276
- function coreProviderView(provider) {
5277
- return {
5278
- ...provider,
5279
- stream: () => {
5280
- throw new Error("COPILOT_MANAGED_ADVANCED_STREAM_UNSUPPORTED");
5281
- },
5282
- streamSimple: (model, context, options) => coreEventStream(provider.streamSimple(model, context, options))
5283
- };
5284
- }
5285
- //#endregion
5286
- //#region lib/types/response-error-body.js
5287
- const maxErrorBytes = 8192;
5288
- const errorReadTimeoutMs = 250;
5289
- async function readError(reader) {
5290
- const decoder = new TextDecoder("utf-8", { fatal: true });
5291
- let bytes = 0, chunks = 0, text = "";
5292
- while (true) {
5293
- if (chunks++ > maxErrorBytes) return void 0;
5294
- const chunk = await reader.read();
5295
- if (chunk.done) break;
5296
- bytes += chunk.value.byteLength;
5297
- if (bytes > maxErrorBytes) return void 0;
5298
- text += decoder.decode(chunk.value, { stream: true });
5299
- }
5300
- return JSON.parse(text + decoder.decode());
5301
- }
5302
- /** Optional classification evidence only; an unreadable clone leaves native handling unchanged. */
5303
- async function readResponseErrorJson(response, signal) {
5304
- if (signal?.aborted) return void 0;
5305
- let reader;
5306
- let timeout;
5307
- let onAbort;
5308
- try {
5309
- const clone = response.clone();
5310
- if (!clone.body) return void 0;
5311
- reader = clone.body.getReader();
5312
- const interrupted = new Promise((resolve) => {
5313
- onAbort = () => resolve(void 0);
5314
- signal?.addEventListener("abort", onAbort, { once: true });
5315
- timeout = setTimeout(() => resolve(void 0), errorReadTimeoutMs);
5316
- if (signal?.aborted) resolve(void 0);
5317
- });
5318
- const result = await Promise.race([readError(reader), interrupted]);
5319
- return signal?.aborted ? void 0 : result;
5320
- } catch {
5321
- return;
5322
- } finally {
5323
- if (timeout !== void 0) clearTimeout(timeout);
5324
- if (onAbort) signal?.removeEventListener("abort", onAbort);
5325
- if (reader) {
5326
- try {
5327
- reader.cancel().catch(() => {});
5328
- } catch {}
5329
- try {
5330
- reader.releaseLock();
5331
- } catch {}
5332
- }
5333
- }
5267
+ //#region lib/types/request-body-evidence.js
5268
+ const REQUEST_BODY_EVIDENCE_LIMITS = Object.freeze({
5269
+ bytes: 16777216,
5270
+ values: 65536,
5271
+ tokens: 131072,
5272
+ depth: 64,
5273
+ keyCharacters: 128
5274
+ });
5275
+ function formatRequestBodyEvidence(evidence, responseHeadersMs) {
5276
+ const elapsed = responseHeadersMs === void 0 ? void 0 : Math.round(responseHeadersMs);
5277
+ const timing = responseHeadersMs !== void 0 && responseHeadersMs >= 0 && elapsed !== void 0 && Number.isSafeInteger(elapsed) ? `Fetch-to-response-headers: ${elapsed} ms (round trip, not upload duration).` : "Fetch-to-response-headers timing unavailable.";
5278
+ if (evidence.state !== "complete") return `Composition unavailable (${evidence.state}); no partial totals inferred. ${timing}`;
5279
+ return `Composition (wire UTF-8 bytes): conversation ${evidence.conversationBytes}, tool definitions ${evidence.toolSchemaBytes}, top-level system/instructions ${evidence.systemBytes}, other/framing ${evidence.otherBytes}. Within conversation (disjoint subsets): image blocks ${evidence.imageBlockBytes}, opaque replay ${evidence.opaqueReplayBytes}, remaining ${evidence.remainingConversationBytes} (text/tool history, framing and unrecognized fields). Image blocks include URLs/references, not decoded image sizes; unknown encodings stay in remaining/other. ${timing}`;
5334
5280
  }
5335
- //#endregion
5336
- //#region lib/types/responses-replay-compat.js
5337
- const replayDiagnostics = {
5338
- "scope-mismatch": "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH: Copilot Responses input references belong to a different connection.",
5339
- unsupported: "COPILOT_RESPONSES_REPLAY_UNSUPPORTED: Copilot Responses input cannot be replayed safely without connection-scoped references.",
5340
- "invalid-payload": "COPILOT_RESPONSES_REPLAY_INVALID_PAYLOAD: Copilot Responses payload has an invalid replay structure."
5341
- };
5342
- /** Fixed diagnostics only: never include provider bodies, IDs, arguments or replay content. */
5343
- var CopilotResponsesReplayError = class extends Error {
5344
- constructor(reason = "unsupported") {
5345
- super(replayDiagnostics[reason]);
5346
- this.name = "CopilotResponsesReplayError";
5281
+ var EvidenceParseError = class extends Error {
5282
+ state;
5283
+ constructor(state) {
5284
+ super(state);
5285
+ this.state = state;
5347
5286
  }
5348
5287
  };
5349
- function isRecord$1(value) {
5350
- if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
5351
- const prototype = Object.getPrototypeOf(value);
5352
- return prototype === Object.prototype || prototype === null;
5353
- }
5354
- function nonemptyString(value) {
5355
- return typeof value === "string" && value.trim().length > 0;
5356
- }
5357
- function emptyReasoningShell(item) {
5358
- return item.type === "reasoning" && nonemptyString(item.id) && (item.status === void 0 || item.status === "completed") && Array.isArray(item.summary) && item.summary.length === 0 && (item.content === void 0 || Array.isArray(item.content) && item.content.length === 0) && item.encrypted_content === void 0 && Object.keys(item).every((key) => [
5359
- "type",
5360
- "id",
5361
- "status",
5362
- "summary",
5363
- "content",
5364
- "encrypted_content"
5365
- ].includes(key));
5366
- }
5367
- function normalizeItem(item) {
5368
- if (!isRecord$1(item)) throw new CopilotResponsesReplayError("invalid-payload");
5369
- if (item.type === "item_reference") throw new CopilotResponsesReplayError();
5370
- if (emptyReasoningShell(item)) return void 0;
5371
- if ((item.type === "message" || item.type === void 0) && (item.role === "user" || item.role === "system" || item.role === "developer")) return item;
5372
- if (!Object.hasOwn(item, "id") || item.id === void 0) return item;
5373
- if (!nonemptyString(item.id)) throw new CopilotResponsesReplayError("invalid-payload");
5374
- if (!((item.status === void 0 || item.status === "completed") && (item.type === "message" && item.role === "assistant" && Array.isArray(item.content) || item.type === "function_call" && nonemptyString(item.call_id) && nonemptyString(item.name) && typeof item.arguments === "string" || item.type === "reasoning" && nonemptyString(item.encrypted_content)))) throw new CopilotResponsesReplayError();
5375
- const normalized = { ...item };
5376
- delete normalized.id;
5377
- return normalized;
5288
+ function object$2(value) {
5289
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5378
5290
  }
5379
- /** Normalize only the outgoing managed Responses payload, never stored history/context. */
5380
- function normalizeCopilotResponsesPayload(payload) {
5381
- try {
5382
- if (!isRecord$1(payload) || typeof payload.input !== "string" && !Array.isArray(payload.input)) throw new CopilotResponsesReplayError("invalid-payload");
5383
- if (payload.previous_response_id !== void 0 && payload.previous_response_id !== null && payload.previous_response_id !== "") throw new CopilotResponsesReplayError(typeof payload.previous_response_id === "string" ? "unsupported" : "invalid-payload");
5384
- if (typeof payload.input === "string") return payload;
5385
- let changed = false;
5386
- const input = [];
5387
- for (const item of payload.input) {
5388
- const normalized = normalizeItem(item);
5389
- changed ||= normalized !== item;
5390
- if (normalized !== void 0) input.push(normalized);
5291
+ /** Diagnostic-only traversal of the original JSON spans; never reserializes or changes a request. */
5292
+ function requestBodyEvidence(body, protocol) {
5293
+ if (body === void 0) return { state: "unavailable" };
5294
+ const totalBytes = Buffer.byteLength(body, "utf8");
5295
+ if (totalBytes > REQUEST_BODY_EVIDENCE_LIMITS.bytes) return {
5296
+ state: "size-limit",
5297
+ totalBytes
5298
+ };
5299
+ let nesting = 0, tokens = 0;
5300
+ for (let index = 0; index < body.length; index++) {
5301
+ const character = body[index];
5302
+ if (character === "{" || character === "[") {
5303
+ if (++nesting > REQUEST_BODY_EVIDENCE_LIMITS.depth) return {
5304
+ state: "work-limit",
5305
+ totalBytes
5306
+ };
5307
+ tokens++;
5308
+ } else if (character === "}" || character === "]") nesting--;
5309
+ else if (character === "\"") {
5310
+ tokens++;
5311
+ while (++index < body.length) if (body[index] === "\\") index++;
5312
+ else if (body[index] === "\"") break;
5313
+ } else if (character !== " " && character !== "\n" && character !== "\r" && character !== " " && character !== ":" && character !== ",") {
5314
+ tokens++;
5315
+ while (index + 1 < body.length && !/[\s,\]}]/u.test(body[index + 1])) index++;
5391
5316
  }
5392
- return changed ? {
5393
- ...payload,
5394
- input
5395
- } : payload;
5396
- } catch (error) {
5397
- if (error instanceof CopilotResponsesReplayError) throw error;
5398
- throw new CopilotResponsesReplayError("invalid-payload");
5317
+ if (tokens > REQUEST_BODY_EVIDENCE_LIMITS.tokens) return {
5318
+ state: "work-limit",
5319
+ totalBytes
5320
+ };
5399
5321
  }
5400
- }
5401
- const retryLifetimeMs = 6e4;
5402
- const maxRetryBytes = 2097152;
5403
- function cacheBytes(value) {
5404
- let json;
5322
+ let parsed;
5405
5323
  try {
5406
- json = JSON.stringify(value);
5407
- } catch {
5408
- return;
5409
- }
5410
- if (json === void 0 || Buffer.byteLength(json, "utf8") > maxRetryBytes) return void 0;
5411
- return json;
5412
- }
5413
- /** A single lease can admit one HTTP-verified retry at a time; it never reads durable history. */
5414
- var ResponsesRetryReplay = class {
5415
- snapshot;
5416
- active = 0;
5417
- disposed = false;
5418
- dispose() {
5419
- this.disposed = true;
5420
- this.snapshot = void 0;
5421
- }
5422
- belongsTo(sessionId) {
5423
- return this.snapshot?.sessionId === sessionId;
5424
- }
5425
- begin(context, signal, sessionId, modelId) {
5426
- const contextBytes = cacheBytes(context);
5427
- const overlapping = this.active++ !== 0;
5428
- if (overlapping) this.snapshot = void 0;
5429
- const previous = this.snapshot;
5430
- 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;
5431
- const eligible = contextBytes !== void 0 && !overlapping && !this.disposed && !signal?.aborted && this.snapshot;
5432
- let candidate;
5433
- let payloadBytes;
5434
- let finished = false;
5435
- let observed = false;
5324
+ parsed = JSON.parse(body);
5325
+ } catch (error) {
5326
+ if (!(error instanceof SyntaxError)) throw error;
5436
5327
  return {
5437
- normalize: (payload) => {
5438
- if (this.disposed || signal?.aborted) throw new CopilotResponsesReplayError();
5439
- const rawBytes = cacheBytes(payload);
5440
- let normalized;
5441
- let reused = false;
5442
- try {
5443
- normalized = normalizeCopilotResponsesPayload(payload);
5444
- } catch (error) {
5445
- if (!(error instanceof CopilotResponsesReplayError) || !eligible || !isRecord$1(payload) || !Array.isArray(payload.input) || !isRecord$1(eligible.raw) || !Array.isArray(eligible.raw.input)) {
5446
- this.snapshot = void 0;
5447
- throw error;
5448
- }
5449
- try {
5450
- const prior = eligible.raw.input;
5451
- if (payload.input.length !== prior.length) throw error;
5452
- let references = 0;
5453
- const restored = payload.input.map((item, index) => {
5454
- if (!isRecord$1(item) || !Object.hasOwn(item, "id")) return item;
5455
- const original = prior[index];
5456
- if (!isRecord$1(original) || !nonemptyString(item.id) || original.id !== item.id || ![
5457
- "reasoning",
5458
- "message",
5459
- "function_call"
5460
- ].includes(String(original.type)) || normalizeItem(original) === original) throw error;
5461
- if (item.type === "item_reference") {
5462
- if (Object.keys(item).length !== 2) throw error;
5463
- } 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;
5328
+ state: "invalid-json",
5329
+ totalBytes
5330
+ };
5331
+ }
5332
+ const conversationKey = protocol === "openai-responses" ? "input" : "messages";
5333
+ const systemKey = protocol === "openai-responses" ? "instructions" : protocol === "anthropic-messages" ? "system" : void 0;
5334
+ if (!object$2(parsed) || !Array.isArray(parsed[conversationKey])) return {
5335
+ state: "unsupported-shape",
5336
+ totalBytes
5337
+ };
5338
+ let position = 0, values = 0, conversationBytes = 0, toolSchemaBytes = 0, systemBytes = 0;
5339
+ let imageBlockBytes = 0, opaqueReplayBytes = 0;
5340
+ const whitespace = () => {
5341
+ while (position < body.length && /\s/u.test(body[position])) position++;
5342
+ };
5343
+ const bytes = (start) => Buffer.byteLength(body.slice(start, position), "utf8");
5344
+ const stringEnd = () => {
5345
+ if (body[position++] !== "\"") throw new EvidenceParseError("invalid-json");
5346
+ while (position < body.length) {
5347
+ const character = body[position++];
5348
+ if (character === "\"") return;
5349
+ if (character === "\\") position++;
5350
+ }
5351
+ throw new EvidenceParseError("invalid-json");
5352
+ };
5353
+ const isImage = (value) => protocol === "anthropic-messages" ? value.type === "image" && object$2(value.source) && (value.source.type === "base64" && typeof value.source.data === "string" || value.source.type === "url" && typeof value.source.url === "string") : protocol === "openai-responses" ? value.type === "input_image" && (typeof value.image_url === "string" || typeof value.file_id === "string") : value.type === "image_url" && object$2(value.image_url) && typeof value.image_url.url === "string";
5354
+ const isOpaque = (parent, key, location) => protocol === "openai-responses" ? location === "conversation" && parent.type === "reasoning" && key === "encrypted_content" : location === "content" && protocol === "anthropic-messages" && (parent.type === "thinking" && key === "signature" || parent.type === "redacted_thinking" && key === "data");
5355
+ const visit = (value, depth, location) => {
5356
+ if (++values > REQUEST_BODY_EVIDENCE_LIMITS.values || depth > REQUEST_BODY_EVIDENCE_LIMITS.depth) throw new EvidenceParseError("work-limit");
5357
+ whitespace();
5358
+ const start = position;
5359
+ let image = 0, replay = 0;
5360
+ if (Array.isArray(value)) {
5361
+ if (body[position++] !== "[") throw new EvidenceParseError("invalid-json");
5362
+ for (let index = 0; index < value.length; index++) {
5363
+ if (index > 0) {
5364
+ whitespace();
5365
+ if (body[position++] !== ",") throw new EvidenceParseError("invalid-json");
5366
+ }
5367
+ const child = visit(value[index], depth + 1, location);
5368
+ image += child.image;
5369
+ replay += child.replay;
5370
+ }
5371
+ whitespace();
5372
+ if (body[position++] !== "]") throw new EvidenceParseError("invalid-json");
5373
+ } else if (object$2(value)) {
5374
+ if (body[position++] !== "{") throw new EvidenceParseError("invalid-json");
5375
+ const imageBlock = location === "content" && isImage(value);
5376
+ const seen = /* @__PURE__ */ new Set();
5377
+ whitespace();
5378
+ while (body[position] !== "}") {
5379
+ if (seen.size > 0) {
5380
+ if (body[position++] !== ",") throw new EvidenceParseError("invalid-json");
5381
+ whitespace();
5382
+ }
5383
+ const keyStart = position;
5384
+ stringEnd();
5385
+ if (position - keyStart > REQUEST_BODY_EVIDENCE_LIMITS.keyCharacters) throw new EvidenceParseError("work-limit");
5386
+ const key = JSON.parse(body.slice(keyStart, position));
5387
+ if (typeof key !== "string" || seen.has(key) || !Object.hasOwn(value, key)) throw new EvidenceParseError("invalid-json");
5388
+ seen.add(key);
5389
+ whitespace();
5390
+ if (body[position++] !== ":") throw new EvidenceParseError("invalid-json");
5391
+ whitespace();
5392
+ const childLocation = imageBlock ? "other" : depth === 0 && key === conversationKey ? "conversation" : key === "content" && (location === "conversation" || location === "content") && Array.isArray(value[key]) ? "content" : "other";
5393
+ const childStart = position, child = visit(value[key], depth + 1, childLocation);
5394
+ const childBytes = depth === 0 || isOpaque(value, key, location) && typeof value[key] === "string" ? bytes(childStart) : 0;
5395
+ if (depth === 0) {
5396
+ if (key === conversationKey) {
5397
+ conversationBytes = childBytes;
5398
+ imageBlockBytes = child.image;
5399
+ opaqueReplayBytes = child.replay;
5400
+ } else if ((key === "tools" || protocol === "openai-completions" && key === "functions") && Array.isArray(value[key])) toolSchemaBytes += childBytes;
5401
+ else if (key === systemKey && (typeof value[key] === "string" || Array.isArray(value[key]))) systemBytes += childBytes;
5402
+ }
5403
+ image += child.image;
5404
+ replay += isOpaque(value, key, location) && typeof value[key] === "string" ? childBytes : child.replay;
5405
+ whitespace();
5406
+ }
5407
+ position++;
5408
+ if (imageBlock) {
5409
+ image = bytes(start);
5410
+ replay = 0;
5411
+ }
5412
+ } else if (typeof value === "string") stringEnd();
5413
+ else {
5414
+ while (position < body.length && !/[\s,\]}]/u.test(body[position])) position++;
5415
+ if (position === start) throw new EvidenceParseError("invalid-json");
5416
+ }
5417
+ return {
5418
+ image,
5419
+ replay
5420
+ };
5421
+ };
5422
+ try {
5423
+ visit(parsed, 0, "root");
5424
+ whitespace();
5425
+ if (position !== body.length) return {
5426
+ state: "invalid-json",
5427
+ totalBytes
5428
+ };
5429
+ } catch (cause) {
5430
+ if (!(cause instanceof EvidenceParseError)) throw cause;
5431
+ return {
5432
+ state: cause.state,
5433
+ totalBytes
5434
+ };
5435
+ }
5436
+ const otherBytes = totalBytes - conversationBytes - toolSchemaBytes - systemBytes;
5437
+ const remainingConversationBytes = conversationBytes - imageBlockBytes - opaqueReplayBytes;
5438
+ if (otherBytes < 0 || remainingConversationBytes < 0) return {
5439
+ state: "invalid-json",
5440
+ totalBytes
5441
+ };
5442
+ return {
5443
+ state: "complete",
5444
+ totalBytes,
5445
+ conversationBytes,
5446
+ toolSchemaBytes,
5447
+ systemBytes,
5448
+ otherBytes,
5449
+ imageBlockBytes,
5450
+ opaqueReplayBytes,
5451
+ remainingConversationBytes
5452
+ };
5453
+ }
5454
+ //#endregion
5455
+ //#region lib/types/replay-recovery.js
5456
+ function record$7(value) {
5457
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5458
+ }
5459
+ function parsed(body) {
5460
+ if (requestBodyEvidence(body, "openai-responses").state !== "complete" || body === void 0) throw new Error("COPILOT_REPLAY_RECOVERY_EVIDENCE_UNAVAILABLE");
5461
+ const payload = JSON.parse(body);
5462
+ if (!record$7(payload) || !Array.isArray(payload.input) || !payload.input.every(record$7)) throw new Error("COPILOT_REPLAY_RECOVERY_INVALID_PAYLOAD");
5463
+ return {
5464
+ input: payload.input,
5465
+ payload
5466
+ };
5467
+ }
5468
+ function hash(item) {
5469
+ if (item.type !== "reasoning" || typeof item.encrypted_content !== "string" || !item.encrypted_content) return void 0;
5470
+ if (item.status !== void 0 && item.status !== "completed") throw new Error("COPILOT_REPLAY_RECOVERY_INCOMPLETE_ITEM");
5471
+ return createHash("sha256").update(JSON.stringify(item)).digest("hex");
5472
+ }
5473
+ /** Host-lifetime opt-in only. Stores fingerprints, never request bodies or opaque replay. */
5474
+ var ReplayRecoveryStore = class {
5475
+ now;
5476
+ owners = /* @__PURE__ */ new Map();
5477
+ constructor(now = Date.now) {
5478
+ this.now = now;
5479
+ }
5480
+ current(owner, proof) {
5481
+ const state = this.owners.get(owner);
5482
+ if (state && (proof !== state.proof || this.now() - state.at >= 36e5)) {
5483
+ this.owners.delete(owner);
5484
+ return;
5485
+ }
5486
+ return state;
5487
+ }
5488
+ view(owner, proof) {
5489
+ const state = this.current(owner, proof);
5490
+ return state ? {
5491
+ state: state.enabled ? "enabled" : "available",
5492
+ revision: state.revision,
5493
+ itemCount: state.hashes.size,
5494
+ model: state.model
5495
+ } : { state: "unavailable" };
5496
+ }
5497
+ recordFailure(owner, proof, model, body) {
5498
+ const hashes = new Set(parsed(body).input.map(hash).filter((value) => value !== void 0));
5499
+ if (!hashes.size) return;
5500
+ const previous = this.current(owner, proof);
5501
+ if (previous?.model === model) for (const value of previous.hashes) hashes.add(value);
5502
+ if (hashes.size > 512) throw new Error("COPILOT_REPLAY_RECOVERY_EVIDENCE_LIMIT");
5503
+ this.owners.set(owner, {
5504
+ proof,
5505
+ model,
5506
+ hashes,
5507
+ revision: randomUUID(),
5508
+ at: this.now(),
5509
+ enabled: false
5510
+ });
5511
+ if (this.owners.size > 64) this.owners.delete(this.owners.keys().next().value);
5512
+ }
5513
+ setEnabled(owner, proof, revision, enabled) {
5514
+ const state = this.current(owner, proof);
5515
+ if (!state || revision !== state.revision) throw new Error("COPILOT_REPLAY_RECOVERY_STALE_EVIDENCE");
5516
+ state.enabled = enabled;
5517
+ return this.view(owner, proof);
5518
+ }
5519
+ prepare(owner, proof, model) {
5520
+ const state = this.current(owner, proof);
5521
+ const admitted = state?.enabled && state.model === model ? state.hashes : void 0;
5522
+ return (payload) => {
5523
+ if (!admitted) return payload;
5524
+ if (this.current(owner, proof) !== state) throw new Error("COPILOT_REPLAY_RECOVERY_REVOKED");
5525
+ let body;
5526
+ try {
5527
+ body = JSON.stringify(payload);
5528
+ } catch {
5529
+ throw new Error("COPILOT_REPLAY_RECOVERY_INVALID_PAYLOAD");
5530
+ }
5531
+ const decoded = parsed(body);
5532
+ if (decoded.input.filter((item) => {
5533
+ const value = hash(item);
5534
+ return value === void 0 || !admitted.has(value);
5535
+ }).length === decoded.input.length) return payload;
5536
+ if (!record$7(payload) || !Array.isArray(payload.input)) throw new Error("COPILOT_REPLAY_RECOVERY_INVALID_PAYLOAD");
5537
+ const input = payload.input.filter((_, index) => {
5538
+ const item = decoded.input[index];
5539
+ const value = hash(item);
5540
+ return value === void 0 || !admitted.has(value);
5541
+ });
5542
+ return {
5543
+ ...payload,
5544
+ input
5545
+ };
5546
+ };
5547
+ }
5548
+ remove(owner) {
5549
+ this.owners.delete(owner);
5550
+ }
5551
+ clear() {
5552
+ this.owners.clear();
5553
+ }
5554
+ };
5555
+ //#endregion
5556
+ //#region lib/types/replay-recovery-host.js
5557
+ var __runInitializers$1 = function(thisArg, initializers, value) {
5558
+ var useValue = arguments.length > 2;
5559
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
5560
+ return useValue ? value : void 0;
5561
+ };
5562
+ var __esDecorate$1 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
5563
+ function accept(f) {
5564
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
5565
+ return f;
5566
+ }
5567
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5568
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
5569
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
5570
+ var _, done = false;
5571
+ for (var i = decorators.length - 1; i >= 0; i--) {
5572
+ var context = {};
5573
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
5574
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
5575
+ context.addInitializer = function(f) {
5576
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
5577
+ extraInitializers.push(accept(f || null));
5578
+ };
5579
+ var result = (0, decorators[i])(kind === "accessor" ? {
5580
+ get: descriptor.get,
5581
+ set: descriptor.set
5582
+ } : descriptor[key], context);
5583
+ if (kind === "accessor") {
5584
+ if (result === void 0) continue;
5585
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
5586
+ if (_ = accept(result.get)) descriptor.get = _;
5587
+ if (_ = accept(result.set)) descriptor.set = _;
5588
+ if (_ = accept(result.init)) initializers.unshift(_);
5589
+ } else if (_ = accept(result)) {
5590
+ if (kind === "field") initializers.unshift(_);
5591
+ else descriptor[key] = _;
5592
+ }
5593
+ }
5594
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
5595
+ done = true;
5596
+ };
5597
+ let ReplayRecoveryController = (() => {
5598
+ let _classSuper = TypertRemoteService;
5599
+ let _instanceExtraInitializers = [];
5600
+ let _get_decorators;
5601
+ let _setEnabled_decorators;
5602
+ return class ReplayRecoveryController extends _classSuper {
5603
+ static {
5604
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
5605
+ _get_decorators = [Remote];
5606
+ _setEnabled_decorators = [Remote];
5607
+ __esDecorate$1(this, null, _get_decorators, {
5608
+ kind: "method",
5609
+ name: "get",
5610
+ static: false,
5611
+ private: false,
5612
+ access: {
5613
+ has: (obj) => "get" in obj,
5614
+ get: (obj) => obj.get
5615
+ },
5616
+ metadata: _metadata
5617
+ }, null, _instanceExtraInitializers);
5618
+ __esDecorate$1(this, null, _setEnabled_decorators, {
5619
+ kind: "method",
5620
+ name: "setEnabled",
5621
+ static: false,
5622
+ private: false,
5623
+ access: {
5624
+ has: (obj) => "setEnabled" in obj,
5625
+ get: (obj) => obj.setEnabled
5626
+ },
5627
+ metadata: _metadata
5628
+ }, null, _instanceExtraInitializers);
5629
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
5630
+ enumerable: true,
5631
+ configurable: true,
5632
+ writable: true,
5633
+ value: _metadata
5634
+ });
5635
+ }
5636
+ store = __runInitializers$1(this, _instanceExtraInitializers);
5637
+ proof;
5638
+ busy;
5639
+ constructor(ctx, store, proof, busy) {
5640
+ super(ctx, "githubCopilotReplayRecovery");
5641
+ this.store = store;
5642
+ this.proof = proof;
5643
+ this.busy = busy;
5644
+ }
5645
+ get(agent) {
5646
+ return this.store.view(agent.session, this.proof());
5647
+ }
5648
+ setEnabled(agent, revision, enabled) {
5649
+ if (this.busy.has(agent.session)) throw new Error("COPILOT_REPLAY_RECOVERY_TURN_ACTIVE");
5650
+ return this.store.setEnabled(agent.session, this.proof(), revision, enabled);
5651
+ }
5652
+ };
5653
+ })();
5654
+ function installReplayRecovery(ctx, proof) {
5655
+ const store = new ReplayRecoveryStore();
5656
+ const requests = /* @__PURE__ */ new WeakMap();
5657
+ const currentRequests = /* @__PURE__ */ new WeakMap();
5658
+ const busy = /* @__PURE__ */ new WeakSet();
5659
+ new ReplayRecoveryController(ctx, store, proof, busy);
5660
+ const removeRequest = ctx.on("agent/request", async ({ agent, turn, signal }, next) => {
5661
+ const result = await next();
5662
+ if (!signal.aborted) {
5663
+ requests.set(signal, {
5664
+ session: agent.session,
5665
+ turn
5666
+ });
5667
+ currentRequests.set(agent.session, signal);
5668
+ busy.add(agent.session);
5669
+ }
5670
+ return result;
5671
+ });
5672
+ const removeEvents = ctx.on("session/event", (session, event) => {
5673
+ if (event.type === "turn/end") {
5674
+ busy.delete(session);
5675
+ currentRequests.delete(session);
5676
+ }
5677
+ });
5678
+ const removeAgent = ctx.on("agent/disposed", ({ agent }) => {
5679
+ store.remove(agent.session);
5680
+ busy.delete(agent.session);
5681
+ currentRequests.delete(agent.session);
5682
+ });
5683
+ let active = true;
5684
+ return {
5685
+ prepare(request) {
5686
+ if (!active || request.signal === void 0 || request.signal.aborted || request.purpose !== void 0 || request.provider !== "github-copilot-preview") return void 0;
5687
+ const binding = requests.get(request.signal);
5688
+ const currentProof = proof();
5689
+ if (!binding || binding.session.id !== request.sessionId || !busy.has(binding.session) || currentProof === void 0) return void 0;
5690
+ const transform = store.prepare(binding.session, currentProof, request.model);
5691
+ const current = () => active && !request.signal?.aborted && proof() === currentProof && currentRequests.get(binding.session) === request.signal && busy.has(binding.session);
5692
+ return {
5693
+ transform(payload) {
5694
+ if (!current()) throw new Error("COPILOT_REPLAY_RECOVERY_REVOKED");
5695
+ return transform(payload);
5696
+ },
5697
+ rejected(body) {
5698
+ if (!current()) return;
5699
+ try {
5700
+ store.recordFailure(binding.session, currentProof, request.model, body);
5701
+ } catch {
5702
+ ctx.logger.warn("[github-copilot] COPILOT_REPLAY_RECOVERY_EVIDENCE_UNAVAILABLE");
5703
+ }
5704
+ }
5705
+ };
5706
+ },
5707
+ dispose() {
5708
+ active = false;
5709
+ removeRequest();
5710
+ removeEvents();
5711
+ removeAgent();
5712
+ store.clear();
5713
+ }
5714
+ };
5715
+ }
5716
+ //#endregion
5717
+ //#region lib/types/pi-provider-bridge.js
5718
+ /** Retain the same stream object after proving its public surface; only SDK-private nominal identity differs. */
5719
+ function coreEventStream(stream) {
5720
+ return stream;
5721
+ }
5722
+ /**
5723
+ * The published Core adapter consumes streamSimple. Do not pretend its older
5724
+ * protocol-specific clients are interchangeable with a newer SDK's clients.
5725
+ */
5726
+ function coreProviderView(provider) {
5727
+ return {
5728
+ ...provider,
5729
+ stream: () => {
5730
+ throw new Error("COPILOT_MANAGED_ADVANCED_STREAM_UNSUPPORTED");
5731
+ },
5732
+ streamSimple: (model, context, options) => coreEventStream(provider.streamSimple(model, context, options))
5733
+ };
5734
+ }
5735
+ //#endregion
5736
+ //#region lib/types/response-error-body.js
5737
+ const maxErrorBytes = 8192;
5738
+ const errorReadTimeoutMs = 250;
5739
+ async function readError(reader) {
5740
+ const decoder = new TextDecoder("utf-8", { fatal: true });
5741
+ let bytes = 0, chunks = 0, text = "";
5742
+ while (true) {
5743
+ if (chunks++ > maxErrorBytes) return void 0;
5744
+ const chunk = await reader.read();
5745
+ if (chunk.done) break;
5746
+ bytes += chunk.value.byteLength;
5747
+ if (bytes > maxErrorBytes) return void 0;
5748
+ text += decoder.decode(chunk.value, { stream: true });
5749
+ }
5750
+ return JSON.parse(text + decoder.decode());
5751
+ }
5752
+ /** Optional classification evidence only; an unreadable clone leaves native handling unchanged. */
5753
+ async function readResponseErrorJson(response, signal) {
5754
+ if (signal?.aborted) return void 0;
5755
+ let reader;
5756
+ let timeout;
5757
+ let onAbort;
5758
+ try {
5759
+ const clone = response.clone();
5760
+ if (!clone.body) return void 0;
5761
+ reader = clone.body.getReader();
5762
+ const interrupted = new Promise((resolve) => {
5763
+ onAbort = () => resolve(void 0);
5764
+ signal?.addEventListener("abort", onAbort, { once: true });
5765
+ timeout = setTimeout(() => resolve(void 0), errorReadTimeoutMs);
5766
+ if (signal?.aborted) resolve(void 0);
5767
+ });
5768
+ const result = await Promise.race([readError(reader), interrupted]);
5769
+ return signal?.aborted ? void 0 : result;
5770
+ } catch {
5771
+ return;
5772
+ } finally {
5773
+ if (timeout !== void 0) clearTimeout(timeout);
5774
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
5775
+ if (reader) {
5776
+ try {
5777
+ reader.cancel().catch(() => {});
5778
+ } catch {}
5779
+ try {
5780
+ reader.releaseLock();
5781
+ } catch {}
5782
+ }
5783
+ }
5784
+ }
5785
+ //#endregion
5786
+ //#region lib/types/responses-replay-compat.js
5787
+ const replayDiagnostics = {
5788
+ "scope-mismatch": "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH: Copilot Responses input references belong to a different connection.",
5789
+ unsupported: "COPILOT_RESPONSES_REPLAY_UNSUPPORTED: Copilot Responses input cannot be replayed safely without connection-scoped references.",
5790
+ "invalid-payload": "COPILOT_RESPONSES_REPLAY_INVALID_PAYLOAD: Copilot Responses payload has an invalid replay structure."
5791
+ };
5792
+ /** Fixed diagnostics and bounded counts only; never retain request or replay content. */
5793
+ var CopilotResponsesReplayError = class extends Error {
5794
+ constructor(reason = "unsupported", dispatch) {
5795
+ super(replayDiagnostics[reason] + (reason === "scope-mismatch" && dispatch !== void 0 ? ` ${replayDispatchEvidence(dispatch)}` : ""));
5796
+ this.name = "CopilotResponsesReplayError";
5797
+ }
5798
+ };
5799
+ function replayDispatchEvidence(dispatch) {
5800
+ const presence = (value) => value === void 0 ? "unavailable" : value ? "present" : "absent";
5801
+ const headers = `sessionHeader=${presence(dispatch.sessionHeader)}, clientRequestHeader=${presence(dispatch.clientRequestHeader)}.`;
5802
+ const evidence = requestBodyEvidence(dispatch.body, "openai-responses");
5803
+ const unavailable = (state) => `Replay structure unavailable (${state}); no zero counts inferred. ${headers}`;
5804
+ if (evidence.state !== "complete" || dispatch.body === void 0) return unavailable(evidence.state);
5805
+ const payload = JSON.parse(dispatch.body);
5806
+ if (!isRecord$1(payload) || !Array.isArray(payload.input) || !payload.input.every(isRecord$1)) return unavailable("unsupported-shape");
5807
+ let directIds = 0, references = 0, encryptedReasoning = 0, otherItems = 0;
5808
+ for (const item of payload.input) {
5809
+ if (Object.hasOwn(item, "id")) directIds++;
5810
+ if (item.type === "item_reference") references++;
5811
+ if (item.type === "reasoning" && typeof item.encrypted_content === "string" && item.encrypted_content.length > 0) encryptedReasoning++;
5812
+ const known = typeof item.type === "string" && [
5813
+ "message",
5814
+ "reasoning",
5815
+ "function_call",
5816
+ "function_call_output",
5817
+ "item_reference"
5818
+ ].includes(item.type);
5819
+ const message = item.type === void 0 && typeof item.role === "string" && [
5820
+ "user",
5821
+ "system",
5822
+ "developer",
5823
+ "assistant"
5824
+ ].includes(item.role);
5825
+ if (!known && !message) otherItems++;
5826
+ }
5827
+ const previous = payload.previous_response_id;
5828
+ const previousResponse = previous === void 0 || previous === null || previous === "" ? "absent" : typeof previous === "string" ? "present" : "invalid";
5829
+ const store = payload.store === void 0 ? "absent" : typeof payload.store === "boolean" ? String(payload.store) : "invalid";
5830
+ return `Dispatched Responses structure: items=${payload.input.length}, directIds=${directIds}, references=${references}, encryptedReasoning=${encryptedReasoning}, otherItems=${otherItems}; previousResponse=${previousResponse}, store=${store}; ${headers} Counts do not identify the rejected item or prove opaque replay is portable. History, authorization and native retry policy are unchanged.`;
5831
+ }
5832
+ function isRecord$1(value) {
5833
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
5834
+ const prototype = Object.getPrototypeOf(value);
5835
+ return prototype === Object.prototype || prototype === null;
5836
+ }
5837
+ function nonemptyString(value) {
5838
+ return typeof value === "string" && value.trim().length > 0;
5839
+ }
5840
+ function emptyReasoningShell(item) {
5841
+ return item.type === "reasoning" && nonemptyString(item.id) && (item.status === void 0 || item.status === "completed") && Array.isArray(item.summary) && item.summary.length === 0 && (item.content === void 0 || Array.isArray(item.content) && item.content.length === 0) && item.encrypted_content === void 0 && Object.keys(item).every((key) => [
5842
+ "type",
5843
+ "id",
5844
+ "status",
5845
+ "summary",
5846
+ "content",
5847
+ "encrypted_content"
5848
+ ].includes(key));
5849
+ }
5850
+ function normalizeItem(item) {
5851
+ if (!isRecord$1(item)) throw new CopilotResponsesReplayError("invalid-payload");
5852
+ if (item.type === "item_reference") throw new CopilotResponsesReplayError();
5853
+ if (emptyReasoningShell(item)) return void 0;
5854
+ if ((item.type === "message" || item.type === void 0) && (item.role === "user" || item.role === "system" || item.role === "developer")) return item;
5855
+ if (!Object.hasOwn(item, "id") || item.id === void 0) return item;
5856
+ if (!nonemptyString(item.id)) throw new CopilotResponsesReplayError("invalid-payload");
5857
+ if (!((item.status === void 0 || item.status === "completed") && (item.type === "message" && item.role === "assistant" && Array.isArray(item.content) || item.type === "function_call" && nonemptyString(item.call_id) && nonemptyString(item.name) && typeof item.arguments === "string" || item.type === "reasoning" && nonemptyString(item.encrypted_content)))) throw new CopilotResponsesReplayError();
5858
+ const normalized = { ...item };
5859
+ delete normalized.id;
5860
+ return normalized;
5861
+ }
5862
+ /** Normalize only the outgoing managed Responses payload, never stored history/context. */
5863
+ function normalizeCopilotResponsesPayload(payload) {
5864
+ try {
5865
+ if (!isRecord$1(payload) || typeof payload.input !== "string" && !Array.isArray(payload.input)) throw new CopilotResponsesReplayError("invalid-payload");
5866
+ if (payload.previous_response_id !== void 0 && payload.previous_response_id !== null && payload.previous_response_id !== "") throw new CopilotResponsesReplayError(typeof payload.previous_response_id === "string" ? "unsupported" : "invalid-payload");
5867
+ if (typeof payload.input === "string") return payload;
5868
+ let changed = false;
5869
+ const input = [];
5870
+ for (const item of payload.input) {
5871
+ const normalized = normalizeItem(item);
5872
+ changed ||= normalized !== item;
5873
+ if (normalized !== void 0) input.push(normalized);
5874
+ }
5875
+ return changed ? {
5876
+ ...payload,
5877
+ input
5878
+ } : payload;
5879
+ } catch (error) {
5880
+ if (error instanceof CopilotResponsesReplayError) throw error;
5881
+ throw new CopilotResponsesReplayError("invalid-payload");
5882
+ }
5883
+ }
5884
+ const retryLifetimeMs = 6e4;
5885
+ const maxRetryBytes = 2097152;
5886
+ function cacheBytes(value) {
5887
+ let json;
5888
+ try {
5889
+ json = JSON.stringify(value);
5890
+ } catch {
5891
+ return;
5892
+ }
5893
+ if (json === void 0 || Buffer.byteLength(json, "utf8") > maxRetryBytes) return void 0;
5894
+ return json;
5895
+ }
5896
+ /** A single lease can admit one HTTP-verified retry at a time; it never reads durable history. */
5897
+ var ResponsesRetryReplay = class {
5898
+ snapshot;
5899
+ active = 0;
5900
+ disposed = false;
5901
+ dispose() {
5902
+ this.disposed = true;
5903
+ this.snapshot = void 0;
5904
+ }
5905
+ belongsTo(sessionId) {
5906
+ return this.snapshot?.sessionId === sessionId;
5907
+ }
5908
+ begin(context, signal, sessionId, modelId) {
5909
+ const contextBytes = cacheBytes(context);
5910
+ const overlapping = this.active++ !== 0;
5911
+ if (overlapping) this.snapshot = void 0;
5912
+ const previous = this.snapshot;
5913
+ 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;
5914
+ const eligible = contextBytes !== void 0 && !overlapping && !this.disposed && !signal?.aborted && this.snapshot;
5915
+ let candidate;
5916
+ let payloadBytes;
5917
+ let finished = false;
5918
+ let observed = false;
5919
+ return {
5920
+ normalize: (payload) => {
5921
+ if (this.disposed || signal?.aborted) throw new CopilotResponsesReplayError();
5922
+ const rawBytes = cacheBytes(payload);
5923
+ let normalized;
5924
+ let reused = false;
5925
+ try {
5926
+ normalized = normalizeCopilotResponsesPayload(payload);
5927
+ } catch (error) {
5928
+ if (!(error instanceof CopilotResponsesReplayError) || !eligible || !isRecord$1(payload) || !Array.isArray(payload.input) || !isRecord$1(eligible.raw) || !Array.isArray(eligible.raw.input)) {
5929
+ this.snapshot = void 0;
5930
+ throw error;
5931
+ }
5932
+ try {
5933
+ const prior = eligible.raw.input;
5934
+ if (payload.input.length !== prior.length) throw error;
5935
+ let references = 0;
5936
+ const restored = payload.input.map((item, index) => {
5937
+ if (!isRecord$1(item) || !Object.hasOwn(item, "id")) return item;
5938
+ const original = prior[index];
5939
+ if (!isRecord$1(original) || !nonemptyString(item.id) || original.id !== item.id || ![
5940
+ "reasoning",
5941
+ "message",
5942
+ "function_call"
5943
+ ].includes(String(original.type)) || normalizeItem(original) === original) throw error;
5944
+ if (item.type === "item_reference") {
5945
+ if (Object.keys(item).length !== 2) throw error;
5946
+ } 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;
5464
5947
  references++;
5465
5948
  return original;
5466
5949
  });
@@ -5526,194 +6009,6 @@ async function isCopilotInputItemScopeError(response, signal) {
5526
6009
  //#region lib/types/request-body-timeout-marker.js
5527
6010
  const REQUEST_BODY_TIMEOUT_MARKER = "COPILOT_REQUEST_BODY_TIMEOUT: Copilot returned HTTP 408 / user_request_timeout while reading the request body; this is not context-window overflow.";
5528
6011
  //#endregion
5529
- //#region lib/types/request-body-evidence.js
5530
- const REQUEST_BODY_EVIDENCE_LIMITS = Object.freeze({
5531
- bytes: 16777216,
5532
- values: 65536,
5533
- tokens: 131072,
5534
- depth: 64,
5535
- keyCharacters: 128
5536
- });
5537
- function formatRequestBodyEvidence(evidence, responseHeadersMs) {
5538
- const elapsed = responseHeadersMs === void 0 ? void 0 : Math.round(responseHeadersMs);
5539
- const timing = responseHeadersMs !== void 0 && responseHeadersMs >= 0 && elapsed !== void 0 && Number.isSafeInteger(elapsed) ? `Fetch-to-response-headers: ${elapsed} ms (round trip, not upload duration).` : "Fetch-to-response-headers timing unavailable.";
5540
- if (evidence.state !== "complete") return `Composition unavailable (${evidence.state}); no partial totals inferred. ${timing}`;
5541
- return `Composition (wire UTF-8 bytes): conversation ${evidence.conversationBytes}, tool definitions ${evidence.toolSchemaBytes}, top-level system/instructions ${evidence.systemBytes}, other/framing ${evidence.otherBytes}. Within conversation (disjoint subsets): image blocks ${evidence.imageBlockBytes}, opaque replay ${evidence.opaqueReplayBytes}, remaining ${evidence.remainingConversationBytes} (text/tool history, framing and unrecognized fields). Image blocks include URLs/references, not decoded image sizes; unknown encodings stay in remaining/other. ${timing}`;
5542
- }
5543
- var EvidenceParseError = class extends Error {
5544
- state;
5545
- constructor(state) {
5546
- super(state);
5547
- this.state = state;
5548
- }
5549
- };
5550
- function object$2(value) {
5551
- return typeof value === "object" && value !== null && !Array.isArray(value);
5552
- }
5553
- /** Diagnostic-only traversal of the original JSON spans; never reserializes or changes a request. */
5554
- function requestBodyEvidence(body, protocol) {
5555
- if (body === void 0) return { state: "unavailable" };
5556
- const totalBytes = Buffer.byteLength(body, "utf8");
5557
- if (totalBytes > REQUEST_BODY_EVIDENCE_LIMITS.bytes) return {
5558
- state: "size-limit",
5559
- totalBytes
5560
- };
5561
- let nesting = 0, tokens = 0;
5562
- for (let index = 0; index < body.length; index++) {
5563
- const character = body[index];
5564
- if (character === "{" || character === "[") {
5565
- if (++nesting > REQUEST_BODY_EVIDENCE_LIMITS.depth) return {
5566
- state: "work-limit",
5567
- totalBytes
5568
- };
5569
- tokens++;
5570
- } else if (character === "}" || character === "]") nesting--;
5571
- else if (character === "\"") {
5572
- tokens++;
5573
- while (++index < body.length) if (body[index] === "\\") index++;
5574
- else if (body[index] === "\"") break;
5575
- } else if (character !== " " && character !== "\n" && character !== "\r" && character !== " " && character !== ":" && character !== ",") {
5576
- tokens++;
5577
- while (index + 1 < body.length && !/[\s,\]}]/u.test(body[index + 1])) index++;
5578
- }
5579
- if (tokens > REQUEST_BODY_EVIDENCE_LIMITS.tokens) return {
5580
- state: "work-limit",
5581
- totalBytes
5582
- };
5583
- }
5584
- let parsed;
5585
- try {
5586
- parsed = JSON.parse(body);
5587
- } catch (error) {
5588
- if (!(error instanceof SyntaxError)) throw error;
5589
- return {
5590
- state: "invalid-json",
5591
- totalBytes
5592
- };
5593
- }
5594
- const conversationKey = protocol === "openai-responses" ? "input" : "messages";
5595
- const systemKey = protocol === "openai-responses" ? "instructions" : protocol === "anthropic-messages" ? "system" : void 0;
5596
- if (!object$2(parsed) || !Array.isArray(parsed[conversationKey])) return {
5597
- state: "unsupported-shape",
5598
- totalBytes
5599
- };
5600
- let position = 0, values = 0, conversationBytes = 0, toolSchemaBytes = 0, systemBytes = 0;
5601
- let imageBlockBytes = 0, opaqueReplayBytes = 0;
5602
- const whitespace = () => {
5603
- while (position < body.length && /\s/u.test(body[position])) position++;
5604
- };
5605
- const bytes = (start) => Buffer.byteLength(body.slice(start, position), "utf8");
5606
- const stringEnd = () => {
5607
- if (body[position++] !== "\"") throw new EvidenceParseError("invalid-json");
5608
- while (position < body.length) {
5609
- const character = body[position++];
5610
- if (character === "\"") return;
5611
- if (character === "\\") position++;
5612
- }
5613
- throw new EvidenceParseError("invalid-json");
5614
- };
5615
- const isImage = (value) => protocol === "anthropic-messages" ? value.type === "image" && object$2(value.source) && (value.source.type === "base64" && typeof value.source.data === "string" || value.source.type === "url" && typeof value.source.url === "string") : protocol === "openai-responses" ? value.type === "input_image" && (typeof value.image_url === "string" || typeof value.file_id === "string") : value.type === "image_url" && object$2(value.image_url) && typeof value.image_url.url === "string";
5616
- const isOpaque = (parent, key, location) => protocol === "openai-responses" ? location === "conversation" && parent.type === "reasoning" && key === "encrypted_content" : location === "content" && protocol === "anthropic-messages" && (parent.type === "thinking" && key === "signature" || parent.type === "redacted_thinking" && key === "data");
5617
- const visit = (value, depth, location) => {
5618
- if (++values > REQUEST_BODY_EVIDENCE_LIMITS.values || depth > REQUEST_BODY_EVIDENCE_LIMITS.depth) throw new EvidenceParseError("work-limit");
5619
- whitespace();
5620
- const start = position;
5621
- let image = 0, replay = 0;
5622
- if (Array.isArray(value)) {
5623
- if (body[position++] !== "[") throw new EvidenceParseError("invalid-json");
5624
- for (let index = 0; index < value.length; index++) {
5625
- if (index > 0) {
5626
- whitespace();
5627
- if (body[position++] !== ",") throw new EvidenceParseError("invalid-json");
5628
- }
5629
- const child = visit(value[index], depth + 1, location);
5630
- image += child.image;
5631
- replay += child.replay;
5632
- }
5633
- whitespace();
5634
- if (body[position++] !== "]") throw new EvidenceParseError("invalid-json");
5635
- } else if (object$2(value)) {
5636
- if (body[position++] !== "{") throw new EvidenceParseError("invalid-json");
5637
- const imageBlock = location === "content" && isImage(value);
5638
- const seen = /* @__PURE__ */ new Set();
5639
- whitespace();
5640
- while (body[position] !== "}") {
5641
- if (seen.size > 0) {
5642
- if (body[position++] !== ",") throw new EvidenceParseError("invalid-json");
5643
- whitespace();
5644
- }
5645
- const keyStart = position;
5646
- stringEnd();
5647
- if (position - keyStart > REQUEST_BODY_EVIDENCE_LIMITS.keyCharacters) throw new EvidenceParseError("work-limit");
5648
- const key = JSON.parse(body.slice(keyStart, position));
5649
- if (typeof key !== "string" || seen.has(key) || !Object.hasOwn(value, key)) throw new EvidenceParseError("invalid-json");
5650
- seen.add(key);
5651
- whitespace();
5652
- if (body[position++] !== ":") throw new EvidenceParseError("invalid-json");
5653
- whitespace();
5654
- const childLocation = imageBlock ? "other" : depth === 0 && key === conversationKey ? "conversation" : key === "content" && (location === "conversation" || location === "content") && Array.isArray(value[key]) ? "content" : "other";
5655
- const childStart = position, child = visit(value[key], depth + 1, childLocation);
5656
- const childBytes = depth === 0 || isOpaque(value, key, location) && typeof value[key] === "string" ? bytes(childStart) : 0;
5657
- if (depth === 0) {
5658
- if (key === conversationKey) {
5659
- conversationBytes = childBytes;
5660
- imageBlockBytes = child.image;
5661
- opaqueReplayBytes = child.replay;
5662
- } else if ((key === "tools" || protocol === "openai-completions" && key === "functions") && Array.isArray(value[key])) toolSchemaBytes += childBytes;
5663
- else if (key === systemKey && (typeof value[key] === "string" || Array.isArray(value[key]))) systemBytes += childBytes;
5664
- }
5665
- image += child.image;
5666
- replay += isOpaque(value, key, location) && typeof value[key] === "string" ? childBytes : child.replay;
5667
- whitespace();
5668
- }
5669
- position++;
5670
- if (imageBlock) {
5671
- image = bytes(start);
5672
- replay = 0;
5673
- }
5674
- } else if (typeof value === "string") stringEnd();
5675
- else {
5676
- while (position < body.length && !/[\s,\]}]/u.test(body[position])) position++;
5677
- if (position === start) throw new EvidenceParseError("invalid-json");
5678
- }
5679
- return {
5680
- image,
5681
- replay
5682
- };
5683
- };
5684
- try {
5685
- visit(parsed, 0, "root");
5686
- whitespace();
5687
- if (position !== body.length) return {
5688
- state: "invalid-json",
5689
- totalBytes
5690
- };
5691
- } catch (cause) {
5692
- if (!(cause instanceof EvidenceParseError)) throw cause;
5693
- return {
5694
- state: cause.state,
5695
- totalBytes
5696
- };
5697
- }
5698
- const otherBytes = totalBytes - conversationBytes - toolSchemaBytes - systemBytes;
5699
- const remainingConversationBytes = conversationBytes - imageBlockBytes - opaqueReplayBytes;
5700
- if (otherBytes < 0 || remainingConversationBytes < 0) return {
5701
- state: "invalid-json",
5702
- totalBytes
5703
- };
5704
- return {
5705
- state: "complete",
5706
- totalBytes,
5707
- conversationBytes,
5708
- toolSchemaBytes,
5709
- systemBytes,
5710
- otherBytes,
5711
- imageBlockBytes,
5712
- opaqueReplayBytes,
5713
- remainingConversationBytes
5714
- };
5715
- }
5716
- //#endregion
5717
6012
  //#region lib/types/request-body-timeout.js
5718
6013
  const observedMessage = "Timed out reading request body. Try again, or use a smaller request size.";
5719
6014
  function record$6(value) {
@@ -6063,7 +6358,8 @@ function createAccountProvider(descriptors, guard, baseURL) {
6063
6358
  if (lease.signal.aborted || options.signal?.aborted) throw new Error("COPILOT_MANAGED_ABORTED");
6064
6359
  try {
6065
6360
  const effective = replacement === void 0 ? payload : replacement;
6066
- return retry === void 0 ? normalizeCopilotResponsesPayload(effective) : retry.normalize(effective);
6361
+ const normalized = retry === void 0 ? normalizeCopilotResponsesPayload(effective) : retry.normalize(effective);
6362
+ return guard.recoverReplay === void 0 ? normalized : guard.recoverReplay(normalized);
6067
6363
  } catch (error) {
6068
6364
  if (error instanceof CopilotResponsesReplayError) reportReplayFailure(error);
6069
6365
  throw error;
@@ -6073,6 +6369,12 @@ function createAccountProvider(descriptors, guard, baseURL) {
6073
6369
  const observeResponse = async (input, init) => {
6074
6370
  guard.onRequestBodyTimeout?.(void 0);
6075
6371
  liveness?.beginRequest(typeof init?.body === "string" ? init.body : void 0);
6372
+ const replayHeaders = responses && init?.headers !== void 0 ? new Headers(init.headers) : void 0;
6373
+ const replayDispatch = responses ? {
6374
+ body: typeof init?.body === "string" ? init.body : void 0,
6375
+ sessionHeader: replayHeaders?.has("session_id"),
6376
+ clientRequestHeader: replayHeaders?.has("x-client-request-id")
6377
+ } : void 0;
6076
6378
  let response;
6077
6379
  const startedAt = performance.now();
6078
6380
  try {
@@ -6091,8 +6393,10 @@ function createAccountProvider(descriptors, guard, baseURL) {
6091
6393
  if (!lease.signal.aborted && !options.signal?.aborted) guard.onRequestBodyTimeout(diagnostic);
6092
6394
  }
6093
6395
  if (response.status === 401) {
6094
- if (responses && await isCopilotInputItemScopeError(response, lease.signal)) reportReplayFailure(new CopilotResponsesReplayError("scope-mismatch"));
6095
- else unauthorized = true;
6396
+ if (responses && await isCopilotInputItemScopeError(response, lease.signal)) {
6397
+ guard.onReplayScopeRejected?.(replayDispatch?.body);
6398
+ reportReplayFailure(new CopilotResponsesReplayError("scope-mismatch", replayDispatch));
6399
+ } else unauthorized = true;
6096
6400
  }
6097
6401
  return liveness?.observe(response) ?? response;
6098
6402
  };
@@ -8544,7 +8848,8 @@ var PreviewAdapter = class extends PiAiAdapter {
8544
8848
  refreshRejected;
8545
8849
  requestBudgetSettings;
8546
8850
  accountModelSettings;
8547
- constructor(lifetime, optionsFor, discoverSnapshot, refreshRejected, requestBudgetSettings, accountModelSettings) {
8851
+ replayRecovery;
8852
+ constructor(lifetime, optionsFor, discoverSnapshot, refreshRejected, requestBudgetSettings, accountModelSettings, replayRecovery) {
8548
8853
  super(optionsFor());
8549
8854
  this.lifetime = lifetime;
8550
8855
  this.optionsFor = optionsFor;
@@ -8552,6 +8857,7 @@ var PreviewAdapter = class extends PiAiAdapter {
8552
8857
  this.refreshRejected = refreshRejected;
8553
8858
  this.requestBudgetSettings = requestBudgetSettings;
8554
8859
  this.accountModelSettings = accountModelSettings;
8860
+ this.replayRecovery = replayRecovery;
8555
8861
  }
8556
8862
  async listModels(provider) {
8557
8863
  owned(provider);
@@ -8665,6 +8971,7 @@ var PreviewAdapter = class extends PiAiAdapter {
8665
8971
  if (typeof mapping !== "string" || mapping.length === 0) throw failure("COPILOT_PREVIEW_REASONING_UNSUPPORTED", "INVALID_REQUEST");
8666
8972
  }
8667
8973
  let requestFailure;
8974
+ const recovery = owner.replayRecovery?.prepare(options);
8668
8975
  let wireAbort;
8669
8976
  let bodyTimeout;
8670
8977
  let liveness;
@@ -8691,6 +8998,10 @@ var PreviewAdapter = class extends PiAiAdapter {
8691
8998
  try {
8692
8999
  const native = new PiAiAdapter(owner.optionsFor(lease, {
8693
9000
  inspectRequest,
9001
+ ...recovery === void 0 ? {} : {
9002
+ recoverReplay: recovery.transform,
9003
+ onReplayScopeRejected: recovery.rejected
9004
+ },
8694
9005
  onWireAbort(code) {
8695
9006
  wireAbort = code;
8696
9007
  },
@@ -8830,6 +9141,10 @@ function apply$1(ctx, config = {}) {
8830
9141
  const proofFor = (snapshot) => source.readSnapshot() === snapshot && snapshotProof !== void 0 && snapshotProof.expires > Date.now() ? displayProofFor(snapshot) : void 0;
8831
9142
  const exclusionTurns = new ModelExclusionTurns();
8832
9143
  const lifetime = new PreviewLifetime(store, source, proofFor, displayProofFor, (modelId) => excludedModels().has(modelId), exclusionTurns);
9144
+ const replayRecovery = installReplayRecovery(ctx, () => {
9145
+ if (snapshotProof === void 0 || snapshotProof.expires <= Date.now()) return void 0;
9146
+ return `${lifetime.revision}:${snapshotProof.accountKey}:${snapshotProof.tokenFingerprint}`;
9147
+ });
8833
9148
  const removeStepListener = ctx.on("session/event", (session, event) => {
8834
9149
  if (event.type === "step/start" || event.type === "turn/end") lifetime.clearSessionRetries(session.id);
8835
9150
  if (event.type === "turn/end") exclusionTurns.end(session);
@@ -9055,7 +9370,7 @@ function apply$1(ctx, config = {}) {
9055
9370
  if (!exclusionTurns.admit(agent.session, turn, model, signal, excludedModels())) throw failure("COPILOT_PREVIEW_MODEL_EXCLUDED", "INVALID_REQUEST");
9056
9371
  }
9057
9372
  });
9058
- const registration = ctx.llm.registerAdapter([GITHUB_COPILOT_PREVIEW_PROVIDER_ID], new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings));
9373
+ const registration = ctx.llm.registerAdapter([GITHUB_COPILOT_PREVIEW_PROVIDER_ID], new PreviewAdapter(lifetime, optionsFor, discoverSnapshot, refreshRejected, budgetSettings, cacheSettings, replayRecovery));
9059
9374
  let exclusionSignature = JSON.stringify([...excludedModels()]);
9060
9375
  const removeSettings = onSettingsNamespaceUpdated(ctx, (namespace) => {
9061
9376
  if (namespace !== "github-copilot") return;
@@ -9161,6 +9476,7 @@ function apply$1(ctx, config = {}) {
9161
9476
  ctx.effect(() => () => {
9162
9477
  lifetime.dispose();
9163
9478
  removeStepListener();
9479
+ replayRecovery.dispose();
9164
9480
  removeListener();
9165
9481
  removeSettings();
9166
9482
  removeAutoRoute();