dsh-github-copilot 0.4.0-alpha.121 → 0.4.0-alpha.123

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";
@@ -331,7 +331,20 @@ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine
331
331
  if (this.visibleHistory.has(agent) && lease.api !== "openai-responses") throw new Error("COPILOT_COMPACTION_REPLAY_UNAVAILABLE");
332
332
  const agents = this.ctx.get("agents");
333
333
  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));
334
+ const summarize = async (candidate) => {
335
+ const observed = this.ctx.get("githubCopilotDiagnostics")?.collector.begin("compaction-summary");
336
+ observed?.stage("summary-attempt");
337
+ try {
338
+ const result = await (agents === void 0 ? super.summarize(candidate, agent, operationSignal) : agents.withInitiator(agent, () => super.summarize(candidate, agent, operationSignal)));
339
+ observed?.finish("success");
340
+ return result;
341
+ } catch (error) {
342
+ const reason = diagnosticsReason(error);
343
+ if (operationSignal.aborted) this.ctx.get("githubCopilotDiagnostics")?.markCompactionCancelled(agent.session);
344
+ observed?.finish(operationSignal.aborted ? "cancelled" : diagnosticsOutcome(reason), reason);
345
+ throw error;
346
+ }
347
+ };
335
348
  const budget = calculateRequestBudget(lease.limits, maxTokens, resolveRequestBudgetPolicy(lease.policy));
336
349
  if (!budget.ok) throw recoverError(budget.code);
337
350
  const toolHistoryBytes = Buffer.byteLength(JSON.stringify(agent.session.toolHistory()), "utf8");
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",
@@ -687,6 +687,20 @@ const contribution$2 = {
687
687
  };
688
688
  //#endregion
689
689
  //#region lib/types/session-continuation-types.js
690
+ const CompactionContinuationStatusSchema = z.object({
691
+ id: z.string().min(1).max(256),
692
+ state: z.enum([
693
+ "running",
694
+ "completed",
695
+ "failed",
696
+ "cancelled",
697
+ "blocked"
698
+ ])
699
+ }).strict();
700
+ z.object({
701
+ id: z.string().nullable(),
702
+ running: z.boolean()
703
+ }).strict();
690
704
  const SessionContinuationPreferenceSchema = z.object({
691
705
  sessionId: z.string().min(1).max(256).refine((value) => !/[\p{Cc}\p{Cf}]/u.test(value)),
692
706
  version: z.literal(1),
@@ -707,11 +721,12 @@ const SessionContinuationViewSchema = z.object({
707
721
  revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
708
722
  activeTurnEnabled: z.boolean().optional(),
709
723
  source: z.enum(["default", "session"]).optional(),
710
- nextTurnAuthorized: z.boolean().optional()
724
+ nextTurnAuthorized: z.boolean().optional(),
725
+ compaction: CompactionContinuationStatusSchema.optional()
711
726
  }).strict();
712
727
  //#endregion
713
728
  //#region lib/types/session-continuation-remote.js
714
- const contribution$1 = {
729
+ const contribution$2 = {
715
730
  package: "dsh-github-copilot",
716
731
  descriptors: [
717
732
  "get",
@@ -746,6 +761,192 @@ const contribution$1 = {
746
761
  }))
747
762
  };
748
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
749
950
  //#region lib/types/remote.js
750
951
  /**
751
952
  * Client-safe Remote contribution for the plugin-owned authorization bridge.
@@ -974,6 +1175,7 @@ const contribution = {
974
1175
  parameters: [],
975
1176
  result: strictRemoteCodec(GITHUB_COPILOT_MIGRATION_STATUS_TYPE_SYMBOL, GitHubCopilotMigrationStatusSchema)
976
1177
  },
1178
+ ...contribution$9.descriptors,
977
1179
  ...contribution$8.descriptors,
978
1180
  ...contribution$7.descriptors,
979
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
  /**
@@ -3,6 +3,40 @@ import { getSupportedThinkingLevels } from "@earendil-works/pi-ai";
3
3
  import { builtinProviders, getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
4
4
  import { WebError } from "@deepseek-ai/dsh-web";
5
5
  import { attributionHeaders } from "@deepseek-ai/dsh-llm";
6
+ //#region lib/types/settings-reader.js
7
+ function isLiveSetting(value) {
8
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "get") === "function";
9
+ }
10
+ /** Capture a native volatile field for one operation, or retain a plain fixture value. */
11
+ function readConfigValue(value) {
12
+ return isLiveSetting(value) ? value.get() : value;
13
+ }
14
+ function isRecord(value) {
15
+ return typeof value === "object" && value !== null;
16
+ }
17
+ function isSettingsForms(value) {
18
+ return isRecord(value) && typeof value.describe === "function";
19
+ }
20
+ function isLegacySettings(value) {
21
+ return isRecord(value) && typeof value.get === "function";
22
+ }
23
+ /** Read non-secret configuration through the API available on the running Core. */
24
+ function readSettingsNamespace(ctx, namespace) {
25
+ const settings = ctx.get("settings");
26
+ if (isLegacySettings(settings)) return settings.get(namespace);
27
+ if (!isSettingsForms(settings)) return void 0;
28
+ return settings.describe({ redactSecrets: true }).find((candidate) => candidate.ns === namespace)?.value;
29
+ }
30
+ /** Subscribe to namespace changes across the legacy settings provider and current form service. */
31
+ function onSettingsNamespaceUpdated(ctx, listener) {
32
+ const disposeDocument = ctx.on("settings/document-updated", (namespace) => listener(namespace));
33
+ const disposeLegacy = ctx.on("settings/updated", (namespace) => listener(namespace));
34
+ return () => {
35
+ disposeDocument();
36
+ disposeLegacy();
37
+ };
38
+ }
39
+ //#endregion
6
40
  //#region lib/types/model-protocol.js
7
41
  /** Project only public leaves and the same pi library's supported wire efforts. */
8
42
  function projectModelFacts(model) {
@@ -40,40 +74,6 @@ function isPluginPreviewProvider(ctx, provider) {
40
74
  return typeof view === "object" && view !== null && Reflect.get(view, "provider") === provider;
41
75
  }
42
76
  //#endregion
43
- //#region lib/types/settings-reader.js
44
- function isLiveSetting(value) {
45
- return typeof value === "object" && value !== null && typeof Reflect.get(value, "get") === "function";
46
- }
47
- /** Capture a native volatile field for one operation, or retain a plain fixture value. */
48
- function readConfigValue(value) {
49
- return isLiveSetting(value) ? value.get() : value;
50
- }
51
- function isRecord(value) {
52
- return typeof value === "object" && value !== null;
53
- }
54
- function isSettingsForms(value) {
55
- return isRecord(value) && typeof value.describe === "function";
56
- }
57
- function isLegacySettings(value) {
58
- return isRecord(value) && typeof value.get === "function";
59
- }
60
- /** Read non-secret configuration through the API available on the running Core. */
61
- function readSettingsNamespace(ctx, namespace) {
62
- const settings = ctx.get("settings");
63
- if (isLegacySettings(settings)) return settings.get(namespace);
64
- if (!isSettingsForms(settings)) return void 0;
65
- return settings.describe({ redactSecrets: true }).find((candidate) => candidate.ns === namespace)?.value;
66
- }
67
- /** Subscribe to namespace changes across the legacy settings provider and current form service. */
68
- function onSettingsNamespaceUpdated(ctx, listener) {
69
- const disposeDocument = ctx.on("settings/document-updated", (namespace) => listener(namespace));
70
- const disposeLegacy = ctx.on("settings/updated", (namespace) => listener(namespace));
71
- return () => {
72
- disposeDocument();
73
- disposeLegacy();
74
- };
75
- }
76
- //#endregion
77
77
  //#region lib/types/http.js
78
78
  /**
79
79
  * Shared HTTP plumbing for the capability probe and the inline wires:
@@ -789,4 +789,4 @@ async function routeSessionSearch(request, signal, deps) {
789
789
  };
790
790
  }
791
791
  //#endregion
792
- export { providerErrorMessage as C, readSettingsNamespace as D, readConfigValue as E, isPluginPreviewProvider as O, isAbortError as S, onSettingsNamespaceUpdated as T, sameCandidates as _, COPILOT_HOSTED_SEARCH_PROVIDER_ID as a, currentSearchSelection as b, applyRequestAuth as c, ANTHROPIC_WEB_SEARCH_TOOL_TYPE as d, GITHUB_COPILOT_CREDENTIAL_KEY as f, candidatesForRoute as g, WEB_SEARCH_TOOL_TYPE as h, describeSearchBackend as i, readCopilotCatalog as k, normalizeRequestAuth as l, SearchPlan as m, routeSessionSearch as n, GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID as o, RESPONSES_WEB_SEARCH_TOOL_TYPE as p, DescribedSearchFallbackError as r, createTraditionalSearchProvider as s, isCopilotSearchSelection as t, providerRequestHeaders as u, currentChatRoute as v, readBounded as w, abortable as x, currentSearchInitiator as y };
792
+ export { providerErrorMessage as C, onSettingsNamespaceUpdated as D, readCopilotCatalog as E, readConfigValue as O, isAbortError as S, isPluginPreviewProvider as T, sameCandidates as _, COPILOT_HOSTED_SEARCH_PROVIDER_ID as a, currentSearchSelection as b, applyRequestAuth as c, ANTHROPIC_WEB_SEARCH_TOOL_TYPE as d, GITHUB_COPILOT_CREDENTIAL_KEY as f, candidatesForRoute as g, WEB_SEARCH_TOOL_TYPE as h, describeSearchBackend as i, readSettingsNamespace as k, normalizeRequestAuth as l, SearchPlan as m, routeSessionSearch as n, GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID as o, RESPONSES_WEB_SEARCH_TOOL_TYPE as p, DescribedSearchFallbackError as r, createTraditionalSearchProvider as s, isCopilotSearchSelection as t, providerRequestHeaders as u, currentChatRoute as v, readBounded as w, abortable as x, currentSearchInitiator as y };