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.
package/lib/index.js CHANGED
@@ -1,12 +1,12 @@
1
+ import { a as selectCompactionReasoning, c as DiagnosticsRowSchema, d as diagnosticsBucket, f as diagnosticsOutcome, i as resolveRequestBudgetPolicy, l as DiagnosticsSnapshotSchema, n as assessRequestBudget, p as diagnosticsReason, r as calculateRequestBudget, s as DIAGNOSTICS_RETENTION_MS, t as DEFAULT_REQUEST_BUDGET_POLICY, u as DiagnosticsViewSchema } from "./request-budget-Cui2hCi1.js";
2
+ import { C as providerErrorMessage, D as onSettingsNamespaceUpdated, E as readCopilotCatalog, O as readConfigValue, S as isAbortError, T as isPluginPreviewProvider, _ as sameCandidates, a as COPILOT_HOSTED_SEARCH_PROVIDER_ID, b as currentSearchSelection, c as applyRequestAuth, d as ANTHROPIC_WEB_SEARCH_TOOL_TYPE, f as GITHUB_COPILOT_CREDENTIAL_KEY$1, g as candidatesForRoute, h as WEB_SEARCH_TOOL_TYPE, i as describeSearchBackend, k as readSettingsNamespace, l as normalizeRequestAuth, m as SearchPlan, n as routeSessionSearch, o as GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID, p as RESPONSES_WEB_SEARCH_TOOL_TYPE, r as DescribedSearchFallbackError, s as createTraditionalSearchProvider, t as isCopilotSearchSelection, u as providerRequestHeaders, v as currentChatRoute, w as readBounded, x as abortable$1, y as currentSearchInitiator } from "./search-routing-CV2hs8as.js";
1
3
  import { a as GITHUB_COPILOT_PREVIEW_PROVIDER_ID, i as GITHUB_COPILOT_CREDENTIAL_KEY, n as GITHUB_COPILOT_AUTO_INTELLIGENCE_MODEL_ID, o as GITHUB_COPILOT_PROVIDER_ID, r as GITHUB_COPILOT_AUTO_MODEL_ID, s as autoModelPreference, t as GITHUB_COPILOT_AUTO_EFFICIENCY_MODEL_ID } from "./copilot-identity-DRZY_d2X.js";
2
- import { C as providerErrorMessage, D as readSettingsNamespace, E as readConfigValue, O as isPluginPreviewProvider, S as isAbortError, T as onSettingsNamespaceUpdated, _ as sameCandidates, a as COPILOT_HOSTED_SEARCH_PROVIDER_ID, b as currentSearchSelection, c as applyRequestAuth, d as ANTHROPIC_WEB_SEARCH_TOOL_TYPE, f as GITHUB_COPILOT_CREDENTIAL_KEY$1, g as candidatesForRoute, h as WEB_SEARCH_TOOL_TYPE, i as describeSearchBackend, k as readCopilotCatalog, l as normalizeRequestAuth, m as SearchPlan, n as routeSessionSearch, o as GITHUB_COPILOT_HOSTED_SEARCH_PROVIDER_ID, p as RESPONSES_WEB_SEARCH_TOOL_TYPE, r as DescribedSearchFallbackError, s as createTraditionalSearchProvider, t as isCopilotSearchSelection, u as providerRequestHeaders, v as currentChatRoute, w as readBounded, x as abortable$1, y as currentSearchInitiator } from "./search-routing-CHyF6TbO.js";
3
- import { a as selectCompactionReasoning, i as resolveRequestBudgetPolicy, n as assessRequestBudget, r as calculateRequestBudget, t as DEFAULT_REQUEST_BUDGET_POLICY } from "./request-budget-DLY_aRq0.js";
4
+ import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
5
+ import { z } from "zod";
4
6
  import AuthorizationService from "@deepseek-ai/dsh-authorization";
5
7
  import { createHash, randomUUID } from "node:crypto";
6
8
  import * as dshScope from "@deepseek-ai/dsh-scope";
7
- import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
8
- import z from "@deepseek-ai/schemastery";
9
- import { z as z$1 } from "zod";
9
+ import z$1 from "@deepseek-ai/schemastery";
10
10
  import { getCACertificates } from "node:tls";
11
11
  import { Agent } from "undici";
12
12
  import { createModels, getSupportedThinkingLevels, hasApi, lazyStream } from "@earendil-works/pi-ai";
@@ -22,282 +22,1120 @@ import { CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, ReasoningEffortId, attributionH
22
22
  import { setImmediate } from "node:timers/promises";
23
23
  import { Config as Config$1, PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
24
24
  import { estimateContextTokens, estimateMessageTokens } from "@earendil-works/pi-ai/utils/estimate";
25
- //#region lib/types/dual-model-host.js
26
- /** Retired planner/executor entry points; retained policies stay enforceable without migration. */
27
- var __runInitializers$8 = function(thisArg, initializers, value) {
28
- var useValue = arguments.length > 2;
29
- for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
30
- return useValue ? value : void 0;
25
+ //#region lib/types/diagnostics-collector.js
26
+ const noop = {
27
+ stage() {},
28
+ finish() {}
31
29
  };
32
- var __esDecorate$8 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
33
- function accept(f) {
34
- if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
35
- return f;
30
+ function emptyDiagnostics() {
31
+ return {
32
+ schemaVersion: 1,
33
+ coverageVersion: 1,
34
+ epoch: 0,
35
+ updatedAt: 0,
36
+ rows: [],
37
+ pending: [],
38
+ dropped: 0,
39
+ clientDropped: 0,
40
+ clientUnconfirmed: 0,
41
+ saturated: 0,
42
+ evicted: 0,
43
+ interrupted: 0
44
+ };
45
+ }
46
+ /** Only fixed dimensions cross this boundary; live handles never leave the owner. */
47
+ var DiagnosticsCollector = class {
48
+ version;
49
+ layer;
50
+ changed;
51
+ wall;
52
+ mono;
53
+ data = emptyDiagnostics();
54
+ live = /* @__PURE__ */ new Set();
55
+ enabled = false;
56
+ lastWall = 0;
57
+ constructor(version, layer, changed = () => {}, wall = Date.now, mono = () => performance.now()) {
58
+ this.version = version;
59
+ this.layer = layer;
60
+ this.changed = changed;
61
+ this.wall = wall;
62
+ this.mono = mono;
63
+ }
64
+ restore(snapshot) {
65
+ this.data = DiagnosticsSnapshotSchema.parse(snapshot);
66
+ this.lastWall = this.data.updatedAt;
67
+ for (const pending of this.data.pending) {
68
+ this.add(pending.operation, pending.stage, "interrupted", "unknown", pending.bucket, pending.count, pending.version);
69
+ this.increment("interrupted", pending.count);
70
+ }
71
+ this.data.pending = [];
72
+ this.expire();
73
+ }
74
+ setEnabled(enabled) {
75
+ if (enabled === this.enabled) return;
76
+ if (enabled) this.assertCanEnable();
77
+ if (this.enabled && !enabled) {
78
+ for (const live of this.live) this.settle(live, "interrupted", "unknown");
79
+ this.add("collection", "admitted", "paused", "none", 0);
80
+ }
81
+ if (this.data.epoch >= Number.MAX_SAFE_INTEGER) {
82
+ this.enabled = false;
83
+ this.increment("saturated");
84
+ this.changed();
85
+ return;
86
+ }
87
+ this.data.epoch++;
88
+ this.enabled = enabled;
89
+ this.changed();
36
90
  }
37
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
38
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
39
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
40
- var _, done = false;
41
- for (var i = decorators.length - 1; i >= 0; i--) {
42
- var context = {};
43
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
44
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
45
- context.addInitializer = function(f) {
46
- if (done) throw new TypeError("Cannot add initializers after decoration has completed");
47
- extraInitializers.push(accept(f || null));
91
+ assertCanEnable() {
92
+ if (!this.enabled && this.data.epoch >= Number.MAX_SAFE_INTEGER) throw new Error("COPILOT_DIAGNOSTICS_EPOCH_LIMIT");
93
+ }
94
+ clear() {
95
+ const epoch = this.data.epoch + 1;
96
+ if (!Number.isSafeInteger(epoch)) throw new Error("COPILOT_DIAGNOSTICS_EPOCH_LIMIT");
97
+ this.live.clear();
98
+ this.data = {
99
+ ...emptyDiagnostics(),
100
+ epoch
101
+ };
102
+ this.changed();
103
+ }
104
+ begin(operation) {
105
+ if (!this.enabled) return noop;
106
+ if (this.live.size >= 128) {
107
+ this.increment("dropped");
108
+ this.changed();
109
+ return noop;
110
+ }
111
+ const live = {
112
+ operation,
113
+ stage: "admitted",
114
+ start: this.mono(),
115
+ epoch: this.data.epoch
116
+ };
117
+ this.live.add(live);
118
+ this.add(operation, live.stage, "started", "none", 0);
119
+ return {
120
+ stage: (stage) => {
121
+ if (!this.live.has(live) || live.epoch !== this.data.epoch) return;
122
+ live.stage = stage;
123
+ this.add(operation, stage, "stage", "none", this.age(live));
124
+ },
125
+ finish: (outcome, reason = "none") => this.settle(live, outcome, reason)
48
126
  };
49
- var result = (0, decorators[i])(kind === "accessor" ? {
50
- get: descriptor.get,
51
- set: descriptor.set
52
- } : descriptor[key], context);
53
- if (kind === "accessor") {
54
- if (result === void 0) continue;
55
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
56
- if (_ = accept(result.get)) descriptor.get = _;
57
- if (_ = accept(result.set)) descriptor.set = _;
58
- if (_ = accept(result.init)) initializers.unshift(_);
59
- } else if (_ = accept(result)) {
60
- if (kind === "field") initializers.unshift(_);
61
- else descriptor[key] = _;
62
- }
63
127
  }
64
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
65
- done = true;
66
- };
67
- const DUAL_MODEL_NAMESPACE = "github-copilot-dual-model";
68
- const DUAL_MODEL_PROJECTION = "githubCopilotDualModelPolicy";
69
- const DUAL_MODEL_EXECUTE_TOOL = "copilot_execute";
70
- const DEFAULT_CONFIG = Object.freeze({
71
- enabled: false,
72
- plannerModel: "",
73
- executorModel: ""
74
- });
75
- const configSchema = z.object({
76
- enabled: z.boolean().default(false),
77
- plannerModel: z.string().default(""),
78
- executorModel: z.string().default("")
79
- });
80
- const ConfigJson = z$1.object({
81
- enabled: z$1.boolean(),
82
- plannerModel: z$1.string().max(512),
83
- executorModel: z$1.string().max(512)
84
- }).strict();
85
- const RevisionJson = z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
86
- const CreateJson = z$1.object({
87
- requestId: z$1.string().uuid(),
88
- workspaceId: z$1.string().min(1).max(512),
89
- expectedRevision: RevisionJson
90
- }).strict();
91
- const SaveJson = z$1.object({
92
- configuration: ConfigJson,
93
- expectedRevision: RevisionJson
94
- }).strict();
95
- const ExecuteJson = z$1.object({
96
- description: z$1.string().min(1).max(160),
97
- prompt: z$1.string().min(1).max(1e5)
98
- }).strict();
99
- const PolicyJson = z$1.object({
100
- version: z$1.literal(1),
101
- rootSessionId: z$1.string(),
102
- requestId: z$1.string(),
103
- workspaceId: z$1.string(),
104
- settingsRevision: z$1.number().int().nonnegative(),
105
- cwd: z$1.string(),
106
- agentPreset: z$1.string(),
107
- provider: z$1.literal(GITHUB_COPILOT_PREVIEW_PROVIDER_ID),
108
- plannerModel: z$1.string().min(1),
109
- executorModel: z$1.string().min(1),
110
- executorTools: z$1.array(z$1.string()),
111
- plannerTools: z$1.array(z$1.string())
112
- }).strict();
113
- const ChildJson = z$1.object({
114
- version: z$1.literal(3),
115
- mode: z$1.literal("continuable"),
116
- provider: z$1.literal("spawn"),
117
- agentProvider: z$1.string(),
118
- agentModel: z$1.string()
119
- }).strict();
120
- const ChildWireJson = ChildJson.extend({
121
- label: z$1.string(),
122
- agentReasoningEffort: z$1.string().optional(),
123
- persona: z$1.string().optional(),
124
- toolFilter: z$1.object({
125
- allow: z$1.array(z$1.string()).optional(),
126
- deny: z$1.array(z$1.string()).optional()
127
- }).strict().refine((value) => value.allow !== void 0 || value.deny !== void 0).optional()
128
- }).strict().transform(({ version, mode, provider, agentProvider, agentModel }) => ({
129
- version,
130
- mode,
131
- provider,
132
- agentProvider,
133
- agentModel
134
- }));
135
- const ProjectionJson = z$1.object({
136
- id: z$1.string(),
137
- parentId: z$1.string().nullable(),
138
- origin: z$1.string().nullable(),
139
- inherited: z$1.number(),
140
- policy: PolicyJson.nullable(),
141
- child: ChildJson.nullable(),
142
- invalid: z$1.boolean()
143
- });
144
- /** A root policy is authoritative only in its own suffix, never in a fork seed. */
145
- const dualModelProjection = {
146
- key: DUAL_MODEL_PROJECTION,
147
- stateVersion: 2,
148
- stateSchema: ProjectionJson,
149
- init: (header, inherited = 0) => ({
150
- id: header.id,
151
- parentId: header.parentSession ?? null,
152
- origin: header.origin ?? null,
153
- inherited,
154
- policy: null,
155
- child: null,
156
- invalid: false
157
- }),
158
- apply: (state, event) => {
159
- if (event.seq < state.inherited) return state;
160
- if (event.type === "github-copilot/dual-model-policy") {
161
- const parsed = PolicyJson.safeParse(event.data);
162
- if (state.policy !== null || !parsed.success || parsed.data.rootSessionId !== state.id || state.parentId !== null || event.ignorable !== true) return {
163
- ...state,
164
- invalid: true
165
- };
166
- return {
167
- ...state,
168
- policy: parsed.data
169
- };
128
+ settle(live, outcome, reason) {
129
+ if (!this.live.delete(live) || live.epoch !== this.data.epoch) return;
130
+ this.add(live.operation, live.stage, outcome, reason, this.age(live));
131
+ if (outcome === "interrupted") this.increment("interrupted");
132
+ }
133
+ age(live) {
134
+ return diagnosticsBucket(Math.max(0, this.mono() - live.start));
135
+ }
136
+ increment(field, amount = 1) {
137
+ if (field !== "saturated" && this.data[field] > Number.MAX_SAFE_INTEGER - amount) this.data.saturated = Math.min(Number.MAX_SAFE_INTEGER, this.data.saturated + 1);
138
+ this.data[field] = Math.min(Number.MAX_SAFE_INTEGER, this.data[field] + amount);
139
+ }
140
+ expire() {
141
+ const now = this.wall();
142
+ const oldest = Math.floor((now - DIAGNOSTICS_RETENTION_MS) / 36e5) * 36e5;
143
+ const kept = this.data.rows.filter((row) => row.hour > oldest);
144
+ this.increment("evicted", this.data.rows.length - kept.length);
145
+ if (kept.length !== this.data.rows.length) this.changed();
146
+ this.data.rows = kept;
147
+ }
148
+ add(operation, stage, metric, reason, bucket, count = 1, version = this.version) {
149
+ this.expire();
150
+ const now = this.wall();
151
+ const discontinuity = now < this.lastWall;
152
+ this.lastWall = now;
153
+ const row = {
154
+ hour: Math.floor(now / 36e5) * 36e5,
155
+ version,
156
+ layer: this.layer,
157
+ operation,
158
+ stage,
159
+ metric,
160
+ reason,
161
+ bucket,
162
+ count
163
+ };
164
+ const existing = this.data.rows.find((item) => item.hour === row.hour && item.version === row.version && item.layer === row.layer && item.operation === operation && item.stage === stage && item.metric === metric && item.reason === reason && item.bucket === bucket);
165
+ if (existing) {
166
+ if (existing.count > Number.MAX_SAFE_INTEGER - count) this.increment("saturated");
167
+ existing.count = Math.min(Number.MAX_SAFE_INTEGER, existing.count + count);
168
+ } else {
169
+ if (this.data.rows.length >= 4096) {
170
+ const index = this.oldestIndex();
171
+ this.increment("evicted");
172
+ if (row.hour < this.data.rows[index].hour) {
173
+ this.changed();
174
+ return;
175
+ }
176
+ this.data.rows.splice(index, 1);
177
+ }
178
+ this.data.rows.push(row);
179
+ }
180
+ this.changed();
181
+ if (discontinuity) this.add("collection", "admitted", "clock-discontinuity", "unknown", 0);
182
+ }
183
+ oldestIndex() {
184
+ let index = 0;
185
+ for (let candidate = 1; candidate < this.data.rows.length; candidate++) if (this.data.rows[candidate].hour < this.data.rows[index].hour) index = candidate;
186
+ return index;
187
+ }
188
+ snapshot() {
189
+ this.expire();
190
+ const pending = [];
191
+ for (const live of this.live) {
192
+ const bucket = this.age(live);
193
+ const existing = pending.find((row) => row.operation === live.operation && row.stage === live.stage && row.bucket === bucket);
194
+ if (existing) existing.count++;
195
+ else pending.push({
196
+ version: this.version,
197
+ operation: live.operation,
198
+ stage: live.stage,
199
+ bucket,
200
+ count: 1
201
+ });
170
202
  }
171
- if (event.type === "subagent/descriptor" && state.origin === "subagent") {
172
- const parsed = ChildWireJson.safeParse(event.data);
173
- if (state.child !== null || !parsed.success) return {
174
- ...state,
175
- child: null,
176
- invalid: true
177
- };
178
- return {
179
- ...state,
180
- child: parsed.data
181
- };
203
+ return DiagnosticsSnapshotSchema.parse({
204
+ ...this.data,
205
+ updatedAt: this.wall(),
206
+ pending
207
+ });
208
+ }
209
+ close() {
210
+ this.setEnabled(false);
211
+ }
212
+ noteDropped() {
213
+ if (this.enabled) {
214
+ this.increment("dropped");
215
+ this.changed();
216
+ }
217
+ }
218
+ noteClientGaps(dropped, unconfirmed) {
219
+ if (!this.enabled) return;
220
+ this.increment("clientDropped", dropped);
221
+ this.increment("clientUnconfirmed", unconfirmed);
222
+ if (dropped || unconfirmed) this.changed();
223
+ }
224
+ mergeClient(rows) {
225
+ if (!this.enabled) return;
226
+ const now = this.wall();
227
+ for (const row of rows) {
228
+ if (row.layer !== "client" || row.hour > now || row.hour <= now - 12096e5) {
229
+ this.noteDropped();
230
+ continue;
231
+ }
232
+ const existing = this.data.rows.find((item) => Object.keys(row).every((key) => key === "count" || Reflect.get(item, key) === Reflect.get(row, key)));
233
+ if (existing) {
234
+ if (existing.count > Number.MAX_SAFE_INTEGER - row.count) this.increment("saturated");
235
+ existing.count = Math.min(Number.MAX_SAFE_INTEGER, existing.count + row.count);
236
+ } else {
237
+ if (this.data.rows.length >= 4096) {
238
+ const index = this.oldestIndex();
239
+ this.increment("evicted");
240
+ if (row.hour < this.data.rows[index].hour) {
241
+ this.changed();
242
+ continue;
243
+ }
244
+ this.data.rows.splice(index, 1);
245
+ }
246
+ this.data.rows.push({ ...row });
247
+ }
248
+ this.changed();
182
249
  }
183
- return state;
184
250
  }
185
251
  };
186
- const EXECUTOR_PERSONA = "You are the execution agent for a dedicated Copilot planner/executor session. Implement only the delegated task. Your provider and model are fixed by the session policy. Do not create other agents, workflows, dynamic plugins, or alternate model calls. Report the changed files, verification, limitations, and actual results to your direct parent with send_message. Do not claim tests or work you did not perform.";
187
- function roleText(policy, role) {
188
- return role === "planner" ? `You are the planning and acceptance agent. Read the current code and evidence, plan, clarify, delegate implementation through ${DUAL_MODEL_EXECUTE_TOOL}, and independently review results. Do not implement changes or run commands directly. Your planning model is ${policy.plannerModel}; execution is fixed to ${policy.executorModel}. Use the original send_message/list_agents/interrupt_agent controls to continue and inspect your execution children. Provider: ${GITHUB_COPILOT_PREVIEW_PROVIDER_ID}.` : EXECUTOR_PERSONA;
189
- }
190
- function fail$2(reason, creation) {
191
- throw new RemoteError("copilot/dual-model", reason, {
192
- reason,
193
- ...creation === void 0 ? {} : { creation }
194
- });
195
- }
196
- function creationOf(error) {
197
- return ownRemoteFailure(error)?.creation ?? "uncertain";
198
- }
199
- function object$8(value) {
200
- return typeof value === "object" && value !== null && !Array.isArray(value);
201
- }
202
- function api$1(ctx, key, methods) {
203
- const value = ctx.get(key);
204
- return object$8(value) && methods.every((method) => typeof value[method] === "function") ? value : void 0;
205
- }
206
- function revision(value) {
207
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
252
+ //#endregion
253
+ //#region lib/types/remote-codec.js
254
+ /** Client-safe bridge between legacy schema codecs and alpha.2 create factories. */
255
+ function strictRemoteCodec(typeSymbol, schema) {
256
+ return {
257
+ mode: "strict",
258
+ typeSymbol,
259
+ schema,
260
+ create: () => schema
261
+ };
208
262
  }
209
- const ERROR_REASONS = /* @__PURE__ */ new Set([
210
- "DUAL_MODEL_RETIRED",
211
- "DUAL_MODEL_UNSUPPORTED",
212
- "DUAL_MODEL_READ_ONLY",
213
- "DUAL_MODEL_REVISION_CONFLICT",
214
- "DUAL_MODEL_MODEL_UNAVAILABLE",
215
- "DUAL_MODEL_WORKSPACE_UNAVAILABLE",
216
- "DUAL_MODEL_DISABLED",
217
- "DUAL_MODEL_INVALID_REQUEST",
218
- "DUAL_MODEL_REQUEST_CONFLICT",
219
- "DUAL_MODEL_SAVE_FAILED",
220
- "DUAL_MODEL_CREATE_UNCERTAIN",
221
- "DUAL_MODEL_POLICY_INVALID",
222
- "DUAL_MODEL_SELECTION_LOCKED",
223
- "DUAL_MODEL_DELEGATION_DENIED",
224
- "DUAL_MODEL_EXECUTION_FAILED"
225
- ]);
226
- /** Remote errors cross bundle/realm boundaries; constructor identity is not a protocol. */
227
- function ownRemoteFailure(error) {
228
- try {
229
- if (!object$8(error) || error.isDSHRemoteError !== true || error.code !== "copilot/dual-model" || !object$8(error.details)) return void 0;
230
- const reason = error.details.reason;
231
- if (typeof reason !== "string" || !ERROR_REASONS.has(reason)) return void 0;
232
- const creation = error.details.creation;
233
- return {
234
- reason,
235
- ...creation === "not-created" || creation === "uncertain" ? { creation } : {}
236
- };
237
- } catch {
238
- return;
263
+ //#endregion
264
+ //#region lib/types/diagnostics-remote.js
265
+ const ClientDiagnosticsBatchSchema = z.object({
266
+ epoch: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
267
+ rows: z.array(DiagnosticsRowSchema.refine((row) => row.layer === "client")).max(128),
268
+ dropped: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
269
+ unconfirmed: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()
270
+ }).strict();
271
+ const result$1 = strictRemoteCodec("dsh-github-copilot#DiagnosticsView", DiagnosticsViewSchema);
272
+ [
273
+ {
274
+ method: "get",
275
+ parameters: []
276
+ },
277
+ {
278
+ method: "clear",
279
+ parameters: []
280
+ },
281
+ {
282
+ method: "setEnabled",
283
+ parameters: [{
284
+ name: "enabled",
285
+ wire: "enabled",
286
+ source: "json",
287
+ codec: strictRemoteCodec("dsh-github-copilot#DiagnosticsEnabled", z.boolean())
288
+ }]
289
+ },
290
+ {
291
+ method: "recordClient",
292
+ parameters: [{
293
+ name: "batch",
294
+ wire: "batch",
295
+ source: "json",
296
+ codec: strictRemoteCodec("dsh-github-copilot#ClientDiagnosticsBatch", ClientDiagnosticsBatchSchema)
297
+ }]
239
298
  }
240
- }
241
- function reasonOf(error, fallback) {
242
- const own = ownRemoteFailure(error);
243
- if (own) return own.reason;
244
- try {
245
- if (object$8(error) && error.code === "SETTINGS_CONFLICT") return "DUAL_MODEL_REVISION_CONFLICT";
246
- } catch {}
247
- return fallback;
248
- }
249
- function dualModelSessionId(requestId) {
250
- return `copilot-dual-${createHash("sha256").update(requestId).digest("hex")}`;
251
- }
252
- function requestKey(request) {
253
- return JSON.stringify([
254
- request.requestId,
255
- request.workspaceId,
256
- request.expectedRevision
257
- ]);
258
- }
259
- function policyMatches(policy, request) {
260
- return policy.requestId === request.requestId && policy.workspaceId === request.workspaceId && policy.settingsRevision === request.expectedRevision;
261
- }
262
- function dedicatedAddress(agent) {
263
- const owned = /^copilot-dual-[0-9a-f]{64}$/;
264
- return owned.test(agent.id) || agent.session.header.origin === "subagent" && owned.test(agent.session.header.parentSession ?? "");
265
- }
266
- let GitHubCopilotDualModel = (() => {
267
- let _classSuper = TypertRemoteService;
268
- let _instanceExtraInitializers = [];
269
- let _view_decorators;
270
- let _save_decorators;
271
- let _create_decorators;
272
- return class GitHubCopilotDualModel extends _classSuper {
273
- static {
274
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
275
- _view_decorators = [Remote];
276
- _save_decorators = [Remote];
277
- _create_decorators = [Remote];
278
- __esDecorate$8(this, null, _view_decorators, {
279
- kind: "method",
280
- name: "view",
281
- static: false,
282
- private: false,
283
- access: {
284
- has: (obj) => "view" in obj,
285
- get: (obj) => obj.view
286
- },
287
- metadata: _metadata
288
- }, null, _instanceExtraInitializers);
289
- __esDecorate$8(this, null, _save_decorators, {
290
- kind: "method",
291
- name: "save",
292
- static: false,
293
- private: false,
294
- access: {
295
- has: (obj) => "save" in obj,
296
- get: (obj) => obj.save
297
- },
298
- metadata: _metadata
299
- }, null, _instanceExtraInitializers);
300
- __esDecorate$8(this, null, _create_decorators, {
299
+ ].map((descriptor) => ({
300
+ ...descriptor,
301
+ id: `dsh-github-copilot:githubCopilotDiagnostics.${descriptor.method}`,
302
+ namespace: "githubCopilotDiagnostics",
303
+ service: "githubCopilotDiagnostics",
304
+ invocation: { kind: "direct" },
305
+ result: result$1
306
+ }));
307
+ //#endregion
308
+ //#region package.json
309
+ var package_default = {
310
+ name: "dsh-github-copilot",
311
+ description: "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
312
+ version: "0.4.0-alpha.123",
313
+ publishConfig: {
314
+ "access": "public",
315
+ "registry": "https://registry.npmjs.org/",
316
+ "tag": "alpha"
317
+ },
318
+ packageManager: "pnpm@11.7.0",
319
+ repository: {
320
+ "type": "git",
321
+ "url": "git+https://github.com/cloga/dsh-github-copilot.git"
322
+ },
323
+ type: "module",
324
+ exports: {
325
+ ".": {
326
+ "types": "./lib/types/index.d.ts",
327
+ "default": "./lib/index.js"
328
+ },
329
+ "./client": {
330
+ "types": "./lib/types/client.d.ts",
331
+ "default": "./lib/client.js"
332
+ },
333
+ "./remote": {
334
+ "types": "./lib/types/remote.d.ts",
335
+ "default": "./lib/remote.js"
336
+ },
337
+ "./web-delegate": {
338
+ "types": "./lib/types/web-delegate.d.ts",
339
+ "default": "./lib/web-delegate.js"
340
+ },
341
+ "./routed-web": {
342
+ "types": "./lib/types/routed-web.d.ts",
343
+ "default": "./lib/routed-web.js"
344
+ },
345
+ "./manual-compaction-recovery": {
346
+ "types": "./lib/types/manual-compaction-recovery.d.ts",
347
+ "default": "./lib/manual-compaction-recovery.js"
348
+ },
349
+ "./deployment-baseline.json": "./deployment-baseline.json",
350
+ "./package.json": "./package.json"
351
+ },
352
+ files: [
353
+ "cordis.patch.yml",
354
+ "deployment-baseline.json",
355
+ "lib/*.js",
356
+ "lib/*.js.map",
357
+ "lib/types/**/*.d.ts",
358
+ "README.md",
359
+ "README.zh.md",
360
+ "CHANGELOG.md",
361
+ "CONTRIBUTING.md",
362
+ "SECURITY.md",
363
+ "AGENTS.md",
364
+ "docs/agent-readiness.md",
365
+ "docs/model-compatibility-acceptance.md",
366
+ "docs/single-route-migration.md",
367
+ "docs/session-search-routing.md",
368
+ "docs/npm-distribution.md",
369
+ "docs/dual-model.md",
370
+ "docs/official-first-016-alpha2.md",
371
+ "docs/official-first-020-rc1.md",
372
+ "docs/official-first-020-rc2.md",
373
+ "docs/web-lifecycle-rc2.md",
374
+ "docs/copilot-compaction.md",
375
+ "docs/manual-compaction-recovery.md",
376
+ "docs/copilot-usage.md",
377
+ "docs/copilot-accounts.md",
378
+ "docs/session-continuation.md",
379
+ "docs/account-management-experience.md",
380
+ "docs/mockups/copilot-account-management.html",
381
+ "docs/mockups/copilot-account-dropdown.html",
382
+ "docs/automatic-model-routing.md",
383
+ "docs/auto-task-routing.md",
384
+ "docs/auto-high-cost.md",
385
+ "docs/evidence-driven-iteration.md",
386
+ "docs/plugin-diagnostics.md",
387
+ "docs/auto-iteration-review.json",
388
+ "scripts/iteration-review.mjs",
389
+ "docs/image-input-compatibility.md",
390
+ "output/auto-model-mockup/index.html",
391
+ "docs/images/dual-model-provenance.json",
392
+ "scripts/check-search-composition.mjs",
393
+ "docs/images/"
394
+ ],
395
+ keywords: [
396
+ "dsh",
397
+ "deepseek-harness",
398
+ "plugin",
399
+ "cordis",
400
+ "github-copilot",
401
+ "oauth",
402
+ "model-provider",
403
+ "hosted-search",
404
+ "web-search",
405
+ "openai-responses",
406
+ "typescript"
407
+ ],
408
+ license: "MIT",
409
+ engines: {
410
+ "node": ">=22.19.0",
411
+ "dsh": "0.2.0-rc.2"
412
+ },
413
+ scripts: {
414
+ "build": "pnpm clean && tsc -p tsconfig.json && tsdown",
415
+ "clean": "node -e \"require('node:fs').rmSync('lib', { recursive: true, force: true })\"",
416
+ "prepare": "tsc -p tsconfig.json && tsdown",
417
+ "prepack": "pnpm verify:baseline",
418
+ "test": "vitest run",
419
+ "test:watch": "vitest",
420
+ "typecheck": "tsc -p tsconfig.json --noEmit",
421
+ "typecheck:tests": "tsc -p tsconfig.tests.json",
422
+ "test:scripts": "node --test \"tests/scripts/*.test.mjs\"",
423
+ "agent:describe": "node scripts/agent.mjs describe --json",
424
+ "agent:doctor": "node scripts/agent.mjs doctor --json",
425
+ "agent:plan": "node scripts/agent.mjs plan",
426
+ "preflight:search": "node scripts/check-search-composition.mjs",
427
+ "verify:agent": "node scripts/verify-agent-contract.mjs",
428
+ "verify:tarball": "node scripts/verify-tarball.mjs",
429
+ "verify:baseline": "node scripts/verify-deployment-baseline.mjs",
430
+ "verify:package": "node scripts/verify-package.mjs",
431
+ "verify:controlled-core": "node scripts/verify-controlled-core.mjs",
432
+ "verify:reasoning-ui": "node scripts/verify-reasoning-presentation.mjs",
433
+ "verify:upstream": "node scripts/verify-upstream-baseline.mjs",
434
+ "release:check": "node scripts/release-policy.mjs",
435
+ "verify": "pnpm verify:agent && pnpm typecheck && pnpm typecheck:tests && pnpm verify:baseline && pnpm build && pnpm test && pnpm test:scripts && pnpm verify:package"
436
+ },
437
+ peerDependencies: {
438
+ "@deepseek-ai/cordis": "^4.0.4",
439
+ "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
440
+ "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
441
+ "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
442
+ "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
443
+ "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
444
+ "@deepseek-ai/dsh-api-remotes": "0.2.0-rc.2",
445
+ "@deepseek-ai/dsh-authorization": "0.2.0-rc.2",
446
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
447
+ "@deepseek-ai/dsh-client-ui-settings-models": "0.2.0-rc.2",
448
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
449
+ "@deepseek-ai/dsh-credentials": "0.2.0-rc.2",
450
+ "@deepseek-ai/dsh-launch-environment": "0.2.0-rc.2",
451
+ "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
452
+ "@deepseek-ai/dsh-llm-pi-ai": "0.2.0-rc.2",
453
+ "@deepseek-ai/dsh-session": "0.2.0-rc.2",
454
+ "@deepseek-ai/dsh-scope": "0.2.0-rc.2",
455
+ "@deepseek-ai/dsh-settings": "0.2.0-rc.2",
456
+ "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
457
+ "@deepseek-ai/dsh-web": "0.2.0-rc.2",
458
+ "@deepseek-ai/dsh-web-search-deepseek": "0.2.0-rc.2",
459
+ "@deepseek-ai/schemastery": "^3.18.4"
460
+ },
461
+ peerDependenciesMeta: {
462
+ "@deepseek-ai/dsh-web-search-deepseek": { "optional": true },
463
+ "@deepseek-ai/dsh-launch-environment": { "optional": true },
464
+ "@deepseek-ai/dsh-api-remotes": { "optional": true },
465
+ "@deepseek-ai/dsh-client-ui-renderer": { "optional": true },
466
+ "@deepseek-ai/dsh-client-ui-settings-models": { "optional": true },
467
+ "@deepseek-ai/dsh-client-ui-slots": { "optional": true },
468
+ "@deepseek-ai/dsh-typert-protocol": { "optional": true }
469
+ },
470
+ dependencies: {
471
+ "@earendil-works/pi-ai": "0.87.1",
472
+ "undici": "6.28.1",
473
+ "zod": "4.6.5"
474
+ },
475
+ devDependencies: {
476
+ "@deepseek-ai/cordis": "~4.0.4",
477
+ "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
478
+ "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
479
+ "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
480
+ "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
481
+ "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
482
+ "@deepseek-ai/dsh-jobs": "0.2.0-rc.2",
483
+ "@deepseek-ai/dsh-api-gateway": "0.2.0-rc.2",
484
+ "@deepseek-ai/dsh-api-remotes": "0.2.0-rc.2",
485
+ "@deepseek-ai/dsh-app-boot": "0.2.0-rc.2",
486
+ "@deepseek-ai/dsh-config-editor": "0.2.0-rc.2",
487
+ "@deepseek-ai/dsh-attachment": "0.2.0-rc.2",
488
+ "@deepseek-ai/dsh-authorization": "0.2.0-rc.2",
489
+ "@deepseek-ai/dsh-client-connection": "0.2.0-rc.2",
490
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
491
+ "@deepseek-ai/dsh-client-ui-settings-models": "0.2.0-rc.2",
492
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
493
+ "@deepseek-ai/dsh-credentials": "0.2.0-rc.2",
494
+ "@deepseek-ai/dsh-fs": "0.2.0-rc.2",
495
+ "@deepseek-ai/dsh-launch-environment": "0.2.0-rc.2",
496
+ "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
497
+ "@deepseek-ai/dsh-llm-pi-ai": "0.2.0-rc.2",
498
+ "@deepseek-ai/dsh-scope": "0.2.0-rc.2",
499
+ "@deepseek-ai/dsh-session": "0.2.0-rc.2",
500
+ "@deepseek-ai/dsh-session-format-catalog": "0.2.0-rc.2",
501
+ "@deepseek-ai/dsh-session-projection": "0.2.0-rc.2",
502
+ "@deepseek-ai/dsh-settings": "0.2.0-rc.2",
503
+ "@deepseek-ai/dsh-storage": "0.2.0-rc.2",
504
+ "@deepseek-ai/dsh-storage-domain": "0.2.0-rc.2",
505
+ "@deepseek-ai/dsh-storage-json": "0.2.0-rc.2",
506
+ "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
507
+ "@deepseek-ai/dsh-tool-web": "0.2.0-rc.2",
508
+ "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
509
+ "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
510
+ "@deepseek-ai/dsh-typert-registry": "0.2.0-rc.2",
511
+ "@deepseek-ai/dsh-web": "0.2.0-rc.2",
512
+ "@deepseek-ai/dsh-web-search-deepseek": "0.2.0-rc.2",
513
+ "@deepseek-ai/schemastery": "^3.18.4",
514
+ "@types/node": "^22.0.0",
515
+ "@types/react": "~18.3.1",
516
+ "@types/react-dom": "18.3.7",
517
+ "jsdom": "^26.1.0",
518
+ "react": "^18.2.0",
519
+ "react-dom": "18.3.1",
520
+ "tsdown": "^0.22.2",
521
+ "typescript": "^5.9.0",
522
+ "unrun": "^0.3.1",
523
+ "vitest": "^3.2.0"
524
+ },
525
+ main: "lib/index.js",
526
+ types: "lib/types/index.d.ts",
527
+ imports: { "#package.json": "./package.json" },
528
+ dsh: {
529
+ "bundle": { "patch": "./cordis.patch.yml" },
530
+ "client": {
531
+ "external": ["react"],
532
+ "inject": ["@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-ui-settings-models"],
533
+ "platform": "web"
534
+ }
535
+ }
536
+ };
537
+ //#endregion
538
+ //#region lib/types/diagnostics-host.js
539
+ var __runInitializers$9 = function(thisArg, initializers, value) {
540
+ var useValue = arguments.length > 2;
541
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
542
+ return useValue ? value : void 0;
543
+ };
544
+ var __esDecorate$9 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
545
+ function accept(f) {
546
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
547
+ return f;
548
+ }
549
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
550
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
551
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
552
+ var _, done = false;
553
+ for (var i = decorators.length - 1; i >= 0; i--) {
554
+ var context = {};
555
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
556
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
557
+ context.addInitializer = function(f) {
558
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
559
+ extraInitializers.push(accept(f || null));
560
+ };
561
+ var result = (0, decorators[i])(kind === "accessor" ? {
562
+ get: descriptor.get,
563
+ set: descriptor.set
564
+ } : descriptor[key], context);
565
+ if (kind === "accessor") {
566
+ if (result === void 0) continue;
567
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
568
+ if (_ = accept(result.get)) descriptor.get = _;
569
+ if (_ = accept(result.set)) descriptor.set = _;
570
+ if (_ = accept(result.init)) initializers.unshift(_);
571
+ } else if (_ = accept(result)) {
572
+ if (kind === "field") initializers.unshift(_);
573
+ else descriptor[key] = _;
574
+ }
575
+ }
576
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
577
+ done = true;
578
+ };
579
+ const diagnosticsDomain = {
580
+ name: "github_copilot_diagnostics",
581
+ version: 1,
582
+ tables: {},
583
+ global: {
584
+ schema: DiagnosticsSnapshotSchema,
585
+ initial: emptyDiagnostics()
586
+ }
587
+ };
588
+ function diagnosticsDomainForProfile(profileId) {
589
+ if (!/^[a-zA-Z0-9_-]{1,48}$/.test(profileId)) throw new Error("COPILOT_DIAGNOSTICS_PROFILE_UNAVAILABLE");
590
+ return {
591
+ ...diagnosticsDomain,
592
+ name: `github_copilot_diagnostics_${Buffer.from(profileId).toString("hex")}`
593
+ };
594
+ }
595
+ function beginDiagnostics(ctx, operation) {
596
+ return ctx.get("githubCopilotDiagnostics")?.collector.begin(operation);
597
+ }
598
+ /** Keeps diagnostics durability failures separate from observed business failures. */
599
+ let DiagnosticsController = (() => {
600
+ let _classSuper = TypertRemoteService;
601
+ let _instanceExtraInitializers = [];
602
+ let _get_decorators;
603
+ let _setEnabled_decorators;
604
+ let _clear_decorators;
605
+ let _recordClient_decorators;
606
+ return class DiagnosticsController extends _classSuper {
607
+ static {
608
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
609
+ _get_decorators = [Remote];
610
+ _setEnabled_decorators = [Remote];
611
+ _clear_decorators = [Remote];
612
+ _recordClient_decorators = [Remote];
613
+ __esDecorate$9(this, null, _get_decorators, {
614
+ kind: "method",
615
+ name: "get",
616
+ static: false,
617
+ private: false,
618
+ access: {
619
+ has: (obj) => "get" in obj,
620
+ get: (obj) => obj.get
621
+ },
622
+ metadata: _metadata
623
+ }, null, _instanceExtraInitializers);
624
+ __esDecorate$9(this, null, _setEnabled_decorators, {
625
+ kind: "method",
626
+ name: "setEnabled",
627
+ static: false,
628
+ private: false,
629
+ access: {
630
+ has: (obj) => "setEnabled" in obj,
631
+ get: (obj) => obj.setEnabled
632
+ },
633
+ metadata: _metadata
634
+ }, null, _instanceExtraInitializers);
635
+ __esDecorate$9(this, null, _clear_decorators, {
636
+ kind: "method",
637
+ name: "clear",
638
+ static: false,
639
+ private: false,
640
+ access: {
641
+ has: (obj) => "clear" in obj,
642
+ get: (obj) => obj.clear
643
+ },
644
+ metadata: _metadata
645
+ }, null, _instanceExtraInitializers);
646
+ __esDecorate$9(this, null, _recordClient_decorators, {
647
+ kind: "method",
648
+ name: "recordClient",
649
+ static: false,
650
+ private: false,
651
+ access: {
652
+ has: (obj) => "recordClient" in obj,
653
+ get: (obj) => obj.recordClient
654
+ },
655
+ metadata: _metadata
656
+ }, null, _instanceExtraInitializers);
657
+ if (_metadata) Object.defineProperty(this, Symbol.metadata, {
658
+ enumerable: true,
659
+ configurable: true,
660
+ writable: true,
661
+ value: _metadata
662
+ });
663
+ }
664
+ collector = __runInitializers$9(this, _instanceExtraInitializers);
665
+ domain;
666
+ state = "unavailable";
667
+ problem = "storage-unavailable";
668
+ enabled = false;
669
+ dirty = false;
670
+ persistedAt;
671
+ revision = 0;
672
+ writing;
673
+ closed = false;
674
+ settingsBusy = false;
675
+ brackets = /* @__PURE__ */ new Map();
676
+ constructor(ctx) {
677
+ super(ctx, "githubCopilotDiagnostics");
678
+ this.collector = new DiagnosticsCollector(package_default.version, "host", () => {
679
+ this.dirty = true;
680
+ this.revision++;
681
+ });
682
+ const readEnabled = () => {
683
+ const value = ctx.get("settings")?.describe({ redactSecrets: true }).find((row) => row.ns === "github-copilot")?.value;
684
+ this.enabled = typeof value === "object" && value !== null && "diagnosticsEnabled" in value && value.diagnosticsEnabled === true;
685
+ this.collector.setEnabled(this.enabled && this.state === "ready");
686
+ if (!this.enabled) this.brackets.clear();
687
+ };
688
+ ctx.inject(["settings"], (scope) => {
689
+ readEnabled();
690
+ const dispose = onSettingsNamespaceUpdated(scope, (ns) => {
691
+ if (ns === "github-copilot") readEnabled();
692
+ });
693
+ scope.effect(() => dispose);
694
+ });
695
+ ctx.inject(["storageDomain"], async (scope) => {
696
+ this.state = "loading";
697
+ try {
698
+ const profile = scope.get("profileContext");
699
+ if (!profile) throw new Error("COPILOT_DIAGNOSTICS_PROFILE_UNAVAILABLE");
700
+ const domain = await scope.storageDomain.open(diagnosticsDomainForProfile(profile.name));
701
+ if (this.closed) {
702
+ await domain.close();
703
+ return;
704
+ }
705
+ this.domain = domain;
706
+ this.collector.restore(domain.global.get());
707
+ this.state = "ready";
708
+ this.problem = "none";
709
+ readEnabled();
710
+ await this.flush();
711
+ } catch (error) {
712
+ this.state = "error";
713
+ this.problem = error instanceof Error && error.message === "COPILOT_DIAGNOSTICS_PROFILE_UNAVAILABLE" ? "profile-unavailable" : typeof error === "object" && error !== null && "code" in error && (error.code === "invalid-record" || error.code === "malformed-medium" || error.code === "version-mismatch") ? "storage-invalid" : "storage-unavailable";
714
+ this.collector.setEnabled(false);
715
+ ctx.logger.warn("[github-copilot] COPILOT_DIAGNOSTICS_STORAGE_UNAVAILABLE");
716
+ }
717
+ if (this.closed) return;
718
+ const timer = setInterval(() => {
719
+ this.flush().catch(() => {
720
+ ctx.logger.warn("[github-copilot] COPILOT_DIAGNOSTICS_STORAGE_WRITE_FAILED");
721
+ });
722
+ }, 1e4);
723
+ timer.unref();
724
+ scope.effect(() => async () => {
725
+ clearInterval(timer);
726
+ this.collector.close();
727
+ try {
728
+ await this.flush();
729
+ } finally {
730
+ await this.domain?.close();
731
+ this.domain = void 0;
732
+ this.state = "unavailable";
733
+ this.problem = "storage-unavailable";
734
+ }
735
+ });
736
+ });
737
+ ctx.on("session/event", (session, event) => {
738
+ if (event.type === "compaction/start") {
739
+ if (!this.enabled || this.state !== "ready") return;
740
+ if (this.brackets.has(session) || this.brackets.size >= 128) {
741
+ this.collector.noteDropped();
742
+ return;
743
+ }
744
+ this.brackets.set(session, {
745
+ id: event.data.compactionId,
746
+ committed: false,
747
+ cancelled: false,
748
+ operation: this.collector.begin("compaction")
749
+ });
750
+ }
751
+ const bracket = this.brackets.get(session);
752
+ if (!bracket) return;
753
+ if (event.type === "user/message" && event.data.source.kind === "compact-checkpoint" && event.data.source.compactionId === bracket.id) {
754
+ bracket.committed = true;
755
+ bracket.operation.stage("checkpoint-committed");
756
+ }
757
+ if (event.type !== "compaction/end" || event.data.compactionId !== bracket.id) return;
758
+ bracket.operation.stage("ended");
759
+ if (bracket.cancelled) bracket.operation.finish("cancelled");
760
+ else if (event.data.error === void 0) bracket.operation.finish(bracket.committed ? "success" : "unknown");
761
+ else {
762
+ const reason = diagnosticsReason(new Error(event.data.error));
763
+ bracket.operation.finish(diagnosticsOutcome(reason), reason);
764
+ }
765
+ this.brackets.delete(session);
766
+ });
767
+ ctx.on("agent/disposed", ({ agent }) => {
768
+ this.brackets.get(agent.session)?.operation.finish("interrupted", "unknown");
769
+ this.brackets.delete(agent.session);
770
+ });
771
+ ctx.effect(() => async () => {
772
+ this.collector.close();
773
+ this.brackets.clear();
774
+ try {
775
+ await this.flush();
776
+ } finally {
777
+ this.closed = true;
778
+ }
779
+ });
780
+ }
781
+ async flush() {
782
+ if (this.writing) {
783
+ await this.writing;
784
+ if (this.dirty) return this.flush();
785
+ return;
786
+ }
787
+ if (!this.domain || !this.dirty || this.closed) return;
788
+ const domain = this.domain;
789
+ const revision = this.revision;
790
+ const snapshot = this.collector.snapshot();
791
+ this.writing = domain.global.set(snapshot).then(() => {
792
+ this.persistedAt = snapshot.updatedAt;
793
+ this.dirty = this.revision !== revision;
794
+ this.state = "ready";
795
+ this.problem = "none";
796
+ }, () => {
797
+ this.problem = "storage-write-failed";
798
+ throw new Error("COPILOT_DIAGNOSTICS_STORAGE_WRITE_FAILED");
799
+ }).finally(() => {
800
+ this.writing = void 0;
801
+ });
802
+ await this.writing;
803
+ }
804
+ markCompactionCancelled(session) {
805
+ const bracket = this.brackets.get(session);
806
+ if (bracket) bracket.cancelled = true;
807
+ }
808
+ get() {
809
+ return {
810
+ enabled: this.enabled,
811
+ state: this.state,
812
+ diagnostic: this.problem,
813
+ ...this.persistedAt === void 0 ? {} : { persistedAt: this.persistedAt },
814
+ dirty: this.dirty,
815
+ snapshot: this.collector.snapshot()
816
+ };
817
+ }
818
+ async setEnabled(enabled) {
819
+ if (typeof enabled !== "boolean") throw new Error("COPILOT_DIAGNOSTICS_INVALID_CONTROL");
820
+ if (this.settingsBusy) throw new Error("COPILOT_DIAGNOSTICS_CONTROL_BUSY");
821
+ if (enabled && !this.domain) throw new Error("COPILOT_DIAGNOSTICS_STORAGE_UNAVAILABLE");
822
+ if (enabled) this.collector.assertCanEnable();
823
+ this.settingsBusy = true;
824
+ try {
825
+ const settings = this.ctx.get("settings");
826
+ const row = settings?.describe({ redactSecrets: true }).find((item) => item.ns === "github-copilot");
827
+ if (!settings || !row) throw new Error("COPILOT_DIAGNOSTICS_SETTINGS_UNAVAILABLE");
828
+ await settings.mutate("github-copilot", [{
829
+ op: "set",
830
+ path: ["diagnosticsEnabled"],
831
+ value: enabled
832
+ }], row.revision);
833
+ const saved = settings.describe({ redactSecrets: true }).find((item) => item.ns === "github-copilot")?.value;
834
+ if (typeof saved !== "object" || saved === null || !("diagnosticsEnabled" in saved) || saved.diagnosticsEnabled !== enabled) throw new Error("COPILOT_DIAGNOSTICS_SETTINGS_COMMIT_UNCERTAIN");
835
+ this.enabled = enabled;
836
+ this.collector.setEnabled(enabled);
837
+ await this.flush();
838
+ return this.get();
839
+ } finally {
840
+ this.settingsBusy = false;
841
+ }
842
+ }
843
+ async clear() {
844
+ if (!this.domain) throw new Error("COPILOT_DIAGNOSTICS_STORAGE_UNAVAILABLE");
845
+ this.collector.clear();
846
+ await this.flush();
847
+ return this.get();
848
+ }
849
+ async recordClient(batch) {
850
+ const parsed = ClientDiagnosticsBatchSchema.safeParse(batch);
851
+ if (!parsed.success) throw new Error("COPILOT_DIAGNOSTICS_INVALID_CLIENT_REPORT");
852
+ if (!this.enabled || !this.domain || parsed.data.epoch !== this.collector.snapshot().epoch) return {
853
+ ...this.get(),
854
+ diagnostic: "client-report-revoked"
855
+ };
856
+ this.collector.mergeClient(parsed.data.rows);
857
+ this.collector.noteClientGaps(parsed.data.dropped ?? 0, parsed.data.unconfirmed ?? 0);
858
+ return this.get();
859
+ }
860
+ };
861
+ })();
862
+ //#endregion
863
+ //#region lib/types/dual-model-host.js
864
+ /** Retired planner/executor entry points; retained policies stay enforceable without migration. */
865
+ var __runInitializers$8 = function(thisArg, initializers, value) {
866
+ var useValue = arguments.length > 2;
867
+ for (var i = 0; i < initializers.length; i++) value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
868
+ return useValue ? value : void 0;
869
+ };
870
+ var __esDecorate$8 = function(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
871
+ function accept(f) {
872
+ if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected");
873
+ return f;
874
+ }
875
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
876
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
877
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
878
+ var _, done = false;
879
+ for (var i = decorators.length - 1; i >= 0; i--) {
880
+ var context = {};
881
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
882
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
883
+ context.addInitializer = function(f) {
884
+ if (done) throw new TypeError("Cannot add initializers after decoration has completed");
885
+ extraInitializers.push(accept(f || null));
886
+ };
887
+ var result = (0, decorators[i])(kind === "accessor" ? {
888
+ get: descriptor.get,
889
+ set: descriptor.set
890
+ } : descriptor[key], context);
891
+ if (kind === "accessor") {
892
+ if (result === void 0) continue;
893
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
894
+ if (_ = accept(result.get)) descriptor.get = _;
895
+ if (_ = accept(result.set)) descriptor.set = _;
896
+ if (_ = accept(result.init)) initializers.unshift(_);
897
+ } else if (_ = accept(result)) {
898
+ if (kind === "field") initializers.unshift(_);
899
+ else descriptor[key] = _;
900
+ }
901
+ }
902
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
903
+ done = true;
904
+ };
905
+ const DUAL_MODEL_NAMESPACE = "github-copilot-dual-model";
906
+ const DUAL_MODEL_PROJECTION = "githubCopilotDualModelPolicy";
907
+ const DUAL_MODEL_EXECUTE_TOOL = "copilot_execute";
908
+ const DEFAULT_CONFIG = Object.freeze({
909
+ enabled: false,
910
+ plannerModel: "",
911
+ executorModel: ""
912
+ });
913
+ const configSchema = z$1.object({
914
+ enabled: z$1.boolean().default(false),
915
+ plannerModel: z$1.string().default(""),
916
+ executorModel: z$1.string().default("")
917
+ });
918
+ const ConfigJson = z.object({
919
+ enabled: z.boolean(),
920
+ plannerModel: z.string().max(512),
921
+ executorModel: z.string().max(512)
922
+ }).strict();
923
+ const RevisionJson = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
924
+ const CreateJson = z.object({
925
+ requestId: z.string().uuid(),
926
+ workspaceId: z.string().min(1).max(512),
927
+ expectedRevision: RevisionJson
928
+ }).strict();
929
+ const SaveJson = z.object({
930
+ configuration: ConfigJson,
931
+ expectedRevision: RevisionJson
932
+ }).strict();
933
+ const ExecuteJson = z.object({
934
+ description: z.string().min(1).max(160),
935
+ prompt: z.string().min(1).max(1e5)
936
+ }).strict();
937
+ const PolicyJson = z.object({
938
+ version: z.literal(1),
939
+ rootSessionId: z.string(),
940
+ requestId: z.string(),
941
+ workspaceId: z.string(),
942
+ settingsRevision: z.number().int().nonnegative(),
943
+ cwd: z.string(),
944
+ agentPreset: z.string(),
945
+ provider: z.literal(GITHUB_COPILOT_PREVIEW_PROVIDER_ID),
946
+ plannerModel: z.string().min(1),
947
+ executorModel: z.string().min(1),
948
+ executorTools: z.array(z.string()),
949
+ plannerTools: z.array(z.string())
950
+ }).strict();
951
+ const ChildJson = z.object({
952
+ version: z.literal(3),
953
+ mode: z.literal("continuable"),
954
+ provider: z.literal("spawn"),
955
+ agentProvider: z.string(),
956
+ agentModel: z.string()
957
+ }).strict();
958
+ const ChildWireJson = ChildJson.extend({
959
+ label: z.string(),
960
+ agentReasoningEffort: z.string().optional(),
961
+ persona: z.string().optional(),
962
+ toolFilter: z.object({
963
+ allow: z.array(z.string()).optional(),
964
+ deny: z.array(z.string()).optional()
965
+ }).strict().refine((value) => value.allow !== void 0 || value.deny !== void 0).optional()
966
+ }).strict().transform(({ version, mode, provider, agentProvider, agentModel }) => ({
967
+ version,
968
+ mode,
969
+ provider,
970
+ agentProvider,
971
+ agentModel
972
+ }));
973
+ const ProjectionJson = z.object({
974
+ id: z.string(),
975
+ parentId: z.string().nullable(),
976
+ origin: z.string().nullable(),
977
+ inherited: z.number(),
978
+ policy: PolicyJson.nullable(),
979
+ child: ChildJson.nullable(),
980
+ invalid: z.boolean()
981
+ });
982
+ /** A root policy is authoritative only in its own suffix, never in a fork seed. */
983
+ const dualModelProjection = {
984
+ key: DUAL_MODEL_PROJECTION,
985
+ stateVersion: 2,
986
+ stateSchema: ProjectionJson,
987
+ init: (header, inherited = 0) => ({
988
+ id: header.id,
989
+ parentId: header.parentSession ?? null,
990
+ origin: header.origin ?? null,
991
+ inherited,
992
+ policy: null,
993
+ child: null,
994
+ invalid: false
995
+ }),
996
+ apply: (state, event) => {
997
+ if (event.seq < state.inherited) return state;
998
+ if (event.type === "github-copilot/dual-model-policy") {
999
+ const parsed = PolicyJson.safeParse(event.data);
1000
+ if (state.policy !== null || !parsed.success || parsed.data.rootSessionId !== state.id || state.parentId !== null || event.ignorable !== true) return {
1001
+ ...state,
1002
+ invalid: true
1003
+ };
1004
+ return {
1005
+ ...state,
1006
+ policy: parsed.data
1007
+ };
1008
+ }
1009
+ if (event.type === "subagent/descriptor" && state.origin === "subagent") {
1010
+ const parsed = ChildWireJson.safeParse(event.data);
1011
+ if (state.child !== null || !parsed.success) return {
1012
+ ...state,
1013
+ child: null,
1014
+ invalid: true
1015
+ };
1016
+ return {
1017
+ ...state,
1018
+ child: parsed.data
1019
+ };
1020
+ }
1021
+ return state;
1022
+ }
1023
+ };
1024
+ const EXECUTOR_PERSONA = "You are the execution agent for a dedicated Copilot planner/executor session. Implement only the delegated task. Your provider and model are fixed by the session policy. Do not create other agents, workflows, dynamic plugins, or alternate model calls. Report the changed files, verification, limitations, and actual results to your direct parent with send_message. Do not claim tests or work you did not perform.";
1025
+ function roleText(policy, role) {
1026
+ return role === "planner" ? `You are the planning and acceptance agent. Read the current code and evidence, plan, clarify, delegate implementation through ${DUAL_MODEL_EXECUTE_TOOL}, and independently review results. Do not implement changes or run commands directly. Your planning model is ${policy.plannerModel}; execution is fixed to ${policy.executorModel}. Use the original send_message/list_agents/interrupt_agent controls to continue and inspect your execution children. Provider: ${GITHUB_COPILOT_PREVIEW_PROVIDER_ID}.` : EXECUTOR_PERSONA;
1027
+ }
1028
+ function fail$2(reason, creation) {
1029
+ throw new RemoteError("copilot/dual-model", reason, {
1030
+ reason,
1031
+ ...creation === void 0 ? {} : { creation }
1032
+ });
1033
+ }
1034
+ function creationOf(error) {
1035
+ return ownRemoteFailure(error)?.creation ?? "uncertain";
1036
+ }
1037
+ function object$8(value) {
1038
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1039
+ }
1040
+ function api$1(ctx, key, methods) {
1041
+ const value = ctx.get(key);
1042
+ return object$8(value) && methods.every((method) => typeof value[method] === "function") ? value : void 0;
1043
+ }
1044
+ function revision(value) {
1045
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
1046
+ }
1047
+ const ERROR_REASONS = /* @__PURE__ */ new Set([
1048
+ "DUAL_MODEL_RETIRED",
1049
+ "DUAL_MODEL_UNSUPPORTED",
1050
+ "DUAL_MODEL_READ_ONLY",
1051
+ "DUAL_MODEL_REVISION_CONFLICT",
1052
+ "DUAL_MODEL_MODEL_UNAVAILABLE",
1053
+ "DUAL_MODEL_WORKSPACE_UNAVAILABLE",
1054
+ "DUAL_MODEL_DISABLED",
1055
+ "DUAL_MODEL_INVALID_REQUEST",
1056
+ "DUAL_MODEL_REQUEST_CONFLICT",
1057
+ "DUAL_MODEL_SAVE_FAILED",
1058
+ "DUAL_MODEL_CREATE_UNCERTAIN",
1059
+ "DUAL_MODEL_POLICY_INVALID",
1060
+ "DUAL_MODEL_SELECTION_LOCKED",
1061
+ "DUAL_MODEL_DELEGATION_DENIED",
1062
+ "DUAL_MODEL_EXECUTION_FAILED"
1063
+ ]);
1064
+ /** Remote errors cross bundle/realm boundaries; constructor identity is not a protocol. */
1065
+ function ownRemoteFailure(error) {
1066
+ try {
1067
+ if (!object$8(error) || error.isDSHRemoteError !== true || error.code !== "copilot/dual-model" || !object$8(error.details)) return void 0;
1068
+ const reason = error.details.reason;
1069
+ if (typeof reason !== "string" || !ERROR_REASONS.has(reason)) return void 0;
1070
+ const creation = error.details.creation;
1071
+ return {
1072
+ reason,
1073
+ ...creation === "not-created" || creation === "uncertain" ? { creation } : {}
1074
+ };
1075
+ } catch {
1076
+ return;
1077
+ }
1078
+ }
1079
+ function reasonOf(error, fallback) {
1080
+ const own = ownRemoteFailure(error);
1081
+ if (own) return own.reason;
1082
+ try {
1083
+ if (object$8(error) && error.code === "SETTINGS_CONFLICT") return "DUAL_MODEL_REVISION_CONFLICT";
1084
+ } catch {}
1085
+ return fallback;
1086
+ }
1087
+ function dualModelSessionId(requestId) {
1088
+ return `copilot-dual-${createHash("sha256").update(requestId).digest("hex")}`;
1089
+ }
1090
+ function requestKey(request) {
1091
+ return JSON.stringify([
1092
+ request.requestId,
1093
+ request.workspaceId,
1094
+ request.expectedRevision
1095
+ ]);
1096
+ }
1097
+ function policyMatches(policy, request) {
1098
+ return policy.requestId === request.requestId && policy.workspaceId === request.workspaceId && policy.settingsRevision === request.expectedRevision;
1099
+ }
1100
+ function dedicatedAddress(agent) {
1101
+ const owned = /^copilot-dual-[0-9a-f]{64}$/;
1102
+ return owned.test(agent.id) || agent.session.header.origin === "subagent" && owned.test(agent.session.header.parentSession ?? "");
1103
+ }
1104
+ let GitHubCopilotDualModel = (() => {
1105
+ let _classSuper = TypertRemoteService;
1106
+ let _instanceExtraInitializers = [];
1107
+ let _view_decorators;
1108
+ let _save_decorators;
1109
+ let _create_decorators;
1110
+ return class GitHubCopilotDualModel extends _classSuper {
1111
+ static {
1112
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
1113
+ _view_decorators = [Remote];
1114
+ _save_decorators = [Remote];
1115
+ _create_decorators = [Remote];
1116
+ __esDecorate$8(this, null, _view_decorators, {
1117
+ kind: "method",
1118
+ name: "view",
1119
+ static: false,
1120
+ private: false,
1121
+ access: {
1122
+ has: (obj) => "view" in obj,
1123
+ get: (obj) => obj.view
1124
+ },
1125
+ metadata: _metadata
1126
+ }, null, _instanceExtraInitializers);
1127
+ __esDecorate$8(this, null, _save_decorators, {
1128
+ kind: "method",
1129
+ name: "save",
1130
+ static: false,
1131
+ private: false,
1132
+ access: {
1133
+ has: (obj) => "save" in obj,
1134
+ get: (obj) => obj.save
1135
+ },
1136
+ metadata: _metadata
1137
+ }, null, _instanceExtraInitializers);
1138
+ __esDecorate$8(this, null, _create_decorators, {
301
1139
  kind: "method",
302
1140
  name: "create",
303
1141
  static: false,
@@ -737,9 +1575,9 @@ let GitHubCopilotDualModel = (() => {
737
1575
  })();
738
1576
  //#endregion
739
1577
  //#region lib/types/search-routing-remote.js
740
- const SearchProviderCatalogSchema = z$1.object({
741
- supported: z$1.boolean(),
742
- providers: z$1.array(z$1.object({ id: z$1.string().min(1).max(512) }).strict()).max(512)
1578
+ const SearchProviderCatalogSchema = z.object({
1579
+ supported: z.boolean(),
1580
+ providers: z.array(z.object({ id: z.string().min(1).max(512) }).strict()).max(512)
743
1581
  }).strict();
744
1582
  //#endregion
745
1583
  //#region lib/types/search-routing-host.js
@@ -1179,36 +2017,36 @@ function createAccountModelAuth(credentials, renewRejectedCredential) {
1179
2017
  }
1180
2018
  //#endregion
1181
2019
  //#region lib/types/copilot-usage-normalize.js
1182
- const amount = z$1.number().finite().min(0).max(0xe8d4a51000);
1183
- const entitlement = z$1.union([
2020
+ const amount = z.number().finite().min(0).max(0xe8d4a51000);
2021
+ const entitlement = z.union([
1184
2022
  amount,
1185
- z$1.literal(-1),
1186
- z$1.string().max(32).regex(/^(?:-1|(?:0|[1-9]\d*)(?:\.\d+)?)$/u)
2023
+ z.literal(-1),
2024
+ z.string().max(32).regex(/^(?:-1|(?:0|[1-9]\d*)(?:\.\d+)?)$/u)
1187
2025
  ]).transform(Number).refine((value) => Number.isFinite(value) && value <= 0xe8d4a51000);
1188
- const resetSeconds = z$1.unknown().transform((value) => typeof value === "number" && Number.isInteger(value) && value > 0 && value <= Math.floor(0xe677d21fdbff / 1e3) ? value * 1e3 : void 0);
1189
- const resetCalendar = z$1.unknown().transform(resetDate);
1190
- const snapshot = z$1.object({
1191
- unlimited: z$1.boolean(),
2026
+ const resetSeconds = z.unknown().transform((value) => typeof value === "number" && Number.isInteger(value) && value > 0 && value <= Math.floor(0xe677d21fdbff / 1e3) ? value * 1e3 : void 0);
2027
+ const resetCalendar = z.unknown().transform(resetDate);
2028
+ const snapshot = z.object({
2029
+ unlimited: z.boolean(),
1192
2030
  entitlement: entitlement.optional(),
1193
- percent_remaining: z$1.number().finite().min(0).max(100).optional(),
2031
+ percent_remaining: z.number().finite().min(0).max(100).optional(),
1194
2032
  quota_remaining: amount.optional(),
1195
2033
  credits_used: amount.optional(),
1196
- has_quota: z$1.boolean().optional(),
1197
- token_based_billing: z$1.boolean().optional(),
2034
+ has_quota: z.boolean().optional(),
2035
+ token_based_billing: z.boolean().optional(),
1198
2036
  quota_reset_at: resetSeconds.optional()
1199
2037
  });
1200
- const response = z$1.object({
1201
- token_based_billing: z$1.boolean().optional(),
1202
- access_type_sku: z$1.string().max(128).optional(),
2038
+ const response = z.object({
2039
+ token_based_billing: z.boolean().optional(),
2040
+ access_type_sku: z.string().max(128).optional(),
1203
2041
  quota_reset_date: resetCalendar.optional(),
1204
2042
  quota_reset_date_utc: resetCalendar.optional(),
1205
2043
  limited_user_reset_date: resetCalendar.optional(),
1206
- quota_snapshots: z$1.object({
2044
+ quota_snapshots: z.object({
1207
2045
  chat: snapshot.optional(),
1208
2046
  premium_interactions: snapshot.optional()
1209
2047
  }).optional(),
1210
- monthly_quotas: z$1.object({ chat: amount }).optional(),
1211
- limited_user_quotas: z$1.object({ chat: amount }).optional()
2048
+ monthly_quotas: z.object({ chat: amount }).optional(),
2049
+ limited_user_quotas: z.object({ chat: amount }).optional()
1212
2050
  });
1213
2051
  function unavailableCopilotUsage(diagnostic, billing = "unknown", budget = "unknown") {
1214
2052
  return {
@@ -1349,7 +2187,7 @@ var Budget = class {
1349
2187
  if (this.consumed > ACCOUNT_MODEL_CATALOG_LIMITS.maxBytes) fail$1("CATALOG_TOO_LARGE", true);
1350
2188
  }
1351
2189
  };
1352
- function record$13(value, code) {
2190
+ function record$14(value, code) {
1353
2191
  if (typeof value !== "object" || value === null || Array.isArray(value)) fail$1(code);
1354
2192
  return value;
1355
2193
  }
@@ -1402,11 +2240,11 @@ function normalizeModel(raw, id, options, budget) {
1402
2240
  if (options.availableModelIds?.has(id) !== true) fail$1("MISSING_POLICY");
1403
2241
  policySource = "account-available-id";
1404
2242
  } else {
1405
- if (text$2(field(record$13(rawPolicy, "INVALID_POLICY"), "state", budget), 64, "INVALID_POLICY", budget) !== "enabled") fail$1("POLICY_NOT_ENABLED");
2243
+ if (text$2(field(record$14(rawPolicy, "INVALID_POLICY"), "state", budget), 64, "INVALID_POLICY", budget) !== "enabled") fail$1("POLICY_NOT_ENABLED");
1406
2244
  policySource = "server-enabled";
1407
2245
  }
1408
- const capabilities = record$13(field(raw, "capabilities", budget), "INVALID_CAPABILITIES");
1409
- const supports = record$13(field(capabilities, "supports", budget), "INVALID_SUPPORTS");
2246
+ const capabilities = record$14(field(raw, "capabilities", budget), "INVALID_CAPABILITIES");
2247
+ const supports = record$14(field(capabilities, "supports", budget), "INVALID_SUPPORTS");
1410
2248
  const streaming = field(supports, "streaming", budget);
1411
2249
  if (streaming === false) fail$1("STREAMING_UNSUPPORTED");
1412
2250
  if (streaming !== true) fail$1("INVALID_SUPPORTS");
@@ -1427,7 +2265,7 @@ function normalizeModel(raw, id, options, budget) {
1427
2265
  if (selected === void 0) fail$1(unsupportedEndpointCount === 0 && endpoints.includes("ws:/responses") ? "WEBSOCKET_ONLY" : "UNSUPPORTED_ENDPOINTS");
1428
2266
  const rawLimits = field(capabilities, "limits", budget);
1429
2267
  if (rawLimits === void 0) fail$1("MISSING_LIMITS");
1430
- const limits = record$13(rawLimits, "INVALID_LIMITS");
2268
+ const limits = record$14(rawLimits, "INVALID_LIMITS");
1431
2269
  const maxContext = optionalPositive(limits, "max_context_window_tokens", "INVALID_LIMITS", budget);
1432
2270
  const maxInputTokens = optionalPositive(limits, "max_prompt_tokens", "INVALID_LIMITS", budget);
1433
2271
  if (maxContext === void 0 && maxInputTokens === void 0) fail$1("MISSING_CONTEXT_LIMIT");
@@ -1445,7 +2283,7 @@ function normalizeModel(raw, id, options, budget) {
1445
2283
  if (vision === true) {
1446
2284
  const rawVisionLimits = field(limits, "vision", budget);
1447
2285
  if (rawVisionLimits !== void 0) {
1448
- const rawMediaTypes = field(record$13(rawVisionLimits, "INVALID_VISION_LIMITS"), "supported_media_types", budget);
2286
+ const rawMediaTypes = field(record$14(rawVisionLimits, "INVALID_VISION_LIMITS"), "supported_media_types", budget);
1449
2287
  if (rawMediaTypes !== void 0) {
1450
2288
  const mediaTypes = stringList(rawMediaTypes, ACCOUNT_MODEL_CATALOG_LIMITS.maxMediaTypes, 128, "INVALID_VISION_LIMITS", budget);
1451
2289
  const mime = /^[a-z0-9][a-z0-9!#$%&'*+.^_`|~-]*\/[a-z0-9][a-z0-9!#$%&'*+.^_`|~-]*$/iu;
@@ -1507,7 +2345,7 @@ function normalizeAccountModelCatalog(raw, options = {}) {
1507
2345
  fail$1("INVALID_JSON", true);
1508
2346
  }
1509
2347
  }
1510
- const data = field(record$13(raw, "INVALID_CATALOG"), "data", budget);
2348
+ const data = field(record$14(raw, "INVALID_CATALOG"), "data", budget);
1511
2349
  if (!Array.isArray(data)) fail$1("INVALID_CATALOG");
1512
2350
  const count = field(data, "length", budget);
1513
2351
  if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) fail$1("INVALID_CATALOG");
@@ -1530,7 +2368,7 @@ function normalizeAccountModelCatalog(raw, options = {}) {
1530
2368
  for (let index = 0; index < count; index++) {
1531
2369
  let id;
1532
2370
  try {
1533
- const candidate = record$13(field(data, String(index), budget), "INVALID_MODEL");
2371
+ const candidate = record$14(field(data, String(index), budget), "INVALID_MODEL");
1534
2372
  const candidateId = text$2(field(candidate, "id", budget), ACCOUNT_MODEL_CATALOG_LIMITS.maxIdLength, "INVALID_ID", budget);
1535
2373
  if (!identifier.test(candidateId)) fail$1("INVALID_ID");
1536
2374
  id = candidateId;
@@ -2553,16 +3391,16 @@ function formatRequestUploadEvidence(evidence) {
2553
3391
  //#endregion
2554
3392
  //#region lib/types/request-body-timeout.js
2555
3393
  const observedMessage = "Timed out reading request body. Try again, or use a smaller request size.";
2556
- function record$12(value) {
3394
+ function record$13(value) {
2557
3395
  return typeof value === "object" && value !== null && !Array.isArray(value);
2558
3396
  }
2559
3397
  /** Verified provider evidence, not guessed capabilities, token limits or network cause. */
2560
3398
  async function requestBodyTimeoutDiagnostic(response, body, signal, dispatch) {
2561
3399
  if (response.status !== 408 || signal?.aborted) return void 0;
2562
3400
  const value = await readResponseErrorJson(response, signal);
2563
- if (signal?.aborted || !record$12(value)) return void 0;
3401
+ if (signal?.aborted || !record$13(value)) return void 0;
2564
3402
  const error = Object.hasOwn(value, "error") ? value.error : value;
2565
- if (!record$12(error) || error.code !== "user_request_timeout" || error.message !== observedMessage || value.code !== void 0 && value.code !== error.code || value.message !== void 0 && value.message !== error.message) return void 0;
3403
+ if (!record$13(error) || error.code !== "user_request_timeout" || error.message !== observedMessage || value.code !== void 0 && value.code !== error.code || value.message !== void 0 && value.message !== error.message) return void 0;
2566
3404
  const size = body === void 0 ? "Request body size unavailable." : `Request body: ${Buffer.byteLength(body, "utf8")} UTF-8 bytes (not context tokens).`;
2567
3405
  const composition = formatRequestBodyEvidence(dispatch === void 0 ? { state: "unavailable" } : requestBodyEvidence(body, dispatch.protocol), dispatch?.responseHeadersMs);
2568
3406
  const upload = formatRequestUploadEvidence(dispatch?.upload);
@@ -2779,446 +3617,220 @@ function createAccountProvider(descriptors, guard, baseURL) {
2779
3617
  const models = Object.freeze(descriptors.map((descriptor) => accountModelFromDescriptor(descriptor, baseURL)));
2780
3618
  const table = new Map(models.map((model) => [model.id, model]));
2781
3619
  if (table.size !== models.length) throw new Error("COPILOT_MANAGED_DUPLICATE_MODEL");
2782
- const selected = () => {
2783
- if (guard.selectedModelId === void 0 || !table.has(guard.selectedModelId)) throw new Error("COPILOT_MANAGED_MODEL_NOT_PREPARED");
2784
- return guard.selectedModelId;
2785
- };
2786
- const guardedOAuth = {
2787
- name: oauth.name,
2788
- isSubscription: true,
2789
- login: async () => {
2790
- throw new Error("COPILOT_MANAGED_USE_CANONICAL_SIGN_IN");
2791
- },
2792
- refresh: async (credential, signal) => {
2793
- guard.assertActive();
2794
- const current = normalizeGitHubCopilotOAuthCredential(credential);
2795
- guard.assertAccount(current);
2796
- const operationSignal = signal === void 0 ? guard.signal : AbortSignal.any([signal, guard.signal]);
2797
- let fresh;
2798
- try {
2799
- fresh = await oauth.refresh(current, operationSignal);
2800
- } catch {
2801
- guard.assertActive();
2802
- throw new Error(operationSignal.aborted ? "COPILOT_MANAGED_ABORTED" : "COPILOT_MANAGED_REFRESH_FAILED");
2803
- }
2804
- guard.assertActive();
2805
- const result = normalizeGitHubCopilotOAuthCredential(fresh);
2806
- guard.assertAccount(result);
2807
- return result;
2808
- },
2809
- toAuth: async (credential) => {
2810
- guard.assertActive();
2811
- const current = normalizeGitHubCopilotOAuthCredential(credential);
2812
- guard.assertAccount(current);
2813
- guard.assertEntitled(current, selected());
2814
- let auth;
2815
- try {
2816
- auth = await oauth.toAuth(current);
2817
- } catch {
2818
- throw new Error("COPILOT_MANAGED_AUTH_DERIVATION_FAILED");
2819
- }
2820
- guard.assertActive();
2821
- guard.assertEntitled(current, selected());
2822
- return {
2823
- ...auth,
2824
- baseUrl: trustedGitHubCopilotBaseUrl(auth.baseUrl ?? baseURL, current)
2825
- };
2826
- }
2827
- };
2828
- const provider = {
2829
- id: GITHUB_COPILOT_PREVIEW_PROVIDER_ID,
2830
- name: "GitHub Copilot",
2831
- baseUrl: accountBaseURL(baseURL),
2832
- auth: Object.freeze({ oauth: Object.freeze(guardedOAuth) }),
2833
- getModels: () => models,
2834
- filterModels: (candidates, credential) => {
2835
- if (credential?.type !== "oauth") return [];
2836
- const grant = normalizeGitHubCopilotOAuthCredential(credential);
2837
- return candidates.filter((model) => {
2838
- if (!table.has(model.id)) return false;
2839
- try {
2840
- guard.assertEntitled(grant, model.id);
2841
- return true;
2842
- } catch {
2843
- return false;
2844
- }
2845
- });
2846
- },
2847
- streamSimple: (model, context, options) => lazyStream(model, async () => {
2848
- guard.assertActive();
2849
- const entry = table.get(model.id);
2850
- if (model.provider !== "github-copilot-preview" || model.id !== selected() || entry === void 0 || model.api !== entry.api) throw new Error("COPILOT_MANAGED_MODEL_MISMATCH");
2851
- guard.inspectRequest?.(model, context, options);
2852
- const lease = await guard.beforeWire(model, options);
2853
- if (typeof options?.apiKey !== "string" || options.apiKey.length === 0) {
2854
- lease.release();
2855
- throw new Error("COPILOT_MANAGED_OAUTH_REQUIRED");
2856
- }
2857
- let liveness;
2858
- try {
2859
- if (guard.streamIdleTimeoutMs !== void 0) {
2860
- liveness = new CopilotStreamLiveness(guard.streamIdleTimeoutMs, lease.signal);
2861
- guard.onStreamLiveness?.(liveness);
2862
- }
2863
- } catch (error) {
2864
- liveness?.dispose();
2865
- lease.release();
2866
- throw error;
2867
- }
2868
- let idleReported = false;
2869
- const reportIdleFailure = () => {
2870
- if (!idleReported && liveness?.signal.reason instanceof CopilotStreamIdleError && !lease.signal.aborted && !options.signal?.aborted) {
2871
- idleReported = true;
2872
- guard.onStreamIdleTimeout?.(liveness.signal.reason);
2873
- }
2874
- };
2875
- const headers = {};
2876
- for (const [name, value] of Object.entries(options.headers ?? {})) if (name.toLowerCase() !== "authorization" && name.toLowerCase() !== "x-api-key") headers[name] = value;
2877
- Object.assign(headers, buildCopilotDynamicHeaders({
2878
- messages: context.messages,
2879
- hasImages: hasCopilotVisionInput(context.messages)
2880
- }));
2881
- headers.authorization = `Bearer ${options.apiKey}`;
2882
- headers["x-api-key"] = null;
2883
- let unauthorized = false;
2884
- const responses = model.api === "openai-responses";
2885
- let retry;
2886
- try {
2887
- retry = responses ? guard.retryReplay?.begin(context, guard.retrySignal, options?.sessionId, model.id) : void 0;
2888
- } catch (error) {
2889
- liveness?.dispose();
2890
- lease.release();
2891
- throw error;
2892
- }
2893
- const reportReplayFailure = (error) => {
2894
- if (lease.signal.aborted || options.signal?.aborted) return;
2895
- try {
2896
- guard.onReplayFailure?.(error);
2897
- } catch {}
2898
- };
2899
- const onPayload = responses ? async (payload, selectedModel) => {
2900
- const replacement = await options.onPayload?.(payload, selectedModel);
2901
- if (lease.signal.aborted || options.signal?.aborted) throw new Error("COPILOT_MANAGED_ABORTED");
2902
- try {
2903
- const effective = replacement === void 0 ? payload : replacement;
2904
- if (retry !== void 0) return await retry.normalize(effective, guard.recoverReplay);
2905
- const normalized = normalizeCopilotResponsesPayload(effective);
2906
- return guard.recoverReplay === void 0 ? normalized : await guard.recoverReplay(normalized);
2907
- } catch (error) {
2908
- if (error instanceof CopilotResponsesReplayError) reportReplayFailure(error);
2909
- throw error;
2910
- }
2911
- } : options.onPayload;
2912
- const fetch = options.fetch ?? globalThis.fetch;
2913
- const observeResponse = async (input, init) => {
2914
- guard.requestCheckpoint?.();
2915
- guard.onRequestBodyTimeout?.(void 0);
2916
- liveness?.beginRequest(typeof init?.body === "string" ? init.body : void 0);
2917
- const replayHeaders = responses && init?.headers !== void 0 ? new Headers(init.headers) : void 0;
2918
- const replayDispatch = responses ? {
2919
- body: typeof init?.body === "string" ? init.body : void 0,
2920
- sessionHeader: replayHeaders?.has("session_id"),
2921
- clientRequestHeader: replayHeaders?.has("x-client-request-id")
2922
- } : void 0;
2923
- let response;
2924
- const upload = guard.onRequestBodyTimeout === void 0 ? void 0 : createRequestUploadObserver();
2925
- const startedAt = performance.now();
2926
- try {
2927
- response = await (upload === void 0 ? fetch(input, init) : upload.run(() => fetch(input, init)));
2928
- } catch (error) {
2929
- retry?.observe(void 0, 0);
2930
- throw error;
2931
- } finally {
2932
- upload?.close();
2933
- }
2934
- const responseHeadersMs = performance.now() - startedAt;
2935
- retry?.observe(typeof init?.body === "string" ? init.body : void 0, response.status);
2936
- if (response.status === 408 && guard.onRequestBodyTimeout !== void 0) {
2937
- const diagnostic = await requestBodyTimeoutDiagnostic(response, typeof init?.body === "string" ? init.body : void 0, lease.signal, {
2938
- protocol: entry.api,
2939
- responseHeadersMs,
2940
- ...upload === void 0 ? {} : { upload: upload.snapshot() }
2941
- });
2942
- if (!lease.signal.aborted && !options.signal?.aborted) guard.onRequestBodyTimeout(diagnostic);
2943
- }
2944
- if (response.status === 401) {
2945
- if (responses && await isCopilotInputItemScopeError(response, lease.signal)) {
2946
- guard.onReplayScopeRejected?.(replayDispatch?.body);
2947
- reportReplayFailure(new CopilotResponsesReplayError("scope-mismatch", replayDispatch));
2948
- } else unauthorized = true;
2949
- }
2950
- return liveness?.observe(response) ?? response;
2951
- };
2952
- const wireOptions = model.api === "anthropic-messages" ? {
2953
- ...options,
2954
- signal: liveness?.signal ?? lease.signal,
2955
- apiKey: void 0,
2956
- headers,
2957
- fetch: observeResponse
2958
- } : {
2959
- ...options,
2960
- signal: liveness?.signal ?? lease.signal,
2961
- headers,
2962
- fetch: observeResponse,
2963
- onPayload
2964
- };
2965
- if (!hasApi(model, "openai-responses") && !hasApi(model, "openai-completions") && !hasApi(model, "anthropic-messages")) {
2966
- retry?.finish();
2967
- liveness?.dispose();
2968
- lease.release();
2969
- throw new Error("COPILOT_MANAGED_PROTOCOL_UNSUPPORTED");
2970
- }
2971
- return (async function* () {
2972
- try {
2973
- for await (const event of native.streamSimple(model, context, wireOptions)) {
2974
- reportIdleFailure();
2975
- if (event.type === "error" && event.reason === "aborted" && lease.signal.reason instanceof ManagedWireAbortError) guard.onWireAbort?.(lease.signal.reason.code);
2976
- yield event;
2977
- }
2978
- } finally {
2979
- reportIdleFailure();
2980
- liveness?.dispose();
2981
- if (lease.signal.aborted || options.signal?.aborted) retry?.observe(void 0, 0);
2982
- retry?.finish();
2983
- lease.release();
2984
- if (unauthorized && !guard.signal.aborted && !options.signal?.aborted) try {
2985
- guard.onUnauthorized?.();
2986
- } catch {}
2987
- }
2988
- })();
2989
- })
2990
- };
2991
- return {
2992
- provider: Object.freeze(coreProviderView(provider)),
2993
- models
3620
+ const selected = () => {
3621
+ if (guard.selectedModelId === void 0 || !table.has(guard.selectedModelId)) throw new Error("COPILOT_MANAGED_MODEL_NOT_PREPARED");
3622
+ return guard.selectedModelId;
2994
3623
  };
2995
- }
2996
- //#endregion
2997
- //#region package.json
2998
- var package_default = {
2999
- name: "dsh-github-copilot",
3000
- description: "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
3001
- version: "0.4.0-alpha.121",
3002
- publishConfig: {
3003
- "access": "public",
3004
- "registry": "https://registry.npmjs.org/",
3005
- "tag": "alpha"
3006
- },
3007
- packageManager: "pnpm@11.7.0",
3008
- repository: {
3009
- "type": "git",
3010
- "url": "git+https://github.com/cloga/dsh-github-copilot.git"
3011
- },
3012
- type: "module",
3013
- exports: {
3014
- ".": {
3015
- "types": "./lib/types/index.d.ts",
3016
- "default": "./lib/index.js"
3017
- },
3018
- "./client": {
3019
- "types": "./lib/types/client.d.ts",
3020
- "default": "./lib/client.js"
3021
- },
3022
- "./remote": {
3023
- "types": "./lib/types/remote.d.ts",
3024
- "default": "./lib/remote.js"
3025
- },
3026
- "./web-delegate": {
3027
- "types": "./lib/types/web-delegate.d.ts",
3028
- "default": "./lib/web-delegate.js"
3029
- },
3030
- "./routed-web": {
3031
- "types": "./lib/types/routed-web.d.ts",
3032
- "default": "./lib/routed-web.js"
3624
+ const guardedOAuth = {
3625
+ name: oauth.name,
3626
+ isSubscription: true,
3627
+ login: async () => {
3628
+ throw new Error("COPILOT_MANAGED_USE_CANONICAL_SIGN_IN");
3033
3629
  },
3034
- "./manual-compaction-recovery": {
3035
- "types": "./lib/types/manual-compaction-recovery.d.ts",
3036
- "default": "./lib/manual-compaction-recovery.js"
3630
+ refresh: async (credential, signal) => {
3631
+ guard.assertActive();
3632
+ const current = normalizeGitHubCopilotOAuthCredential(credential);
3633
+ guard.assertAccount(current);
3634
+ const operationSignal = signal === void 0 ? guard.signal : AbortSignal.any([signal, guard.signal]);
3635
+ let fresh;
3636
+ try {
3637
+ fresh = await oauth.refresh(current, operationSignal);
3638
+ } catch {
3639
+ guard.assertActive();
3640
+ throw new Error(operationSignal.aborted ? "COPILOT_MANAGED_ABORTED" : "COPILOT_MANAGED_REFRESH_FAILED");
3641
+ }
3642
+ guard.assertActive();
3643
+ const result = normalizeGitHubCopilotOAuthCredential(fresh);
3644
+ guard.assertAccount(result);
3645
+ return result;
3037
3646
  },
3038
- "./deployment-baseline.json": "./deployment-baseline.json",
3039
- "./package.json": "./package.json"
3040
- },
3041
- files: [
3042
- "cordis.patch.yml",
3043
- "deployment-baseline.json",
3044
- "lib/*.js",
3045
- "lib/*.js.map",
3046
- "lib/types/**/*.d.ts",
3047
- "README.md",
3048
- "README.zh.md",
3049
- "CHANGELOG.md",
3050
- "CONTRIBUTING.md",
3051
- "SECURITY.md",
3052
- "AGENTS.md",
3053
- "docs/agent-readiness.md",
3054
- "docs/model-compatibility-acceptance.md",
3055
- "docs/single-route-migration.md",
3056
- "docs/session-search-routing.md",
3057
- "docs/npm-distribution.md",
3058
- "docs/dual-model.md",
3059
- "docs/official-first-016-alpha2.md",
3060
- "docs/official-first-020-rc1.md",
3061
- "docs/official-first-020-rc2.md",
3062
- "docs/web-lifecycle-rc2.md",
3063
- "docs/copilot-compaction.md",
3064
- "docs/manual-compaction-recovery.md",
3065
- "docs/copilot-usage.md",
3066
- "docs/copilot-accounts.md",
3067
- "docs/session-continuation.md",
3068
- "docs/account-management-experience.md",
3069
- "docs/mockups/copilot-account-management.html",
3070
- "docs/mockups/copilot-account-dropdown.html",
3071
- "docs/automatic-model-routing.md",
3072
- "docs/auto-task-routing.md",
3073
- "docs/auto-high-cost.md",
3074
- "docs/evidence-driven-iteration.md",
3075
- "docs/auto-iteration-review.json",
3076
- "scripts/iteration-review.mjs",
3077
- "docs/image-input-compatibility.md",
3078
- "output/auto-model-mockup/index.html",
3079
- "docs/images/dual-model-provenance.json",
3080
- "scripts/check-search-composition.mjs",
3081
- "docs/images/"
3082
- ],
3083
- keywords: [
3084
- "dsh",
3085
- "deepseek-harness",
3086
- "plugin",
3087
- "cordis",
3088
- "github-copilot",
3089
- "oauth",
3090
- "model-provider",
3091
- "hosted-search",
3092
- "web-search",
3093
- "openai-responses",
3094
- "typescript"
3095
- ],
3096
- license: "MIT",
3097
- engines: {
3098
- "node": ">=22.19.0",
3099
- "dsh": "0.2.0-rc.2"
3100
- },
3101
- scripts: {
3102
- "build": "pnpm clean && tsc -p tsconfig.json && tsdown",
3103
- "clean": "node -e \"require('node:fs').rmSync('lib', { recursive: true, force: true })\"",
3104
- "prepare": "tsc -p tsconfig.json && tsdown",
3105
- "prepack": "pnpm verify:baseline",
3106
- "test": "vitest run",
3107
- "test:watch": "vitest",
3108
- "typecheck": "tsc -p tsconfig.json --noEmit",
3109
- "typecheck:tests": "tsc -p tsconfig.tests.json",
3110
- "test:scripts": "node --test \"tests/scripts/*.test.mjs\"",
3111
- "agent:describe": "node scripts/agent.mjs describe --json",
3112
- "agent:doctor": "node scripts/agent.mjs doctor --json",
3113
- "agent:plan": "node scripts/agent.mjs plan",
3114
- "preflight:search": "node scripts/check-search-composition.mjs",
3115
- "verify:agent": "node scripts/verify-agent-contract.mjs",
3116
- "verify:tarball": "node scripts/verify-tarball.mjs",
3117
- "verify:baseline": "node scripts/verify-deployment-baseline.mjs",
3118
- "verify:package": "node scripts/verify-package.mjs",
3119
- "verify:controlled-core": "node scripts/verify-controlled-core.mjs",
3120
- "verify:reasoning-ui": "node scripts/verify-reasoning-presentation.mjs",
3121
- "verify:upstream": "node scripts/verify-upstream-baseline.mjs",
3122
- "release:check": "node scripts/release-policy.mjs",
3123
- "verify": "pnpm verify:agent && pnpm typecheck && pnpm typecheck:tests && pnpm verify:baseline && pnpm build && pnpm test && pnpm test:scripts && pnpm verify:package"
3124
- },
3125
- peerDependencies: {
3126
- "@deepseek-ai/cordis": "^4.0.4",
3127
- "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
3128
- "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
3129
- "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
3130
- "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
3131
- "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
3132
- "@deepseek-ai/dsh-api-remotes": "0.2.0-rc.2",
3133
- "@deepseek-ai/dsh-authorization": "0.2.0-rc.2",
3134
- "@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
3135
- "@deepseek-ai/dsh-client-ui-settings-models": "0.2.0-rc.2",
3136
- "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
3137
- "@deepseek-ai/dsh-credentials": "0.2.0-rc.2",
3138
- "@deepseek-ai/dsh-launch-environment": "0.2.0-rc.2",
3139
- "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
3140
- "@deepseek-ai/dsh-llm-pi-ai": "0.2.0-rc.2",
3141
- "@deepseek-ai/dsh-session": "0.2.0-rc.2",
3142
- "@deepseek-ai/dsh-scope": "0.2.0-rc.2",
3143
- "@deepseek-ai/dsh-settings": "0.2.0-rc.2",
3144
- "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
3145
- "@deepseek-ai/dsh-web": "0.2.0-rc.2",
3146
- "@deepseek-ai/dsh-web-search-deepseek": "0.2.0-rc.2",
3147
- "@deepseek-ai/schemastery": "^3.18.4"
3148
- },
3149
- peerDependenciesMeta: {
3150
- "@deepseek-ai/dsh-web-search-deepseek": { "optional": true },
3151
- "@deepseek-ai/dsh-launch-environment": { "optional": true },
3152
- "@deepseek-ai/dsh-api-remotes": { "optional": true },
3153
- "@deepseek-ai/dsh-client-ui-renderer": { "optional": true },
3154
- "@deepseek-ai/dsh-client-ui-settings-models": { "optional": true },
3155
- "@deepseek-ai/dsh-client-ui-slots": { "optional": true },
3156
- "@deepseek-ai/dsh-typert-protocol": { "optional": true }
3157
- },
3158
- dependencies: {
3159
- "@earendil-works/pi-ai": "0.87.1",
3160
- "undici": "6.28.1",
3161
- "zod": "^4.4.3"
3162
- },
3163
- devDependencies: {
3164
- "@deepseek-ai/cordis": "~4.0.4",
3165
- "@deepseek-ai/dsh-agent": "0.2.0-rc.2",
3166
- "@deepseek-ai/dsh-agent-default-model": "0.2.0-rc.2",
3167
- "@deepseek-ai/dsh-commands": "0.2.0-rc.2",
3168
- "@deepseek-ai/dsh-compaction": "0.2.0-rc.2",
3169
- "@deepseek-ai/dsh-compaction-basic": "0.2.0-rc.2",
3170
- "@deepseek-ai/dsh-jobs": "0.2.0-rc.2",
3171
- "@deepseek-ai/dsh-api-gateway": "0.2.0-rc.2",
3172
- "@deepseek-ai/dsh-api-remotes": "0.2.0-rc.2",
3173
- "@deepseek-ai/dsh-app-boot": "0.2.0-rc.2",
3174
- "@deepseek-ai/dsh-config-editor": "0.2.0-rc.2",
3175
- "@deepseek-ai/dsh-attachment": "0.2.0-rc.2",
3176
- "@deepseek-ai/dsh-authorization": "0.2.0-rc.2",
3177
- "@deepseek-ai/dsh-client-connection": "0.2.0-rc.2",
3178
- "@deepseek-ai/dsh-client-ui-renderer": "0.2.0-rc.2",
3179
- "@deepseek-ai/dsh-client-ui-settings-models": "0.2.0-rc.2",
3180
- "@deepseek-ai/dsh-client-ui-slots": "0.2.0-rc.2",
3181
- "@deepseek-ai/dsh-credentials": "0.2.0-rc.2",
3182
- "@deepseek-ai/dsh-fs": "0.2.0-rc.2",
3183
- "@deepseek-ai/dsh-launch-environment": "0.2.0-rc.2",
3184
- "@deepseek-ai/dsh-llm": "0.2.0-rc.2",
3185
- "@deepseek-ai/dsh-llm-pi-ai": "0.2.0-rc.2",
3186
- "@deepseek-ai/dsh-scope": "0.2.0-rc.2",
3187
- "@deepseek-ai/dsh-session": "0.2.0-rc.2",
3188
- "@deepseek-ai/dsh-session-format-catalog": "0.2.0-rc.2",
3189
- "@deepseek-ai/dsh-session-projection": "0.2.0-rc.2",
3190
- "@deepseek-ai/dsh-settings": "0.2.0-rc.2",
3191
- "@deepseek-ai/dsh-system-prompt": "0.2.0-rc.2",
3192
- "@deepseek-ai/dsh-tool-web": "0.2.0-rc.2",
3193
- "@deepseek-ai/dsh-tools": "0.2.0-rc.2",
3194
- "@deepseek-ai/dsh-typert-protocol": "0.2.0-rc.2",
3195
- "@deepseek-ai/dsh-typert-registry": "0.2.0-rc.2",
3196
- "@deepseek-ai/dsh-web": "0.2.0-rc.2",
3197
- "@deepseek-ai/dsh-web-search-deepseek": "0.2.0-rc.2",
3198
- "@deepseek-ai/schemastery": "^3.18.4",
3199
- "@types/node": "^22.0.0",
3200
- "@types/react": "~18.3.1",
3201
- "@types/react-dom": "18.3.7",
3202
- "jsdom": "^26.1.0",
3203
- "react": "^18.2.0",
3204
- "react-dom": "18.3.1",
3205
- "tsdown": "^0.22.2",
3206
- "typescript": "^5.9.0",
3207
- "unrun": "^0.3.1",
3208
- "vitest": "^3.2.0"
3209
- },
3210
- main: "lib/index.js",
3211
- types: "lib/types/index.d.ts",
3212
- imports: { "#package.json": "./package.json" },
3213
- dsh: {
3214
- "bundle": { "patch": "./cordis.patch.yml" },
3215
- "client": {
3216
- "external": ["react"],
3217
- "inject": ["@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-ui-settings-models"],
3218
- "platform": "web"
3647
+ toAuth: async (credential) => {
3648
+ guard.assertActive();
3649
+ const current = normalizeGitHubCopilotOAuthCredential(credential);
3650
+ guard.assertAccount(current);
3651
+ guard.assertEntitled(current, selected());
3652
+ let auth;
3653
+ try {
3654
+ auth = await oauth.toAuth(current);
3655
+ } catch {
3656
+ throw new Error("COPILOT_MANAGED_AUTH_DERIVATION_FAILED");
3657
+ }
3658
+ guard.assertActive();
3659
+ guard.assertEntitled(current, selected());
3660
+ return {
3661
+ ...auth,
3662
+ baseUrl: trustedGitHubCopilotBaseUrl(auth.baseUrl ?? baseURL, current)
3663
+ };
3219
3664
  }
3220
- }
3221
- };
3665
+ };
3666
+ const provider = {
3667
+ id: GITHUB_COPILOT_PREVIEW_PROVIDER_ID,
3668
+ name: "GitHub Copilot",
3669
+ baseUrl: accountBaseURL(baseURL),
3670
+ auth: Object.freeze({ oauth: Object.freeze(guardedOAuth) }),
3671
+ getModels: () => models,
3672
+ filterModels: (candidates, credential) => {
3673
+ if (credential?.type !== "oauth") return [];
3674
+ const grant = normalizeGitHubCopilotOAuthCredential(credential);
3675
+ return candidates.filter((model) => {
3676
+ if (!table.has(model.id)) return false;
3677
+ try {
3678
+ guard.assertEntitled(grant, model.id);
3679
+ return true;
3680
+ } catch {
3681
+ return false;
3682
+ }
3683
+ });
3684
+ },
3685
+ streamSimple: (model, context, options) => lazyStream(model, async () => {
3686
+ guard.assertActive();
3687
+ const entry = table.get(model.id);
3688
+ if (model.provider !== "github-copilot-preview" || model.id !== selected() || entry === void 0 || model.api !== entry.api) throw new Error("COPILOT_MANAGED_MODEL_MISMATCH");
3689
+ guard.inspectRequest?.(model, context, options);
3690
+ const lease = await guard.beforeWire(model, options);
3691
+ if (typeof options?.apiKey !== "string" || options.apiKey.length === 0) {
3692
+ lease.release();
3693
+ throw new Error("COPILOT_MANAGED_OAUTH_REQUIRED");
3694
+ }
3695
+ let liveness;
3696
+ try {
3697
+ if (guard.streamIdleTimeoutMs !== void 0) {
3698
+ liveness = new CopilotStreamLiveness(guard.streamIdleTimeoutMs, lease.signal);
3699
+ guard.onStreamLiveness?.(liveness);
3700
+ }
3701
+ } catch (error) {
3702
+ liveness?.dispose();
3703
+ lease.release();
3704
+ throw error;
3705
+ }
3706
+ let idleReported = false;
3707
+ const reportIdleFailure = () => {
3708
+ if (!idleReported && liveness?.signal.reason instanceof CopilotStreamIdleError && !lease.signal.aborted && !options.signal?.aborted) {
3709
+ idleReported = true;
3710
+ guard.onStreamIdleTimeout?.(liveness.signal.reason);
3711
+ }
3712
+ };
3713
+ const headers = {};
3714
+ for (const [name, value] of Object.entries(options.headers ?? {})) if (name.toLowerCase() !== "authorization" && name.toLowerCase() !== "x-api-key") headers[name] = value;
3715
+ Object.assign(headers, buildCopilotDynamicHeaders({
3716
+ messages: context.messages,
3717
+ hasImages: hasCopilotVisionInput(context.messages)
3718
+ }));
3719
+ headers.authorization = `Bearer ${options.apiKey}`;
3720
+ headers["x-api-key"] = null;
3721
+ let unauthorized = false;
3722
+ const responses = model.api === "openai-responses";
3723
+ let retry;
3724
+ try {
3725
+ retry = responses ? guard.retryReplay?.begin(context, guard.retrySignal, options?.sessionId, model.id) : void 0;
3726
+ } catch (error) {
3727
+ liveness?.dispose();
3728
+ lease.release();
3729
+ throw error;
3730
+ }
3731
+ const reportReplayFailure = (error) => {
3732
+ if (lease.signal.aborted || options.signal?.aborted) return;
3733
+ try {
3734
+ guard.onReplayFailure?.(error);
3735
+ } catch {}
3736
+ };
3737
+ const onPayload = responses ? async (payload, selectedModel) => {
3738
+ const replacement = await options.onPayload?.(payload, selectedModel);
3739
+ if (lease.signal.aborted || options.signal?.aborted) throw new Error("COPILOT_MANAGED_ABORTED");
3740
+ try {
3741
+ const effective = replacement === void 0 ? payload : replacement;
3742
+ if (retry !== void 0) return await retry.normalize(effective, guard.recoverReplay);
3743
+ const normalized = normalizeCopilotResponsesPayload(effective);
3744
+ return guard.recoverReplay === void 0 ? normalized : await guard.recoverReplay(normalized);
3745
+ } catch (error) {
3746
+ if (error instanceof CopilotResponsesReplayError) reportReplayFailure(error);
3747
+ throw error;
3748
+ }
3749
+ } : options.onPayload;
3750
+ const fetch = options.fetch ?? globalThis.fetch;
3751
+ const observeResponse = async (input, init) => {
3752
+ guard.requestCheckpoint?.();
3753
+ guard.onRequestBodyTimeout?.(void 0);
3754
+ liveness?.beginRequest(typeof init?.body === "string" ? init.body : void 0);
3755
+ const replayHeaders = responses && init?.headers !== void 0 ? new Headers(init.headers) : void 0;
3756
+ const replayDispatch = responses ? {
3757
+ body: typeof init?.body === "string" ? init.body : void 0,
3758
+ sessionHeader: replayHeaders?.has("session_id"),
3759
+ clientRequestHeader: replayHeaders?.has("x-client-request-id")
3760
+ } : void 0;
3761
+ let response;
3762
+ const upload = guard.onRequestBodyTimeout === void 0 ? void 0 : createRequestUploadObserver();
3763
+ const startedAt = performance.now();
3764
+ try {
3765
+ response = await (upload === void 0 ? fetch(input, init) : upload.run(() => fetch(input, init)));
3766
+ } catch (error) {
3767
+ retry?.observe(void 0, 0);
3768
+ throw error;
3769
+ } finally {
3770
+ upload?.close();
3771
+ }
3772
+ const responseHeadersMs = performance.now() - startedAt;
3773
+ retry?.observe(typeof init?.body === "string" ? init.body : void 0, response.status);
3774
+ if (response.status === 408 && guard.onRequestBodyTimeout !== void 0) {
3775
+ const diagnostic = await requestBodyTimeoutDiagnostic(response, typeof init?.body === "string" ? init.body : void 0, lease.signal, {
3776
+ protocol: entry.api,
3777
+ responseHeadersMs,
3778
+ ...upload === void 0 ? {} : { upload: upload.snapshot() }
3779
+ });
3780
+ if (!lease.signal.aborted && !options.signal?.aborted) guard.onRequestBodyTimeout(diagnostic);
3781
+ }
3782
+ if (response.status === 401) {
3783
+ if (responses && await isCopilotInputItemScopeError(response, lease.signal)) {
3784
+ guard.onReplayScopeRejected?.(replayDispatch?.body);
3785
+ reportReplayFailure(new CopilotResponsesReplayError("scope-mismatch", replayDispatch));
3786
+ } else unauthorized = true;
3787
+ }
3788
+ return liveness?.observe(response) ?? response;
3789
+ };
3790
+ const wireOptions = model.api === "anthropic-messages" ? {
3791
+ ...options,
3792
+ signal: liveness?.signal ?? lease.signal,
3793
+ apiKey: void 0,
3794
+ headers,
3795
+ fetch: observeResponse
3796
+ } : {
3797
+ ...options,
3798
+ signal: liveness?.signal ?? lease.signal,
3799
+ headers,
3800
+ fetch: observeResponse,
3801
+ onPayload
3802
+ };
3803
+ if (!hasApi(model, "openai-responses") && !hasApi(model, "openai-completions") && !hasApi(model, "anthropic-messages")) {
3804
+ retry?.finish();
3805
+ liveness?.dispose();
3806
+ lease.release();
3807
+ throw new Error("COPILOT_MANAGED_PROTOCOL_UNSUPPORTED");
3808
+ }
3809
+ return (async function* () {
3810
+ try {
3811
+ for await (const event of native.streamSimple(model, context, wireOptions)) {
3812
+ reportIdleFailure();
3813
+ if (event.type === "error" && event.reason === "aborted" && lease.signal.reason instanceof ManagedWireAbortError) guard.onWireAbort?.(lease.signal.reason.code);
3814
+ yield event;
3815
+ }
3816
+ } finally {
3817
+ reportIdleFailure();
3818
+ liveness?.dispose();
3819
+ if (lease.signal.aborted || options.signal?.aborted) retry?.observe(void 0, 0);
3820
+ retry?.finish();
3821
+ lease.release();
3822
+ if (unauthorized && !guard.signal.aborted && !options.signal?.aborted) try {
3823
+ guard.onUnauthorized?.();
3824
+ } catch {}
3825
+ }
3826
+ })();
3827
+ })
3828
+ };
3829
+ return {
3830
+ provider: Object.freeze(coreProviderView(provider)),
3831
+ models
3832
+ };
3833
+ }
3222
3834
  //#endregion
3223
3835
  //#region lib/types/migration-status.js
3224
3836
  const { name: name$1, version } = package_default;
@@ -3858,15 +4470,34 @@ var CopilotAccountsHost = class {
3858
4470
  return this.viewForAccount(accountId);
3859
4471
  }
3860
4472
  async readIdentity(accountId, force) {
4473
+ const operation = beginDiagnostics(this.ctx, "identity-read");
4474
+ try {
4475
+ const view = await this.readIdentityObserved(accountId, force, operation);
4476
+ const reason = view.state === "error" ? diagnosticsReason(new Error(view.diagnostic)) : "none";
4477
+ operation?.finish(reason === "none" ? "success" : diagnosticsOutcome(reason), reason);
4478
+ return view;
4479
+ } catch (error) {
4480
+ const reason = diagnosticsReason(error);
4481
+ operation?.finish(diagnosticsOutcome(reason), reason);
4482
+ throw error;
4483
+ }
4484
+ }
4485
+ async readIdentityObserved(accountId, force, operation) {
3861
4486
  id(accountId);
3862
4487
  if (this.disposed) fail("COPILOT_ACCOUNTS_DISPOSED");
3863
4488
  let flight = this.identityFlights.get(accountId);
3864
4489
  let problem;
3865
4490
  const failed = this.identityFailures.get(accountId);
3866
4491
  const cached = this.identities.get(accountId);
3867
- if (flight === void 0 && !force && cached && Date.now() - cached.at < IDENTITY_TTL) return this.viewForAccount(accountId);
3868
- if (flight === void 0 && !force && failed && Date.now() - failed.at < IDENTITY_FAILURE_COOLDOWN) problem = failed.diagnostic;
3869
- else {
4492
+ if (flight === void 0 && !force && cached && Date.now() - cached.at < IDENTITY_TTL) {
4493
+ operation?.stage("cache-hit");
4494
+ return this.viewForAccount(accountId);
4495
+ }
4496
+ if (flight === void 0 && !force && failed && Date.now() - failed.at < IDENTITY_FAILURE_COOLDOWN) {
4497
+ problem = failed.diagnostic;
4498
+ operation?.stage("cooldown");
4499
+ } else {
4500
+ if (flight !== void 0) operation?.stage("joined-flight");
3870
4501
  if (flight === void 0) {
3871
4502
  if (this.identityFlights.size >= 32) fail("COPILOT_ACCOUNTS_LIMIT");
3872
4503
  const abort = new AbortController();
@@ -3878,15 +4509,20 @@ var CopilotAccountsHost = class {
3878
4509
  flight = {
3879
4510
  abort,
3880
4511
  promise: Promise.resolve().then(async () => {
4512
+ const observed = beginDiagnostics(this.ctx, "identity-flight");
4513
+ observed?.stage("identity-validation");
3881
4514
  let lease;
3882
4515
  try {
3883
4516
  signal.throwIfAborted();
3884
4517
  lease = this.acquire(void 0, false, accountId);
3885
4518
  await abortable$1(this.identity(lease.binding, signal), signal);
3886
4519
  this.identityFailures.delete(accountId);
4520
+ observed?.finish("success");
3887
4521
  return;
3888
4522
  } catch (error) {
3889
4523
  const problem = signal.aborted ? signal.reason instanceof DOMException && signal.reason.name === "TimeoutError" ? "COPILOT_ACCOUNTS_IDENTITY_TIMEOUT" : "COPILOT_ACCOUNTS_CHANGED" : diagnostic(error, "COPILOT_ACCOUNTS_IDENTITY_UNAVAILABLE");
4524
+ const reason = diagnosticsReason(new Error(problem));
4525
+ observed?.finish(diagnosticsOutcome(reason), reason);
3890
4526
  if (!abort.signal.aborted && !this.disposed) {
3891
4527
  this.identities.delete(accountId);
3892
4528
  this.unavailableIdentities.add(accountId);
@@ -3937,6 +4573,8 @@ var CopilotAccountsHost = class {
3937
4573
  if (!expectedKey || value === void 0 || copilotAccountKey(normalizeGitHubCopilotOAuthCredential(value)) !== expectedKey) fail("COPILOT_ACCOUNTS_CHANGED");
3938
4574
  }
3939
4575
  async switchAccount(accountId, expectedRevision) {
4576
+ const observed = beginDiagnostics(this.ctx, "account-global-switch");
4577
+ observed?.stage("host-received");
3940
4578
  let committed = false, fenced = false;
3941
4579
  try {
3942
4580
  id(accountId);
@@ -3956,9 +4594,11 @@ var CopilotAccountsHost = class {
3956
4594
  AbortSignal.timeout(6e4)
3957
4595
  ]);
3958
4596
  const identity = (async () => {
4597
+ observed?.stage("identity-validation");
3959
4598
  await this.identity(binding, signal);
3960
4599
  return this.identities.get(accountId)?.key;
3961
4600
  })();
4601
+ observed?.stage("model-validation");
3962
4602
  const models = this.validateModels(binding, signal);
3963
4603
  let identityKey;
3964
4604
  try {
@@ -3975,6 +4615,7 @@ var CopilotAccountsHost = class {
3975
4615
  if (this.leases.size > 0 || this.ctx.get("authorization")?.describe(recordKey("canonical"))?.inFlight === true) fail("COPILOT_ACCOUNTS_BUSY");
3976
4616
  const current = this.selection();
3977
4617
  if (current.revision !== expectedRevision || current.accountId !== before.accountId) fail("COPILOT_ACCOUNTS_CONFLICT");
4618
+ observed?.stage("cas");
3978
4619
  try {
3979
4620
  await this.settings().mutate("github-copilot", [{
3980
4621
  op: "set",
@@ -3991,6 +4632,7 @@ var CopilotAccountsHost = class {
3991
4632
  fail("COPILOT_ACCOUNTS_CONFLICT");
3992
4633
  }
3993
4634
  committed = true;
4635
+ observed?.stage("readback");
3994
4636
  const after = this.selection();
3995
4637
  if (after.accountId !== accountId || after.revision === expectedRevision) fail("COPILOT_ACCOUNTS_COMMIT_UNCERTAIN");
3996
4638
  await this.assertIdentityCurrent(this.capture(accountId), identityKey);
@@ -3998,10 +4640,21 @@ var CopilotAccountsHost = class {
3998
4640
  this.lastFailure = void 0;
3999
4641
  } catch (error) {
4000
4642
  this.lastFailure = committed ? "COPILOT_ACCOUNTS_COMMIT_UNCERTAIN" : diagnostic(error, "COPILOT_ACCOUNTS_CHANGED");
4643
+ const reason = diagnosticsReason(new Error(this.lastFailure));
4644
+ observed?.finish(diagnosticsOutcome(reason), reason);
4001
4645
  } finally {
4002
4646
  if (fenced) this.operation = void 0;
4003
4647
  }
4004
- return this.get();
4648
+ try {
4649
+ const view = await this.get();
4650
+ const reason = view.state === "error" ? diagnosticsReason(new Error(view.diagnostic)) : "none";
4651
+ observed?.finish(view.state === "error" ? diagnosticsOutcome(reason) : "success", reason);
4652
+ return view;
4653
+ } catch (error) {
4654
+ const reason = diagnosticsReason(error);
4655
+ observed?.finish(diagnosticsOutcome(reason), reason);
4656
+ throw error;
4657
+ }
4005
4658
  }
4006
4659
  async add() {
4007
4660
  return this.authorize(randomUUID());
@@ -5062,10 +5715,11 @@ var SessionAccountsHost = class {
5062
5715
  if (!binding) throw new Error("COPILOT_SESSION_ACCOUNTS_UNAVAILABLE");
5063
5716
  return this.bindingForAccount(binding.accountId);
5064
5717
  }
5065
- async set(agent, accountId, revision) {
5718
+ async set(agent, accountId, revision, observed) {
5066
5719
  const accounts = this.ctx.get("githubCopilotAccounts");
5067
5720
  if (!accounts) throw new Error("COPILOT_SESSION_ACCOUNTS_UNAVAILABLE");
5068
5721
  if (accountId !== null) {
5722
+ observed?.stage("identity-validation");
5069
5723
  const binding = this.bindingForAccount(accountId);
5070
5724
  await accounts.host.validateAccount(binding);
5071
5725
  }
@@ -5080,11 +5734,13 @@ var SessionAccountsHost = class {
5080
5734
  accountId
5081
5735
  });
5082
5736
  if (next.length > 2048) throw new Error("COPILOT_SESSION_ACCOUNTS_LIMIT");
5737
+ observed?.stage("cas");
5083
5738
  await settings.mutate("github-copilot", [{
5084
5739
  op: "set",
5085
5740
  path: ["sessionAccounts"],
5086
5741
  value: next
5087
5742
  }], revision);
5743
+ observed?.stage("readback");
5088
5744
  const actual = this.selected(agent);
5089
5745
  if (actual.source !== (accountId === null ? "global" : "session") || accountId !== null && actual.accountId !== accountId) throw new Error("COPILOT_SESSION_ACCOUNTS_COMMIT_UNCERTAIN");
5090
5746
  }
@@ -5256,8 +5912,20 @@ let SessionAccountController = (() => {
5256
5912
  };
5257
5913
  }
5258
5914
  async set(agent, accountId, revision) {
5259
- await this.owner.set(agent, accountId, revision);
5260
- return this.get(agent);
5915
+ const operation = beginDiagnostics(this.ctx, accountId === null ? "account-session-inherit" : "account-session-select");
5916
+ operation?.stage("host-received");
5917
+ try {
5918
+ await this.owner.set(agent, accountId, revision, operation);
5919
+ operation?.stage("readback");
5920
+ const result = await this.get(agent);
5921
+ const reason = result.accounts.state === "error" ? diagnosticsReason(new Error(result.accounts.diagnostic)) : "none";
5922
+ operation?.finish(result.accounts.state === "error" ? diagnosticsOutcome(reason) : "success", reason);
5923
+ return result;
5924
+ } catch (error) {
5925
+ const reason = diagnosticsReason(error);
5926
+ operation?.finish(diagnosticsOutcome(reason), reason);
5927
+ throw error;
5928
+ }
5261
5929
  }
5262
5930
  async refreshIdentity(agent) {
5263
5931
  return this.readIdentity(agent, true);
@@ -5311,21 +5979,21 @@ function isZeroContextUsage(usage) {
5311
5979
  //#endregion
5312
5980
  //#region lib/types/context-evidence.js
5313
5981
  const COPILOT_CONTEXT_EVIDENCE = "githubCopilotContextEvidence";
5314
- const count$2 = z$1.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
5315
- const routeSchema = z$1.object({
5316
- provider: z$1.string().min(1),
5317
- model: z$1.string().min(1)
5982
+ const count$2 = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
5983
+ const routeSchema = z.object({
5984
+ provider: z.string().min(1),
5985
+ model: z.string().min(1)
5318
5986
  }).strict();
5319
- const sampleSchema = z$1.object({
5987
+ const sampleSchema = z.object({
5320
5988
  tokens: count$2,
5321
5989
  seq: count$2,
5322
5990
  route: routeSchema
5323
5991
  }).strict();
5324
- const ContextEvidenceSchema = z$1.object({
5992
+ const ContextEvidenceSchema = z.object({
5325
5993
  route: routeSchema.nullable(),
5326
5994
  sample: sampleSchema.nullable(),
5327
- invalid: z$1.boolean(),
5328
- reason: z$1.enum([
5995
+ invalid: z.boolean(),
5996
+ reason: z.enum([
5329
5997
  "none",
5330
5998
  "failed-zero",
5331
5999
  "compaction",
@@ -5333,7 +6001,7 @@ const ContextEvidenceSchema = z$1.object({
5333
6001
  "unknown"
5334
6002
  ])
5335
6003
  }).strict();
5336
- const usageSchema = z$1.object({
6004
+ const usageSchema = z.object({
5337
6005
  inputTokens: count$2,
5338
6006
  outputTokens: count$2,
5339
6007
  cacheReadTokens: count$2.optional(),
@@ -5341,7 +6009,7 @@ const usageSchema = z$1.object({
5341
6009
  totalTokens: count$2.optional(),
5342
6010
  reasoningTokens: count$2.optional()
5343
6011
  });
5344
- function record$11(value) {
6012
+ function record$12(value) {
5345
6013
  return typeof value === "object" && value !== null && !Array.isArray(value);
5346
6014
  }
5347
6015
  function sameRoute$1(left, right) {
@@ -5360,10 +6028,10 @@ function initialContextEvidence() {
5360
6028
  }
5361
6029
  /** Read only counts and routing leaves; never message content or opaque replay. */
5362
6030
  function foldContextEvidence(state, event) {
5363
- if (!record$11(event) || typeof event.type !== "string" || !record$11(event.data)) return state;
6031
+ if (!record$12(event) || typeof event.type !== "string" || !record$12(event.data)) return state;
5364
6032
  if (event.type === "request/header" || event.type === "model/selection") {
5365
- const raw = event.type === "request/header" ? record$11(event.data.header) ? event.data.header.config : void 0 : event.data;
5366
- if (!record$11(raw)) return {
6033
+ const raw = event.type === "request/header" ? record$12(event.data.header) ? event.data.header.config : void 0 : event.data;
6034
+ if (!record$12(raw)) return {
5367
6035
  ...state,
5368
6036
  route: null,
5369
6037
  sample: null,
@@ -5402,7 +6070,7 @@ function foldContextEvidence(state, event) {
5402
6070
  if (!copilot(state.route)) return state;
5403
6071
  if (event.type === "assistant/message" && event.data.source !== void 0) {
5404
6072
  const source = event.data.source;
5405
- const parsed = routeSchema.safeParse(record$11(source) ? {
6073
+ const parsed = routeSchema.safeParse(record$12(source) ? {
5406
6074
  provider: source.provider,
5407
6075
  model: source.model
5408
6076
  } : source);
@@ -5418,7 +6086,7 @@ function foldContextEvidence(state, event) {
5418
6086
  const settledUsage = usage !== void 0;
5419
6087
  let terminal;
5420
6088
  for (const entry of stream) {
5421
- if (!record$11(entry) || entry.type !== "chunk" || !record$11(entry.chunk)) continue;
6089
+ if (!record$12(entry) || entry.type !== "chunk" || !record$12(entry.chunk)) continue;
5422
6090
  if (!settledUsage && entry.chunk.type === "usage") usage = entry.chunk.usage;
5423
6091
  if (entry.chunk.type === "finish") terminal = entry.chunk.reason;
5424
6092
  }
@@ -5432,7 +6100,7 @@ function foldContextEvidence(state, event) {
5432
6100
  };
5433
6101
  const value = parsed.data;
5434
6102
  const zero = isZeroContextUsage(value);
5435
- const successful = record$11(terminal) && (terminal.kind === "stop" || terminal.kind === "max-tokens" || terminal.kind === "tool-calls");
6103
+ const successful = record$12(terminal) && (terminal.kind === "stop" || terminal.kind === "max-tokens" || terminal.kind === "tool-calls");
5436
6104
  if (zero && !successful) {
5437
6105
  const reason = state.sample !== null || state.reason === "none" ? "failed-zero" : state.reason;
5438
6106
  return {
@@ -5474,7 +6142,7 @@ const contextEvidenceDefinition = {
5474
6142
  function installContextEvidence(ctx) {
5475
6143
  ctx.inject(["sessionProjections"], (scope) => {
5476
6144
  const registry = scope.get("sessionProjections");
5477
- if (!record$11(registry) || typeof registry.register !== "function") {
6145
+ if (!record$12(registry) || typeof registry.register !== "function") {
5478
6146
  scope.logger.warn("[github-copilot] COPILOT_CONTEXT_PROJECTION_UNAVAILABLE");
5479
6147
  return;
5480
6148
  }
@@ -5804,10 +6472,10 @@ const WEB_SEARCH_ROUTING_SETTINGS_NAMESPACE = "github-copilot-search-routing";
5804
6472
  /** Sentinel that disables the default/fixed search backend. */
5805
6473
  const NO_DEFAULT_SEARCH_PROVIDER = "none";
5806
6474
  /** User-facing routing settings; provider-specific credentials and models remain provider-owned. */
5807
- const WebSearchRoutingConfigSchema = z.object({
5808
- searchProvider: z.string(),
5809
- searchMode: z.union(["auto", "fixed"]).default("auto"),
5810
- defaultSearchProvider: z.string().default("deepseek-official")
6475
+ const WebSearchRoutingConfigSchema = z$1.object({
6476
+ searchProvider: z$1.string(),
6477
+ searchMode: z$1.union(["auto", "fixed"]).default("auto"),
6478
+ defaultSearchProvider: z$1.string().default("deepseek-official")
5811
6479
  });
5812
6480
  //#endregion
5813
6481
  //#region lib/types/config.js
@@ -5826,6 +6494,7 @@ function readInlineConfig(config) {
5826
6494
  const defaults = readConfigValue(config.continuationDefaultHistory);
5827
6495
  return {
5828
6496
  ...config,
6497
+ diagnosticsEnabled: readConfigValue(config.diagnosticsEnabled),
5829
6498
  continuationDefaultHistory: defaults === void 0 ? void 0 : Array.from(defaults, (row) => ({
5830
6499
  enabled: row.enabled,
5831
6500
  changedAt: row.changedAt
@@ -5856,51 +6525,52 @@ function readInlineConfig(config) {
5856
6525
  /** Longest timer either bound may take; `setTimeout`/`AbortSignal.timeout` refuse more. */
5857
6526
  const MAX_TIMEOUT_MS = 2147483647;
5858
6527
  /** Schema of the plugin's settings section. */
5859
- const Config = z.object({
5860
- enabled: z.boolean().default(true),
5861
- providers: z.array(z.string()).default([]),
5862
- includeSources: z.boolean().default(true),
5863
- stripServerTools: z.boolean().default(true),
5864
- idleTimeoutMs: z.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e5),
5865
- chatStreamIdleTimeoutMs: z.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e5),
5866
- chatStreamLiveness: z.boolean().default(true),
5867
- chatMaxRequestImageBytes: z.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(20971520),
5868
- probe: z.boolean().default(true),
5869
- probeTimeoutMs: z.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e4),
5870
- accountModelTtlMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(864e5),
5871
- accountModelFailureCooldownMs: z.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(3e5),
5872
- excludedModelIds: z.array(z.string()).default([]).hidden().volatile(),
5873
- highCostModelIds: z.array(z.string()).default([]).hidden().volatile(),
5874
- activeAccountId: z.string().hidden().volatile(),
5875
- sessionAccounts: z.array(z.object({
5876
- sessionId: z.string().min(1).max(256),
5877
- accountId: z.string().min(1).max(36)
6528
+ const Config = z$1.object({
6529
+ diagnosticsEnabled: z$1.boolean().default(false).hidden().volatile(),
6530
+ enabled: z$1.boolean().default(true),
6531
+ providers: z$1.array(z$1.string()).default([]),
6532
+ includeSources: z$1.boolean().default(true),
6533
+ stripServerTools: z$1.boolean().default(true),
6534
+ idleTimeoutMs: z$1.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e5),
6535
+ chatStreamIdleTimeoutMs: z$1.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e5),
6536
+ chatStreamLiveness: z$1.boolean().default(true),
6537
+ chatMaxRequestImageBytes: z$1.number().step(1).min(1).max(Number.MAX_SAFE_INTEGER).default(20971520),
6538
+ probe: z$1.boolean().default(true),
6539
+ probeTimeoutMs: z$1.number().step(1).min(1).max(MAX_TIMEOUT_MS).default(3e4),
6540
+ accountModelTtlMs: z$1.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(864e5),
6541
+ accountModelFailureCooldownMs: z$1.number().step(1).min(0).max(MAX_TIMEOUT_MS).default(3e5),
6542
+ excludedModelIds: z$1.array(z$1.string()).default([]).hidden().volatile(),
6543
+ highCostModelIds: z$1.array(z$1.string()).default([]).hidden().volatile(),
6544
+ activeAccountId: z$1.string().hidden().volatile(),
6545
+ sessionAccounts: z$1.array(z$1.object({
6546
+ sessionId: z$1.string().min(1).max(256),
6547
+ accountId: z$1.string().min(1).max(36)
5878
6548
  })).default([]).hidden().volatile(),
5879
- sessionContinuation: z.array(z.object({
5880
- sessionId: z.string().min(1).max(256),
5881
- version: z.const(1),
5882
- consentedAt: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER),
5883
- enabled: z.boolean()
6549
+ sessionContinuation: z$1.array(z$1.object({
6550
+ sessionId: z$1.string().min(1).max(256),
6551
+ version: z$1.const(1),
6552
+ consentedAt: z$1.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER),
6553
+ enabled: z$1.boolean()
5884
6554
  })).default([]).hidden().volatile(),
5885
- continuationDefaultHistory: z.array(z.object({
5886
- enabled: z.boolean(),
5887
- changedAt: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER)
6555
+ continuationDefaultHistory: z$1.array(z$1.object({
6556
+ enabled: z$1.boolean(),
6557
+ changedAt: z$1.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER)
5888
6558
  })).default([]).hidden().volatile(),
5889
- followParentModel: z.boolean().default(false).volatile(),
5890
- autoSemanticAssessment: z.boolean().default(true),
5891
- autoAllocationEvidence: z.boolean().default(true),
5892
- parentModelFollow: z.array(z.object({
5893
- childSessionId: z.string().min(1),
5894
- parentSessionId: z.string().min(1)
6559
+ followParentModel: z$1.boolean().default(false).volatile(),
6560
+ autoSemanticAssessment: z$1.boolean().default(true),
6561
+ autoAllocationEvidence: z$1.boolean().default(true),
6562
+ parentModelFollow: z$1.array(z$1.object({
6563
+ childSessionId: z$1.string().min(1),
6564
+ parentSessionId: z$1.string().min(1)
5895
6565
  })).default([]).hidden().volatile(),
5896
- requestBudgetSafetyTokens: z.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens),
5897
- requestBudgetPressureRatio: z.number().step(.01).min(.01).max(1).default(DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio),
5898
- compactionReasoning: z.union(["prefer-low", "preserve"]).default(DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning),
5899
- routeWebSearch: z.boolean().default(true),
5900
- searchFallback: z.union(["none", "deepseek"]).default("deepseek"),
5901
- searchModel: z.string().hidden().volatile(),
6566
+ requestBudgetSafetyTokens: z$1.number().step(1).min(0).max(Number.MAX_SAFE_INTEGER).default(DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens),
6567
+ requestBudgetPressureRatio: z$1.number().step(.01).min(.01).max(1).default(DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio),
6568
+ compactionReasoning: z$1.union(["prefer-low", "preserve"]).default(DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning),
6569
+ routeWebSearch: z$1.boolean().default(true),
6570
+ searchFallback: z$1.union(["none", "deepseek"]).default("deepseek"),
6571
+ searchModel: z$1.string().hidden().volatile(),
5902
6572
  searchRouting: WebSearchRoutingConfigSchema.default({}).volatile(),
5903
- temporaryRouteBackup: z.string().hidden().volatile()
6573
+ temporaryRouteBackup: z$1.string().hidden().volatile()
5904
6574
  });
5905
6575
  //#endregion
5906
6576
  //#region lib/types/search-tool-routing.js
@@ -6533,7 +7203,7 @@ function buildAnthropicWireBody(request, cfg, model) {
6533
7203
  }
6534
7204
  //#endregion
6535
7205
  //#region lib/types/responses-reasoning-text.js
6536
- function record$10(value) {
7206
+ function record$11(value) {
6537
7207
  return typeof value === "object" && value !== null;
6538
7208
  }
6539
7209
  function responseIndex(value) {
@@ -6591,13 +7261,13 @@ var ResponsesReasoningText = class {
6591
7261
  }
6592
7262
  /** Only recognized public text fields are examined; no copying of the item. */
6593
7263
  snapshot(item) {
6594
- if (!record$10(item) || item.type !== "reasoning") return "";
7264
+ if (!record$11(item) || item.type !== "reasoning") return "";
6595
7265
  let delta = "";
6596
7266
  for (const family of ["summary", "raw"]) {
6597
7267
  const value = family === "summary" ? item.summary : item.content;
6598
7268
  if (!Array.isArray(value)) continue;
6599
7269
  for (const [index, part] of value.entries()) {
6600
- if (!record$10(part) || part.type !== (family === "summary" ? "summary_text" : "reasoning_text")) continue;
7270
+ if (!record$11(part) || part.type !== (family === "summary" ? "summary_text" : "reasoning_text")) continue;
6601
7271
  delta += this.update(family, index, part.text, true);
6602
7272
  }
6603
7273
  }
@@ -7924,15 +8594,15 @@ function excludedModelSet(value) {
7924
8594
  //#endregion
7925
8595
  //#region lib/types/auto-allocation.js
7926
8596
  const AUTO_ALLOCATION_POLICY = "high-cost-v1";
7927
- const AutoAllocationSchema = z$1.object({
7928
- policyVersion: z$1.literal(AUTO_ALLOCATION_POLICY),
7929
- selectedModelId: z$1.string().min(1).max(512),
7930
- candidates: z$1.array(z$1.object({
7931
- modelId: z$1.string().min(1).max(512),
7932
- highCost: z$1.boolean(),
7933
- previous: z$1.boolean(),
7934
- weight: z$1.number().positive().max(1.5),
7935
- expectedShare: z$1.number().positive().max(1)
8597
+ const AutoAllocationSchema = z.object({
8598
+ policyVersion: z.literal(AUTO_ALLOCATION_POLICY),
8599
+ selectedModelId: z.string().min(1).max(512),
8600
+ candidates: z.array(z.object({
8601
+ modelId: z.string().min(1).max(512),
8602
+ highCost: z.boolean(),
8603
+ previous: z.boolean(),
8604
+ weight: z.number().positive().max(1.5),
8605
+ expectedShare: z.number().positive().max(1)
7936
8606
  }).strict()).min(1).max(512)
7937
8607
  }).strict().refine((value) => {
7938
8608
  const total = value.candidates.reduce((sum, row) => sum + row.weight, 0);
@@ -8936,13 +9606,13 @@ function resolveCopilotResponsesReasoning(ctx, request, candidate) {
8936
9606
  }
8937
9607
  //#endregion
8938
9608
  //#region lib/types/replay-recovery.js
8939
- function record$9(value) {
9609
+ function record$10(value) {
8940
9610
  return value !== null && typeof value === "object" && !Array.isArray(value);
8941
9611
  }
8942
9612
  function parsed(body) {
8943
9613
  if (requestBodyEvidence(body, "openai-responses").state !== "complete" || body === void 0) throw new Error("COPILOT_REPLAY_RECOVERY_EVIDENCE_UNAVAILABLE");
8944
9614
  const payload = JSON.parse(body);
8945
- if (!record$9(payload) || !Array.isArray(payload.input) || !payload.input.every(record$9)) throw new Error("COPILOT_REPLAY_RECOVERY_INVALID_PAYLOAD");
9615
+ if (!record$10(payload) || !Array.isArray(payload.input) || !payload.input.every(record$10)) throw new Error("COPILOT_REPLAY_RECOVERY_INVALID_PAYLOAD");
8946
9616
  return {
8947
9617
  input: payload.input,
8948
9618
  payload
@@ -9038,7 +9708,7 @@ var ReplayRecoveryStore = class {
9038
9708
  const value = hash(item);
9039
9709
  return value === void 0 || !admitted.has(value);
9040
9710
  }).length === decoded.input.length) return payload;
9041
- if (!record$9(payload) || !Array.isArray(payload.input)) throw new Error("COPILOT_REPLAY_RECOVERY_INVALID_PAYLOAD");
9711
+ if (!record$10(payload) || !Array.isArray(payload.input)) throw new Error("COPILOT_REPLAY_RECOVERY_INVALID_PAYLOAD");
9042
9712
  const input = payload.input.filter((_, index) => {
9043
9713
  const item = decoded.input[index];
9044
9714
  const value = hash(item);
@@ -9244,7 +9914,7 @@ const SESSION_CONTINUATION_LIMITS = Object.freeze({
9244
9914
  ciphertextCodeUnits: 67108864,
9245
9915
  chunkCodeUnits: 65536
9246
9916
  });
9247
- function record$8(value) {
9917
+ function record$9(value) {
9248
9918
  return typeof value === "object" && value !== null && !Array.isArray(value);
9249
9919
  }
9250
9920
  /** One admitted turn; fingerprints never become durable history or account provenance. */
@@ -9257,7 +9927,7 @@ var SessionContinuationTurn = class {
9257
9927
  async transform(payload, assertCurrent = () => {}) {
9258
9928
  assertCurrent();
9259
9929
  if (this.processing) throw new Error("COPILOT_CONTINUATION_PROCESSING_OVERLAP");
9260
- if (!record$8(payload) || !Array.isArray(payload.input) || payload.input.length > SESSION_CONTINUATION_LIMITS.inputItems) throw new Error("COPILOT_CONTINUATION_INVALID_PAYLOAD");
9930
+ if (!record$9(payload) || !Array.isArray(payload.input) || payload.input.length > SESSION_CONTINUATION_LIMITS.inputItems) throw new Error("COPILOT_CONTINUATION_INVALID_PAYLOAD");
9261
9931
  this.processing = true;
9262
9932
  try {
9263
9933
  const hashes = /* @__PURE__ */ new Map();
@@ -9268,7 +9938,7 @@ var SessionContinuationTurn = class {
9268
9938
  assertCurrent();
9269
9939
  }
9270
9940
  const item = payload.input[index];
9271
- if (!record$8(item)) throw new Error("COPILOT_CONTINUATION_INVALID_PAYLOAD");
9941
+ if (!record$9(item)) throw new Error("COPILOT_CONTINUATION_INVALID_PAYLOAD");
9272
9942
  if (item.type !== "reasoning") continue;
9273
9943
  const ciphertext = item.encrypted_content;
9274
9944
  if (typeof ciphertext !== "string" || !ciphertext || item.status !== void 0 && item.status !== "completed") throw new Error("COPILOT_CONTINUATION_UNSUPPORTED_REASONING");
@@ -9303,29 +9973,157 @@ var SessionContinuationTurn = class {
9303
9973
  };
9304
9974
  //#endregion
9305
9975
  //#region lib/types/session-continuation-types.js
9306
- const SessionContinuationPreferenceSchema = z$1.object({
9307
- sessionId: z$1.string().min(1).max(256).refine((value) => !/[\p{Cc}\p{Cf}]/u.test(value)),
9308
- version: z$1.literal(1),
9309
- consentedAt: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
9310
- enabled: z$1.boolean().optional()
9976
+ const COMPACTION_CONTINUATION = "githubCopilotCompactionLifecycle";
9977
+ const CompactionContinuationStatusSchema = z.object({
9978
+ id: z.string().min(1).max(256),
9979
+ state: z.enum([
9980
+ "running",
9981
+ "completed",
9982
+ "failed",
9983
+ "cancelled",
9984
+ "blocked"
9985
+ ])
9986
+ }).strict();
9987
+ const CompactionContinuationLifecycleSchema = z.object({
9988
+ id: z.string().nullable(),
9989
+ running: z.boolean()
9311
9990
  }).strict();
9312
- const SessionContinuationPreferencesSchema = z$1.array(SessionContinuationPreferenceSchema).max(2048).refine((rows) => new Set(rows.map((row) => row.sessionId)).size === rows.length);
9313
- const ContinuationDefaultHistorySchema = z$1.array(z$1.object({
9314
- enabled: z$1.boolean(),
9315
- changedAt: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
9991
+ const SessionContinuationPreferenceSchema = z.object({
9992
+ sessionId: z.string().min(1).max(256).refine((value) => !/[\p{Cc}\p{Cf}]/u.test(value)),
9993
+ version: z.literal(1),
9994
+ consentedAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
9995
+ enabled: z.boolean().optional()
9996
+ }).strict();
9997
+ const SessionContinuationPreferencesSchema = z.array(SessionContinuationPreferenceSchema).max(2048).refine((rows) => new Set(rows.map((row) => row.sessionId)).size === rows.length);
9998
+ const ContinuationDefaultHistorySchema = z.array(z.object({
9999
+ enabled: z.boolean(),
10000
+ changedAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
9316
10001
  }).strict()).max(2048).refine((rows) => rows.every((row, index) => index === 0 || row.changedAt > rows[index - 1].changedAt));
9317
- z$1.object({
9318
- enabled: z$1.boolean(),
9319
- revision: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
10002
+ z.object({
10003
+ enabled: z.boolean(),
10004
+ revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)
9320
10005
  }).strict();
9321
- z$1.object({
9322
- enabled: z$1.boolean(),
9323
- revision: z$1.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
9324
- activeTurnEnabled: z$1.boolean().optional(),
9325
- source: z$1.enum(["default", "session"]).optional(),
9326
- nextTurnAuthorized: z$1.boolean().optional()
10006
+ z.object({
10007
+ enabled: z.boolean(),
10008
+ revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
10009
+ activeTurnEnabled: z.boolean().optional(),
10010
+ source: z.enum(["default", "session"]).optional(),
10011
+ nextTurnAuthorized: z.boolean().optional(),
10012
+ compaction: CompactionContinuationStatusSchema.optional()
9327
10013
  }).strict();
9328
10014
  //#endregion
10015
+ //#region lib/types/compaction-continuation.js
10016
+ const compactionContinuationDefinition = {
10017
+ key: COMPACTION_CONTINUATION,
10018
+ stateVersion: 1,
10019
+ stateSchema: CompactionContinuationLifecycleSchema,
10020
+ init: () => ({
10021
+ id: null,
10022
+ running: false
10023
+ }),
10024
+ apply(state, event) {
10025
+ if (event.type === "compaction/start") return {
10026
+ id: event.data.compactionId,
10027
+ running: true
10028
+ };
10029
+ if (event.type === "compaction/end" && event.data.compactionId === state.id) return {
10030
+ ...state,
10031
+ running: false
10032
+ };
10033
+ return state;
10034
+ },
10035
+ wire: {
10036
+ viewSchema: CompactionContinuationLifecycleSchema,
10037
+ view: (state) => state
10038
+ }
10039
+ };
10040
+ function record$8(value) {
10041
+ return typeof value === "object" && value !== null && !Array.isArray(value);
10042
+ }
10043
+ /** Native brackets authorize scope, never loss; the existing Session policy authorizes loss. */
10044
+ function installCompactionContinuation(ctx, enabled) {
10045
+ const operations = /* @__PURE__ */ new Map();
10046
+ const statuses = /* @__PURE__ */ new Map();
10047
+ let disposed = false;
10048
+ const removeProjection = ctx.inject(["sessionProjections"], (scope) => {
10049
+ const registry = scope.get("sessionProjections");
10050
+ if (!record$8(registry) || typeof registry.register !== "function") throw new Error("COPILOT_CONTINUATION_COMPACTION_PROJECTION_UNAVAILABLE");
10051
+ const remove = registry.register(compactionContinuationDefinition);
10052
+ if (typeof remove !== "function") throw new Error("COPILOT_CONTINUATION_COMPACTION_PROJECTION_DISPOSER_UNAVAILABLE");
10053
+ return () => {
10054
+ remove();
10055
+ };
10056
+ });
10057
+ const removeEvents = ctx.on("session/event", (session, event) => {
10058
+ if (event.type === "compaction/start") {
10059
+ if (operations.size >= 64 || operations.has(session.id)) {
10060
+ ctx.logger.warn("COPILOT_CONTINUATION_COMPACTION_LIMIT");
10061
+ return;
10062
+ }
10063
+ operations.set(session.id, {
10064
+ session,
10065
+ id: event.data.compactionId,
10066
+ replaced: false
10067
+ });
10068
+ statuses.delete(session.id);
10069
+ }
10070
+ const operation = operations.get(session.id);
10071
+ if (!operation || operation.session !== session) return;
10072
+ if (event.type === "user/message" && event.data.source.kind === "compact-checkpoint" && event.data.source.compactionId === operation.id) operation.replaced = true;
10073
+ if (event.type !== "compaction/end" || event.data.compactionId !== operation.id) return;
10074
+ if (operation.enabled) statuses.set(session.id, {
10075
+ id: operation.id,
10076
+ state: event.data.error === void 0 && operation.replaced ? "completed" : operation.signal?.aborted ? "cancelled" : "failed"
10077
+ });
10078
+ else if (operation.enabled === false && typeof event.data.error === "string" && /(?:^|[^A-Z_])COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH(?:$|[^A-Z_])/.test(event.data.error)) statuses.set(session.id, {
10079
+ id: operation.id,
10080
+ state: "blocked"
10081
+ });
10082
+ operations.delete(session.id);
10083
+ while (statuses.size > 128) statuses.delete(statuses.keys().next().value);
10084
+ });
10085
+ const removeAgent = ctx.on("agent/disposed", ({ agent }) => {
10086
+ operations.delete(agent.session.id);
10087
+ statuses.delete(agent.session.id);
10088
+ });
10089
+ return {
10090
+ status(agent) {
10091
+ const operation = operations.get(agent.session.id);
10092
+ return operation?.enabled ? {
10093
+ id: operation.id,
10094
+ state: "running"
10095
+ } : statuses.get(agent.session.id);
10096
+ },
10097
+ prepare(request) {
10098
+ if (request.provider !== "github-copilot-preview" || request.purpose !== "compaction") return void 0;
10099
+ if (!request.sessionId || !request.signal) throw new Error("COPILOT_CONTINUATION_COMPACTION_SCOPE_UNAVAILABLE");
10100
+ const operation = operations.get(request.sessionId);
10101
+ if (!operation) throw new Error("COPILOT_CONTINUATION_COMPACTION_BOUNDARY_UNAVAILABLE");
10102
+ const agent = ctx.get("agents")?.get(request.sessionId);
10103
+ if (!agent || agent.session !== operation.session) throw new Error("COPILOT_CONTINUATION_COMPACTION_AGENT_UNAVAILABLE");
10104
+ const initiator = ctx.get("agents")?.currentInitiator();
10105
+ if (initiator && initiator !== agent) throw new Error("COPILOT_CONTINUATION_COMPACTION_SCOPE_MISMATCH");
10106
+ operation.enabled ??= enabled(agent);
10107
+ if (!operation.enabled) return void 0;
10108
+ if (operation.model !== void 0 && operation.model !== request.model) throw new Error("COPILOT_CONTINUATION_COMPACTION_MODEL_CHANGED");
10109
+ operation.model = request.model;
10110
+ operation.signal = request.signal;
10111
+ const assertCurrent = () => {
10112
+ if (disposed || request.signal.aborted || operation.signal !== request.signal || operations.get(request.sessionId) !== operation) throw new Error("COPILOT_CONTINUATION_REVOKED");
10113
+ };
10114
+ return (payload) => new SessionContinuationTurn().transform(payload, assertCurrent);
10115
+ },
10116
+ dispose() {
10117
+ disposed = true;
10118
+ removeEvents();
10119
+ removeAgent();
10120
+ removeProjection.dispose();
10121
+ operations.clear();
10122
+ statuses.clear();
10123
+ }
10124
+ };
10125
+ }
10126
+ //#endregion
9329
10127
  //#region lib/types/session-continuation-host.js
9330
10128
  var __runInitializers$1 = function(thisArg, initializers, value) {
9331
10129
  var useValue = arguments.length > 2;
@@ -9455,11 +10253,13 @@ let SessionContinuationController = (() => {
9455
10253
  active = __runInitializers$1(this, _instanceExtraInitializers);
9456
10254
  once;
9457
10255
  ready;
9458
- constructor(ctx, active, once = /* @__PURE__ */ new Set(), ready = Promise.resolve()) {
10256
+ summaryStatus;
10257
+ constructor(ctx, active, once = /* @__PURE__ */ new Set(), ready = Promise.resolve(), summaryStatus = () => void 0) {
9459
10258
  super(ctx, "githubCopilotSessionContinuation");
9460
10259
  this.active = active;
9461
10260
  this.once = once;
9462
10261
  this.ready = ready;
10262
+ this.summaryStatus = summaryStatus;
9463
10263
  }
9464
10264
  async get(agent) {
9465
10265
  await this.ready;
@@ -9467,12 +10267,14 @@ let SessionContinuationController = (() => {
9467
10267
  if (!entry) throw new Error("COPILOT_CONTINUATION_SETTINGS_UNAVAILABLE");
9468
10268
  const admission = this.active.get(agent.session);
9469
10269
  const explicit = preferences(entry.value).find((row) => row.sessionId === agent.session.id);
10270
+ const compaction = this.summaryStatus(agent);
9470
10271
  return {
9471
10272
  enabled: resolveEnabled(agent, entry.value),
9472
10273
  source: explicit ? "session" : "default",
9473
10274
  nextTurnAuthorized: this.once.has(agent.session),
9474
10275
  revision: entry.revision,
9475
- ...admission ? { activeTurnEnabled: admission.enabled } : {}
10276
+ ...admission ? { activeTurnEnabled: admission.enabled } : {},
10277
+ ...compaction ? { compaction } : {}
9476
10278
  };
9477
10279
  }
9478
10280
  async set(agent, revision, enabled) {
@@ -9569,11 +10371,15 @@ function installSessionContinuation(ctx) {
9569
10371
  const active = /* @__PURE__ */ new Map();
9570
10372
  const once = /* @__PURE__ */ new Set();
9571
10373
  const requests = /* @__PURE__ */ new WeakMap();
10374
+ let initialized = false;
9572
10375
  const ready = (async () => {
9573
10376
  const settings = ctx.get("settings");
9574
10377
  const entry = settings?.describe({ redactSecrets: true }).find((row) => row.ns === "github-copilot");
9575
10378
  if (!settings || !entry) throw new Error("COPILOT_CONTINUATION_SETTINGS_UNAVAILABLE");
9576
- if (defaultHistory(entry.value).length) return;
10379
+ if (defaultHistory(entry.value).length) {
10380
+ initialized = true;
10381
+ return;
10382
+ }
9577
10383
  await settings.mutate("github-copilot", [{
9578
10384
  op: "set",
9579
10385
  path: ["continuationDefaultHistory"],
@@ -9583,9 +10389,14 @@ function installSessionContinuation(ctx) {
9583
10389
  }]
9584
10390
  }], entry.revision);
9585
10391
  if (!defaultHistory(readSettingsNamespace(ctx, "github-copilot")).length) throw new Error("COPILOT_CONTINUATION_COMMIT_UNCERTAIN");
10392
+ initialized = true;
9586
10393
  })();
9587
10394
  ready.catch(() => ctx.logger.warn("COPILOT_CONTINUATION_INITIALIZATION_FAILED"));
9588
- new SessionContinuationController(ctx, active, once, ready);
10395
+ const summaries = installCompactionContinuation(ctx, (agent) => {
10396
+ if (!initialized) throw new Error("COPILOT_CONTINUATION_SETTINGS_UNAVAILABLE");
10397
+ return active.get(agent.session)?.persistentEnabled ?? resolveEnabled(agent, readSettingsNamespace(ctx, "github-copilot"));
10398
+ });
10399
+ new SessionContinuationController(ctx, active, once, ready, (agent) => summaries.status(agent));
9589
10400
  const removeRequest = ctx.on("agent/request", async ({ agent, turn, step, signal }, next) => {
9590
10401
  const result = await next();
9591
10402
  if (signal.aborted || result.provider !== "github-copilot-preview") return result;
@@ -9595,10 +10406,12 @@ function installSessionContinuation(ctx) {
9595
10406
  let admission = active.get(agent.session);
9596
10407
  if (admission && admission.turn !== turn) throw new Error("COPILOT_CONTINUATION_TURN_UNSETTLED");
9597
10408
  if (!admission) {
10409
+ const persistentEnabled = resolveEnabled(agent, readSettingsNamespace(ctx, "github-copilot"));
9598
10410
  admission = {
9599
10411
  turn,
9600
10412
  step,
9601
- enabled: resolveEnabled(agent, readSettingsNamespace(ctx, "github-copilot")) || once.has(agent.session),
10413
+ enabled: persistentEnabled || once.has(agent.session),
10414
+ persistentEnabled,
9602
10415
  filter: new SessionContinuationTurn(),
9603
10416
  signal
9604
10417
  };
@@ -9621,6 +10434,7 @@ function installSessionContinuation(ctx) {
9621
10434
  return {
9622
10435
  ready,
9623
10436
  prepare(request) {
10437
+ if (request.purpose === "compaction") return summaries.prepare(request);
9624
10438
  if (request.provider !== "github-copilot-preview" || request.purpose !== void 0 || !request.signal) return void 0;
9625
10439
  const session = requests.get(request.signal);
9626
10440
  const admission = session && active.get(session);
@@ -9635,6 +10449,7 @@ function installSessionContinuation(ctx) {
9635
10449
  },
9636
10450
  dispose() {
9637
10451
  disposed = true;
10452
+ summaries.dispose();
9638
10453
  removeRequest();
9639
10454
  removeEvents();
9640
10455
  removeAgent();
@@ -9905,12 +10720,12 @@ function installCopilotPreStepPressure(ctx, callbacks) {
9905
10720
  }
9906
10721
  //#endregion
9907
10722
  //#region lib/types/auto-assessment-evidence.js
9908
- const milliseconds = z$1.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
9909
- const SemanticAssessmentEvidenceSchema = z$1.object({
9910
- modelId: z$1.string().min(1).max(200).regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u).optional(),
10723
+ const milliseconds = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
10724
+ const SemanticAssessmentEvidenceSchema = z.object({
10725
+ modelId: z.string().min(1).max(200).regex(/^[A-Za-z0-9][A-Za-z0-9._:/-]*$/u).optional(),
9911
10726
  budgetMs: milliseconds.refine((value) => value > 0),
9912
10727
  elapsedMs: milliseconds,
9913
- stage: z$1.enum([
10728
+ stage: z.enum([
9914
10729
  "preparing",
9915
10730
  "model-selected",
9916
10731
  "adapter-started",
@@ -9919,9 +10734,9 @@ const SemanticAssessmentEvidenceSchema = z$1.object({
9919
10734
  ]),
9920
10735
  adapterStartedMs: milliseconds.optional(),
9921
10736
  firstTextMs: milliseconds.optional(),
9922
- nativeFinish: z$1.enum(["stop", "non-stop"]).optional(),
9923
- outputCharacters: z$1.number().int().min(0).max(2049),
9924
- validation: z$1.enum([
10737
+ nativeFinish: z.enum(["stop", "non-stop"]).optional(),
10738
+ outputCharacters: z.number().int().min(0).max(2049),
10739
+ validation: z.enum([
9925
10740
  "not-validated",
9926
10741
  "valid",
9927
10742
  "invalid",
@@ -9988,14 +10803,14 @@ function assessmentEvidence(budgetMs) {
9988
10803
  }
9989
10804
  //#endregion
9990
10805
  //#region lib/types/auto-task-assessment.js
9991
- const TaskAssessmentSchema = z$1.object({
9992
- demand: z$1.enum([
10806
+ const TaskAssessmentSchema = z.object({
10807
+ demand: z.enum([
9993
10808
  "simple",
9994
10809
  "routine",
9995
10810
  "complex",
9996
10811
  "unknown"
9997
10812
  ]),
9998
- signals: z$1.array(z$1.enum([
10813
+ signals: z.array(z.enum([
9999
10814
  "isolated-greeting",
10000
10815
  "bounded-transformation",
10001
10816
  "reasoning",
@@ -10431,30 +11246,30 @@ function autoModelInputModalities(models) {
10431
11246
  }
10432
11247
  //#endregion
10433
11248
  //#region lib/types/auto-allocation-evidence.js
10434
- const AutoAllocationSummarySchema = z$1.object({
10435
- policyVersion: z$1.literal(AUTO_ALLOCATION_POLICY),
10436
- scope: z$1.literal("viewed-session-host-lifetime"),
10437
- status: z$1.enum(["observed", "not-collected"]),
10438
- retainedDecisions: z$1.number().int().nonnegative().max(128),
10439
- noFitDecisions: z$1.number().int().nonnegative().max(128),
10440
- rowsTruncated: z$1.boolean(),
10441
- completeHistory: z$1.literal(false),
10442
- observationStart: z$1.number().int().nonnegative().nullable(),
10443
- observationEnd: z$1.number().int().nonnegative().nullable(),
10444
- rows: z$1.array(z$1.object({
10445
- modelId: z$1.string().min(1).max(512),
10446
- category: z$1.enum([
11249
+ const AutoAllocationSummarySchema = z.object({
11250
+ policyVersion: z.literal(AUTO_ALLOCATION_POLICY),
11251
+ scope: z.literal("viewed-session-host-lifetime"),
11252
+ status: z.enum(["observed", "not-collected"]),
11253
+ retainedDecisions: z.number().int().nonnegative().max(128),
11254
+ noFitDecisions: z.number().int().nonnegative().max(128),
11255
+ rowsTruncated: z.boolean(),
11256
+ completeHistory: z.literal(false),
11257
+ observationStart: z.number().int().nonnegative().nullable(),
11258
+ observationEnd: z.number().int().nonnegative().nullable(),
11259
+ rows: z.array(z.object({
11260
+ modelId: z.string().min(1).max(512),
11261
+ category: z.enum([
10447
11262
  "powerful",
10448
11263
  "versatile",
10449
11264
  "lightweight",
10450
11265
  "unknown"
10451
11266
  ]),
10452
- highCost: z$1.boolean(),
10453
- previous: z$1.boolean(),
10454
- weight: z$1.number().positive().max(1.5),
10455
- opportunities: z$1.number().int().positive().max(128),
10456
- expectedSelections: z$1.number().nonnegative().max(128),
10457
- selections: z$1.number().int().nonnegative().max(128)
11267
+ highCost: z.boolean(),
11268
+ previous: z.boolean(),
11269
+ weight: z.number().positive().max(1.5),
11270
+ opportunities: z.number().int().positive().max(128),
11271
+ expectedSelections: z.number().nonnegative().max(128),
11272
+ selections: z.number().int().nonnegative().max(128)
10458
11273
  }).strict()).max(512)
10459
11274
  }).strict();
10460
11275
  /** Recompute only from captured bounded decisions, never today's settings or history content. */
@@ -10517,10 +11332,10 @@ function summarizeAutoAllocations(explanations, window) {
10517
11332
  }
10518
11333
  //#endregion
10519
11334
  //#region lib/types/turn-selection.js
10520
- const ExplanationSchema = z$1.object({
11335
+ const ExplanationSchema = z.object({
10521
11336
  assessment: TaskAssessmentSchema.extend({
10522
- source: z$1.enum(["local", "semantic"]),
10523
- diagnostic: z$1.enum([
11337
+ source: z.enum(["local", "semantic"]),
11338
+ diagnostic: z.enum([
10524
11339
  "disabled",
10525
11340
  "unavailable",
10526
11341
  "invalid-result",
@@ -10530,46 +11345,46 @@ const ExplanationSchema = z$1.object({
10530
11345
  ]).optional(),
10531
11346
  semantic: SemanticAssessmentEvidenceSchema.optional()
10532
11347
  }).strict(),
10533
- targetCategory: z$1.enum([
11348
+ targetCategory: z.enum([
10534
11349
  "powerful",
10535
11350
  "versatile",
10536
11351
  "lightweight"
10537
11352
  ]),
10538
- selectedCategory: z$1.enum([
11353
+ selectedCategory: z.enum([
10539
11354
  "powerful",
10540
11355
  "versatile",
10541
11356
  "lightweight",
10542
11357
  "unknown"
10543
11358
  ]),
10544
- categoryCandidateCount: z$1.number().int().min(0).max(512),
10545
- method: z$1.enum([
11359
+ categoryCandidateCount: z.number().int().min(0).max(512),
11360
+ method: z.enum([
10546
11361
  "continuity",
10547
11362
  "equal-distribution",
10548
11363
  "weighted-distribution",
10549
11364
  "only-candidate",
10550
11365
  "no-fit"
10551
11366
  ]),
10552
- fallback: z$1.boolean(),
11367
+ fallback: z.boolean(),
10553
11368
  allocation: AutoAllocationSchema.optional()
10554
11369
  }).strict();
10555
- z$1.discriminatedUnion("mode", [
10556
- z$1.object({ mode: z$1.literal("unknown") }).strict(),
10557
- z$1.object({ mode: z$1.literal("manual") }).strict(),
10558
- z$1.object({
10559
- mode: z$1.literal("auto"),
10560
- preference: z$1.enum([
11370
+ z.discriminatedUnion("mode", [
11371
+ z.object({ mode: z.literal("unknown") }).strict(),
11372
+ z.object({ mode: z.literal("manual") }).strict(),
11373
+ z.object({
11374
+ mode: z.literal("auto"),
11375
+ preference: z.enum([
10561
11376
  "efficiency",
10562
11377
  "balance",
10563
11378
  "intelligence"
10564
11379
  ]),
10565
- reason: z$1.enum([
11380
+ reason: z.enum([
10566
11381
  "short-text-turn",
10567
11382
  "standard-turn",
10568
11383
  "large-structured-turn",
10569
11384
  "image-capability"
10570
11385
  ]),
10571
- candidateCount: z$1.number().int().positive(),
10572
- fittingCandidateCount: z$1.number().int().nonnegative().optional(),
11386
+ candidateCount: z.number().int().positive(),
11387
+ fittingCandidateCount: z.number().int().nonnegative().optional(),
10573
11388
  explanation: ExplanationSchema.optional()
10574
11389
  }).strict()
10575
11390
  ]);
@@ -10642,21 +11457,21 @@ var TurnSelectionStore = class {
10642
11457
  //#endregion
10643
11458
  //#region lib/types/turn-request-models.js
10644
11459
  const TURN_REQUEST_MODELS = "githubCopilotTurnRequestModels";
10645
- const count$1 = z$1.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
10646
- const route = z$1.object({
10647
- provider: z$1.string().trim().min(1).max(1024),
10648
- model: z$1.string().trim().min(1).max(1024)
11460
+ const count$1 = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
11461
+ const route = z.object({
11462
+ provider: z.string().trim().min(1).max(1024),
11463
+ model: z.string().trim().min(1).max(1024)
10649
11464
  }).strict();
10650
- const row = z$1.object({
10651
- routes: z$1.array(route).max(32),
10652
- incomplete: z$1.boolean()
11465
+ const row = z.object({
11466
+ routes: z.array(route).max(32),
11467
+ incomplete: z.boolean()
10653
11468
  }).strict().extend({ turn: count$1 }).strict();
10654
- const TurnRequestModelsStateSchema = z$1.object({
10655
- active: z$1.object({
11469
+ const TurnRequestModelsStateSchema = z.object({
11470
+ active: z.object({
10656
11471
  turn: count$1,
10657
11472
  step: count$1.nullable()
10658
11473
  }).strict().nullable(),
10659
- turns: z$1.array(row).max(128)
11474
+ turns: z.array(row).max(128)
10660
11475
  }).strict();
10661
11476
  function record$3(value) {
10662
11477
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -11016,15 +11831,15 @@ function resolveParentModel(child, bindings, lookup, followAll = false) {
11016
11831
  //#endregion
11017
11832
  //#region lib/types/auto-model-intent.js
11018
11833
  const AUTO_MODEL_INTENT_PROJECTION = "githubCopilotAutoModelIntent";
11019
- const count = z$1.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
11020
- const selectionSchema = z$1.object({
11021
- provider: z$1.string().min(1),
11022
- model: z$1.string().min(1)
11834
+ const count = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
11835
+ const selectionSchema = z.object({
11836
+ provider: z.string().min(1),
11837
+ model: z.string().min(1)
11023
11838
  }).strict();
11024
- const AutoModelIntentSchema = z$1.object({
11839
+ const AutoModelIntentSchema = z.object({
11025
11840
  inherited: count,
11026
11841
  selection: selectionSchema.nullable(),
11027
- blocked: z$1.boolean()
11842
+ blocked: z.boolean()
11028
11843
  }).strict();
11029
11844
  function record$1(value) {
11030
11845
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -11223,17 +12038,17 @@ function installAutoModelRouting(ctx, dependencies) {
11223
12038
  const agentDisposers = /* @__PURE__ */ new WeakMap();
11224
12039
  const activeDisposers = /* @__PURE__ */ new Set();
11225
12040
  const followed = /* @__PURE__ */ new WeakMap();
11226
- const selectionSchema = z$1.object({
11227
- provider: z$1.string().min(1),
11228
- model: z$1.string().min(1)
12041
+ const selectionSchema = z.object({
12042
+ provider: z.string().min(1),
12043
+ model: z.string().min(1)
11229
12044
  }).strict();
11230
- const followSchema = z$1.object({
11231
- inherited: z$1.number().int().nonnegative(),
11232
- turn: z$1.number().int().nonnegative().nullable(),
11233
- started: z$1.boolean(),
12045
+ const followSchema = z.object({
12046
+ inherited: z.number().int().nonnegative(),
12047
+ turn: z.number().int().nonnegative().nullable(),
12048
+ started: z.boolean(),
11234
12049
  explicit: selectionSchema.nullable(),
11235
- descriptor: z$1.boolean(),
11236
- blocked: z$1.boolean()
12050
+ descriptor: z.boolean(),
12051
+ blocked: z.boolean()
11237
12052
  }).strict();
11238
12053
  let removeFollowProjection;
11239
12054
  const followIntent = (agent) => {
@@ -12026,7 +12841,7 @@ var PreviewAdapter = class extends PiAiAdapter {
12026
12841
  if (typeof mapping !== "string" || mapping.length === 0) throw failure("COPILOT_PREVIEW_REASONING_UNSUPPORTED", "INVALID_REQUEST");
12027
12842
  }
12028
12843
  let requestFailure;
12029
- const recovery = owner.replayRecovery?.prepare(options);
12844
+ const recovery = options.purpose === "compaction" && model.api !== "openai-responses" ? void 0 : owner.replayRecovery?.prepare(options);
12030
12845
  let wireAbort;
12031
12846
  let bodyTimeout;
12032
12847
  let liveness;
@@ -12760,6 +13575,9 @@ function observeSettingsNamespace(ctx, namespace, config, hooks) {
12760
13575
  * @param config - the composition entry config, used as the settings base layer.
12761
13576
  */
12762
13577
  function apply(ctx, config) {
13578
+ ctx.plugin({ apply(scope) {
13579
+ new DiagnosticsController(scope);
13580
+ } });
12763
13581
  installCopilotToolSchemaCompatibility(ctx);
12764
13582
  installContextEvidence(ctx);
12765
13583
  let promptText = () => "";