dsh-github-copilot 0.4.0-alpha.122 → 0.4.0-alpha.124

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
+ import { f as diagnosticsOutcome, i as resolveRequestBudgetPolicy, p as diagnosticsReason, r as calculateRequestBudget } from "./request-budget-Cui2hCi1.js";
1
2
  import "./copilot-identity-DRZY_d2X.js";
2
- import { i as resolveRequestBudgetPolicy, r as calculateRequestBudget } from "./request-budget-DLY_aRq0.js";
3
3
  import z from "@deepseek-ai/schemastery";
4
4
  import { LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
5
5
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
@@ -178,6 +178,61 @@ function installBackgroundCompaction(ctx, compact) {
178
178
  }, "Copilot background compaction");
179
179
  }
180
180
  //#endregion
181
+ //#region lib/types/compaction-input-estimate.js
182
+ function compactionSafeBoundaries(messages) {
183
+ const pending = /* @__PURE__ */ new Set();
184
+ const boundaries = [0];
185
+ for (let index = 0; index < messages.length; index++) {
186
+ const message = messages[index];
187
+ if (message.role === "assistant") for (const block of message.content) {
188
+ if (block.type !== "tool-call") continue;
189
+ if (!block.id || pending.has(block.id)) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
190
+ pending.add(block.id);
191
+ }
192
+ if (message.role === "tool" && (!message.toolCallId || !pending.delete(message.toolCallId))) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
193
+ if (pending.size === 0) boundaries.push(index + 1);
194
+ }
195
+ if (pending.size !== 0) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
196
+ return boundaries;
197
+ }
198
+ /**
199
+ * Conservative content-byte planning, not provider-exact token accounting.
200
+ * Native admission still checks converted replay, images and the full request.
201
+ */
202
+ function estimateCompactionInputBytes(input) {
203
+ return Buffer.byteLength(JSON.stringify({
204
+ tools: input.tools,
205
+ messages: input.messages.map((message) => ({
206
+ role: message.role,
207
+ content: message.content,
208
+ ...message.role === "tool" ? {
209
+ toolCallId: message.toolCallId,
210
+ isError: message.isError
211
+ } : {}
212
+ }))
213
+ }), "utf8");
214
+ }
215
+ function reduceCompactionInputLimit(input, inputLimit) {
216
+ const originalSize = estimateCompactionInputBytes(input);
217
+ const fixedSize = estimateCompactionInputBytes({
218
+ tools: input.tools,
219
+ messages: input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : []
220
+ });
221
+ const prefix = input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : [];
222
+ const messages = input.messages.slice(prefix.length);
223
+ let start = 0;
224
+ let minimum = fixedSize;
225
+ for (const end of compactionSafeBoundaries(messages).slice(1)) {
226
+ minimum = Math.max(minimum, estimateCompactionInputBytes({
227
+ tools: input.tools,
228
+ messages: [...prefix, ...messages.slice(start, end)]
229
+ }));
230
+ start = end;
231
+ }
232
+ if (minimum >= originalSize) throw new Error("COPILOT_MANUAL_RECOVERY_INDIVISIBLE");
233
+ return Math.min(inputLimit, Math.max(minimum, fixedSize + Math.floor((originalSize - fixedSize) / 2)));
234
+ }
235
+ //#endregion
181
236
  //#region lib/types/manual-compaction-recovery.js
182
237
  function recoverError(code) {
183
238
  return /* @__PURE__ */ new Error(`COPILOT_MANUAL_RECOVERY_${code}`);
@@ -205,22 +260,7 @@ async function summarizeOversizedManualInput(options) {
205
260
  const prefix = input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : [];
206
261
  const messages = input.messages.slice(prefix.length);
207
262
  if (messages.length === 0) throw recoverError("NO_HISTORY");
208
- const pending = /* @__PURE__ */ new Set();
209
- const safeBoundaries = /* @__PURE__ */ new Set([0]);
210
- for (let index = 0; index < messages.length; index++) {
211
- const message = messages[index];
212
- if (message.role === "assistant") {
213
- for (const block of message.content) if (block.type === "tool-call") {
214
- if (!block.id || pending.has(block.id)) throw recoverError("UNBALANCED");
215
- pending.add(block.id);
216
- }
217
- }
218
- if (message.role === "tool") {
219
- if (!message.toolCallId || !pending.delete(message.toolCallId)) throw recoverError("UNBALANCED");
220
- }
221
- if (pending.size === 0) safeBoundaries.add(index + 1);
222
- }
223
- if (pending.size !== 0) throw recoverError("UNBALANCED");
263
+ const safeBoundaries = new Set(compactionSafeBoundaries(messages));
224
264
  let previous;
225
265
  let offset = 0;
226
266
  let calls = 0;
@@ -331,13 +371,26 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
331
371
  if (this.visibleHistory.has(agent) && lease.api !== "openai-responses") throw new Error("COPILOT_COMPACTION_REPLAY_UNAVAILABLE");
332
372
  const agents = this.ctx.get("agents");
333
373
  if (this.ctx.get("githubCopilotSessionAccounts") !== void 0 && agents === void 0) throw recoverError("INITIATOR_UNAVAILABLE");
334
- const summarize = (candidate) => agents === void 0 ? super.summarize(candidate, agent, operationSignal) : agents.withInitiator(agent, () => super.summarize(candidate, agent, operationSignal));
374
+ const summarize = async (candidate) => {
375
+ const observed = this.ctx.get("githubCopilotDiagnostics")?.collector.begin("compaction-summary");
376
+ observed?.stage("summary-attempt");
377
+ try {
378
+ const result = await (agents === void 0 ? super.summarize(candidate, agent, operationSignal) : agents.withInitiator(agent, () => super.summarize(candidate, agent, operationSignal)));
379
+ observed?.finish("success");
380
+ return result;
381
+ } catch (error) {
382
+ const reason = diagnosticsReason(error);
383
+ if (operationSignal.aborted) this.ctx.get("githubCopilotDiagnostics")?.markCompactionCancelled(agent.session);
384
+ observed?.finish(operationSignal.aborted ? "cancelled" : diagnosticsOutcome(reason), reason);
385
+ throw error;
386
+ }
387
+ };
335
388
  const budget = calculateRequestBudget(lease.limits, maxTokens, resolveRequestBudgetPolicy(lease.policy));
336
389
  if (!budget.ok) throw recoverError(budget.code);
337
390
  const toolHistoryBytes = Buffer.byteLength(JSON.stringify(agent.session.toolHistory()), "utf8");
338
391
  let inputLimit = budget.budget.hardInputLimit - 4096 - toolHistoryBytes;
339
392
  if (inputLimit <= 0) throw recoverError("FIXED_PREFIX");
340
- const estimate = (candidate) => Buffer.byteLength(JSON.stringify(candidate), "utf8");
393
+ const estimate = estimateCompactionInputBytes;
341
394
  operationSignal.throwIfAborted();
342
395
  lease.assertCurrent();
343
396
  const originalSize = estimate(input);
@@ -348,7 +401,7 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
348
401
  operationSignal.throwIfAborted();
349
402
  if (!(error instanceof LlmError) || error.code !== "CONTEXT_WINDOW_EXCEEDED") throw error;
350
403
  lease.assertCurrent();
351
- inputLimit = Math.min(inputLimit, Math.floor(originalSize / 2));
404
+ inputLimit = reduceCompactionInputLimit(input, inputLimit);
352
405
  failedAttempt = true;
353
406
  }
354
407
  this.ctx.logger.info("[github-copilot] Segmented compaction recovery started; up to %d additional model calls.", failedAttempt ? 15 : 16);
package/lib/remote.js CHANGED
@@ -43,7 +43,7 @@ const DualModelCreateSchema = z.object({
43
43
  expectedRevision: revision$1
44
44
  }).strict();
45
45
  const DualModelCreateResultSchema = z.object({ sessionId: id }).strict();
46
- const contribution$8 = {
46
+ const contribution$9 = {
47
47
  package: "dsh-github-copilot",
48
48
  descriptors: [
49
49
  {
@@ -85,7 +85,7 @@ const contribution$8 = {
85
85
  }
86
86
  ]
87
87
  };
88
- const contribution$7 = {
88
+ const contribution$8 = {
89
89
  package: "dsh-github-copilot",
90
90
  descriptors: [{
91
91
  id: "dsh-github-copilot:githubCopilotSearchRouting.providers",
@@ -216,7 +216,7 @@ const CopilotUsageViewSchema = z.object({
216
216
  if (view.remaining !== void 0 && view.percentUsed !== void 0 && Math.abs((1 - view.remaining / view.limit) * 100 - view.percentUsed) > 1) invalid();
217
217
  }
218
218
  });
219
- const contribution$6 = {
219
+ const contribution$7 = {
220
220
  package: "dsh-github-copilot",
221
221
  descriptors: ["get", "refresh"].map((method) => ({
222
222
  id: `dsh-github-copilot:githubCopilotUsage.${method}`,
@@ -409,7 +409,7 @@ z.object({
409
409
  }).strict();
410
410
  //#endregion
411
411
  //#region lib/types/turn-selection-remote.js
412
- const contribution$5 = {
412
+ const contribution$6 = {
413
413
  package: "dsh-github-copilot",
414
414
  descriptors: [
415
415
  {
@@ -489,7 +489,7 @@ const agent$1 = {
489
489
  lookup: "agent",
490
490
  codec: strictRemoteCodec("@deepseek-ai/dsh-session/types#SessionId", z.string().min(1).max(256))
491
491
  };
492
- const contribution$4 = {
492
+ const contribution$5 = {
493
493
  package: "dsh-github-copilot",
494
494
  descriptors: [
495
495
  {
@@ -597,7 +597,7 @@ const CopilotAccountsViewSchema = z.object({
597
597
  if (row.identity !== void 0 && !row.configured) invalid();
598
598
  }
599
599
  });
600
- const contribution$3 = {
600
+ const contribution$4 = {
601
601
  package: "dsh-github-copilot",
602
602
  descriptors: [
603
603
  "get",
@@ -650,7 +650,7 @@ const agent = {
650
650
  lookup: "agent",
651
651
  codec: strictRemoteCodec("@deepseek-ai/dsh-session/types#SessionId", z.string().min(1).max(256))
652
652
  };
653
- const contribution$2 = {
653
+ const contribution$3 = {
654
654
  package: "dsh-github-copilot",
655
655
  descriptors: [
656
656
  "get",
@@ -726,7 +726,7 @@ const SessionContinuationViewSchema = z.object({
726
726
  }).strict();
727
727
  //#endregion
728
728
  //#region lib/types/session-continuation-remote.js
729
- const contribution$1 = {
729
+ const contribution$2 = {
730
730
  package: "dsh-github-copilot",
731
731
  descriptors: [
732
732
  "get",
@@ -761,6 +761,192 @@ const contribution$1 = {
761
761
  }))
762
762
  };
763
763
  //#endregion
764
+ //#region lib/types/diagnostics-types.js
765
+ const DIAGNOSTICS_OPERATIONS = [
766
+ "account-global-switch",
767
+ "account-session-select",
768
+ "account-session-inherit",
769
+ "identity-read",
770
+ "identity-flight",
771
+ "compaction",
772
+ "compaction-summary",
773
+ "collection"
774
+ ];
775
+ const DIAGNOSTICS_STAGES = [
776
+ "admitted",
777
+ "rpc-invoked",
778
+ "host-received",
779
+ "identity-validation",
780
+ "model-validation",
781
+ "cas",
782
+ "readback",
783
+ "response-received",
784
+ "decoded",
785
+ "client-settled",
786
+ "summary-attempt",
787
+ "checkpoint-committed",
788
+ "ended",
789
+ "cache-hit",
790
+ "joined-flight",
791
+ "cooldown",
792
+ "dispatched"
793
+ ];
794
+ const DIAGNOSTICS_METRICS = [
795
+ "started",
796
+ "stage",
797
+ "success",
798
+ "no-op",
799
+ "cancelled",
800
+ "policy-rejected",
801
+ "revoked",
802
+ "environment-fault",
803
+ "failed",
804
+ "unknown",
805
+ "interrupted",
806
+ "dropped",
807
+ "paused",
808
+ "expired",
809
+ "clock-discontinuity",
810
+ "pending-sample"
811
+ ];
812
+ const DIAGNOSTICS_REASONS = [
813
+ "none",
814
+ "unknown",
815
+ "rpc-unavailable",
816
+ "decode-invalid",
817
+ "COPILOT_ACCOUNTS_BUSY",
818
+ "COPILOT_ACCOUNTS_CONFLICT",
819
+ "COPILOT_ACCOUNTS_CHANGED",
820
+ "COPILOT_ACCOUNTS_COMMIT_UNCERTAIN",
821
+ "COPILOT_ACCOUNTS_IDENTITY_TIMEOUT",
822
+ "COPILOT_ACCOUNTS_IDENTITY_UNAVAILABLE",
823
+ "COPILOT_ACCOUNTS_MODELS_FAILED",
824
+ "COPILOT_ACCOUNTS_SETTINGS_UNAVAILABLE",
825
+ "COPILOT_ACCOUNTS_IDENTITY_TLS",
826
+ "COPILOT_ACCOUNTS_IDENTITY_NETWORK",
827
+ "COPILOT_ACCOUNTS_IDENTITY_RATE_LIMITED",
828
+ "COPILOT_ACCOUNTS_IDENTITY_AUTH_REJECTED",
829
+ "COPILOT_ACCOUNTS_IDENTITY_HTTP_ERROR",
830
+ "COPILOT_ACCOUNTS_IDENTITY_INVALID",
831
+ "COPILOT_SESSION_ACCOUNTS_UNAVAILABLE",
832
+ "COPILOT_SESSION_ACCOUNTS_SETTINGS_UNAVAILABLE",
833
+ "COPILOT_SESSION_ACCOUNTS_COMMIT_UNCERTAIN",
834
+ "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH",
835
+ "CONTEXT_WINDOW_EXCEEDED",
836
+ "COPILOT_MANUAL_RECOVERY_FIXED_PREFIX",
837
+ "COPILOT_MANUAL_RECOVERY_INDIVISIBLE",
838
+ "COPILOT_MANUAL_RECOVERY_CALL_LIMIT",
839
+ "COPILOT_MANUAL_RECOVERY_EMPTY_SUMMARY",
840
+ "COPILOT_MANUAL_RECOVERY_UNBALANCED"
841
+ ];
842
+ const DIAGNOSTICS_MAX_ROWS = 4096;
843
+ const DIAGNOSTICS_MAX_BYTES = 2097152;
844
+ const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
845
+ const version = z.string().max(64).regex(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/);
846
+ const DiagnosticsRowSchema = z.object({
847
+ hour: integer.multipleOf(36e5),
848
+ version,
849
+ layer: z.enum(["client", "host"]),
850
+ operation: z.enum(DIAGNOSTICS_OPERATIONS),
851
+ stage: z.enum(DIAGNOSTICS_STAGES),
852
+ metric: z.enum(DIAGNOSTICS_METRICS),
853
+ reason: z.enum(DIAGNOSTICS_REASONS),
854
+ bucket: z.number().int().min(0).max(7),
855
+ count: integer.min(1)
856
+ }).strict();
857
+ const DiagnosticsPendingSchema = z.object({
858
+ version,
859
+ operation: z.enum(DIAGNOSTICS_OPERATIONS),
860
+ stage: z.enum(DIAGNOSTICS_STAGES),
861
+ bucket: z.number().int().min(0).max(7),
862
+ count: integer.min(1).max(128)
863
+ }).strict();
864
+ const DiagnosticsSnapshotSchema = z.object({
865
+ schemaVersion: z.literal(1),
866
+ coverageVersion: z.literal(1),
867
+ epoch: integer,
868
+ updatedAt: integer,
869
+ rows: z.array(DiagnosticsRowSchema).max(DIAGNOSTICS_MAX_ROWS),
870
+ pending: z.array(DiagnosticsPendingSchema).max(128),
871
+ dropped: integer,
872
+ clientDropped: integer,
873
+ clientUnconfirmed: integer,
874
+ saturated: integer,
875
+ evicted: integer,
876
+ interrupted: integer
877
+ }).strict().refine((value) => value.pending.reduce((sum, row) => sum + row.count, 0) <= 128, "Diagnostics pending capacity exceeded").refine((value) => JSON.stringify(value).length <= DIAGNOSTICS_MAX_BYTES, "Diagnostics capacity exceeded");
878
+ const DiagnosticsViewSchema = z.object({
879
+ enabled: z.boolean(),
880
+ state: z.enum([
881
+ "loading",
882
+ "ready",
883
+ "unavailable",
884
+ "error"
885
+ ]),
886
+ diagnostic: z.enum([
887
+ "none",
888
+ "storage-unavailable",
889
+ "storage-invalid",
890
+ "storage-write-failed",
891
+ "profile-unavailable",
892
+ "settings-unavailable",
893
+ "settings-conflict",
894
+ "client-report-failed",
895
+ "client-report-revoked",
896
+ "closed"
897
+ ]),
898
+ persistedAt: integer.optional(),
899
+ dirty: z.boolean(),
900
+ snapshot: DiagnosticsSnapshotSchema
901
+ }).strict();
902
+ //#endregion
903
+ //#region lib/types/diagnostics-remote.js
904
+ const ClientDiagnosticsBatchSchema = z.object({
905
+ epoch: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
906
+ rows: z.array(DiagnosticsRowSchema.refine((row) => row.layer === "client")).max(128),
907
+ dropped: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
908
+ unconfirmed: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()
909
+ }).strict();
910
+ const result$1 = strictRemoteCodec("dsh-github-copilot#DiagnosticsView", DiagnosticsViewSchema);
911
+ const contribution$1 = {
912
+ package: "dsh-github-copilot",
913
+ descriptors: [
914
+ {
915
+ method: "get",
916
+ parameters: []
917
+ },
918
+ {
919
+ method: "clear",
920
+ parameters: []
921
+ },
922
+ {
923
+ method: "setEnabled",
924
+ parameters: [{
925
+ name: "enabled",
926
+ wire: "enabled",
927
+ source: "json",
928
+ codec: strictRemoteCodec("dsh-github-copilot#DiagnosticsEnabled", z.boolean())
929
+ }]
930
+ },
931
+ {
932
+ method: "recordClient",
933
+ parameters: [{
934
+ name: "batch",
935
+ wire: "batch",
936
+ source: "json",
937
+ codec: strictRemoteCodec("dsh-github-copilot#ClientDiagnosticsBatch", ClientDiagnosticsBatchSchema)
938
+ }]
939
+ }
940
+ ].map((descriptor) => ({
941
+ ...descriptor,
942
+ id: `dsh-github-copilot:githubCopilotDiagnostics.${descriptor.method}`,
943
+ namespace: "githubCopilotDiagnostics",
944
+ service: "githubCopilotDiagnostics",
945
+ invocation: { kind: "direct" },
946
+ result: result$1
947
+ }))
948
+ };
949
+ //#endregion
764
950
  //#region lib/types/remote.js
765
951
  /**
766
952
  * Client-safe Remote contribution for the plugin-owned authorization bridge.
@@ -989,6 +1175,7 @@ const contribution = {
989
1175
  parameters: [],
990
1176
  result: strictRemoteCodec(GITHUB_COPILOT_MIGRATION_STATUS_TYPE_SYMBOL, GitHubCopilotMigrationStatusSchema)
991
1177
  },
1178
+ ...contribution$9.descriptors,
992
1179
  ...contribution$8.descriptors,
993
1180
  ...contribution$7.descriptors,
994
1181
  ...contribution$6.descriptors,
@@ -0,0 +1,268 @@
1
+ import { z } from "zod";
2
+ //#region lib/types/diagnostics-types.js
3
+ const DIAGNOSTICS_OPERATIONS = [
4
+ "account-global-switch",
5
+ "account-session-select",
6
+ "account-session-inherit",
7
+ "identity-read",
8
+ "identity-flight",
9
+ "compaction",
10
+ "compaction-summary",
11
+ "collection"
12
+ ];
13
+ const DIAGNOSTICS_STAGES = [
14
+ "admitted",
15
+ "rpc-invoked",
16
+ "host-received",
17
+ "identity-validation",
18
+ "model-validation",
19
+ "cas",
20
+ "readback",
21
+ "response-received",
22
+ "decoded",
23
+ "client-settled",
24
+ "summary-attempt",
25
+ "checkpoint-committed",
26
+ "ended",
27
+ "cache-hit",
28
+ "joined-flight",
29
+ "cooldown",
30
+ "dispatched"
31
+ ];
32
+ const DIAGNOSTICS_METRICS = [
33
+ "started",
34
+ "stage",
35
+ "success",
36
+ "no-op",
37
+ "cancelled",
38
+ "policy-rejected",
39
+ "revoked",
40
+ "environment-fault",
41
+ "failed",
42
+ "unknown",
43
+ "interrupted",
44
+ "dropped",
45
+ "paused",
46
+ "expired",
47
+ "clock-discontinuity",
48
+ "pending-sample"
49
+ ];
50
+ const DIAGNOSTICS_REASONS = [
51
+ "none",
52
+ "unknown",
53
+ "rpc-unavailable",
54
+ "decode-invalid",
55
+ "COPILOT_ACCOUNTS_BUSY",
56
+ "COPILOT_ACCOUNTS_CONFLICT",
57
+ "COPILOT_ACCOUNTS_CHANGED",
58
+ "COPILOT_ACCOUNTS_COMMIT_UNCERTAIN",
59
+ "COPILOT_ACCOUNTS_IDENTITY_TIMEOUT",
60
+ "COPILOT_ACCOUNTS_IDENTITY_UNAVAILABLE",
61
+ "COPILOT_ACCOUNTS_MODELS_FAILED",
62
+ "COPILOT_ACCOUNTS_SETTINGS_UNAVAILABLE",
63
+ "COPILOT_ACCOUNTS_IDENTITY_TLS",
64
+ "COPILOT_ACCOUNTS_IDENTITY_NETWORK",
65
+ "COPILOT_ACCOUNTS_IDENTITY_RATE_LIMITED",
66
+ "COPILOT_ACCOUNTS_IDENTITY_AUTH_REJECTED",
67
+ "COPILOT_ACCOUNTS_IDENTITY_HTTP_ERROR",
68
+ "COPILOT_ACCOUNTS_IDENTITY_INVALID",
69
+ "COPILOT_SESSION_ACCOUNTS_UNAVAILABLE",
70
+ "COPILOT_SESSION_ACCOUNTS_SETTINGS_UNAVAILABLE",
71
+ "COPILOT_SESSION_ACCOUNTS_COMMIT_UNCERTAIN",
72
+ "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH",
73
+ "CONTEXT_WINDOW_EXCEEDED",
74
+ "COPILOT_MANUAL_RECOVERY_FIXED_PREFIX",
75
+ "COPILOT_MANUAL_RECOVERY_INDIVISIBLE",
76
+ "COPILOT_MANUAL_RECOVERY_CALL_LIMIT",
77
+ "COPILOT_MANUAL_RECOVERY_EMPTY_SUMMARY",
78
+ "COPILOT_MANUAL_RECOVERY_UNBALANCED"
79
+ ];
80
+ const DIAGNOSTICS_MAX_ROWS = 4096;
81
+ const DIAGNOSTICS_MAX_BYTES = 2097152;
82
+ const DIAGNOSTICS_RETENTION_MS = 12096e5;
83
+ const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
84
+ const version = z.string().max(64).regex(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/);
85
+ const DiagnosticsRowSchema = z.object({
86
+ hour: integer.multipleOf(36e5),
87
+ version,
88
+ layer: z.enum(["client", "host"]),
89
+ operation: z.enum(DIAGNOSTICS_OPERATIONS),
90
+ stage: z.enum(DIAGNOSTICS_STAGES),
91
+ metric: z.enum(DIAGNOSTICS_METRICS),
92
+ reason: z.enum(DIAGNOSTICS_REASONS),
93
+ bucket: z.number().int().min(0).max(7),
94
+ count: integer.min(1)
95
+ }).strict();
96
+ const DiagnosticsPendingSchema = z.object({
97
+ version,
98
+ operation: z.enum(DIAGNOSTICS_OPERATIONS),
99
+ stage: z.enum(DIAGNOSTICS_STAGES),
100
+ bucket: z.number().int().min(0).max(7),
101
+ count: integer.min(1).max(128)
102
+ }).strict();
103
+ const DiagnosticsSnapshotSchema = z.object({
104
+ schemaVersion: z.literal(1),
105
+ coverageVersion: z.literal(1),
106
+ epoch: integer,
107
+ updatedAt: integer,
108
+ rows: z.array(DiagnosticsRowSchema).max(DIAGNOSTICS_MAX_ROWS),
109
+ pending: z.array(DiagnosticsPendingSchema).max(128),
110
+ dropped: integer,
111
+ clientDropped: integer,
112
+ clientUnconfirmed: integer,
113
+ saturated: integer,
114
+ evicted: integer,
115
+ interrupted: integer
116
+ }).strict().refine((value) => value.pending.reduce((sum, row) => sum + row.count, 0) <= 128, "Diagnostics pending capacity exceeded").refine((value) => JSON.stringify(value).length <= DIAGNOSTICS_MAX_BYTES, "Diagnostics capacity exceeded");
117
+ const DiagnosticsViewSchema = z.object({
118
+ enabled: z.boolean(),
119
+ state: z.enum([
120
+ "loading",
121
+ "ready",
122
+ "unavailable",
123
+ "error"
124
+ ]),
125
+ diagnostic: z.enum([
126
+ "none",
127
+ "storage-unavailable",
128
+ "storage-invalid",
129
+ "storage-write-failed",
130
+ "profile-unavailable",
131
+ "settings-unavailable",
132
+ "settings-conflict",
133
+ "client-report-failed",
134
+ "client-report-revoked",
135
+ "closed"
136
+ ]),
137
+ persistedAt: integer.optional(),
138
+ dirty: z.boolean(),
139
+ snapshot: DiagnosticsSnapshotSchema
140
+ }).strict();
141
+ function diagnosticsBucket(ms) {
142
+ return [
143
+ 100,
144
+ 500,
145
+ 1e3,
146
+ 5e3,
147
+ 15e3,
148
+ 6e4,
149
+ 3e5
150
+ ].findIndex((bound) => ms < bound) === -1 ? 7 : [
151
+ 100,
152
+ 500,
153
+ 1e3,
154
+ 5e3,
155
+ 15e3,
156
+ 6e4,
157
+ 3e5
158
+ ].findIndex((bound) => ms < bound);
159
+ }
160
+ function diagnosticsReason(error) {
161
+ const seen = /* @__PURE__ */ new Set();
162
+ for (let depth = 0; depth < 8 && error instanceof Error && !seen.has(error); depth++) {
163
+ seen.add(error);
164
+ const nativeCode = "code" in error ? error.code : void 0;
165
+ const typed = DIAGNOSTICS_REASONS.find((code) => code !== "none" && code !== "unknown" && code === nativeCode);
166
+ if (typed !== void 0) return typed;
167
+ const message = error.message.slice(0, 4096);
168
+ for (const code of DIAGNOSTICS_REASONS) if (code.startsWith("COPILOT_") || code === "CONTEXT_WINDOW_EXCEEDED") {
169
+ if (new RegExp(`(?:^|[^A-Za-z0-9_])${code}(?:$|[^A-Za-z0-9_])`).test(message)) return code;
170
+ }
171
+ error = error.cause;
172
+ }
173
+ return "unknown";
174
+ }
175
+ function diagnosticsOutcome(reason) {
176
+ if (reason === "COPILOT_ACCOUNTS_BUSY" || reason === "COPILOT_ACCOUNTS_CONFLICT") return "policy-rejected";
177
+ if (reason === "COPILOT_ACCOUNTS_CHANGED") return "revoked";
178
+ if (reason.endsWith("SETTINGS_UNAVAILABLE") || reason === "COPILOT_SESSION_ACCOUNTS_UNAVAILABLE") return "environment-fault";
179
+ return "failed";
180
+ }
181
+ //#endregion
182
+ //#region lib/types/request-budget.js
183
+ /** The safety allowance matches the pinned native SDK; pressure is a separate opt-in check. */
184
+ const DEFAULT_REQUEST_BUDGET_POLICY = Object.freeze({
185
+ safetyTokens: 4096,
186
+ pressureRatio: .9,
187
+ compactionReasoning: "prefer-low"
188
+ });
189
+ /** Validate deployment policy before applying defaults; unknown keys fail rather than silently drift. */
190
+ function resolveRequestBudgetPolicy(config = {}) {
191
+ const keys = /* @__PURE__ */ new Set([
192
+ "safetyTokens",
193
+ "pressureRatio",
194
+ "compactionReasoning"
195
+ ]);
196
+ for (const key of Object.keys(config)) if (!keys.has(key)) throw new Error(`COPILOT_REQUEST_BUDGET_POLICY_INVALID: unknown setting ${key}`);
197
+ const safetyTokens = config.safetyTokens === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens : config.safetyTokens;
198
+ const pressureRatio = config.pressureRatio === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio : config.pressureRatio;
199
+ const compactionReasoning = config.compactionReasoning === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning : config.compactionReasoning;
200
+ if (!Number.isSafeInteger(safetyTokens) || safetyTokens < 0) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: safetyTokens must be a non-negative safe integer");
201
+ if (!Number.isFinite(pressureRatio) || pressureRatio <= 0 || pressureRatio > 1) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: pressureRatio must be greater than zero and at most one");
202
+ if (compactionReasoning !== "prefer-low" && compactionReasoning !== "preserve") throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: unsupported compactionReasoning");
203
+ return Object.freeze({
204
+ safetyTokens,
205
+ pressureRatio,
206
+ compactionReasoning
207
+ });
208
+ }
209
+ function failure(code, message) {
210
+ return Object.freeze({
211
+ ok: false,
212
+ code,
213
+ message: `${code}: ${message}`
214
+ });
215
+ }
216
+ function positiveInteger(value) {
217
+ return Number.isSafeInteger(value) && value > 0;
218
+ }
219
+ /**
220
+ * Reserve output under the combined context and independently enforce the prompt ceiling.
221
+ * `policy` must come from resolveRequestBudgetPolicy; no caller cap or catalog object is changed.
222
+ */
223
+ function calculateRequestBudget(limits, requestedMaxTokens, policy = DEFAULT_REQUEST_BUDGET_POLICY) {
224
+ const { contextWindow, maxInputTokens, maxTokens } = limits;
225
+ if (!positiveInteger(contextWindow) || !positiveInteger(maxTokens) || maxInputTokens !== void 0 && !positiveInteger(maxInputTokens)) return failure("COPILOT_REQUEST_INVALID_LIMITS", "model token capacities must be positive safe integers");
226
+ if (requestedMaxTokens !== void 0 && !positiveInteger(requestedMaxTokens)) return failure("COPILOT_REQUEST_INVALID_OUTPUT_LIMIT", "request output cap must be a positive safe integer");
227
+ const outputReservation = requestedMaxTokens ?? maxTokens;
228
+ if (outputReservation > maxTokens) return failure("COPILOT_REQUEST_OUTPUT_LIMIT_EXCEEDED", `request output cap ${outputReservation} exceeds model output capacity ${maxTokens}`);
229
+ const contextInputLimit = contextWindow - outputReservation;
230
+ const limitingFactor = maxInputTokens !== void 0 && maxInputTokens <= contextInputLimit ? "prompt" : "context";
231
+ const hardInputLimit = Math.min(maxInputTokens ?? contextInputLimit, contextInputLimit) - policy.safetyTokens;
232
+ if (hardInputLimit <= 0) return failure("COPILOT_REQUEST_NO_INPUT_HEADROOM", "output reservation and safety allowance leave no positive input budget");
233
+ return Object.freeze({
234
+ ok: true,
235
+ budget: Object.freeze({
236
+ contextWindow,
237
+ ...maxInputTokens === void 0 ? {} : { maxInputTokens },
238
+ maxOutputTokens: maxTokens,
239
+ outputReservation,
240
+ hardInputLimit,
241
+ pressureInputLimit: Math.floor(hardInputLimit * policy.pressureRatio),
242
+ limitingFactor
243
+ })
244
+ });
245
+ }
246
+ /**
247
+ * Check an estimated full prompt; estimates are not provider-exact token counts.
248
+ * Enable pressure only for an owned ordinary loop call with a compaction recovery path.
249
+ * Auxiliary and agentless calls use hard admission, including compaction itself.
250
+ */
251
+ function assessRequestBudget(estimatedInput, budget, pressure = false) {
252
+ if (!Number.isFinite(estimatedInput) || estimatedInput < 0 || estimatedInput > Number.MAX_SAFE_INTEGER) return failure("COPILOT_REQUEST_INVALID_ESTIMATE", "estimated input must be finite, non-negative, and safely representable");
253
+ const input = Math.ceil(estimatedInput);
254
+ if (input > budget.hardInputLimit) return failure(budget.limitingFactor === "prompt" ? "COPILOT_REQUEST_INPUT_LIMIT_EXCEEDED" : "COPILOT_REQUEST_CONTEXT_LIMIT_EXCEEDED", `estimated input ${input} exceeds input budget ${budget.hardInputLimit} with output reservation ${budget.outputReservation}`);
255
+ if (pressure && input > budget.pressureInputLimit) return failure("COPILOT_REQUEST_PRESSURE_EXCEEDED", `estimated input ${input} exceeds proactive compaction budget ${budget.pressureInputLimit}`);
256
+ return Object.freeze({ ok: true });
257
+ }
258
+ /**
259
+ * Select a low-cost supported effort only for a caller-confirmed compaction request.
260
+ * A supplied effort, including a materialized provider default, wins unchanged; native validation
261
+ * remains authoritative. Unsupported low-cost controls preserve the provider default, never off/none.
262
+ */
263
+ function selectCompactionReasoning(supportedEfforts, requestedEffort, mode = DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning) {
264
+ if (requestedEffort !== void 0 || mode === "preserve") return requestedEffort;
265
+ return supportedEfforts.find((effort) => effort === "minimal") ?? supportedEfforts.find((effort) => effort === "low");
266
+ }
267
+ //#endregion
268
+ export { selectCompactionReasoning as a, DiagnosticsRowSchema as c, diagnosticsBucket as d, diagnosticsOutcome as f, resolveRequestBudgetPolicy as i, DiagnosticsSnapshotSchema as l, assessRequestBudget as n, DIAGNOSTICS_MAX_ROWS as o, diagnosticsReason as p, calculateRequestBudget as r, DIAGNOSTICS_RETENTION_MS as s, DEFAULT_REQUEST_BUDGET_POLICY as t, DiagnosticsViewSchema as u };
package/lib/routed-web.js CHANGED
@@ -1,5 +1,5 @@
1
+ import { T as isPluginPreviewProvider, b as currentSearchSelection, t as isCopilotSearchSelection, y as currentSearchInitiator } from "./search-routing-CV2hs8as.js";
1
2
  import "./copilot-identity-DRZY_d2X.js";
2
- import { O as isPluginPreviewProvider, b as currentSearchSelection, t as isCopilotSearchSelection, y as currentSearchInitiator } from "./search-routing-CHyF6TbO.js";
3
3
  import { WebError, WebRuntime } from "@deepseek-ai/dsh-web";
4
4
  //#region lib/types/routed-web.js
5
5
  /**