dsh-github-copilot 0.4.0-alpha.128 → 0.4.0-alpha.130

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.
@@ -0,0 +1,295 @@
1
+ import { z } from 'zod';
2
+ import type { DiagnosticsSnapshot, DiagnosticsView } from './diagnostics-types.ts';
3
+ export declare const DiagnosticsAnalysisReportSchema: z.ZodObject<{
4
+ reportVersion: z.ZodLiteral<1>;
5
+ coverageVersion: z.ZodLiteral<1>;
6
+ interpretation: z.ZodLiteral<"descriptive-observations-only">;
7
+ source: z.ZodEnum<{
8
+ "reviewed-view": "reviewed-view";
9
+ "persisted-snapshot": "persisted-snapshot";
10
+ }>;
11
+ observedAt: z.ZodNumber;
12
+ snapshotAt: z.ZodNumber;
13
+ ageMs: z.ZodNullable<z.ZodNumber>;
14
+ epoch: z.ZodNumber;
15
+ coverageComplete: z.ZodLiteral<false>;
16
+ effectivenessVerified: z.ZodLiteral<false>;
17
+ gaps: z.ZodArray<z.ZodEnum<{
18
+ "clock-discontinuity": "clock-discontinuity";
19
+ "persisted-only": "persisted-only";
20
+ "live-enabled-state-unknown": "live-enabled-state-unknown";
21
+ "live-pending-state-unknown": "live-pending-state-unknown";
22
+ "unflushed-tail-unknown": "unflushed-tail-unknown";
23
+ "stored-pending-is-not-live": "stored-pending-is-not-live";
24
+ "no-retained-operation-observations": "no-retained-operation-observations";
25
+ "account-switch-not-observed": "account-switch-not-observed";
26
+ "compaction-not-observed": "compaction-not-observed";
27
+ "stale-snapshot": "stale-snapshot";
28
+ "expired-in-stored-snapshot": "expired-in-stored-snapshot";
29
+ "host-dropped": "host-dropped";
30
+ "client-dropped": "client-dropped";
31
+ "client-unconfirmed": "client-unconfirmed";
32
+ "retention-or-capacity-eviction": "retention-or-capacity-eviction";
33
+ "collector-saturated": "collector-saturated";
34
+ "interrupted-observations": "interrupted-observations";
35
+ "recorded-pause": "recorded-pause";
36
+ "unpersisted-observations": "unpersisted-observations";
37
+ "collection-paused": "collection-paused";
38
+ "storage-not-ready": "storage-not-ready";
39
+ "analysis-count-overflow": "analysis-count-overflow";
40
+ "no-cross-layer-correlation": "no-cross-layer-correlation";
41
+ "no-unique-impact": "no-unique-impact";
42
+ "hour-boundary-censoring": "hour-boundary-censoring";
43
+ "no-collection-coverage-clock": "no-collection-coverage-clock";
44
+ "no-calibrated-alert-thresholds": "no-calibrated-alert-thresholds";
45
+ "no-baseline-trend": "no-baseline-trend";
46
+ "no-root-cause-proof": "no-root-cause-proof";
47
+ }>>;
48
+ collection: z.ZodObject<{
49
+ enabled: z.ZodNullable<z.ZodBoolean>;
50
+ state: z.ZodNullable<z.ZodEnum<{
51
+ error: "error";
52
+ ready: "ready";
53
+ unavailable: "unavailable";
54
+ loading: "loading";
55
+ }>>;
56
+ diagnostic: z.ZodNullable<z.ZodEnum<{
57
+ none: "none";
58
+ "storage-unavailable": "storage-unavailable";
59
+ "storage-invalid": "storage-invalid";
60
+ "storage-write-failed": "storage-write-failed";
61
+ "profile-unavailable": "profile-unavailable";
62
+ "settings-unavailable": "settings-unavailable";
63
+ "settings-conflict": "settings-conflict";
64
+ "client-report-failed": "client-report-failed";
65
+ "client-report-revoked": "client-report-revoked";
66
+ closed: "closed";
67
+ }>>;
68
+ dirty: z.ZodNullable<z.ZodBoolean>;
69
+ persistedAt: z.ZodNullable<z.ZodNumber>;
70
+ }, z.core.$strict>;
71
+ counters: z.ZodObject<{
72
+ dropped: z.ZodNumber;
73
+ clientDropped: z.ZodNumber;
74
+ clientUnconfirmed: z.ZodNumber;
75
+ evicted: z.ZodNumber;
76
+ saturated: z.ZodNumber;
77
+ interrupted: z.ZodNumber;
78
+ }, z.core.$strict>;
79
+ populations: z.ZodArray<z.ZodObject<{
80
+ version: z.ZodString;
81
+ layer: z.ZodEnum<{
82
+ client: "client";
83
+ host: "host";
84
+ }>;
85
+ operation: z.ZodEnum<{
86
+ compaction: "compaction";
87
+ "account-global-switch": "account-global-switch";
88
+ "account-session-select": "account-session-select";
89
+ "account-session-inherit": "account-session-inherit";
90
+ "identity-read": "identity-read";
91
+ "identity-flight": "identity-flight";
92
+ "compaction-summary": "compaction-summary";
93
+ collection: "collection";
94
+ }>;
95
+ successMeaning: z.ZodEnum<{
96
+ "owner-terminal-observation-only": "owner-terminal-observation-only";
97
+ "matching-checkpoint-and-end-observed": "matching-checkpoint-and-end-observed";
98
+ "summary-call-fulfilled-not-checkpoint-commit": "summary-call-fulfilled-not-checkpoint-commit";
99
+ }>;
100
+ firstHour: z.ZodNumber;
101
+ lastHour: z.ZodNumber;
102
+ started: z.ZodObject<{
103
+ value: z.ZodNullable<z.ZodNumber>;
104
+ overflow: z.ZodBoolean;
105
+ }, z.core.$strict>;
106
+ terminalObservations: z.ZodObject<{
107
+ value: z.ZodNullable<z.ZodNumber>;
108
+ overflow: z.ZodBoolean;
109
+ }, z.core.$strict>;
110
+ outcomes: z.ZodObject<{
111
+ success: z.ZodObject<{
112
+ value: z.ZodNullable<z.ZodNumber>;
113
+ overflow: z.ZodBoolean;
114
+ }, z.core.$strict>;
115
+ 'no-op': z.ZodObject<{
116
+ value: z.ZodNullable<z.ZodNumber>;
117
+ overflow: z.ZodBoolean;
118
+ }, z.core.$strict>;
119
+ cancelled: z.ZodObject<{
120
+ value: z.ZodNullable<z.ZodNumber>;
121
+ overflow: z.ZodBoolean;
122
+ }, z.core.$strict>;
123
+ 'policy-rejected': z.ZodObject<{
124
+ value: z.ZodNullable<z.ZodNumber>;
125
+ overflow: z.ZodBoolean;
126
+ }, z.core.$strict>;
127
+ revoked: z.ZodObject<{
128
+ value: z.ZodNullable<z.ZodNumber>;
129
+ overflow: z.ZodBoolean;
130
+ }, z.core.$strict>;
131
+ 'environment-fault': z.ZodObject<{
132
+ value: z.ZodNullable<z.ZodNumber>;
133
+ overflow: z.ZodBoolean;
134
+ }, z.core.$strict>;
135
+ failed: z.ZodObject<{
136
+ value: z.ZodNullable<z.ZodNumber>;
137
+ overflow: z.ZodBoolean;
138
+ }, z.core.$strict>;
139
+ unknown: z.ZodObject<{
140
+ value: z.ZodNullable<z.ZodNumber>;
141
+ overflow: z.ZodBoolean;
142
+ }, z.core.$strict>;
143
+ interrupted: z.ZodObject<{
144
+ value: z.ZodNullable<z.ZodNumber>;
145
+ overflow: z.ZodBoolean;
146
+ }, z.core.$strict>;
147
+ }, z.core.$strict>;
148
+ terminalLatency: z.ZodArray<z.ZodObject<{
149
+ lowerMs: z.ZodNumber;
150
+ upperExclusiveMs: z.ZodNullable<z.ZodNumber>;
151
+ count: z.ZodObject<{
152
+ value: z.ZodNullable<z.ZodNumber>;
153
+ overflow: z.ZodBoolean;
154
+ }, z.core.$strict>;
155
+ }, z.core.$strict>>;
156
+ stageAgeObservations: z.ZodArray<z.ZodObject<{
157
+ lowerMs: z.ZodNumber;
158
+ upperExclusiveMs: z.ZodNullable<z.ZodNumber>;
159
+ count: z.ZodObject<{
160
+ value: z.ZodNullable<z.ZodNumber>;
161
+ overflow: z.ZodBoolean;
162
+ }, z.core.$strict>;
163
+ }, z.core.$strict>>;
164
+ pendingSamples: z.ZodObject<{
165
+ value: z.ZodNullable<z.ZodNumber>;
166
+ overflow: z.ZodBoolean;
167
+ }, z.core.$strict>;
168
+ pendingSampleAges: z.ZodArray<z.ZodObject<{
169
+ lowerMs: z.ZodNumber;
170
+ upperExclusiveMs: z.ZodNullable<z.ZodNumber>;
171
+ count: z.ZodObject<{
172
+ value: z.ZodNullable<z.ZodNumber>;
173
+ overflow: z.ZodBoolean;
174
+ }, z.core.$strict>;
175
+ }, z.core.$strict>>;
176
+ stageObservations: z.ZodObject<{
177
+ value: z.ZodNullable<z.ZodNumber>;
178
+ overflow: z.ZodBoolean;
179
+ }, z.core.$strict>;
180
+ startsMinusTerminals: z.ZodNull;
181
+ exactOperationFailureRate: z.ZodNull;
182
+ }, z.core.$strict>>;
183
+ pendingAtSnapshot: z.ZodArray<z.ZodObject<{
184
+ version: z.ZodString;
185
+ operation: z.ZodEnum<{
186
+ compaction: "compaction";
187
+ "account-global-switch": "account-global-switch";
188
+ "account-session-select": "account-session-select";
189
+ "account-session-inherit": "account-session-inherit";
190
+ "identity-read": "identity-read";
191
+ "identity-flight": "identity-flight";
192
+ "compaction-summary": "compaction-summary";
193
+ collection: "collection";
194
+ }>;
195
+ stage: z.ZodEnum<{
196
+ ended: "ended";
197
+ admitted: "admitted";
198
+ "rpc-invoked": "rpc-invoked";
199
+ "host-received": "host-received";
200
+ "identity-validation": "identity-validation";
201
+ "model-validation": "model-validation";
202
+ cas: "cas";
203
+ readback: "readback";
204
+ "response-received": "response-received";
205
+ decoded: "decoded";
206
+ "client-settled": "client-settled";
207
+ "summary-attempt": "summary-attempt";
208
+ "checkpoint-committed": "checkpoint-committed";
209
+ "cache-hit": "cache-hit";
210
+ "joined-flight": "joined-flight";
211
+ cooldown: "cooldown";
212
+ dispatched: "dispatched";
213
+ }>;
214
+ bucket: z.ZodNumber;
215
+ count: z.ZodNumber;
216
+ }, z.core.$strict>>;
217
+ investigationCandidates: z.ZodArray<z.ZodObject<{
218
+ fingerprint: z.ZodString;
219
+ category: z.ZodEnum<{
220
+ "recorded-failure": "recorded-failure";
221
+ "unknown-outcome": "unknown-outcome";
222
+ }>;
223
+ layer: z.ZodEnum<{
224
+ client: "client";
225
+ host: "host";
226
+ }>;
227
+ operation: z.ZodEnum<{
228
+ compaction: "compaction";
229
+ "account-global-switch": "account-global-switch";
230
+ "account-session-select": "account-session-select";
231
+ "account-session-inherit": "account-session-inherit";
232
+ "identity-read": "identity-read";
233
+ "identity-flight": "identity-flight";
234
+ "compaction-summary": "compaction-summary";
235
+ collection: "collection";
236
+ }>;
237
+ metric: z.ZodEnum<{
238
+ unknown: "unknown";
239
+ "environment-fault": "environment-fault";
240
+ failed: "failed";
241
+ }>;
242
+ reason: z.ZodEnum<{
243
+ none: "none";
244
+ COPILOT_ACCOUNTS_SETTINGS_UNAVAILABLE: "COPILOT_ACCOUNTS_SETTINGS_UNAVAILABLE";
245
+ COPILOT_ACCOUNTS_CHANGED: "COPILOT_ACCOUNTS_CHANGED";
246
+ COPILOT_ACCOUNTS_BUSY: "COPILOT_ACCOUNTS_BUSY";
247
+ COPILOT_ACCOUNTS_CONFLICT: "COPILOT_ACCOUNTS_CONFLICT";
248
+ COPILOT_ACCOUNTS_COMMIT_UNCERTAIN: "COPILOT_ACCOUNTS_COMMIT_UNCERTAIN";
249
+ COPILOT_ACCOUNTS_MODELS_FAILED: "COPILOT_ACCOUNTS_MODELS_FAILED";
250
+ COPILOT_ACCOUNTS_IDENTITY_UNAVAILABLE: "COPILOT_ACCOUNTS_IDENTITY_UNAVAILABLE";
251
+ COPILOT_ACCOUNTS_IDENTITY_INVALID: "COPILOT_ACCOUNTS_IDENTITY_INVALID";
252
+ COPILOT_ACCOUNTS_IDENTITY_TIMEOUT: "COPILOT_ACCOUNTS_IDENTITY_TIMEOUT";
253
+ COPILOT_ACCOUNTS_IDENTITY_TLS: "COPILOT_ACCOUNTS_IDENTITY_TLS";
254
+ COPILOT_ACCOUNTS_IDENTITY_NETWORK: "COPILOT_ACCOUNTS_IDENTITY_NETWORK";
255
+ COPILOT_ACCOUNTS_IDENTITY_AUTH_REJECTED: "COPILOT_ACCOUNTS_IDENTITY_AUTH_REJECTED";
256
+ COPILOT_ACCOUNTS_IDENTITY_RATE_LIMITED: "COPILOT_ACCOUNTS_IDENTITY_RATE_LIMITED";
257
+ COPILOT_ACCOUNTS_IDENTITY_HTTP_ERROR: "COPILOT_ACCOUNTS_IDENTITY_HTTP_ERROR";
258
+ unknown: "unknown";
259
+ "rpc-unavailable": "rpc-unavailable";
260
+ "decode-invalid": "decode-invalid";
261
+ COPILOT_SESSION_ACCOUNTS_UNAVAILABLE: "COPILOT_SESSION_ACCOUNTS_UNAVAILABLE";
262
+ COPILOT_SESSION_ACCOUNTS_SETTINGS_UNAVAILABLE: "COPILOT_SESSION_ACCOUNTS_SETTINGS_UNAVAILABLE";
263
+ COPILOT_SESSION_ACCOUNTS_COMMIT_UNCERTAIN: "COPILOT_SESSION_ACCOUNTS_COMMIT_UNCERTAIN";
264
+ COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH: "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH";
265
+ CONTEXT_WINDOW_EXCEEDED: "CONTEXT_WINDOW_EXCEEDED";
266
+ COPILOT_MANUAL_RECOVERY_FIXED_PREFIX: "COPILOT_MANUAL_RECOVERY_FIXED_PREFIX";
267
+ COPILOT_MANUAL_RECOVERY_INDIVISIBLE: "COPILOT_MANUAL_RECOVERY_INDIVISIBLE";
268
+ COPILOT_MANUAL_RECOVERY_CALL_LIMIT: "COPILOT_MANUAL_RECOVERY_CALL_LIMIT";
269
+ COPILOT_MANUAL_RECOVERY_EMPTY_SUMMARY: "COPILOT_MANUAL_RECOVERY_EMPTY_SUMMARY";
270
+ COPILOT_MANUAL_RECOVERY_UNBALANCED: "COPILOT_MANUAL_RECOVERY_UNBALANCED";
271
+ }>;
272
+ versions: z.ZodArray<z.ZodString>;
273
+ firstHour: z.ZodNumber;
274
+ lastHour: z.ZodNumber;
275
+ observations: z.ZodObject<{
276
+ value: z.ZodNullable<z.ZodNumber>;
277
+ overflow: z.ZodBoolean;
278
+ }, z.core.$strict>;
279
+ regressionProven: z.ZodLiteral<false>;
280
+ persistentFaultProven: z.ZodLiteral<false>;
281
+ rootCause: z.ZodLiteral<"unknown">;
282
+ }, z.core.$strict>>;
283
+ }, z.core.$strict>;
284
+ export type DiagnosticsAnalysisReport = z.infer<typeof DiagnosticsAnalysisReportSchema>;
285
+ export type DiagnosticsAnalysisSource = 'reviewed-view' | 'persisted-snapshot';
286
+ export declare function diagnosticsUnitName(profileName: string): string;
287
+ export declare function parseReviewedView(text: string): DiagnosticsView;
288
+ export declare function parsePersistedUnit(text: string, expectedUnit: string): DiagnosticsSnapshot;
289
+ export declare function analyzeSnapshot(input: unknown, options: {
290
+ source: DiagnosticsAnalysisSource;
291
+ observedAt: number;
292
+ view?: DiagnosticsView;
293
+ }): DiagnosticsAnalysisReport;
294
+ export declare function analyzeReviewedView(view: DiagnosticsView, observedAt: number): DiagnosticsAnalysisReport;
295
+ //# sourceMappingURL=diagnostics-analysis.d.ts.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-github-copilot",
3
3
  "description": "DSH companion for GitHub Copilot sign-in, account-aware model profiles, tool compatibility, and provider-hosted search.",
4
- "version": "0.4.0-alpha.128",
4
+ "version": "0.4.0-alpha.130",
5
5
  "publishConfig": {
6
6
  "access": "public",
7
7
  "registry": "https://registry.npmjs.org/",
@@ -76,6 +76,7 @@
76
76
  "docs/evidence-driven-iteration.md",
77
77
  "docs/plugin-diagnostics.md",
78
78
  "docs/auto-iteration-review.json",
79
+ "scripts/analyze-diagnostics.mjs",
79
80
  "scripts/iteration-review.mjs",
80
81
  "docs/image-input-compatibility.md",
81
82
  "output/auto-model-mockup/index.html",
@@ -231,6 +232,7 @@
231
232
  "typecheck": "tsc -p tsconfig.json --noEmit",
232
233
  "typecheck:tests": "tsc -p tsconfig.tests.json",
233
234
  "test:scripts": "node --test \"tests/scripts/*.test.mjs\"",
235
+ "diagnostics:analyze": "node scripts/analyze-diagnostics.mjs",
234
236
  "agent:describe": "node scripts/agent.mjs describe --json",
235
237
  "agent:doctor": "node scripts/agent.mjs doctor --json",
236
238
  "agent:plan": "node scripts/agent.mjs plan",
@@ -0,0 +1,91 @@
1
+ import { open } from 'node:fs/promises'
2
+ import { basename, isAbsolute, parse, resolve } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import {
5
+ analyzeReviewedView, analyzeSnapshot, diagnosticsUnitName, parsePersistedUnit, parseReviewedView,
6
+ } from '../lib/diagnostics-analysis.js'
7
+ import { readBoundedDiagnosticsFile } from '../lib/diagnostics-analysis-io.js'
8
+
9
+ const usage = 'Usage: node scripts/analyze-diagnostics.mjs --input <absolute-file> --mode persisted-unit --profile-name <name> --output <new-local-file>\n'
10
+ + ' or: node scripts/analyze-diagnostics.mjs --input <absolute-file> --mode reviewed-view --output <new-local-file>'
11
+ const supportedErrors = new Set([
12
+ 'INVALID_PROFILE', 'INVALID_UNIT', 'INVALID_SNAPSHOT', 'DUPLICATE_AGGREGATE',
13
+ 'INVALID_OPTIONS', 'INVALID_VIEW', 'INVALID_ARGUMENTS', 'INPUT_LIMIT', 'INVALID_JSON', 'INVALID_PATH',
14
+ 'SYMLINK_REJECTED', 'NOT_REGULAR_FILE', 'FILE_CHANGED', 'FILE_READ_FAILED', 'INVALID_UTF8',
15
+ 'INVALID_REPORT', 'OUTPUT_UNAVAILABLE',
16
+ ])
17
+
18
+ function parseArguments(args) {
19
+ const values = new Map()
20
+ for (let index = 0; index < args.length; index += 2) {
21
+ const key = args[index]
22
+ const value = args[index + 1]
23
+ if (!['--input', '--mode', '--profile-name', '--output'].includes(key)
24
+ || !value || value.startsWith('--') || values.has(key)) {
25
+ throw new Error('COPILOT_DIAGNOSTICS_ANALYSIS_INVALID_ARGUMENTS')
26
+ }
27
+ values.set(key, value)
28
+ }
29
+ const mode = values.get('--mode')
30
+ if (!values.has('--input') || !values.has('--output')
31
+ || !['persisted-unit', 'reviewed-view'].includes(mode)
32
+ || (mode === 'persisted-unit') !== values.has('--profile-name')) {
33
+ throw new Error('COPILOT_DIAGNOSTICS_ANALYSIS_INVALID_ARGUMENTS')
34
+ }
35
+ const input = values.get('--input')
36
+ const output = values.get('--output')
37
+ if (!isAbsolute(input) || !isAbsolute(output))
38
+ throw new Error('COPILOT_DIAGNOSTICS_ANALYSIS_INVALID_PATH')
39
+ const inputPath = resolve(input)
40
+ const outputPath = resolve(output)
41
+ const comparable = value => process.platform === 'win32' ? value.toLowerCase() : value
42
+ if (comparable(inputPath) === comparable(outputPath)
43
+ || (process.platform === 'win32' && parse(outputPath).root.startsWith('\\\\'))) {
44
+ throw new Error('COPILOT_DIAGNOSTICS_ANALYSIS_INVALID_PATH')
45
+ }
46
+ return {
47
+ inputPath, outputPath, mode,
48
+ profileName: values.get('--profile-name'),
49
+ }
50
+ }
51
+
52
+ function errorCode(error) {
53
+ const prefix = 'COPILOT_DIAGNOSTICS_ANALYSIS_'
54
+ if (error instanceof Error && error.message.startsWith(prefix)) {
55
+ const candidate = error.message.slice(prefix.length)
56
+ if (supportedErrors.has(candidate)) return candidate
57
+ }
58
+ return 'ANALYSIS_FAILED'
59
+ }
60
+
61
+ async function main(args) {
62
+ if (args.length === 1 && args[0] === '--help') {
63
+ process.stdout.write(`${usage}\n`)
64
+ return
65
+ }
66
+ const options = parseArguments(args)
67
+ const text = await readBoundedDiagnosticsFile(options.inputPath)
68
+ const observedAt = Date.now()
69
+ let report
70
+ if (options.mode === 'persisted-unit') {
71
+ const unitName = diagnosticsUnitName(options.profileName)
72
+ if (basename(options.inputPath) !== `${unitName}.json`)
73
+ throw new Error('COPILOT_DIAGNOSTICS_ANALYSIS_INVALID_UNIT')
74
+ const snapshot = parsePersistedUnit(text, unitName)
75
+ report = analyzeSnapshot(snapshot, { source: 'persisted-snapshot', observedAt })
76
+ } else {
77
+ report = analyzeReviewedView(parseReviewedView(text), observedAt)
78
+ }
79
+ let handle
80
+ try { handle = await open(options.outputPath, 'wx') } catch {
81
+ throw new Error('COPILOT_DIAGNOSTICS_ANALYSIS_OUTPUT_UNAVAILABLE')
82
+ }
83
+ try { await handle.writeFile(`${JSON.stringify(report, null, 2)}\n`, 'utf8') } finally { await handle.close() }
84
+ }
85
+
86
+ if (process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
87
+ main(process.argv.slice(2)).catch(error => {
88
+ process.stderr.write(`COPILOT_DIAGNOSTICS_ANALYSIS_${errorCode(error)}\n`)
89
+ process.exitCode = 1
90
+ })
91
+ }
@@ -1,268 +0,0 @@
1
- import { z } from "zod";
2
- //#region lib/types/diagnostics-types.js
3
- const DIAGNOSTICS_OPERATIONS = [
4
- "account-global-switch",
5
- "account-session-select",
6
- "account-session-inherit",
7
- "identity-read",
8
- "identity-flight",
9
- "compaction",
10
- "compaction-summary",
11
- "collection"
12
- ];
13
- const DIAGNOSTICS_STAGES = [
14
- "admitted",
15
- "rpc-invoked",
16
- "host-received",
17
- "identity-validation",
18
- "model-validation",
19
- "cas",
20
- "readback",
21
- "response-received",
22
- "decoded",
23
- "client-settled",
24
- "summary-attempt",
25
- "checkpoint-committed",
26
- "ended",
27
- "cache-hit",
28
- "joined-flight",
29
- "cooldown",
30
- "dispatched"
31
- ];
32
- const DIAGNOSTICS_METRICS = [
33
- "started",
34
- "stage",
35
- "success",
36
- "no-op",
37
- "cancelled",
38
- "policy-rejected",
39
- "revoked",
40
- "environment-fault",
41
- "failed",
42
- "unknown",
43
- "interrupted",
44
- "dropped",
45
- "paused",
46
- "expired",
47
- "clock-discontinuity",
48
- "pending-sample"
49
- ];
50
- const DIAGNOSTICS_REASONS = [
51
- "none",
52
- "unknown",
53
- "rpc-unavailable",
54
- "decode-invalid",
55
- "COPILOT_ACCOUNTS_BUSY",
56
- "COPILOT_ACCOUNTS_CONFLICT",
57
- "COPILOT_ACCOUNTS_CHANGED",
58
- "COPILOT_ACCOUNTS_COMMIT_UNCERTAIN",
59
- "COPILOT_ACCOUNTS_IDENTITY_TIMEOUT",
60
- "COPILOT_ACCOUNTS_IDENTITY_UNAVAILABLE",
61
- "COPILOT_ACCOUNTS_MODELS_FAILED",
62
- "COPILOT_ACCOUNTS_SETTINGS_UNAVAILABLE",
63
- "COPILOT_ACCOUNTS_IDENTITY_TLS",
64
- "COPILOT_ACCOUNTS_IDENTITY_NETWORK",
65
- "COPILOT_ACCOUNTS_IDENTITY_RATE_LIMITED",
66
- "COPILOT_ACCOUNTS_IDENTITY_AUTH_REJECTED",
67
- "COPILOT_ACCOUNTS_IDENTITY_HTTP_ERROR",
68
- "COPILOT_ACCOUNTS_IDENTITY_INVALID",
69
- "COPILOT_SESSION_ACCOUNTS_UNAVAILABLE",
70
- "COPILOT_SESSION_ACCOUNTS_SETTINGS_UNAVAILABLE",
71
- "COPILOT_SESSION_ACCOUNTS_COMMIT_UNCERTAIN",
72
- "COPILOT_RESPONSES_REPLAY_SCOPE_MISMATCH",
73
- "CONTEXT_WINDOW_EXCEEDED",
74
- "COPILOT_MANUAL_RECOVERY_FIXED_PREFIX",
75
- "COPILOT_MANUAL_RECOVERY_INDIVISIBLE",
76
- "COPILOT_MANUAL_RECOVERY_CALL_LIMIT",
77
- "COPILOT_MANUAL_RECOVERY_EMPTY_SUMMARY",
78
- "COPILOT_MANUAL_RECOVERY_UNBALANCED"
79
- ];
80
- const DIAGNOSTICS_MAX_ROWS = 4096;
81
- const DIAGNOSTICS_MAX_BYTES = 2097152;
82
- const DIAGNOSTICS_RETENTION_MS = 12096e5;
83
- const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
84
- const version = z.string().max(64).regex(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/);
85
- const DiagnosticsRowSchema = z.object({
86
- hour: integer.multipleOf(36e5),
87
- version,
88
- layer: z.enum(["client", "host"]),
89
- operation: z.enum(DIAGNOSTICS_OPERATIONS),
90
- stage: z.enum(DIAGNOSTICS_STAGES),
91
- metric: z.enum(DIAGNOSTICS_METRICS),
92
- reason: z.enum(DIAGNOSTICS_REASONS),
93
- bucket: z.number().int().min(0).max(7),
94
- count: integer.min(1)
95
- }).strict();
96
- const DiagnosticsPendingSchema = z.object({
97
- version,
98
- operation: z.enum(DIAGNOSTICS_OPERATIONS),
99
- stage: z.enum(DIAGNOSTICS_STAGES),
100
- bucket: z.number().int().min(0).max(7),
101
- count: integer.min(1).max(128)
102
- }).strict();
103
- const DiagnosticsSnapshotSchema = z.object({
104
- schemaVersion: z.literal(1),
105
- coverageVersion: z.literal(1),
106
- epoch: integer,
107
- updatedAt: integer,
108
- rows: z.array(DiagnosticsRowSchema).max(DIAGNOSTICS_MAX_ROWS),
109
- pending: z.array(DiagnosticsPendingSchema).max(128),
110
- dropped: integer,
111
- clientDropped: integer,
112
- clientUnconfirmed: integer,
113
- saturated: integer,
114
- evicted: integer,
115
- interrupted: integer
116
- }).strict().refine((value) => value.pending.reduce((sum, row) => sum + row.count, 0) <= 128, "Diagnostics pending capacity exceeded").refine((value) => JSON.stringify(value).length <= DIAGNOSTICS_MAX_BYTES, "Diagnostics capacity exceeded");
117
- const DiagnosticsViewSchema = z.object({
118
- enabled: z.boolean(),
119
- state: z.enum([
120
- "loading",
121
- "ready",
122
- "unavailable",
123
- "error"
124
- ]),
125
- diagnostic: z.enum([
126
- "none",
127
- "storage-unavailable",
128
- "storage-invalid",
129
- "storage-write-failed",
130
- "profile-unavailable",
131
- "settings-unavailable",
132
- "settings-conflict",
133
- "client-report-failed",
134
- "client-report-revoked",
135
- "closed"
136
- ]),
137
- persistedAt: integer.optional(),
138
- dirty: z.boolean(),
139
- snapshot: DiagnosticsSnapshotSchema
140
- }).strict();
141
- function diagnosticsBucket(ms) {
142
- return [
143
- 100,
144
- 500,
145
- 1e3,
146
- 5e3,
147
- 15e3,
148
- 6e4,
149
- 3e5
150
- ].findIndex((bound) => ms < bound) === -1 ? 7 : [
151
- 100,
152
- 500,
153
- 1e3,
154
- 5e3,
155
- 15e3,
156
- 6e4,
157
- 3e5
158
- ].findIndex((bound) => ms < bound);
159
- }
160
- function diagnosticsReason(error) {
161
- const seen = /* @__PURE__ */ new Set();
162
- for (let depth = 0; depth < 8 && error instanceof Error && !seen.has(error); depth++) {
163
- seen.add(error);
164
- const nativeCode = "code" in error ? error.code : void 0;
165
- const typed = DIAGNOSTICS_REASONS.find((code) => code !== "none" && code !== "unknown" && code === nativeCode);
166
- if (typed !== void 0) return typed;
167
- const message = error.message.slice(0, 4096);
168
- for (const code of DIAGNOSTICS_REASONS) if (code.startsWith("COPILOT_") || code === "CONTEXT_WINDOW_EXCEEDED") {
169
- if (new RegExp(`(?:^|[^A-Za-z0-9_])${code}(?:$|[^A-Za-z0-9_])`).test(message)) return code;
170
- }
171
- error = error.cause;
172
- }
173
- return "unknown";
174
- }
175
- function diagnosticsOutcome(reason) {
176
- if (reason === "COPILOT_ACCOUNTS_BUSY" || reason === "COPILOT_ACCOUNTS_CONFLICT") return "policy-rejected";
177
- if (reason === "COPILOT_ACCOUNTS_CHANGED") return "revoked";
178
- if (reason.endsWith("SETTINGS_UNAVAILABLE") || reason === "COPILOT_SESSION_ACCOUNTS_UNAVAILABLE") return "environment-fault";
179
- return "failed";
180
- }
181
- //#endregion
182
- //#region lib/types/request-budget.js
183
- /** The safety allowance matches the pinned native SDK; pressure is a separate opt-in check. */
184
- const DEFAULT_REQUEST_BUDGET_POLICY = Object.freeze({
185
- safetyTokens: 4096,
186
- pressureRatio: .9,
187
- compactionReasoning: "prefer-low"
188
- });
189
- /** Validate deployment policy before applying defaults; unknown keys fail rather than silently drift. */
190
- function resolveRequestBudgetPolicy(config = {}) {
191
- const keys = /* @__PURE__ */ new Set([
192
- "safetyTokens",
193
- "pressureRatio",
194
- "compactionReasoning"
195
- ]);
196
- for (const key of Object.keys(config)) if (!keys.has(key)) throw new Error(`COPILOT_REQUEST_BUDGET_POLICY_INVALID: unknown setting ${key}`);
197
- const safetyTokens = config.safetyTokens === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.safetyTokens : config.safetyTokens;
198
- const pressureRatio = config.pressureRatio === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.pressureRatio : config.pressureRatio;
199
- const compactionReasoning = config.compactionReasoning === void 0 ? DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning : config.compactionReasoning;
200
- if (!Number.isSafeInteger(safetyTokens) || safetyTokens < 0) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: safetyTokens must be a non-negative safe integer");
201
- if (!Number.isFinite(pressureRatio) || pressureRatio <= 0 || pressureRatio > 1) throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: pressureRatio must be greater than zero and at most one");
202
- if (compactionReasoning !== "prefer-low" && compactionReasoning !== "preserve") throw new Error("COPILOT_REQUEST_BUDGET_POLICY_INVALID: unsupported compactionReasoning");
203
- return Object.freeze({
204
- safetyTokens,
205
- pressureRatio,
206
- compactionReasoning
207
- });
208
- }
209
- function failure(code, message) {
210
- return Object.freeze({
211
- ok: false,
212
- code,
213
- message: `${code}: ${message}`
214
- });
215
- }
216
- function positiveInteger(value) {
217
- return Number.isSafeInteger(value) && value > 0;
218
- }
219
- /**
220
- * Reserve output under the combined context and independently enforce the prompt ceiling.
221
- * `policy` must come from resolveRequestBudgetPolicy; no caller cap or catalog object is changed.
222
- */
223
- function calculateRequestBudget(limits, requestedMaxTokens, policy = DEFAULT_REQUEST_BUDGET_POLICY) {
224
- const { contextWindow, maxInputTokens, maxTokens } = limits;
225
- if (!positiveInteger(contextWindow) || !positiveInteger(maxTokens) || maxInputTokens !== void 0 && !positiveInteger(maxInputTokens)) return failure("COPILOT_REQUEST_INVALID_LIMITS", "model token capacities must be positive safe integers");
226
- if (requestedMaxTokens !== void 0 && !positiveInteger(requestedMaxTokens)) return failure("COPILOT_REQUEST_INVALID_OUTPUT_LIMIT", "request output cap must be a positive safe integer");
227
- const outputReservation = requestedMaxTokens ?? maxTokens;
228
- if (outputReservation > maxTokens) return failure("COPILOT_REQUEST_OUTPUT_LIMIT_EXCEEDED", `request output cap ${outputReservation} exceeds model output capacity ${maxTokens}`);
229
- const contextInputLimit = contextWindow - outputReservation;
230
- const limitingFactor = maxInputTokens !== void 0 && maxInputTokens <= contextInputLimit ? "prompt" : "context";
231
- const hardInputLimit = Math.min(maxInputTokens ?? contextInputLimit, contextInputLimit) - policy.safetyTokens;
232
- if (hardInputLimit <= 0) return failure("COPILOT_REQUEST_NO_INPUT_HEADROOM", "output reservation and safety allowance leave no positive input budget");
233
- return Object.freeze({
234
- ok: true,
235
- budget: Object.freeze({
236
- contextWindow,
237
- ...maxInputTokens === void 0 ? {} : { maxInputTokens },
238
- maxOutputTokens: maxTokens,
239
- outputReservation,
240
- hardInputLimit,
241
- pressureInputLimit: Math.floor(hardInputLimit * policy.pressureRatio),
242
- limitingFactor
243
- })
244
- });
245
- }
246
- /**
247
- * Check an estimated full prompt; estimates are not provider-exact token counts.
248
- * Enable pressure only for an owned ordinary loop call with a compaction recovery path.
249
- * Auxiliary and agentless calls use hard admission, including compaction itself.
250
- */
251
- function assessRequestBudget(estimatedInput, budget, pressure = false) {
252
- if (!Number.isFinite(estimatedInput) || estimatedInput < 0 || estimatedInput > Number.MAX_SAFE_INTEGER) return failure("COPILOT_REQUEST_INVALID_ESTIMATE", "estimated input must be finite, non-negative, and safely representable");
253
- const input = Math.ceil(estimatedInput);
254
- if (input > budget.hardInputLimit) return failure(budget.limitingFactor === "prompt" ? "COPILOT_REQUEST_INPUT_LIMIT_EXCEEDED" : "COPILOT_REQUEST_CONTEXT_LIMIT_EXCEEDED", `estimated input ${input} exceeds input budget ${budget.hardInputLimit} with output reservation ${budget.outputReservation}`);
255
- if (pressure && input > budget.pressureInputLimit) return failure("COPILOT_REQUEST_PRESSURE_EXCEEDED", `estimated input ${input} exceeds proactive compaction budget ${budget.pressureInputLimit}`);
256
- return Object.freeze({ ok: true });
257
- }
258
- /**
259
- * Select a low-cost supported effort only for a caller-confirmed compaction request.
260
- * A supplied effort, including a materialized provider default, wins unchanged; native validation
261
- * remains authoritative. Unsupported low-cost controls preserve the provider default, never off/none.
262
- */
263
- function selectCompactionReasoning(supportedEfforts, requestedEffort, mode = DEFAULT_REQUEST_BUDGET_POLICY.compactionReasoning) {
264
- if (requestedEffort !== void 0 || mode === "preserve") return requestedEffort;
265
- return supportedEfforts.find((effort) => effort === "minimal") ?? supportedEfforts.find((effort) => effort === "low");
266
- }
267
- //#endregion
268
- export { selectCompactionReasoning as a, DiagnosticsRowSchema as c, diagnosticsBucket as d, diagnosticsOutcome as f, resolveRequestBudgetPolicy as i, DiagnosticsSnapshotSchema as l, assessRequestBudget as n, DIAGNOSTICS_MAX_ROWS as o, diagnosticsReason as p, calculateRequestBudget as r, DIAGNOSTICS_RETENTION_MS as s, DEFAULT_REQUEST_BUDGET_POLICY as t, DiagnosticsViewSchema as u };