dsh-github-copilot 0.1.0-alpha.1.dsh.0.2.1.alpha.5

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.
Files changed (209) hide show
  1. package/AGENTS.md +439 -0
  2. package/CHANGELOG.md +875 -0
  3. package/CONTRIBUTING.md +55 -0
  4. package/LICENSE +21 -0
  5. package/README.md +366 -0
  6. package/README.zh.md +341 -0
  7. package/SECURITY.md +29 -0
  8. package/cordis.patch.yml +16 -0
  9. package/deployment-baseline.json +1580 -0
  10. package/docs/account-management-experience.md +143 -0
  11. package/docs/agent-readiness.md +110 -0
  12. package/docs/auto-high-cost.md +255 -0
  13. package/docs/auto-iteration-review.json +22 -0
  14. package/docs/auto-review-sampling.md +60 -0
  15. package/docs/auto-task-routing.md +341 -0
  16. package/docs/automatic-model-routing.md +236 -0
  17. package/docs/copilot-accounts.md +424 -0
  18. package/docs/copilot-compaction.md +148 -0
  19. package/docs/copilot-usage.md +133 -0
  20. package/docs/dual-model.md +66 -0
  21. package/docs/evidence-driven-iteration.md +86 -0
  22. package/docs/image-input-compatibility.md +64 -0
  23. package/docs/images/copilot-accounts-credits.png +0 -0
  24. package/docs/images/copilot-accounts.png +0 -0
  25. package/docs/images/copilot-current-provenance.json +39 -0
  26. package/docs/images/copilot-model-preferences.png +0 -0
  27. package/docs/images/copilot-search-routing.png +0 -0
  28. package/docs/images/copilot-session-continuation.png +0 -0
  29. package/docs/images/dual-model-desktop.png +0 -0
  30. package/docs/images/dual-model-mobile.png +0 -0
  31. package/docs/images/dual-model-provenance.json +35 -0
  32. package/docs/images/parent-model-follow.png +0 -0
  33. package/docs/manual-compaction-recovery.md +109 -0
  34. package/docs/mockups/copilot-account-dropdown.html +71 -0
  35. package/docs/mockups/copilot-account-management.html +393 -0
  36. package/docs/model-compatibility-acceptance.md +182 -0
  37. package/docs/npm-distribution.md +202 -0
  38. package/docs/official-first-016-alpha2.md +66 -0
  39. package/docs/official-first-020-rc1.md +32 -0
  40. package/docs/official-first-020-rc2.md +17 -0
  41. package/docs/official-first-021-alpha4.md +157 -0
  42. package/docs/official-first-021-alpha5.md +83 -0
  43. package/docs/plugin-diagnostics.md +605 -0
  44. package/docs/session-continuation.md +141 -0
  45. package/docs/session-search-routing.md +133 -0
  46. package/docs/single-route-migration.md +131 -0
  47. package/docs/web-lifecycle-rc2.md +55 -0
  48. package/lib/client.js +13236 -0
  49. package/lib/client.js.map +1 -0
  50. package/lib/copilot-identity-DRZY_d2X.js +15 -0
  51. package/lib/diagnostics-analysis-io.js +78 -0
  52. package/lib/diagnostics-analysis.js +427 -0
  53. package/lib/diagnostics-types-CF-qg8Do.js +708 -0
  54. package/lib/index.js +15661 -0
  55. package/lib/manual-compaction-recovery.js +485 -0
  56. package/lib/remote.js +1507 -0
  57. package/lib/request-budget-DLY_aRq0.js +87 -0
  58. package/lib/routed-web.js +120 -0
  59. package/lib/search-routing-CV2hs8as.js +792 -0
  60. package/lib/types/account-dropdown.d.ts +22 -0
  61. package/lib/types/account-model-auth.d.ts +15 -0
  62. package/lib/types/account-model-catalog.d.ts +70 -0
  63. package/lib/types/account-model-source.d.ts +85 -0
  64. package/lib/types/agent-compaction.d.ts +4 -0
  65. package/lib/types/authorization-code-clipboard.d.ts +4 -0
  66. package/lib/types/authorization-controller.d.ts +121 -0
  67. package/lib/types/auto-allocation-card.d.ts +9 -0
  68. package/lib/types/auto-allocation-diagnostics.d.ts +126 -0
  69. package/lib/types/auto-allocation-evidence.d.ts +44 -0
  70. package/lib/types/auto-allocation.d.ts +47 -0
  71. package/lib/types/auto-assessment-evidence.d.ts +111 -0
  72. package/lib/types/auto-model-host.d.ts +30 -0
  73. package/lib/types/auto-model-intent.d.ts +36 -0
  74. package/lib/types/auto-model-presentation.d.ts +57 -0
  75. package/lib/types/auto-model-routing.d.ts +64 -0
  76. package/lib/types/auto-review-sampling.d.ts +6 -0
  77. package/lib/types/auto-selection-explanation.d.ts +9 -0
  78. package/lib/types/auto-task-assessment.d.ts +49 -0
  79. package/lib/types/auto-task-classifier.d.ts +10 -0
  80. package/lib/types/background-compaction.d.ts +30 -0
  81. package/lib/types/client.d.ts +129 -0
  82. package/lib/types/compact-account.d.ts +42 -0
  83. package/lib/types/compaction-continuation-ui.d.ts +29 -0
  84. package/lib/types/compaction-continuation.d.ts +48 -0
  85. package/lib/types/compaction-input-estimate.d.ts +28 -0
  86. package/lib/types/compaction-pressure.d.ts +23 -0
  87. package/lib/types/compaction-replay.d.ts +18 -0
  88. package/lib/types/compatibility.d.ts +17 -0
  89. package/lib/types/composer-notice-style.d.ts +7 -0
  90. package/lib/types/config.d.ts +141 -0
  91. package/lib/types/content-file.d.ts +10 -0
  92. package/lib/types/context-evidence-ui.d.ts +28 -0
  93. package/lib/types/context-evidence.d.ts +256 -0
  94. package/lib/types/context-usage.d.ts +4 -0
  95. package/lib/types/copilot-account-presentation.d.ts +7 -0
  96. package/lib/types/copilot-accounts-card.d.ts +43 -0
  97. package/lib/types/copilot-accounts-host.d.ts +93 -0
  98. package/lib/types/copilot-accounts-remote.d.ts +85 -0
  99. package/lib/types/copilot-accounts-types.d.ts +43 -0
  100. package/lib/types/copilot-auth.d.ts +31 -0
  101. package/lib/types/copilot-grant.d.ts +11 -0
  102. package/lib/types/copilot-identity.d.ts +11 -0
  103. package/lib/types/copilot-request.d.ts +11 -0
  104. package/lib/types/copilot-stream-liveness.d.ts +23 -0
  105. package/lib/types/copilot-usage-card.d.ts +51 -0
  106. package/lib/types/copilot-usage-host.d.ts +61 -0
  107. package/lib/types/copilot-usage-normalize.d.ts +9 -0
  108. package/lib/types/copilot-usage-remote.d.ts +63 -0
  109. package/lib/types/copilot-usage-types.d.ts +20 -0
  110. package/lib/types/copilot-usage-ui.d.ts +4 -0
  111. package/lib/types/current-provider.d.ts +59 -0
  112. package/lib/types/deepseek-search-fallback.d.ts +11 -0
  113. package/lib/types/diagnostics-analysis-io.d.ts +23 -0
  114. package/lib/types/diagnostics-analysis.d.ts +298 -0
  115. package/lib/types/diagnostics-card.d.ts +12 -0
  116. package/lib/types/diagnostics-client.d.ts +13 -0
  117. package/lib/types/diagnostics-collector.d.ts +50 -0
  118. package/lib/types/diagnostics-host.d.ts +183 -0
  119. package/lib/types/diagnostics-remote.d.ts +113 -0
  120. package/lib/types/diagnostics-types.d.ts +893 -0
  121. package/lib/types/dual-model-host.d.ts +119 -0
  122. package/lib/types/dual-model-remote.d.ts +63 -0
  123. package/lib/types/dual-model-types.d.ts +34 -0
  124. package/lib/types/external-link.d.ts +3 -0
  125. package/lib/types/failure.d.ts +38 -0
  126. package/lib/types/http.d.ts +48 -0
  127. package/lib/types/image-input-admission.d.ts +5 -0
  128. package/lib/types/index.d.ts +39 -0
  129. package/lib/types/manual-compaction-recovery.d.ts +67 -0
  130. package/lib/types/migration-status.d.ts +50 -0
  131. package/lib/types/model-exclusions.d.ts +15 -0
  132. package/lib/types/model-preferences-card.d.ts +9 -0
  133. package/lib/types/model-protocol.d.ts +31 -0
  134. package/lib/types/native-select-style.d.ts +4 -0
  135. package/lib/types/native-settings-style.d.ts +10 -0
  136. package/lib/types/parent-model-follow-card.d.ts +32 -0
  137. package/lib/types/parent-model-follow.d.ts +44 -0
  138. package/lib/types/pi-provider-bridge.d.ts +22 -0
  139. package/lib/types/plan.d.ts +148 -0
  140. package/lib/types/pre-step-pressure.d.ts +8 -0
  141. package/lib/types/preview-provider.d.ts +77 -0
  142. package/lib/types/preview-route.d.ts +76 -0
  143. package/lib/types/probe.d.ts +39 -0
  144. package/lib/types/remote-codec.d.ts +10 -0
  145. package/lib/types/remote.d.ts +202 -0
  146. package/lib/types/replay-recovery-host.d.ts +28 -0
  147. package/lib/types/replay-recovery-remote.d.ts +14 -0
  148. package/lib/types/replay-recovery-types.d.ts +24 -0
  149. package/lib/types/replay-recovery-ui.d.ts +28 -0
  150. package/lib/types/replay-recovery.d.ts +17 -0
  151. package/lib/types/request-body-composition.d.ts +17 -0
  152. package/lib/types/request-body-evidence.d.ts +37 -0
  153. package/lib/types/request-body-timeout-marker.d.ts +2 -0
  154. package/lib/types/request-body-timeout.d.ts +4 -0
  155. package/lib/types/request-budget.d.ts +58 -0
  156. package/lib/types/request-diagnostics.d.ts +278 -0
  157. package/lib/types/request-upload-evidence.d.ts +23 -0
  158. package/lib/types/response-error-body.d.ts +3 -0
  159. package/lib/types/responses-reasoning-text.d.ts +24 -0
  160. package/lib/types/responses-reasoning.d.ts +7 -0
  161. package/lib/types/responses-replay-compat.d.ts +31 -0
  162. package/lib/types/responses-request-compression.d.ts +33 -0
  163. package/lib/types/route-ownership.d.ts +70 -0
  164. package/lib/types/routed-web.d.ts +50 -0
  165. package/lib/types/search-backend.d.ts +16 -0
  166. package/lib/types/search-routing-host.d.ts +19 -0
  167. package/lib/types/search-routing-policy.d.ts +18 -0
  168. package/lib/types/search-routing-remote.d.ts +20 -0
  169. package/lib/types/search-routing.d.ts +43 -0
  170. package/lib/types/search-tool-routing.d.ts +22 -0
  171. package/lib/types/serialize.d.ts +106 -0
  172. package/lib/types/session-accounts-controller.d.ts +20 -0
  173. package/lib/types/session-accounts-host.d.ts +33 -0
  174. package/lib/types/session-accounts-remote.d.ts +114 -0
  175. package/lib/types/session-accounts.d.ts +38 -0
  176. package/lib/types/session-continuation-host.d.ts +45 -0
  177. package/lib/types/session-continuation-remote.d.ts +22 -0
  178. package/lib/types/session-continuation-types.d.ts +62 -0
  179. package/lib/types/session-continuation-ui.d.ts +49 -0
  180. package/lib/types/session-continuation.d.ts +14 -0
  181. package/lib/types/settings-reader.d.ts +16 -0
  182. package/lib/types/sse.d.ts +28 -0
  183. package/lib/types/temporary-models.d.ts +25 -0
  184. package/lib/types/tool-schema-compat.d.ts +17 -0
  185. package/lib/types/traditional-search.d.ts +17 -0
  186. package/lib/types/turn-model-provenance.d.ts +45 -0
  187. package/lib/types/turn-request-models.d.ts +55 -0
  188. package/lib/types/turn-selection-card.d.ts +24 -0
  189. package/lib/types/turn-selection-host.d.ts +35 -0
  190. package/lib/types/turn-selection-remote.d.ts +17 -0
  191. package/lib/types/turn-selection.d.ts +186 -0
  192. package/lib/types/turn-usage-evidence.d.ts +66 -0
  193. package/lib/types/turn-usage-notice.d.ts +7 -0
  194. package/lib/types/types.d.ts +69 -0
  195. package/lib/types/usage.d.ts +26 -0
  196. package/lib/types/watchdog.d.ts +22 -0
  197. package/lib/types/web-delegate.d.ts +12 -0
  198. package/lib/types/web-search-routing-card.d.ts +16 -0
  199. package/lib/types/web-search-routing-config.d.ts +12 -0
  200. package/lib/types/wire-anthropic.d.ts +37 -0
  201. package/lib/types/wire.d.ts +56 -0
  202. package/lib/web-delegate.js +9 -0
  203. package/output/auto-model-mockup/index.html +207 -0
  204. package/package.json +261 -0
  205. package/scripts/analyze-diagnostics.mjs +91 -0
  206. package/scripts/check-search-composition.mjs +191 -0
  207. package/scripts/iteration-review.mjs +53 -0
  208. package/scripts/release-policy.mjs +353 -0
  209. package/scripts/select-core-release.mjs +11 -0
@@ -0,0 +1,485 @@
1
+ import "./copilot-identity-DRZY_d2X.js";
2
+ import { d as diagnosticsReason, u as diagnosticsOutcome } from "./diagnostics-types-CF-qg8Do.js";
3
+ import { i as resolveRequestBudgetPolicy, r as calculateRequestBudget } from "./request-budget-DLY_aRq0.js";
4
+ import z from "@deepseek-ai/schemastery";
5
+ import { LlmError, createUserMessage } from "@deepseek-ai/dsh-llm";
6
+ import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
7
+ import { CommandDefinitionId } from "@deepseek-ai/dsh-commands/brand";
8
+ //#region lib/types/background-compaction.js
9
+ const WAIT_MS = 2147483647;
10
+ const USAGE = "Usage: /copilot-compact [status|cancel|visible-history]. visible-history authorizes one lossy summary without old encrypted reasoning or its embedded summaries; stored source history is unchanged.";
11
+ const FAILED = "COPILOT_BACKGROUND_COMPACTION_FAILED: inspect the native compaction/end record; no success is implied.";
12
+ function failureDetail(cause) {
13
+ const allowed = /* @__PURE__ */ new Set([
14
+ "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH",
15
+ "COPILOT_RESPONSES_REPLAY_UNSUPPORTED",
16
+ "COPILOT_RESPONSES_REPLAY_INVALID_PAYLOAD",
17
+ "CONTEXT_WINDOW_EXCEEDED",
18
+ "COPILOT_MANUAL_RECOVERY_ACCOUNT_PROOF_UNAVAILABLE",
19
+ "COPILOT_MANUAL_RECOVERY_FIXED_PREFIX",
20
+ "COPILOT_MANUAL_RECOVERY_INDIVISIBLE",
21
+ "COPILOT_MANUAL_RECOVERY_CALL_LIMIT",
22
+ "COPILOT_MANUAL_RECOVERY_TOKEN_METER_UNAVAILABLE",
23
+ "COPILOT_MANUAL_RECOVERY_TOKEN_ESTIMATE_INVALID",
24
+ "COPILOT_MANUAL_RECOVERY_EMPTY_SUMMARY",
25
+ "COPILOT_MANUAL_RECOVERY_UNBALANCED",
26
+ "COPILOT_COMPACTION_REPLAY_UNAVAILABLE",
27
+ "COPILOT_COMPACTION_REPLAY_REVOKED"
28
+ ]);
29
+ const visited = /* @__PURE__ */ new Set();
30
+ for (let depth = 0; depth < 8 && cause instanceof Error && !visited.has(cause); depth++) {
31
+ visited.add(cause);
32
+ const code = /^[A-Z][A-Z_]+(?=:|$)/.exec(cause.message)?.[0];
33
+ if (code && allowed.has(code)) return `${code}: compaction failed; stored source history is unchanged.${code === "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH" ? " Review loss of hidden context before explicitly using /copilot-compact visible-history. No automatic retry." : ""} Inspect the native compaction/end record.`;
34
+ cause = cause.cause;
35
+ }
36
+ return FAILED;
37
+ }
38
+ /** Own only admission and job lifetime; the selected engine owns all history transactions. */
39
+ var BackgroundCompaction = class {
40
+ jobs;
41
+ compact;
42
+ warn;
43
+ latest = /* @__PURE__ */ new WeakMap();
44
+ active = /* @__PURE__ */ new Map();
45
+ closed = false;
46
+ constructor(jobs, compact, warn) {
47
+ this.jobs = jobs;
48
+ this.compact = compact;
49
+ this.warn = warn;
50
+ }
51
+ execute(agent, rawInput, signal) {
52
+ if (this.closed) return {
53
+ kind: "error",
54
+ text: "COPILOT_BACKGROUND_COMPACTION_DISPOSED"
55
+ };
56
+ if (signal.aborted) return {
57
+ kind: "error",
58
+ text: "Compaction admission cancelled."
59
+ };
60
+ const action = rawInput.trim();
61
+ if (action !== "" && action !== "status" && action !== "cancel" && action !== "visible-history") return {
62
+ kind: "error",
63
+ text: USAGE
64
+ };
65
+ const id = this.latest.get(agent);
66
+ if (action === "status" || action === "cancel") {
67
+ if (id === void 0) return {
68
+ kind: "error",
69
+ text: "No background compaction job for this Session."
70
+ };
71
+ try {
72
+ if (action === "cancel") return {
73
+ kind: "success",
74
+ text: `${id}: cancellation ${this.jobs.kill(id, agent.id)}.`
75
+ };
76
+ const job = this.jobs.get(id, agent.id);
77
+ return {
78
+ kind: "success",
79
+ text: `${id}: ${job.status}${job.detail ? `; ${job.detail}` : ""}`
80
+ };
81
+ } catch {
82
+ return {
83
+ kind: "error",
84
+ text: "COPILOT_BACKGROUND_COMPACTION_JOB_UNAVAILABLE"
85
+ };
86
+ }
87
+ }
88
+ const existing = this.active.get(agent);
89
+ if (existing !== void 0) return {
90
+ kind: "success",
91
+ text: `${existing.id}: already running; use /copilot-compact status or cancel.`
92
+ };
93
+ const cancel = new AbortController();
94
+ let done;
95
+ try {
96
+ const jobId = this.jobs.start({
97
+ kind: "copilot-compaction",
98
+ label: "Manual Copilot context compaction",
99
+ owner: agent.id,
100
+ run: (job) => {
101
+ job.updateProgress("Compacting context; the original history remains until native commit.");
102
+ done = Promise.resolve().then(async () => {
103
+ try {
104
+ cancel.signal.throwIfAborted();
105
+ const result = await this.compact(agent, cancel.signal, action === "visible-history");
106
+ return {
107
+ status: "completed",
108
+ detail: result === null ? "No compactable history." : `Compacted ${result.shadowedSeqs.length} history items (~${result.shadowedTokenCount} tokens).`
109
+ };
110
+ } catch (cause) {
111
+ if (cancel.signal.aborted) return {
112
+ status: "killed",
113
+ detail: "Compaction cancelled; inspect native history for its transaction outcome."
114
+ };
115
+ const detail = failureDetail(cause);
116
+ this.warn(detail);
117
+ return {
118
+ status: "failed",
119
+ detail
120
+ };
121
+ } finally {
122
+ this.active.delete(agent);
123
+ }
124
+ });
125
+ return {
126
+ cancel: () => {
127
+ cancel.abort();
128
+ },
129
+ done
130
+ };
131
+ }
132
+ });
133
+ if (done === void 0) throw new Error("COPILOT_BACKGROUND_COMPACTION_STARTER_MISSING");
134
+ this.active.set(agent, {
135
+ id: jobId,
136
+ cancel,
137
+ done
138
+ });
139
+ this.latest.set(agent, jobId);
140
+ this.jobs.wait(jobId, WAIT_MS, agent.id).then((view) => {
141
+ if (view.status === "running" || view.status === "stopping") {
142
+ this.warn("COPILOT_BACKGROUND_COMPACTION_OBSERVER_EXPIRED");
143
+ cancel.abort();
144
+ }
145
+ }, () => {
146
+ this.warn("COPILOT_BACKGROUND_COMPACTION_OBSERVER_FAILED");
147
+ cancel.abort();
148
+ });
149
+ return {
150
+ kind: "success",
151
+ text: `${jobId}: background compaction started, not completed. Use /copilot-compact status or /copilot-compact cancel.`
152
+ };
153
+ } catch {
154
+ cancel.abort();
155
+ this.warn("COPILOT_BACKGROUND_COMPACTION_ADMISSION_FAILED");
156
+ return {
157
+ kind: "error",
158
+ text: "COPILOT_BACKGROUND_COMPACTION_ADMISSION_FAILED: jobs and a live Session owner are required."
159
+ };
160
+ }
161
+ }
162
+ async dispose() {
163
+ this.closed = true;
164
+ const work = [...this.active.values()];
165
+ for (const entry of work) entry.cancel.abort();
166
+ await Promise.all(work.map((entry) => entry.done));
167
+ }
168
+ };
169
+ function installBackgroundCompaction(ctx, compact) {
170
+ const controller = new BackgroundCompaction(ctx.jobs, compact, (message) => ctx.logger.warn(message));
171
+ ctx.effect(function* () {
172
+ yield () => controller.dispose();
173
+ yield ctx.jobs.attachController("copilot-background-compaction");
174
+ yield ctx.commands.register({
175
+ definitionId: CommandDefinitionId("dsh-github-copilot/background-compaction"),
176
+ name: "copilot-compact",
177
+ description: "Start background manual compaction, inspect status, or cancel",
178
+ input: { hint: "status | cancel | visible-history (explicit lossy recovery; omit for normal compaction)" },
179
+ handler: (invocation) => controller.execute(invocation.agent, invocation.rawInput, invocation.signal)
180
+ });
181
+ }, "Copilot background compaction");
182
+ }
183
+ //#endregion
184
+ //#region lib/types/compaction-input-estimate.js
185
+ function createCompactionTokenEstimator(meter) {
186
+ const messages = /* @__PURE__ */ new WeakMap();
187
+ const tools = /* @__PURE__ */ new WeakMap();
188
+ const valid = (value) => {
189
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("COPILOT_MANUAL_RECOVERY_TOKEN_ESTIMATE_INVALID");
190
+ return value;
191
+ };
192
+ const price = (message) => {
193
+ let value = messages.get(message);
194
+ if (value === void 0) {
195
+ value = valid(meter.estimateMessage(message));
196
+ messages.set(message, value);
197
+ }
198
+ return value;
199
+ };
200
+ return (input) => {
201
+ let total = 0;
202
+ if (input.tools?.length) {
203
+ let value = tools.get(input.tools);
204
+ if (value === void 0) {
205
+ value = price(createUserMessage({
206
+ source: { kind: "user" },
207
+ content: [{
208
+ type: "text",
209
+ text: JSON.stringify(input.tools)
210
+ }]
211
+ }));
212
+ tools.set(input.tools, value);
213
+ }
214
+ total = value;
215
+ }
216
+ for (const message of input.messages) total = valid(total + price(message));
217
+ return total;
218
+ };
219
+ }
220
+ function compactionSafeBoundaries(messages) {
221
+ const pending = /* @__PURE__ */ new Set();
222
+ const boundaries = [0];
223
+ for (let index = 0; index < messages.length; index++) {
224
+ const message = messages[index];
225
+ if (message.role === "assistant") for (const block of message.content) {
226
+ if (block.type !== "tool-call") continue;
227
+ if (!block.id || pending.has(block.id)) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
228
+ pending.add(block.id);
229
+ }
230
+ if (message.role === "tool" && (!message.toolCallId || !pending.delete(message.toolCallId))) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
231
+ if (pending.size === 0) boundaries.push(index + 1);
232
+ }
233
+ if (pending.size !== 0) throw new Error("COPILOT_MANUAL_RECOVERY_UNBALANCED");
234
+ return boundaries;
235
+ }
236
+ /**
237
+ * Conservative content-byte planning, not provider-exact token accounting.
238
+ * Native admission still checks converted replay, images and the full request.
239
+ */
240
+ function estimateCompactionInputBytes(input) {
241
+ return Buffer.byteLength(JSON.stringify({
242
+ tools: input.tools,
243
+ messages: input.messages.map((message) => ({
244
+ role: message.role,
245
+ content: message.content,
246
+ ...message.role === "tool" ? {
247
+ toolCallId: message.toolCallId,
248
+ isError: message.isError
249
+ } : {}
250
+ }))
251
+ }), "utf8");
252
+ }
253
+ function reduceCompactionInputLimit(input, inputLimit, estimate = estimateCompactionInputBytes) {
254
+ const originalSize = estimate(input);
255
+ const fixedSize = estimate({
256
+ tools: input.tools,
257
+ messages: input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : []
258
+ });
259
+ const prefix = input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : [];
260
+ const messages = input.messages.slice(prefix.length);
261
+ let start = 0;
262
+ let minimum = fixedSize;
263
+ for (const end of compactionSafeBoundaries(messages).slice(1)) {
264
+ minimum = Math.max(minimum, estimate({
265
+ tools: input.tools,
266
+ messages: [...prefix, ...messages.slice(start, end)]
267
+ }));
268
+ start = end;
269
+ }
270
+ if (minimum >= originalSize) throw new Error("COPILOT_MANUAL_RECOVERY_INDIVISIBLE");
271
+ return Math.min(inputLimit, Math.max(minimum, fixedSize + Math.floor((originalSize - fixedSize) / 2)));
272
+ }
273
+ //#endregion
274
+ //#region lib/types/manual-compaction-recovery.js
275
+ function recoverError(code) {
276
+ return /* @__PURE__ */ new Error(`COPILOT_MANUAL_RECOVERY_${code}`);
277
+ }
278
+ function sumUsage(usages) {
279
+ const required = (key) => usages.reduce((sum, usage) => sum + usage[key], 0);
280
+ const optional = (key) => usages.every((usage) => usage[key] !== void 0) ? { [key]: usages.reduce((sum, usage) => sum + usage[key], 0) } : {};
281
+ return {
282
+ inputTokens: required("inputTokens"),
283
+ outputTokens: required("outputTokens"),
284
+ ...optional("totalTokens"),
285
+ ...optional("cacheReadTokens"),
286
+ ...optional("cacheWriteTokens"),
287
+ ...optional("reasoningTokens")
288
+ };
289
+ }
290
+ /**
291
+ * Bounded map/fold. The native engine still owns the only
292
+ * durable transaction, source-stability check, shrink check and cancellation.
293
+ */
294
+ async function summarizeOversizedManualInput(options) {
295
+ const { input, signal, estimate, summarize, makeCheckpoint, assertCurrent } = options;
296
+ const maxCalls = options.maxCalls ?? 16;
297
+ if (!Number.isSafeInteger(maxCalls) || maxCalls < 2 || maxCalls > 32 || !Number.isSafeInteger(options.inputLimit) || options.inputLimit <= 0) throw recoverError("INVALID_POLICY");
298
+ const prefix = input.messages[0]?.role === "system" ? input.messages.slice(0, 1) : [];
299
+ const messages = input.messages.slice(prefix.length);
300
+ if (messages.length === 0) throw recoverError("NO_HISTORY");
301
+ const safeBoundaries = new Set(compactionSafeBoundaries(messages));
302
+ let previous;
303
+ let offset = 0;
304
+ let calls = 0;
305
+ const usages = [];
306
+ while (offset < messages.length) {
307
+ signal.throwIfAborted();
308
+ assertCurrent?.();
309
+ const carry = previous === void 0 ? [] : [makeCheckpoint(previous.summary)];
310
+ const head = [...prefix, ...carry];
311
+ if (estimate({
312
+ tools: input.tools,
313
+ messages: head
314
+ }) >= options.inputLimit) throw recoverError("FIXED_PREFIX");
315
+ let end = offset;
316
+ for (let index = offset + 1; index <= messages.length; index++) {
317
+ if (estimate({
318
+ tools: input.tools,
319
+ messages: [...head, ...messages.slice(offset, index)]
320
+ }) > options.inputLimit) break;
321
+ if (safeBoundaries.has(index)) end = index;
322
+ }
323
+ if (end === offset) throw recoverError("INDIVISIBLE");
324
+ if (++calls > maxCalls) throw recoverError("CALL_LIMIT");
325
+ const result = await summarize({
326
+ tools: input.tools,
327
+ messages: [...head, ...messages.slice(offset, end)]
328
+ });
329
+ signal.throwIfAborted();
330
+ assertCurrent?.();
331
+ if (previous !== void 0 && (result.provider !== previous.provider || result.model !== previous.model || result.maxTokens !== previous.maxTokens)) throw recoverError("ROUTE_CHANGED");
332
+ if (result.summary.length === 0 || result.summary.some((block) => block.type !== "text") || !result.summary.some((block) => block.type === "text" && block.text.trim())) throw recoverError("EMPTY_SUMMARY");
333
+ if (result.usage !== void 0) usages.push(result.usage);
334
+ previous = result;
335
+ offset = end;
336
+ }
337
+ if (previous === void 0) throw recoverError("NO_HISTORY");
338
+ return {
339
+ summary: [...previous.summary],
340
+ provider: previous.provider,
341
+ model: previous.model,
342
+ ...previous.maxTokens === void 0 ? {} : { maxTokens: previous.maxTokens },
343
+ ...usages.length === calls ? { usage: sumUsage(usages) } : {}
344
+ };
345
+ }
346
+ /**
347
+ * Deployment-selected alternative to stock BasicCompactionEngine. Do not
348
+ * mount both: Cordis compaction is a singleton, not an overridable service.
349
+ */
350
+ var CopilotManualRecoveryCompactionEngine = class extends BasicCompactionEngine {
351
+ static Config = z.intersect([BasicCompactionEngine.Config, z.object({ automaticRecovery: z.boolean().default(true) })]);
352
+ manual = /* @__PURE__ */ new WeakMap();
353
+ visibleHistory = /* @__PURE__ */ new WeakSet();
354
+ automaticRecovery;
355
+ constructor(ctx, config = {}) {
356
+ const { automaticRecovery = true, ...nativeConfig } = config;
357
+ if (typeof automaticRecovery !== "boolean") throw recoverError("INVALID_POLICY");
358
+ super(ctx, nativeConfig);
359
+ this.automaticRecovery = automaticRecovery;
360
+ ctx.inject(["commands", "jobs"], (scope) => {
361
+ installBackgroundCompaction(scope, (agent, signal, visibleHistory) => {
362
+ if (!visibleHistory) return this.compactNow(agent, signal);
363
+ if (this.manual.has(agent)) throw recoverError("BUSY");
364
+ this.visibleHistory.add(agent);
365
+ return this.compactNow(agent, signal).finally(() => this.visibleHistory.delete(agent));
366
+ });
367
+ });
368
+ }
369
+ async compactNow(agent, signal, sourceCommandId) {
370
+ this.manual.set(agent, (this.manual.get(agent) ?? 0) + 1);
371
+ try {
372
+ return await super.compactNow(agent, signal, sourceCommandId);
373
+ } finally {
374
+ const remaining = this.manual.get(agent) - 1;
375
+ if (remaining === 0) this.manual.delete(agent);
376
+ else this.manual.set(agent, remaining);
377
+ }
378
+ }
379
+ async summarize(input, agent, signal) {
380
+ const routed = agent.session.requestHeader()?.config;
381
+ const target = routed?.provider && routed.model ? routed : agent.options;
382
+ const policy = this.config.modelPolicies.find((item) => item.provider === target.provider && item.model === target.model);
383
+ const configuredProvider = policy?.summarizationProvider ?? this.config.summarizationProvider;
384
+ const configuredModel = policy?.summarizationModel ?? this.config.summarizationModel;
385
+ const selected = configuredProvider.length > 0 ? {
386
+ provider: configuredProvider,
387
+ model: configuredModel
388
+ } : routed?.provider && routed.model ? routed : {
389
+ provider: agent.options.provider,
390
+ model: agent.options.model
391
+ };
392
+ const summaryProvider = selected.provider;
393
+ const summaryModel = selected.model;
394
+ if (!this.manual.has(agent) && !this.automaticRecovery || summaryProvider !== "github-copilot-preview" || !summaryModel) {
395
+ if (this.visibleHistory.has(agent)) throw new Error("COPILOT_COMPACTION_REPLAY_UNAVAILABLE");
396
+ return super.summarize(input, agent, signal);
397
+ }
398
+ const maxTokens = policy?.maxTokens ?? this.config.maxTokens;
399
+ const operationSignal = signal ?? new AbortController().signal;
400
+ const summarize = () => this.summarizeManaged(input, agent, summaryModel, maxTokens, operationSignal);
401
+ if (!this.visibleHistory.has(agent)) return summarize();
402
+ const recovery = this.ctx.get("githubCopilotCompactionReplay");
403
+ if (!recovery) throw new Error("COPILOT_COMPACTION_REPLAY_UNAVAILABLE");
404
+ return recovery.run(agent.session.id, summaryModel, operationSignal, summarize);
405
+ }
406
+ async summarizeManaged(input, agent, summaryModel, maxTokens, operationSignal) {
407
+ const lease = this.ctx.get("githubCopilotPreview")?.recoveryLimits(summaryModel, agent);
408
+ if (lease === void 0) throw recoverError("ACCOUNT_PROOF_UNAVAILABLE");
409
+ if (this.visibleHistory.has(agent) && lease.api !== "openai-responses") throw new Error("COPILOT_COMPACTION_REPLAY_UNAVAILABLE");
410
+ const agents = this.ctx.get("agents");
411
+ if (this.ctx.get("githubCopilotSessionAccounts") !== void 0 && agents === void 0) throw recoverError("INITIATOR_UNAVAILABLE");
412
+ const summarize = async (candidate) => {
413
+ const observed = this.ctx.get("githubCopilotDiagnostics")?.collector.begin("compaction-summary");
414
+ observed?.stage("summary-attempt");
415
+ try {
416
+ const result = await (agents === void 0 ? super.summarize(candidate, agent, operationSignal) : agents.withInitiator(agent, () => super.summarize(candidate, agent, operationSignal)));
417
+ observed?.finish("success");
418
+ return result;
419
+ } catch (error) {
420
+ const reason = diagnosticsReason(error);
421
+ if (operationSignal.aborted) this.ctx.get("githubCopilotDiagnostics")?.markCompactionCancelled(agent.session);
422
+ observed?.finish(operationSignal.aborted ? "cancelled" : diagnosticsOutcome(reason), reason);
423
+ throw error;
424
+ }
425
+ };
426
+ const budget = calculateRequestBudget(lease.limits, maxTokens, resolveRequestBudgetPolicy(lease.policy));
427
+ if (!budget.ok) throw recoverError(budget.code);
428
+ const meter = this.ctx.get("tokenMeter");
429
+ if (!meter || typeof meter.estimateMessage !== "function") throw recoverError("TOKEN_METER_UNAVAILABLE");
430
+ const estimate = createCompactionTokenEstimator(meter);
431
+ const toolHistoryTokens = estimate({ messages: [createUserMessage({
432
+ source: { kind: "user" },
433
+ content: [{
434
+ type: "text",
435
+ text: JSON.stringify(agent.session.toolHistory())
436
+ }]
437
+ })] });
438
+ let inputLimit = budget.budget.hardInputLimit - 4096 - toolHistoryTokens;
439
+ if (inputLimit <= 0) throw recoverError("FIXED_PREFIX");
440
+ operationSignal.throwIfAborted();
441
+ lease.assertCurrent();
442
+ const originalSize = estimate(input);
443
+ let failedAttempt = false;
444
+ if (originalSize <= inputLimit) try {
445
+ return await summarize(input);
446
+ } catch (error) {
447
+ operationSignal.throwIfAborted();
448
+ if (!(error instanceof LlmError) || error.code !== "CONTEXT_WINDOW_EXCEEDED") throw error;
449
+ lease.assertCurrent();
450
+ inputLimit = reduceCompactionInputLimit(input, inputLimit, estimate);
451
+ failedAttempt = true;
452
+ }
453
+ this.ctx.logger.info("[github-copilot] Segmented compaction recovery started; up to %d additional model calls.", failedAttempt ? 15 : 16);
454
+ const result = await summarizeOversizedManualInput({
455
+ input,
456
+ inputLimit,
457
+ signal: operationSignal,
458
+ estimate,
459
+ maxCalls: failedAttempt ? 15 : 16,
460
+ assertCurrent: lease.assertCurrent,
461
+ makeCheckpoint: (summary) => createUserMessage({
462
+ source: { kind: "user" },
463
+ content: [
464
+ {
465
+ type: "text",
466
+ text: "Prior intermediate checkpoint (merge with newer context):\n<compacted-summary>"
467
+ },
468
+ ...summary,
469
+ {
470
+ type: "text",
471
+ text: "</compacted-summary>"
472
+ }
473
+ ]
474
+ }),
475
+ summarize
476
+ });
477
+ if (failedAttempt) {
478
+ const { usage: _usage, ...unaccounted } = result;
479
+ return unaccounted;
480
+ }
481
+ return result;
482
+ }
483
+ };
484
+ //#endregion
485
+ export { CopilotManualRecoveryCompactionEngine, CopilotManualRecoveryCompactionEngine as default, summarizeOversizedManualInput };