dsh-github-copilot 0.4.0-alpha.95 → 0.4.0-alpha.97

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
@@ -19,6 +19,8 @@ import { credentialRef } from "@deepseek-ai/dsh-credentials";
19
19
  import { Config as Config$1, PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
20
20
  import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
21
21
  import { buildCopilotDynamicHeaders, hasCopilotVisionInput } from "@earendil-works/pi-ai/api/github-copilot-headers";
22
+ import { AsyncLocalStorage } from "node:async_hooks";
23
+ import { channel } from "node:diagnostics_channel";
22
24
  //#region lib/types/dual-model-host.js
23
25
  /** Retired planner/executor entry points; retained policies stay enforceable without migration. */
24
26
  var __runInitializers$5 = function(thisArg, initializers, value) {
@@ -193,12 +195,12 @@ function fail$1(reason, creation) {
193
195
  function creationOf(error) {
194
196
  return ownRemoteFailure(error)?.creation ?? "uncertain";
195
197
  }
196
- function object$6(value) {
198
+ function object$7(value) {
197
199
  return typeof value === "object" && value !== null && !Array.isArray(value);
198
200
  }
199
201
  function api$1(ctx, key, methods) {
200
202
  const value = ctx.get(key);
201
- return object$6(value) && methods.every((method) => typeof value[method] === "function") ? value : void 0;
203
+ return object$7(value) && methods.every((method) => typeof value[method] === "function") ? value : void 0;
202
204
  }
203
205
  function revision(value) {
204
206
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
@@ -223,7 +225,7 @@ const ERROR_REASONS = /* @__PURE__ */ new Set([
223
225
  /** Remote errors cross bundle/realm boundaries; constructor identity is not a protocol. */
224
226
  function ownRemoteFailure(error) {
225
227
  try {
226
- if (!object$6(error) || error.isDSHRemoteError !== true || error.code !== "copilot/dual-model" || !object$6(error.details)) return void 0;
228
+ if (!object$7(error) || error.isDSHRemoteError !== true || error.code !== "copilot/dual-model" || !object$7(error.details)) return void 0;
227
229
  const reason = error.details.reason;
228
230
  if (typeof reason !== "string" || !ERROR_REASONS.has(reason)) return void 0;
229
231
  const creation = error.details.creation;
@@ -239,7 +241,7 @@ function reasonOf(error, fallback) {
239
241
  const own = ownRemoteFailure(error);
240
242
  if (own) return own.reason;
241
243
  try {
242
- if (object$6(error) && error.code === "SETTINGS_CONFLICT") return "DUAL_MODEL_REVISION_CONFLICT";
244
+ if (object$7(error) && error.code === "SETTINGS_CONFLICT") return "DUAL_MODEL_REVISION_CONFLICT";
243
245
  } catch {}
244
246
  return fallback;
245
247
  }
@@ -367,7 +369,7 @@ let GitHubCopilotDualModel = (() => {
367
369
  }, { prepend: true });
368
370
  ctx.on("system-prompt/assemble", async (_assembly, context, next) => {
369
371
  const candidate = context.scope;
370
- if (!candidate || !object$6(candidate.session) || !object$6(candidate.session.header) || !dedicatedAddress(candidate)) return next();
372
+ if (!candidate || !object$7(candidate.session) || !object$7(candidate.session.header) || !dedicatedAddress(candidate)) return next();
371
373
  const rehydrating = !this.overlays.has(candidate);
372
374
  if (rehydrating) this.restore(candidate);
373
375
  const installed = this.overlays.get(candidate);
@@ -1654,14 +1656,14 @@ function isZeroContextUsage(usage) {
1654
1656
  //#endregion
1655
1657
  //#region lib/types/context-evidence.js
1656
1658
  const COPILOT_CONTEXT_EVIDENCE = "githubCopilotContextEvidence";
1657
- const count = z$1.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
1659
+ const count$1 = z$1.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
1658
1660
  const routeSchema = z$1.object({
1659
1661
  provider: z$1.string().min(1),
1660
1662
  model: z$1.string().min(1)
1661
1663
  }).strict();
1662
1664
  const sampleSchema = z$1.object({
1663
- tokens: count,
1664
- seq: count,
1665
+ tokens: count$1,
1666
+ seq: count$1,
1665
1667
  route: routeSchema
1666
1668
  }).strict();
1667
1669
  const ContextEvidenceSchema = z$1.object({
@@ -1677,12 +1679,12 @@ const ContextEvidenceSchema = z$1.object({
1677
1679
  ])
1678
1680
  }).strict();
1679
1681
  const usageSchema = z$1.object({
1680
- inputTokens: count,
1681
- outputTokens: count,
1682
- cacheReadTokens: count.optional(),
1683
- cacheWriteTokens: count.optional(),
1684
- totalTokens: count.optional(),
1685
- reasoningTokens: count.optional()
1682
+ inputTokens: count$1,
1683
+ outputTokens: count$1,
1684
+ cacheReadTokens: count$1.optional(),
1685
+ cacheWriteTokens: count$1.optional(),
1686
+ totalTokens: count$1.optional(),
1687
+ reasoningTokens: count$1.optional()
1686
1688
  });
1687
1689
  function record$9(value) {
1688
1690
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1767,7 +1769,7 @@ function foldContextEvidence(state, event) {
1767
1769
  }
1768
1770
  if (usage === void 0) return state;
1769
1771
  const parsed = usageSchema.safeParse(usage);
1770
- if (!parsed.success || !count.safeParse(event.seq).success) return {
1772
+ if (!parsed.success || !count$1.safeParse(event.seq).success) return {
1771
1773
  ...state,
1772
1774
  sample: null,
1773
1775
  invalid: true,
@@ -1795,7 +1797,7 @@ function foldContextEvidence(state, event) {
1795
1797
  ...state,
1796
1798
  sample: {
1797
1799
  tokens,
1798
- seq: count.parse(event.seq),
1800
+ seq: count$1.parse(event.seq),
1799
1801
  route: state.route
1800
1802
  },
1801
1803
  invalid: false,
@@ -1831,7 +1833,7 @@ function installContextEvidence(ctx) {
1831
1833
  //#endregion
1832
1834
  //#region package.json
1833
1835
  var name$1 = "dsh-github-copilot";
1834
- var version = "0.4.0-alpha.95";
1836
+ var version = "0.4.0-alpha.97";
1835
1837
  //#endregion
1836
1838
  //#region lib/types/probe.js
1837
1839
  /**
@@ -4027,19 +4029,19 @@ var TemporaryRouteConflictError = class extends Error {
4027
4029
  this.name = "TemporaryRouteConflictError";
4028
4030
  }
4029
4031
  };
4030
- function object$5(value) {
4032
+ function object$6(value) {
4031
4033
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
4032
4034
  }
4033
4035
  function profileAt(value) {
4034
- return object$5(object$5(object$5(value)?.providers)?.["github-copilot"]);
4036
+ return object$6(object$6(object$6(value)?.providers)?.["github-copilot"]);
4035
4037
  }
4036
4038
  /** Bounded comparison; never stringify or copy unknown model extras or headers. */
4037
4039
  function equalJson(a, b, depth = 0) {
4038
4040
  if (a === b) return true;
4039
4041
  if (depth > 12) return false;
4040
4042
  if (Array.isArray(a) || Array.isArray(b)) return Array.isArray(a) && Array.isArray(b) && a.length <= 512 && a.length === b.length && a.every((value, i) => equalJson(value, b[i], depth + 1));
4041
- const left = object$5(a);
4042
- const right = object$5(b);
4043
+ const left = object$6(a);
4044
+ const right = object$6(b);
4043
4045
  if (!left || !right) return false;
4044
4046
  const keys = Object.keys(left);
4045
4047
  return keys.length <= 512 && keys.length === Object.keys(right).length && keys.every((key) => Object.hasOwn(right, key) && equalJson(left[key], right[key], depth + 1));
@@ -4048,7 +4050,7 @@ const MAX_BACKUP = 131072;
4048
4050
  function safeModels(value) {
4049
4051
  if (!Array.isArray(value) || value.length > 512) throw new TemporaryRouteConflictError();
4050
4052
  return value.map((entry) => {
4051
- const model = object$5(entry);
4053
+ const model = object$6(entry);
4052
4054
  if (!model || typeof model.id !== "string" || !/^[a-zA-Z0-9._:/-]{1,200}$/.test(model.id)) throw new TemporaryRouteConflictError();
4053
4055
  const overlay = temporaryGitHubCopilotModel(model.id, /* @__PURE__ */ new Map());
4054
4056
  if (overlay && Object.keys(model).some((key) => key !== "id" && key !== "api")) {
@@ -4079,10 +4081,10 @@ function readBackup(value) {
4079
4081
  if (value === void 0) return void 0;
4080
4082
  if (typeof value !== "string" || value.length > MAX_BACKUP) throw new TemporaryRouteConflictError("TEMPORARY_ROUTE_INVALID_BACKUP");
4081
4083
  try {
4082
- const decoded = object$5(JSON.parse(value));
4084
+ const decoded = object$6(JSON.parse(value));
4083
4085
  if (!decoded) throw new Error();
4084
4086
  if (decoded.version === void 0 || decoded.version === 2 && decoded.sourceEpoch === void 0) throw new TemporaryRouteConflictError("TEMPORARY_ROUTE_LEGACY_CONFLICT");
4085
- if (decoded.version !== 2 || typeof decoded.providerExisted !== "boolean" || typeof decoded.sourceEpoch !== "string" || !/^[a-f0-9-]{36}$/.test(decoded.sourceEpoch) || !Number.isSafeInteger(decoded.sourceRevision) || Number(decoded.sourceRevision) < 0 || !["overlay", "restoring"].includes(String(decoded.phase)) || !object$5(decoded.preimage) || !object$5(decoded.postimage) || !object$5(decoded.ownedHeaders) || Object.keys(decoded).some((key) => ![
4087
+ if (decoded.version !== 2 || typeof decoded.providerExisted !== "boolean" || typeof decoded.sourceEpoch !== "string" || !/^[a-f0-9-]{36}$/.test(decoded.sourceEpoch) || !Number.isSafeInteger(decoded.sourceRevision) || Number(decoded.sourceRevision) < 0 || !["overlay", "restoring"].includes(String(decoded.phase)) || !object$6(decoded.preimage) || !object$6(decoded.postimage) || !object$6(decoded.ownedHeaders) || Object.keys(decoded).some((key) => ![
4086
4088
  "version",
4087
4089
  "providerExisted",
4088
4090
  "preimage",
@@ -4099,15 +4101,15 @@ function readBackup(value) {
4099
4101
  decoded.postimage,
4100
4102
  ...decoded.phase === "restoring" ? [decoded.target] : []
4101
4103
  ]) {
4102
- const record = object$5(leaf);
4104
+ const record = object$6(leaf);
4103
4105
  if (!record || !equalJson(record, leavesOf(record))) throw new Error();
4104
4106
  }
4105
- const models = object$5(decoded.postimage)?.models ?? [];
4107
+ const models = object$6(decoded.postimage)?.models ?? [];
4106
4108
  const knownHeaders = Object.assign({}, ...models.flatMap((model) => {
4107
4109
  const overlay = temporaryGitHubCopilotModelFromProfile(model);
4108
4110
  return overlay ? [overlay.headers] : [];
4109
4111
  }));
4110
- if (!Object.entries(object$5(decoded.ownedHeaders)).every(([name, header]) => knownHeaders[name] === header)) throw new Error();
4112
+ if (!Object.entries(object$6(decoded.ownedHeaders)).every(([name, header]) => knownHeaders[name] === header)) throw new Error();
4111
4113
  if (decoded.removeProfile !== void 0 && typeof decoded.removeProfile !== "boolean") throw new Error();
4112
4114
  return decoded;
4113
4115
  } catch (error) {
@@ -4133,7 +4135,7 @@ function settingsSnapshot(settings) {
4133
4135
  hasOwnedSecrets,
4134
4136
  routeRevision: route.revision,
4135
4137
  markerRevision: marker.revision,
4136
- backup: readBackup(object$5(marker.value)?.temporaryRouteBackup)
4138
+ backup: readBackup(object$6(marker.value)?.temporaryRouteBackup)
4137
4139
  };
4138
4140
  }
4139
4141
  function assertOwned(current, backup) {
@@ -4166,7 +4168,7 @@ function leafOperations(current, target) {
4166
4168
  }]);
4167
4169
  }
4168
4170
  function ownedHeaderRemoval(current, backup) {
4169
- return Object.entries(object$5(current?.headers) ?? {}).flatMap(([name, value]) => Object.entries(backup.ownedHeaders).some(([ownedName, ownedValue]) => name.toLowerCase() === ownedName.toLowerCase() && value === ownedValue) ? [{
4171
+ return Object.entries(object$6(current?.headers) ?? {}).flatMap(([name, value]) => Object.entries(backup.ownedHeaders).some(([ownedName, ownedValue]) => name.toLowerCase() === ownedName.toLowerCase() && value === ownedValue) ? [{
4170
4172
  op: "unset",
4171
4173
  path: [
4172
4174
  "providers",
@@ -4188,7 +4190,7 @@ function wholeProfileOwned(snapshot, backup) {
4188
4190
  //#endregion
4189
4191
  //#region lib/types/migration-status.js
4190
4192
  const LIMIT = 1024;
4191
- function object$4(value) {
4193
+ function object$5(value) {
4192
4194
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("Invalid evidence");
4193
4195
  return value;
4194
4196
  }
@@ -4197,7 +4199,7 @@ function text$2(value) {
4197
4199
  return value;
4198
4200
  }
4199
4201
  function selection(value, omitDefaultEffort = false) {
4200
- const item = object$4(value);
4202
+ const item = object$5(value);
4201
4203
  const provider = text$2(item.provider), model = text$2(item.model), effort = item.reasoningEffort;
4202
4204
  if (effort !== void 0) text$2(effort);
4203
4205
  return {
@@ -4212,7 +4214,7 @@ function array(value) {
4212
4214
  }
4213
4215
  function api(ctx, name, methods) {
4214
4216
  try {
4215
- const candidate = object$4(ctx.get(name));
4217
+ const candidate = object$5(ctx.get(name));
4216
4218
  return methods.every((key) => typeof candidate[key] === "function") ? candidate : void 0;
4217
4219
  } catch {
4218
4220
  return;
@@ -4282,26 +4284,26 @@ function migrationStatus(ctx) {
4282
4284
  const rows = [], ids = /* @__PURE__ */ new Set();
4283
4285
  let complete = projections !== void 0;
4284
4286
  for (const candidate of array(call(agents, "list"))) {
4285
- const agent = object$4(candidate), id = text$2(agent.id), status = agent.status;
4287
+ const agent = object$5(candidate), id = text$2(agent.id), status = agent.status;
4286
4288
  if (ids.has(id) || status !== "idle" && status !== "running") throw new Error("Invalid agent inventory");
4287
4289
  ids.add(id);
4288
- const session = object$4(agent.session);
4290
+ const session = object$5(agent.session);
4289
4291
  if (text$2(session.id) !== id) throw new Error("Invalid agent identity");
4290
4292
  const header = call(session, "requestHeader");
4291
- const request = header === void 0 ? null : selection(object$4(header).config);
4293
+ const request = header === void 0 ? null : selection(object$5(header).config);
4292
4294
  let effective = null, source = "unknown";
4293
4295
  if (projections) {
4294
4296
  const state = call(projections, "stateOf", session, "modelSelection");
4295
4297
  if (state !== void 0) {
4296
- const pending = object$4(state).pending;
4298
+ const pending = object$5(state).pending;
4297
4299
  if (pending !== null) {
4298
4300
  effective = selection(pending);
4299
4301
  source = "pending";
4300
4302
  } else if (header !== void 0) {
4301
- const defaults = object$4(header).adapterDefaults;
4302
- const defaultEffort = defaults === void 0 ? false : object$4(defaults).reasoningEffort;
4303
+ const defaults = object$5(header).adapterDefaults;
4304
+ const defaultEffort = defaults === void 0 ? false : object$5(defaults).reasoningEffort;
4303
4305
  if (defaultEffort !== void 0 && typeof defaultEffort !== "boolean") throw new Error("Invalid adapter defaults");
4304
- effective = selection(object$4(header).config, defaultEffort === true);
4306
+ effective = selection(object$5(header).config, defaultEffort === true);
4305
4307
  source = "request-header";
4306
4308
  } else if (result.complete.defaultSelection) {
4307
4309
  effective = result.defaultSelection;
@@ -4325,23 +4327,23 @@ function migrationStatus(ctx) {
4325
4327
  const descriptors = array(call(settings, "describe", { redactSecrets: true }));
4326
4328
  const found = /* @__PURE__ */ new Set();
4327
4329
  for (const value of descriptors) {
4328
- const descriptor = object$4(value);
4330
+ const descriptor = object$5(value);
4329
4331
  const ns = text$2(descriptor.ns);
4330
4332
  if (ns !== "llm-pi-ai" && ns !== "github-copilot") continue;
4331
4333
  if (found.has(ns) || !Number.isSafeInteger(descriptor.revision) || descriptor.revision < 0) throw new Error("Invalid settings evidence");
4332
4334
  found.add(ns);
4333
4335
  }
4334
4336
  if (found.size !== 2) throw new Error("Unregistered settings");
4335
- const config = object$4(call(settings, "get", "llm-pi-ai"));
4336
- const profile = (config.providers === void 0 ? void 0 : object$4(config.providers))?.[GITHUB_COPILOT_PROVIDER_ID];
4337
- if (profile !== void 0) object$4(profile);
4337
+ const config = object$5(call(settings, "get", "llm-pi-ai"));
4338
+ const profile = (config.providers === void 0 ? void 0 : object$5(config.providers))?.[GITHUB_COPILOT_PROVIDER_ID];
4339
+ if (profile !== void 0) object$5(profile);
4338
4340
  result.capabilities.settingsCas = true;
4339
4341
  result.routes.nativeConfigured = profile !== void 0;
4340
4342
  } catch {}
4341
4343
  if (llm) try {
4342
4344
  const ids = /* @__PURE__ */ new Set();
4343
4345
  for (const value of array(call(llm, "listProviders"))) {
4344
- const id = text$2(object$4(value).id);
4346
+ const id = text$2(object$5(value).id);
4345
4347
  if (ids.has(id)) throw new Error("Invalid registry evidence");
4346
4348
  ids.add(id);
4347
4349
  }
@@ -4543,7 +4545,7 @@ function modelPreferencesView(ctx, accountModels, error) {
4543
4545
  if (!Number.isSafeInteger(descriptor.revision) || descriptor.revision < 0) return unavailable("COPILOT_MODEL_SETTINGS_INVALID");
4544
4546
  let excludedModelIds;
4545
4547
  try {
4546
- const raw = object$5(descriptor.value);
4548
+ const raw = object$6(descriptor.value);
4547
4549
  if (raw === void 0) return unavailable("COPILOT_MODEL_SETTINGS_INVALID");
4548
4550
  excludedModelIds = normalizeExcludedModelIds(raw.excludedModelIds);
4549
4551
  } catch {
@@ -4660,7 +4662,7 @@ async function repairGitHubCopilotProviderProfile(ctx) {
4660
4662
  try {
4661
4663
  await settings.mutate(namespace, operations, revision);
4662
4664
  } catch (error) {
4663
- if (object$5(error)?.code === "SETTINGS_CONFLICT") throw new TemporaryRouteConflictError();
4665
+ if (object$6(error)?.code === "SETTINGS_CONFLICT") throw new TemporaryRouteConflictError();
4664
4666
  throw error;
4665
4667
  }
4666
4668
  };
@@ -5086,7 +5088,7 @@ let GitHubCopilotAuthorizationController = (() => {
5086
5088
  }], current.revision);
5087
5089
  this.modelPreferenceFailure = void 0;
5088
5090
  } catch (cause) {
5089
- const record = object$5(cause);
5091
+ const record = object$6(cause);
5090
5092
  this.modelPreferenceFailure = record?.code === "SETTINGS_CONFLICT" || cause instanceof Error && /conflict/i.test(cause.message) ? "COPILOT_MODEL_EXCLUSION_CONFLICT" : "COPILOT_MODEL_EXCLUSION_SAVE_FAILED";
5091
5093
  }
5092
5094
  return view();
@@ -5231,7 +5233,7 @@ const levels = [
5231
5233
  "xhigh",
5232
5234
  "max"
5233
5235
  ];
5234
- function object$3(value) {
5236
+ function object$4(value) {
5235
5237
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5236
5238
  }
5237
5239
  function unavailable() {
@@ -5240,18 +5242,18 @@ function unavailable() {
5240
5242
  /** Resolve only the selected model's declared/native efforts, with the same precedence as Core. */
5241
5243
  function resolveCopilotResponsesReasoning(ctx, request, candidate) {
5242
5244
  if (request.provider !== "github-copilot" || candidate.protocol !== "openai-responses" || candidate.model !== request.model) return unavailable();
5243
- const profile = object$3(object$3(object$3(readSettingsNamespace(ctx, "llm-pi-ai"))?.providers)?.["github-copilot"]);
5245
+ const profile = object$4(object$4(object$4(readSettingsNamespace(ctx, "llm-pi-ai"))?.providers)?.["github-copilot"]);
5244
5246
  const effort = request.reasoningEffort ?? profile?.reasoning;
5245
5247
  if (effort === void 0) return void 0;
5246
5248
  const level = levels.find((value) => value === effort);
5247
5249
  if (level === void 0 || profile === void 0) return unavailable();
5248
5250
  const configured = Array.isArray(profile.models) ? profile.models : [];
5249
- const entry = configured.length > 0 ? object$3(configured.find((value) => object$3(value)?.id === request.model)) : object$3(object$3(profile.modelOverrides)?.[request.model]);
5251
+ const entry = configured.length > 0 ? object$4(configured.find((value) => object$4(value)?.id === request.model)) : object$4(object$4(profile.modelOverrides)?.[request.model]);
5250
5252
  if (configured.length > 0 && entry === void 0) return unavailable();
5251
5253
  const declared = entry?.reasoningEfforts;
5252
5254
  if (declared !== void 0) {
5253
5255
  if (declared === false) return level === "off" ? void 0 : unavailable();
5254
- const mapping = object$3(declared);
5256
+ const mapping = object$4(declared);
5255
5257
  if (mapping === void 0) return unavailable();
5256
5258
  const wire = mapping[level];
5257
5259
  if (level === "off" && (wire === null || typeof wire === "string" && wire.length > 0)) return void 0;
@@ -5285,7 +5287,7 @@ var EvidenceParseError = class extends Error {
5285
5287
  this.state = state;
5286
5288
  }
5287
5289
  };
5288
- function object$2(value) {
5290
+ function object$3(value) {
5289
5291
  return typeof value === "object" && value !== null && !Array.isArray(value);
5290
5292
  }
5291
5293
  /** Diagnostic-only traversal of the original JSON spans; never reserializes or changes a request. */
@@ -5331,7 +5333,7 @@ function requestBodyEvidence(body, protocol) {
5331
5333
  }
5332
5334
  const conversationKey = protocol === "openai-responses" ? "input" : "messages";
5333
5335
  const systemKey = protocol === "openai-responses" ? "instructions" : protocol === "anthropic-messages" ? "system" : void 0;
5334
- if (!object$2(parsed) || !Array.isArray(parsed[conversationKey])) return {
5336
+ if (!object$3(parsed) || !Array.isArray(parsed[conversationKey])) return {
5335
5337
  state: "unsupported-shape",
5336
5338
  totalBytes
5337
5339
  };
@@ -5350,7 +5352,7 @@ function requestBodyEvidence(body, protocol) {
5350
5352
  }
5351
5353
  throw new EvidenceParseError("invalid-json");
5352
5354
  };
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";
5355
+ const isImage = (value) => protocol === "anthropic-messages" ? value.type === "image" && object$3(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$3(value.image_url) && typeof value.image_url.url === "string";
5354
5356
  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
5357
  const visit = (value, depth, location) => {
5356
5358
  if (++values > REQUEST_BODY_EVIDENCE_LIMITS.values || depth > REQUEST_BODY_EVIDENCE_LIMITS.depth) throw new EvidenceParseError("work-limit");
@@ -5370,7 +5372,7 @@ function requestBodyEvidence(body, protocol) {
5370
5372
  }
5371
5373
  whitespace();
5372
5374
  if (body[position++] !== "]") throw new EvidenceParseError("invalid-json");
5373
- } else if (object$2(value)) {
5375
+ } else if (object$3(value)) {
5374
5376
  if (body[position++] !== "{") throw new EvidenceParseError("invalid-json");
5375
5377
  const imageBlock = location === "content" && isImage(value);
5376
5378
  const seen = /* @__PURE__ */ new Set();
@@ -5492,7 +5494,9 @@ var ReplayRecoveryStore = class {
5492
5494
  state: state.enabled ? "enabled" : "available",
5493
5495
  revision: state.revision,
5494
5496
  itemCount: state.hashes.size,
5495
- model: state.model
5497
+ model: state.model,
5498
+ expiresAt: state.at + 36e5,
5499
+ ...state.enabled && state.duration ? { duration: state.duration } : {}
5496
5500
  } : { state: "unavailable" };
5497
5501
  }
5498
5502
  recordFailure(owner, proof, model, body) {
@@ -5512,14 +5516,34 @@ var ReplayRecoveryStore = class {
5512
5516
  if (this.owners.size > 64) this.owners.delete(this.owners.keys().next().value);
5513
5517
  }
5514
5518
  setEnabled(owner, proof, revision, enabled) {
5519
+ if (enabled) return this.authorize(owner, proof, revision, "session");
5515
5520
  const state = this.current(owner, proof);
5516
5521
  if (!state || revision !== state.revision) throw new Error("COPILOT_REPLAY_RECOVERY_STALE_EVIDENCE");
5517
- state.enabled = enabled;
5522
+ state.enabled = false;
5518
5523
  return this.view(owner, proof);
5519
5524
  }
5520
- prepare(owner, proof, model) {
5525
+ authorize(owner, proof, revision, duration) {
5526
+ const state = this.current(owner, proof);
5527
+ if (!state || revision !== state.revision) throw new Error("COPILOT_REPLAY_RECOVERY_STALE_EVIDENCE");
5528
+ state.enabled = true;
5529
+ state.duration = duration;
5530
+ delete state.turn;
5531
+ return this.view(owner, proof);
5532
+ }
5533
+ endTurn(owner, turn) {
5534
+ const state = this.owners.get(owner);
5535
+ if (state?.duration === "next-turn" && state.turn === turn) state.enabled = false;
5536
+ }
5537
+ prepare(owner, proof, model, turn) {
5521
5538
  const state = this.current(owner, proof);
5522
- const admitted = state?.enabled && state.model === model ? state.hashes : void 0;
5539
+ let admitted;
5540
+ if (state?.enabled && state.model === model) {
5541
+ if (state.duration !== "next-turn") admitted = state.hashes;
5542
+ else if (turn !== void 0 && Number.isSafeInteger(turn) && turn >= 0) {
5543
+ state.turn ??= turn;
5544
+ if (state.turn === turn) admitted = state.hashes;
5545
+ }
5546
+ }
5523
5547
  return (payload) => {
5524
5548
  if (!admitted) return payload;
5525
5549
  if (this.current(owner, proof) !== state) throw new Error("COPILOT_REPLAY_RECOVERY_REVOKED");
@@ -5600,11 +5624,13 @@ let ReplayRecoveryController = (() => {
5600
5624
  let _instanceExtraInitializers = [];
5601
5625
  let _get_decorators;
5602
5626
  let _setEnabled_decorators;
5627
+ let _authorize_decorators;
5603
5628
  return class ReplayRecoveryController extends _classSuper {
5604
5629
  static {
5605
5630
  const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
5606
5631
  _get_decorators = [Remote];
5607
5632
  _setEnabled_decorators = [Remote];
5633
+ _authorize_decorators = [Remote];
5608
5634
  __esDecorate$1(this, null, _get_decorators, {
5609
5635
  kind: "method",
5610
5636
  name: "get",
@@ -5627,6 +5653,17 @@ let ReplayRecoveryController = (() => {
5627
5653
  },
5628
5654
  metadata: _metadata
5629
5655
  }, null, _instanceExtraInitializers);
5656
+ __esDecorate$1(this, null, _authorize_decorators, {
5657
+ kind: "method",
5658
+ name: "authorize",
5659
+ static: false,
5660
+ private: false,
5661
+ access: {
5662
+ has: (obj) => "authorize" in obj,
5663
+ get: (obj) => obj.authorize
5664
+ },
5665
+ metadata: _metadata
5666
+ }, null, _instanceExtraInitializers);
5630
5667
  if (_metadata) Object.defineProperty(this, Symbol.metadata, {
5631
5668
  enumerable: true,
5632
5669
  configurable: true,
@@ -5650,6 +5687,10 @@ let ReplayRecoveryController = (() => {
5650
5687
  if (this.busy.has(agent.session)) throw new Error("COPILOT_REPLAY_RECOVERY_TURN_ACTIVE");
5651
5688
  return this.store.setEnabled(agent.session, this.proof(), revision, enabled);
5652
5689
  }
5690
+ authorize(agent, revision, duration) {
5691
+ if (this.busy.has(agent.session)) throw new Error("COPILOT_REPLAY_RECOVERY_TURN_ACTIVE");
5692
+ return this.store.authorize(agent.session, this.proof(), revision, duration);
5693
+ }
5653
5694
  };
5654
5695
  })();
5655
5696
  function installReplayRecovery(ctx, proof) {
@@ -5672,6 +5713,7 @@ function installReplayRecovery(ctx, proof) {
5672
5713
  });
5673
5714
  const removeEvents = ctx.on("session/event", (session, event) => {
5674
5715
  if (event.type === "turn/end") {
5716
+ store.endTurn(session, event.data.turn);
5675
5717
  busy.delete(session);
5676
5718
  currentRequests.delete(session);
5677
5719
  }
@@ -5687,8 +5729,8 @@ function installReplayRecovery(ctx, proof) {
5687
5729
  if (!active || request.signal === void 0 || request.signal.aborted || request.purpose !== void 0 || request.provider !== "github-copilot-preview") return void 0;
5688
5730
  const binding = requests.get(request.signal);
5689
5731
  const currentProof = proof();
5690
- if (!binding || binding.session.id !== request.sessionId || !busy.has(binding.session) || currentProof === void 0) return void 0;
5691
- const transform = store.prepare(binding.session, currentProof, request.model);
5732
+ if (!binding || binding.session.id !== request.sessionId || !busy.has(binding.session) || currentProof === void 0 || currentRequests.get(binding.session) !== request.signal) return void 0;
5733
+ const transform = store.prepare(binding.session, currentProof, request.model, binding.turn);
5692
5734
  const current = () => active && !request.signal?.aborted && proof() === currentProof && currentRequests.get(binding.session) === request.signal && busy.has(binding.session);
5693
5735
  return {
5694
5736
  transform(payload) {
@@ -6010,6 +6052,105 @@ async function isCopilotInputItemScopeError(response, signal) {
6010
6052
  //#region lib/types/request-body-timeout-marker.js
6011
6053
  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.";
6012
6054
  //#endregion
6055
+ //#region lib/types/request-upload-evidence.js
6056
+ function object$2(value) {
6057
+ return typeof value === "object" && value !== null;
6058
+ }
6059
+ function count(value) {
6060
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
6061
+ }
6062
+ /** Observe public native events only; never read request fields, mutate transport or imply remote receipt. */
6063
+ function createRequestUploadObserver() {
6064
+ const scope = new AsyncLocalStorage(), token = {}, requests = /* @__PURE__ */ new WeakMap();
6065
+ let startedAt;
6066
+ let requestCount = 0, closed = false, bodyWrite = false;
6067
+ let bodyWriteCompleteMs, nativeResponseHeadersMs;
6068
+ let socket;
6069
+ let connectionAmbiguous = false, socketBoundToRequest = false;
6070
+ let alpn = "unavailable", nodeWritableBufferBytes;
6071
+ const elapsed = () => startedAt === void 0 ? void 0 : count(Math.round(performance.now() - startedAt));
6072
+ const request = (data) => !closed && object$2(data) && object$2(data.request) ? requests.get(data.request) : void 0;
6073
+ const connected = (data, boundToRequest = false) => {
6074
+ if (closed || !object$2(data) || !object$2(data.socket)) return;
6075
+ if (!boundToRequest) {
6076
+ if (socketBoundToRequest || connectionAmbiguous) return;
6077
+ if (socket !== void 0 && socket !== data.socket) {
6078
+ connectionAmbiguous = true;
6079
+ socket = void 0;
6080
+ alpn = "unavailable";
6081
+ nodeWritableBufferBytes = void 0;
6082
+ return;
6083
+ }
6084
+ }
6085
+ socketBoundToRequest = boundToRequest;
6086
+ socket = data.socket;
6087
+ alpn = socket.encrypted === true && (socket.alpnProtocol === "h2" || socket.alpnProtocol === "http/1.1") ? socket.alpnProtocol : "unavailable";
6088
+ };
6089
+ const handlers = {
6090
+ "undici:request:create": (data) => {
6091
+ if (closed || scope.getStore() !== token || !object$2(data) || !object$2(data.request)) return;
6092
+ if (requests.has(data.request) || requestCount > 8) return;
6093
+ requestCount++;
6094
+ if (requestCount <= 8) requests.set(data.request, requestCount);
6095
+ },
6096
+ "undici:client:connected": (data) => {
6097
+ if (scope.getStore() === token && requestCount === 1) connected(data);
6098
+ },
6099
+ "undici:client:sendHeaders": (data) => {
6100
+ if (request(data) === 1) connected(data, true);
6101
+ },
6102
+ "undici:request:bodySent": (data) => {
6103
+ if (request(data) !== 1 || bodyWrite) return;
6104
+ bodyWrite = true;
6105
+ bodyWriteCompleteMs = elapsed();
6106
+ nodeWritableBufferBytes = count(socket?.writableLength);
6107
+ },
6108
+ "undici:request:headers": (data) => {
6109
+ if (request(data) === 1 && nativeResponseHeadersMs === void 0) nativeResponseHeadersMs = elapsed();
6110
+ }
6111
+ };
6112
+ for (const [name, handler] of Object.entries(handlers)) channel(name).subscribe(handler);
6113
+ return {
6114
+ run: (operation) => {
6115
+ if (closed) throw new Error("COPILOT_UPLOAD_OBSERVER_CLOSED");
6116
+ startedAt ??= performance.now();
6117
+ return scope.run(token, operation);
6118
+ },
6119
+ snapshot: () => {
6120
+ if (requestCount === 0) return { state: "unavailable" };
6121
+ if (requestCount > 8) return { state: "work-limit" };
6122
+ if (requestCount !== 1) return {
6123
+ state: "ambiguous",
6124
+ requestCount
6125
+ };
6126
+ return {
6127
+ state: "observed",
6128
+ bodyWrite: bodyWrite ? "observed" : "not-observed",
6129
+ alpn,
6130
+ ...bodyWriteCompleteMs === void 0 ? {} : { bodyWriteCompleteMs },
6131
+ ...nativeResponseHeadersMs === void 0 ? {} : { nativeResponseHeadersMs },
6132
+ ...nodeWritableBufferBytes === void 0 ? {} : { nodeWritableBufferBytes }
6133
+ };
6134
+ },
6135
+ close: () => {
6136
+ if (closed) return;
6137
+ closed = true;
6138
+ for (const [name, handler] of Object.entries(handlers)) channel(name).unsubscribe(handler);
6139
+ socket = void 0;
6140
+ scope.disable();
6141
+ }
6142
+ };
6143
+ }
6144
+ function formatRequestUploadEvidence(evidence) {
6145
+ if (evidence === void 0 || evidence.state === "unavailable") return "Client transport evidence unavailable (no matching native diagnostic events).";
6146
+ if (evidence.state === "ambiguous") return `Client transport evidence unavailable (ambiguous: ${evidence.requestCount} native requests; no combined timings).`;
6147
+ if (evidence.state === "work-limit") return "Client transport evidence unavailable (work-limit; no partial timings).";
6148
+ const body = evidence.bodyWrite === "not-observed" ? "local body-write completion not observed (not proof of incomplete upload)" : evidence.bodyWriteCompleteMs === void 0 ? "local body-write completion observed; timing unavailable" : `local body-write complete at ${evidence.bodyWriteCompleteMs} ms`;
6149
+ const headers = evidence.nativeResponseHeadersMs === void 0 ? "native response-header timing unavailable" : `native response headers at ${evidence.nativeResponseHeadersMs} ms`;
6150
+ const buffer = evidence.nodeWritableBufferBytes === void 0 ? "Node writable-buffer count unavailable" : `Node writable buffer at local body-write completion ${evidence.nodeWritableBufferBytes} bytes`;
6151
+ return `Client transport evidence: ${body}; ${headers}; TLS ALPN ${evidence.alpn}; ${buffer}. Local submission only, not upload duration, kernel ACK, supplier receipt or execution.`;
6152
+ }
6153
+ //#endregion
6013
6154
  //#region lib/types/request-body-timeout.js
6014
6155
  const observedMessage = "Timed out reading request body. Try again, or use a smaller request size.";
6015
6156
  function record$6(value) {
@@ -6024,7 +6165,8 @@ async function requestBodyTimeoutDiagnostic(response, body, signal, dispatch) {
6024
6165
  if (!record$6(error) || error.code !== "user_request_timeout" || error.message !== observedMessage || value.code !== void 0 && value.code !== error.code || value.message !== void 0 && value.message !== error.message) return void 0;
6025
6166
  const size = body === void 0 ? "Request body size unavailable." : `Request body: ${Buffer.byteLength(body, "utf8")} UTF-8 bytes (not context tokens).`;
6026
6167
  const composition = formatRequestBodyEvidence(dispatch === void 0 ? { state: "unavailable" } : requestBodyEvidence(body, dispatch.protocol), dispatch?.responseHeadersMs);
6027
- return `${REQUEST_BODY_TIMEOUT_MARKER} ${size} ${composition} Native retry policy is unchanged. If retries exhaust, use these numbers to choose an explicit attachment/image-offload budget change or native compaction for compressible history; tool definitions and opaque replay may remain. Also check network/proxy health and GitHub service status. Composition alone does not establish a cause or supplier size limit. A larger client timeout does not change this server timeout. No history was trimmed or model switched.`;
6168
+ const upload = formatRequestUploadEvidence(dispatch?.upload);
6169
+ return `${REQUEST_BODY_TIMEOUT_MARKER} ${size} ${composition} ${upload} Native retry policy is unchanged. If retries exhaust, use these numbers to choose an explicit attachment/image-offload budget change or native compaction for compressible history; tool definitions and opaque replay may remain. Also check network/proxy health and GitHub service status. Composition alone does not establish a cause or supplier size limit. A larger client timeout does not change this server timeout. No history was trimmed or model switched.`;
6028
6170
  }
6029
6171
  //#endregion
6030
6172
  //#region lib/types/copilot-stream-liveness.js
@@ -6377,19 +6519,23 @@ function createAccountProvider(descriptors, guard, baseURL) {
6377
6519
  clientRequestHeader: replayHeaders?.has("x-client-request-id")
6378
6520
  } : void 0;
6379
6521
  let response;
6522
+ const upload = guard.onRequestBodyTimeout === void 0 ? void 0 : createRequestUploadObserver();
6380
6523
  const startedAt = performance.now();
6381
6524
  try {
6382
- response = await fetch(input, init);
6525
+ response = await (upload === void 0 ? fetch(input, init) : upload.run(() => fetch(input, init)));
6383
6526
  } catch (error) {
6384
6527
  retry?.observe(void 0, 0);
6385
6528
  throw error;
6529
+ } finally {
6530
+ upload?.close();
6386
6531
  }
6387
6532
  const responseHeadersMs = performance.now() - startedAt;
6388
6533
  retry?.observe(typeof init?.body === "string" ? init.body : void 0, response.status);
6389
6534
  if (response.status === 408 && guard.onRequestBodyTimeout !== void 0) {
6390
6535
  const diagnostic = await requestBodyTimeoutDiagnostic(response, typeof init?.body === "string" ? init.body : void 0, lease.signal, {
6391
6536
  protocol: entry.api,
6392
- responseHeadersMs
6537
+ responseHeadersMs,
6538
+ ...upload === void 0 ? {} : { upload: upload.snapshot() }
6393
6539
  });
6394
6540
  if (!lease.signal.aborted && !options.signal?.aborted) guard.onRequestBodyTimeout(diagnostic);
6395
6541
  }