dsh-github-copilot 0.4.0-alpha.34 → 0.4.0-alpha.36

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
@@ -1131,17 +1131,15 @@ function createAccountModelAuth(credentials, renewRejectedCredential) {
1131
1131
  };
1132
1132
  }
1133
1133
  //#endregion
1134
- //#region lib/types/copilot-usage-types.js
1135
- const COPILOT_USAGE_MAX_AMOUNT = 0xe8d4a51000;
1136
- const COPILOT_USAGE_MAX_TIMESTAMP = 0xe677d21fdbff;
1137
- //#endregion
1138
1134
  //#region lib/types/copilot-usage-normalize.js
1139
- const amount = z$1.number().finite().min(0).max(COPILOT_USAGE_MAX_AMOUNT);
1135
+ const amount = z$1.number().finite().min(0).max(0xe8d4a51000);
1140
1136
  const entitlement = z$1.union([
1141
1137
  amount,
1142
1138
  z$1.literal(-1),
1143
1139
  z$1.string().max(32).regex(/^(?:-1|(?:0|[1-9]\d*)(?:\.\d+)?)$/u)
1144
1140
  ]).transform(Number).refine((value) => Number.isFinite(value) && value <= 0xe8d4a51000);
1141
+ const resetSeconds = z$1.unknown().transform((value) => typeof value === "number" && Number.isInteger(value) && value > 0 && value <= Math.floor(0xe677d21fdbff / 1e3) ? value * 1e3 : void 0);
1142
+ const resetCalendar = z$1.unknown().transform(resetDate);
1145
1143
  const snapshot = z$1.object({
1146
1144
  unlimited: z$1.boolean(),
1147
1145
  entitlement: entitlement.optional(),
@@ -1150,14 +1148,14 @@ const snapshot = z$1.object({
1150
1148
  credits_used: amount.optional(),
1151
1149
  has_quota: z$1.boolean().optional(),
1152
1150
  token_based_billing: z$1.boolean().optional(),
1153
- quota_reset_at: z$1.number().int().min(0).max(Math.floor(COPILOT_USAGE_MAX_TIMESTAMP / 1e3)).optional()
1151
+ quota_reset_at: resetSeconds.optional()
1154
1152
  });
1155
1153
  const response = z$1.object({
1156
1154
  token_based_billing: z$1.boolean().optional(),
1157
1155
  access_type_sku: z$1.string().max(128).optional(),
1158
- quota_reset_date: z$1.string().max(64).optional(),
1159
- quota_reset_date_utc: z$1.string().max(64).optional(),
1160
- limited_user_reset_date: z$1.string().max(64).optional(),
1156
+ quota_reset_date: resetCalendar.optional(),
1157
+ quota_reset_date_utc: resetCalendar.optional(),
1158
+ limited_user_reset_date: resetCalendar.optional(),
1161
1159
  quota_snapshots: z$1.object({
1162
1160
  chat: snapshot.optional(),
1163
1161
  premium_interactions: snapshot.optional()
@@ -1174,7 +1172,7 @@ function unavailableCopilotUsage(diagnostic, billing = "unknown", budget = "unkn
1174
1172
  };
1175
1173
  }
1176
1174
  function resetDate(value) {
1177
- if (!/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2}))?$/u.test(value)) return void 0;
1175
+ if (typeof value !== "string" || value.length > 64 || !/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2}))?$/u.test(value)) return void 0;
1178
1176
  const date = value.slice(0, 10);
1179
1177
  const day = Date.parse(`${date}T00:00:00Z`);
1180
1178
  if (!Number.isFinite(day) || new Date(day).toISOString().slice(0, 10) !== date) return void 0;
@@ -1193,10 +1191,12 @@ function normalizeCopilotUsage(input, observedAt) {
1193
1191
  if (data.token_based_billing === void 0) return unavailableCopilotUsage("COPILOT_USAGE_BILLING_UNKNOWN");
1194
1192
  const billing = data.token_based_billing ? "credits" : "requests";
1195
1193
  const quota = data.access_type_sku === "free_limited_copilot" ? data.quota_snapshots?.chat : data.quota_snapshots?.premium_interactions;
1196
- const reset = data.quota_reset_date_utc ?? data.quota_reset_date ?? data.limited_user_reset_date;
1197
- const accountReset = reset === void 0 ? void 0 : resetDate(reset);
1198
- if (reset !== void 0 && accountReset === void 0) return unavailableCopilotUsage("COPILOT_USAGE_INVALID_RESPONSE", billing);
1199
- const resetAt = quota?.quota_reset_at === void 0 ? accountReset : quota.quota_reset_at * 1e3;
1194
+ const resetAt = [
1195
+ quota?.quota_reset_at,
1196
+ data.quota_reset_date_utc,
1197
+ data.quota_reset_date,
1198
+ data.limited_user_reset_date
1199
+ ].find((value) => value !== void 0 && value > observedAt);
1200
1200
  const dates = {
1201
1201
  observedAt,
1202
1202
  ...resetAt === void 0 ? {} : { resetAt }
@@ -1600,7 +1600,7 @@ let GitHubCopilotUsageController = (() => {
1600
1600
  //#endregion
1601
1601
  //#region package.json
1602
1602
  var name$1 = "dsh-github-copilot";
1603
- var version = "0.4.0-alpha.34";
1603
+ var version = "0.4.0-alpha.36";
1604
1604
  //#endregion
1605
1605
  //#region lib/types/probe.js
1606
1606
  /**
@@ -4904,6 +4904,122 @@ function coreProviderView(provider) {
4904
4904
  };
4905
4905
  }
4906
4906
  //#endregion
4907
+ //#region lib/types/responses-replay-compat.js
4908
+ const replayDiagnostics = {
4909
+ "scope-mismatch": "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH: Copilot Responses input references belong to a different connection.",
4910
+ unsupported: "COPILOT_RESPONSES_REPLAY_UNSUPPORTED: Copilot Responses input cannot be replayed safely without connection-scoped references.",
4911
+ "invalid-payload": "COPILOT_RESPONSES_REPLAY_INVALID_PAYLOAD: Copilot Responses payload has an invalid replay structure."
4912
+ };
4913
+ /** Fixed diagnostics only: never include provider bodies, IDs, arguments or replay content. */
4914
+ var CopilotResponsesReplayError = class extends Error {
4915
+ constructor(reason = "unsupported") {
4916
+ super(replayDiagnostics[reason]);
4917
+ this.name = "CopilotResponsesReplayError";
4918
+ }
4919
+ };
4920
+ function isRecord(value) {
4921
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
4922
+ const prototype = Object.getPrototypeOf(value);
4923
+ return prototype === Object.prototype || prototype === null;
4924
+ }
4925
+ function nonemptyString(value) {
4926
+ return typeof value === "string" && value.trim().length > 0;
4927
+ }
4928
+ function normalizeItem(item) {
4929
+ if (!isRecord(item)) throw new CopilotResponsesReplayError("invalid-payload");
4930
+ if (item.type === "item_reference") throw new CopilotResponsesReplayError();
4931
+ if ((item.type === "message" || item.type === void 0) && (item.role === "user" || item.role === "system" || item.role === "developer")) return item;
4932
+ if (!Object.hasOwn(item, "id") || item.id === void 0) return item;
4933
+ if (!nonemptyString(item.id)) throw new CopilotResponsesReplayError("invalid-payload");
4934
+ 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();
4935
+ const normalized = { ...item };
4936
+ delete normalized.id;
4937
+ return normalized;
4938
+ }
4939
+ /** Normalize only the outgoing managed Responses payload, never stored history/context. */
4940
+ function normalizeCopilotResponsesPayload(payload) {
4941
+ try {
4942
+ if (!isRecord(payload) || typeof payload.input !== "string" && !Array.isArray(payload.input)) throw new CopilotResponsesReplayError("invalid-payload");
4943
+ 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");
4944
+ if (typeof payload.input === "string") return payload;
4945
+ let changed = false;
4946
+ const input = [];
4947
+ for (const item of payload.input) {
4948
+ const normalized = normalizeItem(item);
4949
+ changed ||= normalized !== item;
4950
+ input.push(normalized);
4951
+ }
4952
+ return changed ? {
4953
+ ...payload,
4954
+ input
4955
+ } : payload;
4956
+ } catch (error) {
4957
+ if (error instanceof CopilotResponsesReplayError) throw error;
4958
+ throw new CopilotResponsesReplayError("invalid-payload");
4959
+ }
4960
+ }
4961
+ const scopeMessage = "input item ID does not belong to this connection";
4962
+ const maxErrorBytes = 8192;
4963
+ const errorReadTimeoutMs = 250;
4964
+ async function readScopeError(reader) {
4965
+ const decoder = new TextDecoder("utf-8", { fatal: true });
4966
+ let bytes = 0;
4967
+ let chunks = 0;
4968
+ let text = "";
4969
+ while (true) {
4970
+ if (chunks++ > maxErrorBytes) return false;
4971
+ const chunk = await reader.read();
4972
+ if (chunk.done) break;
4973
+ bytes += chunk.value.byteLength;
4974
+ if (bytes > maxErrorBytes) return false;
4975
+ text += decoder.decode(chunk.value, { stream: true });
4976
+ }
4977
+ text += decoder.decode();
4978
+ const body = JSON.parse(text);
4979
+ if (!isRecord(body)) return false;
4980
+ const error = Object.hasOwn(body, "error") ? body.error : body;
4981
+ if (!isRecord(error) || error.message !== scopeMessage) return false;
4982
+ return (!Object.hasOwn(body, "message") || body.message === scopeMessage) && [
4983
+ body.code,
4984
+ body.type,
4985
+ error.code,
4986
+ error.type
4987
+ ].every((value) => value === void 0 || value === null || value === "");
4988
+ }
4989
+ /** Observe a cloned, bounded 401 body; every unknown result retains native auth behavior. */
4990
+ async function isCopilotInputItemScopeError(response, signal) {
4991
+ if (response.status !== 401 || signal?.aborted) return false;
4992
+ let reader;
4993
+ let timeout;
4994
+ let onAbort;
4995
+ try {
4996
+ const clone = response.clone();
4997
+ if (!clone.body) return false;
4998
+ reader = clone.body.getReader();
4999
+ const interrupted = new Promise((resolve) => {
5000
+ onAbort = () => resolve(false);
5001
+ signal?.addEventListener("abort", onAbort, { once: true });
5002
+ timeout = setTimeout(() => resolve(false), errorReadTimeoutMs);
5003
+ if (signal?.aborted) resolve(false);
5004
+ });
5005
+ const result = await Promise.race([readScopeError(reader), interrupted]);
5006
+ return !signal?.aborted && result;
5007
+ } catch {
5008
+ return false;
5009
+ } finally {
5010
+ if (timeout !== void 0) clearTimeout(timeout);
5011
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
5012
+ if (reader) {
5013
+ try {
5014
+ reader.cancel().catch(() => {});
5015
+ } catch {}
5016
+ try {
5017
+ reader.releaseLock();
5018
+ } catch {}
5019
+ }
5020
+ }
5021
+ }
5022
+ //#endregion
4907
5023
  //#region lib/types/preview-provider.js
4908
5024
  const enabledLevels = [
4909
5025
  "minimal",
@@ -5083,10 +5199,30 @@ function createAccountProvider(descriptors, guard, baseURL) {
5083
5199
  headers.authorization = `Bearer ${options.apiKey}`;
5084
5200
  headers["x-api-key"] = null;
5085
5201
  let unauthorized = false;
5202
+ const responses = model.api === "openai-responses";
5203
+ const reportReplayFailure = (error) => {
5204
+ if (lease.signal.aborted || options.signal?.aborted) return;
5205
+ try {
5206
+ guard.onReplayFailure?.(error);
5207
+ } catch {}
5208
+ };
5209
+ const onPayload = responses ? async (payload, selectedModel) => {
5210
+ const replacement = await options.onPayload?.(payload, selectedModel);
5211
+ if (lease.signal.aborted || options.signal?.aborted) throw new Error("COPILOT_MANAGED_ABORTED");
5212
+ try {
5213
+ return normalizeCopilotResponsesPayload(replacement === void 0 ? payload : replacement);
5214
+ } catch (error) {
5215
+ if (error instanceof CopilotResponsesReplayError) reportReplayFailure(error);
5216
+ throw error;
5217
+ }
5218
+ } : options.onPayload;
5086
5219
  const fetch = options.fetch ?? globalThis.fetch;
5087
5220
  const observeResponse = async (input, init) => {
5088
5221
  const response = await fetch(input, init);
5089
- if (response.status === 401) unauthorized = true;
5222
+ if (response.status === 401) {
5223
+ if (responses && await isCopilotInputItemScopeError(response, lease.signal)) reportReplayFailure(new CopilotResponsesReplayError("scope-mismatch"));
5224
+ else unauthorized = true;
5225
+ }
5090
5226
  return response;
5091
5227
  };
5092
5228
  const wireOptions = model.api === "anthropic-messages" ? {
@@ -5099,7 +5235,8 @@ function createAccountProvider(descriptors, guard, baseURL) {
5099
5235
  ...options,
5100
5236
  signal: lease.signal,
5101
5237
  headers,
5102
- fetch: observeResponse
5238
+ fetch: observeResponse,
5239
+ onPayload
5103
5240
  };
5104
5241
  if (!hasApi(model, "openai-responses") && !hasApi(model, "openai-completions") && !hasApi(model, "anthropic-messages")) {
5105
5242
  lease.release();
@@ -6188,13 +6325,13 @@ var PreviewAdapter = class extends PiAiAdapter {
6188
6325
  const mapping = Object.entries(model.thinkingLevelMap ?? {}).find(([level]) => level === options.reasoningEffort)?.[1];
6189
6326
  if (typeof mapping !== "string" || mapping.length === 0) throw failure("COPILOT_PREVIEW_REASONING_UNSUPPORTED", "INVALID_REQUEST");
6190
6327
  }
6191
- let admissionFailure;
6328
+ let requestFailure;
6192
6329
  const inspectRequest = (_model, context, nativeOptions) => {
6193
6330
  if (signal.aborted) throw failure("COPILOT_PREVIEW_ABORTED", "ABORTED");
6194
6331
  const calculated = calculateRequestBudget(lease.descriptor, nativeOptions?.maxTokens, policy);
6195
6332
  if (!calculated.ok) {
6196
- admissionFailure = budgetFailure(calculated);
6197
- throw admissionFailure;
6333
+ requestFailure = budgetFailure(calculated);
6334
+ throw requestFailure;
6198
6335
  }
6199
6336
  const prefix = estimateContextTokens({
6200
6337
  messages: [],
@@ -6204,12 +6341,17 @@ var PreviewAdapter = class extends PiAiAdapter {
6204
6341
  const fresh = context.messages.reduce((tokens, message) => tokens + estimateMessageTokens(message), prefix);
6205
6342
  const admitted = assessRequestBudget(Math.max(estimateContextTokens(context).tokens, fresh), calculated.budget);
6206
6343
  if (!admitted.ok) {
6207
- admissionFailure = budgetFailure(admitted);
6208
- throw admissionFailure;
6344
+ requestFailure = budgetFailure(admitted);
6345
+ throw requestFailure;
6209
6346
  }
6210
6347
  };
6211
6348
  try {
6212
- const native = new PiAiAdapter(owner.optionsFor(lease, inspectRequest));
6349
+ const native = new PiAiAdapter(owner.optionsFor(lease, {
6350
+ inspectRequest,
6351
+ onReplayFailure(error) {
6352
+ if (!signal.aborted) requestFailure = new LlmError(error.message, "INVALID_REQUEST");
6353
+ }
6354
+ }));
6213
6355
  const prepared = await native.prepareCall(options.provider, options.model, signal);
6214
6356
  const suppliedEffort = options.reasoningEffort ?? prepared.model.reasoning?.defaultEffort;
6215
6357
  const effort = options.purpose === "compaction" ? selectCompactionReasoning(getSupportedThinkingLevels(model), suppliedEffort, policy.compactionReasoning) : suppliedEffort;
@@ -6219,18 +6361,18 @@ var PreviewAdapter = class extends PiAiAdapter {
6219
6361
  ...effort === void 0 ? {} : { reasoningEffort: ReasoningEffortId(effort) }
6220
6362
  };
6221
6363
  for await (const chunk of native.stream(request)) {
6222
- if (admissionFailure !== void 0) {
6364
+ if (requestFailure !== void 0) {
6223
6365
  if (signal.aborted) throw failure("COPILOT_PREVIEW_ABORTED", "ABORTED");
6224
- throw admissionFailure;
6366
+ throw requestFailure;
6225
6367
  }
6226
6368
  if (chunk.type === "finish" && chunk.reason.kind === "error" && chunk.reason.failure.code === "UNKNOWN_MODEL") await owner.refreshRejected(lease.snapshot, signal);
6227
6369
  yield chunk;
6228
6370
  }
6229
- if (admissionFailure !== void 0) throw admissionFailure;
6371
+ if (requestFailure !== void 0) throw requestFailure;
6230
6372
  } catch (cause) {
6231
6373
  if (signal.aborted) throw failure("COPILOT_PREVIEW_ABORTED", "ABORTED");
6232
6374
  if (cause instanceof LlmError && cause.code === "UNKNOWN_MODEL") await owner.refreshRejected(lease.snapshot, signal);
6233
- throw admissionFailure ?? cause;
6375
+ throw requestFailure ?? cause;
6234
6376
  }
6235
6377
  })();
6236
6378
  }
@@ -6452,10 +6594,10 @@ function apply$1(ctx, config = {}) {
6452
6594
  });
6453
6595
  } catch {}
6454
6596
  };
6455
- const optionsFor = (lease, inspectRequest) => {
6597
+ const optionsFor = (lease, hooks = {}) => {
6456
6598
  const guard = {
6457
6599
  ...lifetime.guard(lease),
6458
- ...inspectRequest === void 0 ? {} : { inspectRequest },
6600
+ ...hooks,
6459
6601
  onUnauthorized() {
6460
6602
  if (lease === void 0 || !lifetime.isCurrent(lease.revision) || source.readDisplaySnapshot() !== lease.snapshot || provenSnapshot !== lease.snapshot || snapshotProof !== lease.proof) return;
6461
6603
  rejectedAuth = lease.proof;
@@ -7,7 +7,7 @@ export interface CopilotUsageView {
7
7
  readonly remaining?: number;
8
8
  readonly limit?: number;
9
9
  readonly percentUsed?: number;
10
- /** Unix epoch milliseconds, only when explicitly reported by the supplier. */
10
+ /** Supplier-reported next reset in Unix epoch milliseconds, later than observedAt. */
11
11
  readonly resetAt?: number;
12
12
  readonly observedAt?: number;
13
13
  readonly diagnostic?: string;
@@ -2,6 +2,7 @@ import type { Api, Context as PiContext, Model, StreamOptions } from '@earendil-
2
2
  import type { AccountModelApi, AccountModelDescriptor } from './account-model-catalog.ts';
3
3
  import type { CoreCompatibleProvider } from './pi-provider-bridge.ts';
4
4
  import type { GitHubCopilotOAuthCredential } from './copilot-grant.ts';
5
+ import { CopilotResponsesReplayError } from './responses-replay-compat.ts';
5
6
  /** Per-call authorization/lifetime checks supplied by the owning route. */
6
7
  export interface PreviewProviderGuard {
7
8
  readonly signal: AbortSignal;
@@ -11,8 +12,10 @@ export interface PreviewProviderGuard {
11
12
  signal: AbortSignal;
12
13
  release(): void;
13
14
  }>;
14
- /** Actual model HTTP 401 only; called after release, without replaying the request. */
15
+ /** Actual model HTTP 401, excluding proven Responses replay-scope failures; no request replay. */
15
16
  onUnauthorized?(): void;
17
+ /** Dispatch-local, verified replay failure; never inferred from SDK error text. */
18
+ onReplayFailure?(error: CopilotResponsesReplayError): void;
16
19
  }
17
20
  /** Guard for one selected model in an account-bound descriptor snapshot. */
18
21
  export interface AccountProviderGuard extends PreviewProviderGuard {
@@ -0,0 +1,11 @@
1
+ type ReplayFailure = 'scope-mismatch' | 'unsupported' | 'invalid-payload';
2
+ /** Fixed diagnostics only: never include provider bodies, IDs, arguments or replay content. */
3
+ export declare class CopilotResponsesReplayError extends Error {
4
+ constructor(reason?: ReplayFailure);
5
+ }
6
+ /** Normalize only the outgoing managed Responses payload, never stored history/context. */
7
+ export declare function normalizeCopilotResponsesPayload(payload: unknown): unknown;
8
+ /** Observe a cloned, bounded 401 body; every unknown result retains native auth behavior. */
9
+ export declare function isCopilotInputItemScopeError(response: Response, signal?: AbortSignal): Promise<boolean>;
10
+ export {};
11
+ //# sourceMappingURL=responses-replay-compat.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-github-copilot",
3
3
  "description": "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
4
- "version": "0.4.0-alpha.34",
4
+ "version": "0.4.0-alpha.36",
5
5
  "publishConfig": {
6
6
  "access": "public",
7
7
  "registry": "https://registry.npmjs.org/",