@agentknight/sdk 0.9.56 → 0.9.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,14 @@
1
1
  import {
2
- ConversationNormalizer,
3
2
  LiveTimelineProjection,
4
3
  NotGitDirectoryError,
5
4
  PromptPreparationError,
6
5
  SESSION_PROJECT_IDENTITY_CONCURRENCY,
6
+ SessionDirectoryLister,
7
7
  SessionProjectIdentityError,
8
8
  SessionProjectIdentityReader,
9
9
  SessionRuntimeRegistry,
10
10
  SessionWorkbenchRuntime,
11
11
  isClosedCopilotConnection,
12
- isDisplayableHumanMessage,
13
12
  isDisposedCopilotSession,
14
13
  isSessionRestoreFailure,
15
14
  measureOperationStage,
@@ -18,26 +17,39 @@ import {
18
17
  recordTimelineSyncDiagnostic,
19
18
  resolveGitProjectIdentity,
20
19
  sanitizeGitRemoteUrl
21
- } from "./chunk-6ZPE7VIE.js";
20
+ } from "./chunk-LWJNDBIM.js";
22
21
  import "./chunk-IJPJQF7S.js";
22
+ import {
23
+ AnalyticsIndexResultSchema,
24
+ AnalyticsReplySchema,
25
+ CopilotSessionCompatibilityClient,
26
+ openSessionEventLog,
27
+ readSessionUpdatePage,
28
+ resolveCopilotSessionDirectory,
29
+ resumeWithCopilotSessionCompatibility
30
+ } from "./chunk-DP5KVGWF.js";
31
+ import {
32
+ ConversationNormalizer,
33
+ isDisplayableHumanMessage
34
+ } from "./chunk-ZDKBJFA2.js";
23
35
  import {
24
36
  assertMainSessionId,
25
37
  isResearchSessionId
26
- } from "./chunk-E7QL4CBT.js";
38
+ } from "./chunk-2MERNOK6.js";
27
39
  import {
28
40
  GroupChatError,
29
41
  GroupChatMessageSchema,
30
42
  GroupChatRuntime
31
- } from "./chunk-HFVA7ZOD.js";
32
- import {
33
- isContentfulAssistant
34
- } from "./chunk-5J7BK2Y7.js";
43
+ } from "./chunk-X3ZG6WMN.js";
44
+ import "./chunk-NDEJOXSX.js";
35
45
  import {
36
46
  AgentSessionRenameError,
37
- SessionOperationError,
38
47
  TimelinePageBudgetError,
39
48
  validateSessionName
40
- } from "./chunk-L3A736SO.js";
49
+ } from "./chunk-5DVJ7Y5W.js";
50
+ import {
51
+ SessionOperationError
52
+ } from "./chunk-3OIHMMDF.js";
41
53
  import {
42
54
  ConversationItemSchema,
43
55
  CopilotModelOptionSchema,
@@ -47,6 +59,7 @@ import {
47
59
  PromptImageAttachmentSchema,
48
60
  ReasoningEffortSchema,
49
61
  SESSION_TIMELINE_PAGE_SIZE,
62
+ SessionAnalyticsResultSchema,
50
63
  SessionAvatarPersonaSchema,
51
64
  SessionReasoningEffortSchema,
52
65
  SessionRemoteStatusSchema,
@@ -57,284 +70,16 @@ import {
57
70
  WorkbenchScheduleDraftSchema,
58
71
  WorkbenchScheduleEntrySchema,
59
72
  WorkbenchScheduleProposalSchema,
60
- WorkbenchScheduleSnapshotSchema
61
- } from "./chunk-K5CMKBW6.js";
73
+ WorkbenchScheduleSnapshotSchema,
74
+ WorkbenchTelemetrySchema
75
+ } from "./chunk-LO4ZRE77.js";
62
76
 
63
77
  // src/copilot-adapter.ts
64
78
  import { createHash as createHash4, randomUUID as randomUUID6 } from "node:crypto";
65
- import { readFile as readFile3, realpath as realpath3, stat as stat2 } from "node:fs/promises";
79
+ import { existsSync, statSync } from "node:fs";
80
+ import { readFile as readFile2, realpath as realpath2, stat } from "node:fs/promises";
66
81
  import { createRequire } from "node:module";
67
- import { basename as basename2, extname, isAbsolute as isAbsolute2, relative as relative2, resolve as resolve3 } from "node:path";
68
-
69
- // src/copilot-session-compatibility.ts
70
- import {
71
- appendFile,
72
- mkdir,
73
- readFile,
74
- readdir,
75
- rename,
76
- rm,
77
- stat,
78
- writeFile
79
- } from "node:fs/promises";
80
- import { homedir } from "node:os";
81
- import {
82
- dirname,
83
- isAbsolute,
84
- join,
85
- relative,
86
- resolve,
87
- sep
88
- } from "node:path";
89
- import {
90
- CopilotClient
91
- } from "@github/copilot-sdk";
92
- import { z } from "zod";
93
- var SessionIdSchema = z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u);
94
- var PermissionModeSchema = z.enum(["manual", "allow-all"]);
95
- var PermissionEventSchema = z.object({
96
- type: z.literal("session.permissions_changed"),
97
- data: z.object({
98
- previousMode: PermissionModeSchema,
99
- mode: PermissionModeSchema,
100
- previousAllowAllPermissions: z.boolean().optional(),
101
- allowAllPermissions: z.boolean().optional()
102
- }).passthrough()
103
- }).passthrough();
104
- var PERMISSION_EVENT_MARKER = '"type":"session.permissions_changed"';
105
- var PERMISSION_SCHEMA_MISMATCH = /Session file is corrupted \(line \d+: (?:missing field `previousAllowAllPermissions`|(?:data\.)?previousAllowAllPermissions: Required)\)/u;
106
- var VIRTUAL_SESSION_STATE_PATH = process.platform === "win32" ? "C:\\agentknight-session-state" : "/agentknight-session-state";
107
- function normalizeCopilotSessionEvents(content) {
108
- const output = [];
109
- let migratedEventCount = 0;
110
- let outputCursor = 0;
111
- let searchCursor = 0;
112
- let marker = content.indexOf(PERMISSION_EVENT_MARKER, searchCursor);
113
- while (marker !== -1) {
114
- const lineStart = content.lastIndexOf("\n", marker - 1) + 1;
115
- const nextNewline = content.indexOf("\n", marker);
116
- const lineEnd = nextNewline === -1 ? content.length : nextNewline;
117
- const hasCarriageReturn = lineEnd > lineStart && content.charCodeAt(lineEnd - 1) === 13;
118
- const jsonEnd = hasCarriageReturn ? lineEnd - 1 : lineEnd;
119
- const parsed = PermissionEventSchema.safeParse(
120
- JSON.parse(content.slice(lineStart, jsonEnd))
121
- );
122
- if (parsed.success && parsed.data.data.previousAllowAllPermissions === void 0 && parsed.data.data.allowAllPermissions === void 0) {
123
- output.push(
124
- content.slice(outputCursor, lineStart),
125
- JSON.stringify({
126
- ...parsed.data,
127
- data: {
128
- ...parsed.data.data,
129
- previousAllowAllPermissions: parsed.data.data.previousMode === "allow-all",
130
- allowAllPermissions: parsed.data.data.mode === "allow-all"
131
- }
132
- }),
133
- hasCarriageReturn ? "\r" : ""
134
- );
135
- outputCursor = lineEnd;
136
- migratedEventCount += 1;
137
- }
138
- searchCursor = lineEnd;
139
- marker = content.indexOf(PERMISSION_EVENT_MARKER, searchCursor);
140
- }
141
- if (migratedEventCount === 0) {
142
- return { content, migratedEventCount };
143
- }
144
- output.push(content.slice(outputCursor));
145
- return { content: output.join(""), migratedEventCount };
146
- }
147
- async function resumeWithCopilotSessionCompatibility(resume, resumeCompatibleSession) {
148
- try {
149
- return await resume();
150
- } catch (resumeError) {
151
- if (!(resumeError instanceof Error) || !PERMISSION_SCHEMA_MISMATCH.test(resumeError.message)) {
152
- throw resumeError;
153
- }
154
- return resumeCompatibleSession();
155
- }
156
- }
157
- var CopilotSessionCompatibilityClient = class {
158
- #environment;
159
- #workingDirectory;
160
- #client;
161
- #starting;
162
- constructor(environment = process.env, workingDirectory = process.cwd()) {
163
- this.#environment = environment;
164
- this.#workingDirectory = workingDirectory;
165
- }
166
- async resumeSession(sessionId, config) {
167
- const safeSessionId = SessionIdSchema.parse(sessionId);
168
- const client = await this.#getClient();
169
- return client.resumeSession(safeSessionId, {
170
- ...config,
171
- // The overlay provides files only; disabling Session Store avoids routing
172
- // SQLite through a provider that intentionally does not implement it.
173
- enableSessionStore: false,
174
- createSessionFsProvider: () => createLocalSessionProvider(
175
- safeSessionId,
176
- this.#environment,
177
- VIRTUAL_SESSION_STATE_PATH
178
- )
179
- });
180
- }
181
- async stop() {
182
- const client = this.#client;
183
- const starting = this.#starting;
184
- this.#client = void 0;
185
- this.#starting = void 0;
186
- if (client !== void 0) {
187
- return client.stop();
188
- }
189
- if (starting === void 0) {
190
- return [];
191
- }
192
- try {
193
- return (await starting).stop();
194
- } catch (error) {
195
- return [error instanceof Error ? error : new Error(String(error))];
196
- }
197
- }
198
- async forceStop() {
199
- const client = this.#client;
200
- const starting = this.#starting;
201
- this.#client = void 0;
202
- this.#starting = void 0;
203
- if (client !== void 0) {
204
- await client.forceStop();
205
- } else if (starting !== void 0) {
206
- await (await starting).forceStop();
207
- }
208
- }
209
- #getClient() {
210
- if (this.#client !== void 0) {
211
- return Promise.resolve(this.#client);
212
- }
213
- if (this.#starting !== void 0) {
214
- return this.#starting;
215
- }
216
- const client = new CopilotClient({
217
- mode: "copilot-cli",
218
- sessionFs: {
219
- conventions: process.platform === "win32" ? "windows" : "posix",
220
- initialCwd: this.#workingDirectory,
221
- sessionStatePath: VIRTUAL_SESSION_STATE_PATH
222
- }
223
- });
224
- const starting = client.start().then(
225
- () => {
226
- if (this.#starting === starting) {
227
- this.#client = client;
228
- this.#starting = void 0;
229
- }
230
- return client;
231
- },
232
- async (error) => {
233
- if (this.#starting === starting) {
234
- this.#starting = void 0;
235
- }
236
- await client.forceStop();
237
- throw error;
238
- }
239
- );
240
- this.#starting = starting;
241
- return starting;
242
- }
243
- };
244
- function resolveCopilotSessionDirectory(sessionId, environment = process.env) {
245
- const safeSessionId = SessionIdSchema.parse(sessionId);
246
- if (safeSessionId.endsWith(".") || /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/iu.test(safeSessionId)) {
247
- throw new Error("Expected a safe Copilot session identifier");
248
- }
249
- const configuredHome = environment.COPILOT_HOME?.trim();
250
- const copilotHome = resolve(
251
- configuredHome === void 0 || configuredHome.length === 0 ? join(homedir(), ".copilot") : configuredHome
252
- );
253
- return join(copilotHome, "session-state", safeSessionId);
254
- }
255
- function createLocalSessionProvider(sessionId, environment, virtualSessionStatePath) {
256
- const sessionDirectory = resolveCopilotSessionDirectory(sessionId, environment);
257
- const virtualRoot = resolve(virtualSessionStatePath);
258
- const resolveProviderPath = (path) => {
259
- const resolvedPath = resolve(path);
260
- const relativeToVirtualRoot = relative(virtualRoot, resolvedPath);
261
- const isWithinVirtualRoot = relativeToVirtualRoot === "" || !relativeToVirtualRoot.startsWith(`..${sep}`) && relativeToVirtualRoot !== ".." && !isAbsolute(relativeToVirtualRoot);
262
- const actualPath = isWithinVirtualRoot ? resolve(sessionDirectory, relativeToVirtualRoot) : resolvedPath;
263
- return {
264
- actualPath,
265
- isEventLog: isWithinVirtualRoot && relativeToVirtualRoot.replaceAll("\\", "/") === "events.jsonl"
266
- };
267
- };
268
- return {
269
- async readFile(path) {
270
- const resolved = resolveProviderPath(path);
271
- const content = await readFile(resolved.actualPath, "utf8");
272
- return resolved.isEventLog ? normalizeCopilotSessionEvents(content).content : content;
273
- },
274
- async writeFile(path, content, mode) {
275
- const { actualPath } = resolveProviderPath(path);
276
- await mkdir(dirname(actualPath), { recursive: true });
277
- await writeFile(actualPath, content, { encoding: "utf8", mode });
278
- },
279
- async appendFile(path, content, mode) {
280
- const { actualPath } = resolveProviderPath(path);
281
- await mkdir(dirname(actualPath), { recursive: true });
282
- await appendFile(actualPath, content, { encoding: "utf8", mode });
283
- },
284
- async exists(path) {
285
- const { actualPath } = resolveProviderPath(path);
286
- try {
287
- await stat(actualPath);
288
- return true;
289
- } catch (error) {
290
- if (isNodeError(error, "ENOENT")) {
291
- return false;
292
- }
293
- throw error;
294
- }
295
- },
296
- async stat(path) {
297
- const { actualPath } = resolveProviderPath(path);
298
- const value = await stat(actualPath);
299
- return {
300
- isFile: value.isFile(),
301
- isDirectory: value.isDirectory(),
302
- size: value.size,
303
- mtime: value.mtime.toISOString(),
304
- birthtime: value.birthtime.toISOString()
305
- };
306
- },
307
- async mkdir(path, recursive, mode) {
308
- const { actualPath } = resolveProviderPath(path);
309
- await mkdir(actualPath, { recursive, mode });
310
- },
311
- async readdir(path) {
312
- const { actualPath } = resolveProviderPath(path);
313
- return readdir(actualPath);
314
- },
315
- async readdirWithTypes(path) {
316
- const { actualPath } = resolveProviderPath(path);
317
- return (await readdir(actualPath, { withFileTypes: true })).map(
318
- (entry) => ({
319
- name: entry.name,
320
- type: entry.isDirectory() ? "directory" : "file"
321
- })
322
- );
323
- },
324
- async rm(path, recursive, force) {
325
- const { actualPath } = resolveProviderPath(path);
326
- await rm(actualPath, { recursive, force });
327
- },
328
- async rename(source, destination) {
329
- const { actualPath: sourcePath } = resolveProviderPath(source);
330
- const { actualPath: destinationPath } = resolveProviderPath(destination);
331
- await rename(sourcePath, destinationPath);
332
- }
333
- };
334
- }
335
- function isNodeError(error, code) {
336
- return error instanceof Error && "code" in error && error.code === code;
337
- }
82
+ import { basename as basename2, dirname as dirname2, extname, isAbsolute, join as join3, relative, resolve } from "node:path";
338
83
 
339
84
  // src/adapters/copilot/runtime/client-runtime.ts
340
85
  var CopilotClientRuntime = class {
@@ -560,8 +305,8 @@ var SessionConfiguration = class {
560
305
  const runtime = this.ports.state(sessionId);
561
306
  const previous = runtime.configuration.transition;
562
307
  let release = () => void 0;
563
- const current = new Promise((resolve4) => {
564
- release = resolve4;
308
+ const current = new Promise((resolve2) => {
309
+ release = resolve2;
565
310
  });
566
311
  runtime.configuration.transition = current;
567
312
  await previous;
@@ -796,8 +541,8 @@ import "@github/copilot-sdk";
796
541
 
797
542
  // src/prompt-attachments.ts
798
543
  import { createHash, randomUUID } from "node:crypto";
799
- import { lstat, mkdir as mkdir2, realpath, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
800
- import { basename, dirname as dirname2, join as join2 } from "node:path";
544
+ import { lstat, mkdir, realpath, rm, writeFile } from "node:fs/promises";
545
+ import { basename, dirname, join } from "node:path";
801
546
  function validatePromptAttachments(images, files) {
802
547
  const validateBytes = (attachment) => {
803
548
  const bytes = Buffer.from(attachment.data, "base64");
@@ -827,9 +572,9 @@ function hasCode(error, code) {
827
572
  return error instanceof Error && "code" in error && error.code === code;
828
573
  }
829
574
  async function uploadDirectory(sessionDirectory, create) {
830
- const home = dirname2(dirname2(sessionDirectory));
575
+ const home = dirname(dirname(sessionDirectory));
831
576
  if (create) {
832
- await mkdir2(home, { recursive: true, mode: 448 });
577
+ await mkdir(home, { recursive: true, mode: 448 });
833
578
  }
834
579
  let directory;
835
580
  try {
@@ -839,10 +584,10 @@ async function uploadDirectory(sessionDirectory, create) {
839
584
  throw error;
840
585
  }
841
586
  for (const segment of ["session-state", basename(sessionDirectory), "agentknight-uploads"]) {
842
- directory = join2(directory, segment);
587
+ directory = join(directory, segment);
843
588
  if (create) {
844
589
  try {
845
- await mkdir2(directory, { mode: 448 });
590
+ await mkdir(directory, { mode: 448 });
846
591
  } catch (error) {
847
592
  if (!hasCode(error, "EEXIST")) throw error;
848
593
  }
@@ -863,20 +608,20 @@ async function stagePromptAttachments(sessionId, validated) {
863
608
  if (validated.files.length === 0) return validated.images;
864
609
  const root = await uploadDirectory(resolveCopilotSessionDirectory(sessionId), true);
865
610
  if (root === void 0) throw new Error("Attachment storage is unavailable");
866
- const batchDirectory = join2(root, randomUUID());
867
- await mkdir2(batchDirectory, { mode: 448 });
611
+ const batchDirectory = join(root, randomUUID());
612
+ await mkdir(batchDirectory, { mode: 448 });
868
613
  try {
869
614
  const attachments = [...validated.images];
870
615
  for (const [index, { attachment, bytes }] of validated.files.entries()) {
871
616
  const name = attachment.name.replace(/[^a-zA-Z0-9._-]/gu, "_").slice(-100).replace(/[. ]+$/u, "");
872
- const path = join2(batchDirectory, `${index}-${name || "file"}`);
873
- await writeFile2(path, bytes, { flag: "wx", mode: 384, flush: true });
617
+ const path = join(batchDirectory, `${index}-${name || "file"}`);
618
+ await writeFile(path, bytes, { flag: "wx", mode: 384, flush: true });
874
619
  attachments.push({ type: "file", path, displayName: attachment.name });
875
620
  }
876
621
  return attachments;
877
622
  } catch (error) {
878
623
  try {
879
- await rm2(batchDirectory, { recursive: true, force: true });
624
+ await rm(batchDirectory, { recursive: true, force: true });
880
625
  } catch (cleanupError) {
881
626
  throw new AggregateError([error, cleanupError], "Failed to stage and clean up prompt attachments");
882
627
  }
@@ -886,7 +631,7 @@ async function stagePromptAttachments(sessionId, validated) {
886
631
  async function deletePromptAttachments(sessionDirectory) {
887
632
  const directory = await uploadDirectory(sessionDirectory, false);
888
633
  if (directory !== void 0) {
889
- await rm2(directory, { recursive: true, force: true });
634
+ await rm(directory, { recursive: true, force: true });
890
635
  }
891
636
  }
892
637
 
@@ -953,8 +698,8 @@ var SessionConnections = class {
953
698
  async reloadSessionWhenSendCompletes(sessionId, options = {}, expectedSession) {
954
699
  const runtime = this.#sessionRuntimes.getOrCreate(sessionId);
955
700
  while (runtime.connection.sendInProgressCount > 0 && (expectedSession === void 0 || runtime.connection.session === void 0 || runtime.connection.session === expectedSession)) {
956
- await new Promise((resolve4) => {
957
- runtime.connection.sendCompletionWaiters.add(resolve4);
701
+ await new Promise((resolve2) => {
702
+ runtime.connection.sendCompletionWaiters.add(resolve2);
958
703
  });
959
704
  if (this.ports.runtime().stopping) {
960
705
  throw new Error("Copilot adapter is stopping");
@@ -1187,8 +932,8 @@ var SessionConnections = class {
1187
932
  const remaining = runtime.connection.sendInProgressCount - 1;
1188
933
  if (remaining === 0) {
1189
934
  runtime.connection.sendInProgressCount = 0;
1190
- for (const resolve4 of runtime.connection.sendCompletionWaiters) {
1191
- resolve4();
935
+ for (const resolve2 of runtime.connection.sendCompletionWaiters) {
936
+ resolve2();
1192
937
  }
1193
938
  runtime.connection.sendCompletionWaiters.clear();
1194
939
  } else {
@@ -1527,8 +1272,8 @@ var TimelineImageAssets = class {
1527
1272
  }
1528
1273
  }
1529
1274
  if (normalizer.pendingImageAssetIds().length > 0) {
1530
- await new Promise((resolve4) => {
1531
- setTimeout(resolve4, IMAGE_ASSET_LIVE_GRACE_MS);
1275
+ await new Promise((resolve2) => {
1276
+ setTimeout(resolve2, IMAGE_ASSET_LIVE_GRACE_MS);
1532
1277
  });
1533
1278
  }
1534
1279
  const unresolvedAssetIds = normalizer.pendingImageAssetIds();
@@ -1791,256 +1536,6 @@ var PlanSnapshots = class {
1791
1536
 
1792
1537
  // src/adapters/copilot/timeline/timeline-history.ts
1793
1538
  import "@github/copilot-sdk";
1794
-
1795
- // src/session-update-reader.ts
1796
- import { lstat as lstat2, open, realpath as realpath2 } from "node:fs/promises";
1797
- import { resolve as resolve2 } from "node:path";
1798
- import { z as z2 } from "zod";
1799
- var MAX_HEAD_BYTES = 8 * 1024 * 1024;
1800
- var EnvelopeSchema = z2.object({
1801
- id: z2.string(),
1802
- type: z2.string(),
1803
- timestamp: z2.iso.datetime({ offset: true }),
1804
- agentId: z2.string().optional(),
1805
- data: z2.unknown()
1806
- });
1807
- var HumanSchema = z2.object({
1808
- content: z2.string(),
1809
- messageId: z2.string().optional(),
1810
- interactionId: z2.string().optional(),
1811
- source: z2.string().optional(),
1812
- isAutopilotContinuation: z2.boolean().optional()
1813
- });
1814
- var AssistantSchema = z2.object({
1815
- messageId: z2.string(),
1816
- content: z2.string(),
1817
- parentToolCallId: z2.string().optional(),
1818
- apiCallId: z2.string().optional(),
1819
- chunkIndex: z2.number().int().nonnegative().optional(),
1820
- chunkCount: z2.number().int().positive().optional(),
1821
- interactionId: z2.string().optional(),
1822
- turnId: z2.string().optional()
1823
- });
1824
- var ToolStartSchema = z2.object({
1825
- toolCallId: z2.string(),
1826
- toolName: z2.string(),
1827
- parentToolCallId: z2.string().optional()
1828
- });
1829
- var ImageSchema = z2.object({
1830
- type: z2.literal("image"),
1831
- data: z2.string(),
1832
- mimeType: z2.string()
1833
- });
1834
- var ImageReferenceSchema = z2.object({
1835
- type: z2.literal("image"),
1836
- assetId: z2.string(),
1837
- mimeType: z2.string(),
1838
- byteLength: z2.number()
1839
- });
1840
- var ToolCompleteSchema = z2.object({
1841
- toolCallId: z2.string(),
1842
- success: z2.boolean(),
1843
- result: z2.object({
1844
- content: z2.string().optional(),
1845
- binaryResultsForLlm: z2.array(z2.unknown()).optional(),
1846
- contents: z2.array(z2.unknown()).optional()
1847
- }).optional(),
1848
- toolDescription: z2.object({ name: z2.string() }).optional(),
1849
- parentToolCallId: z2.string().optional()
1850
- });
1851
- var NoticeSchema = z2.object({ message: z2.string() });
1852
- var NotificationSchema = z2.object({ kind: z2.object({ type: z2.string() }).passthrough() });
1853
- var ShellCompletedSchema = z2.object({
1854
- type: z2.literal("shell_completed"),
1855
- shellId: z2.string(),
1856
- exitCode: z2.number().int().optional()
1857
- });
1858
- function metadataEvent(value, preview = false) {
1859
- const event = EnvelopeSchema.parse(value);
1860
- const toolEvent = event.type === "tool.execution_start" || event.type === "tool.execution_complete";
1861
- if (event.agentId !== void 0 && !toolEvent) return void 0;
1862
- const base = {
1863
- id: event.id,
1864
- timestamp: event.timestamp,
1865
- parentId: null,
1866
- ...event.agentId === void 0 ? {} : { agentId: event.agentId }
1867
- };
1868
- switch (event.type) {
1869
- case "session.binary_asset": {
1870
- if (!preview) return void 0;
1871
- const parsed = ImageSchema.extend({ assetId: z2.string(), byteLength: z2.number() }).safeParse(event.data);
1872
- return parsed.success ? { ...base, type: "session.binary_asset", data: parsed.data } : void 0;
1873
- }
1874
- case "user.message": {
1875
- const data = HumanSchema.parse(event.data);
1876
- if (data.isAutopilotContinuation === true) return void 0;
1877
- return { ...base, type: "user.message", data: {
1878
- content: data.content,
1879
- ...data.messageId === void 0 ? {} : { messageId: data.messageId },
1880
- ...data.interactionId === void 0 ? {} : { interactionId: data.interactionId },
1881
- ...data.source === void 0 ? {} : { source: data.source }
1882
- } };
1883
- }
1884
- case "assistant.message": {
1885
- const data = AssistantSchema.parse(event.data);
1886
- if (data.parentToolCallId !== void 0) return void 0;
1887
- return { ...base, type: "assistant.message", data: {
1888
- messageId: data.messageId,
1889
- content: data.content,
1890
- ...data.apiCallId === void 0 ? {} : { apiCallId: data.apiCallId },
1891
- ...data.chunkIndex === void 0 ? {} : { chunkIndex: data.chunkIndex },
1892
- ...data.chunkCount === void 0 ? {} : { chunkCount: data.chunkCount },
1893
- ...data.interactionId === void 0 ? {} : { interactionId: data.interactionId },
1894
- ...data.turnId === void 0 ? {} : { turnId: data.turnId }
1895
- } };
1896
- }
1897
- case "tool.execution_start": {
1898
- const data = ToolStartSchema.parse(event.data);
1899
- return preview || data.toolName === "task_complete" ? {
1900
- ...base,
1901
- type: "tool.execution_start",
1902
- data: {
1903
- toolCallId: data.toolCallId,
1904
- toolName: data.toolName,
1905
- ...data.parentToolCallId === void 0 ? {} : { parentToolCallId: data.parentToolCallId }
1906
- }
1907
- } : void 0;
1908
- }
1909
- case "tool.execution_complete": {
1910
- const data = ToolCompleteSchema.parse(event.data);
1911
- const images = preview ? data.result?.binaryResultsForLlm?.flatMap((value2) => {
1912
- const parsed = z2.union([ImageSchema, ImageReferenceSchema]).safeParse(value2);
1913
- return parsed.success ? [parsed.data] : [];
1914
- }) ?? [] : [];
1915
- const contents = preview ? data.result?.contents?.flatMap((value2) => {
1916
- const parsed = ImageSchema.safeParse(value2);
1917
- return parsed.success ? [parsed.data] : [];
1918
- }) ?? [] : [];
1919
- return {
1920
- ...base,
1921
- type: "tool.execution_complete",
1922
- data: {
1923
- toolCallId: data.toolCallId,
1924
- success: data.success,
1925
- ...data.result === void 0 ? {} : { result: {
1926
- content: data.result.content ?? "",
1927
- binaryResultsForLlm: images,
1928
- contents
1929
- } },
1930
- ...data.toolDescription === void 0 ? {} : { toolDescription: data.toolDescription },
1931
- ...data.parentToolCallId === void 0 ? {} : { parentToolCallId: data.parentToolCallId }
1932
- }
1933
- };
1934
- }
1935
- case "session.error": {
1936
- const data = NoticeSchema.extend({ errorType: z2.string() }).parse(event.data);
1937
- return { ...base, type: "session.error", data };
1938
- }
1939
- case "session.warning": {
1940
- const data = NoticeSchema.extend({ warningType: z2.string() }).parse(event.data);
1941
- return { ...base, type: "session.warning", data };
1942
- }
1943
- case "system.notification": {
1944
- const { kind } = NotificationSchema.parse(event.data);
1945
- if (kind.type !== "shell_completed") return void 0;
1946
- const shell = ShellCompletedSchema.parse(kind);
1947
- return {
1948
- ...base,
1949
- type: "system.notification",
1950
- data: {
1951
- content: "",
1952
- kind: {
1953
- type: "shell_completed",
1954
- shellId: shell.shellId,
1955
- ...shell.exitCode === void 0 ? {} : { exitCode: shell.exitCode }
1956
- }
1957
- }
1958
- };
1959
- }
1960
- default:
1961
- return void 0;
1962
- }
1963
- }
1964
- async function openSessionEventLog(sessionId, environment = process.env, options = {}) {
1965
- const directory = await realpath2(resolveCopilotSessionDirectory(sessionId, environment));
1966
- const expectedPath = resolve2(directory, "events.jsonl");
1967
- if (options.allowMissingEventLog?.() === true) {
1968
- try {
1969
- await lstat2(expectedPath);
1970
- } catch (error) {
1971
- if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
1972
- await realpath2(directory);
1973
- if (options.allowMissingEventLog?.() !== true) throw error;
1974
- return void 0;
1975
- }
1976
- }
1977
- const path = await realpath2(expectedPath);
1978
- if (path !== expectedPath) throw new Error("Session event log must not be a symbolic link");
1979
- return open(path, "r");
1980
- }
1981
- async function readSessionUpdatePage(sessionId, environment = process.env, resolveInputProvenance, options = {}) {
1982
- const file = await openSessionEventLog(sessionId, environment, options);
1983
- if (file === void 0) return { items: [], cursor: "", hasMore: false, cursorStatus: "ok" };
1984
- try {
1985
- const { size } = await file.stat();
1986
- if (size === 0) {
1987
- options.onEventLogRead?.();
1988
- return { items: [], cursor: "", hasMore: false, cursorStatus: "ok" };
1989
- }
1990
- const start = Math.max(0, size - MAX_HEAD_BYTES);
1991
- const buffer = Buffer.alloc(size - start);
1992
- const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
1993
- const text = buffer.subarray(0, bytesRead).toString("utf8");
1994
- const first = start === 0 ? 0 : text.indexOf("\n") + 1;
1995
- const end = text.lastIndexOf("\n");
1996
- if (first === 0 && start > 0 || end < first) {
1997
- throw new Error("Session event log has no complete records in its metadata window");
1998
- }
1999
- const events = text.slice(first, end).split("\n").filter((line) => line.trim().length > 0).map((line) => metadataEvent(JSON.parse(line), options.assistantPreview === true)).filter((event) => event !== void 0);
2000
- const toolStarts = events.filter((event) => event.type === "tool.execution_start");
2001
- const taskCompletionCallIdsWithStart = new Set(events.flatMap((event) => event.type === "tool.execution_start" && event.data.toolName === "task_complete" ? [event.data.toolCallId] : []));
2002
- const rootTools = new Set(toolStarts.filter((event) => event.agentId === void 0 && event.data.parentToolCallId === void 0).map((event) => event.data.toolCallId));
2003
- const childTools = new Set(toolStarts.filter((event) => event.agentId !== void 0 || event.data.parentToolCallId !== void 0).map((event) => event.data.toolCallId));
2004
- const hasCompleteHistory = start === 0;
2005
- const eventsForMetadata = events.filter((event) => {
2006
- if (event.type === "tool.execution_start" && event.data.toolName !== "task_complete") return false;
2007
- if (event.type !== "tool.execution_complete") {
2008
- return true;
2009
- }
2010
- if (options.assistantPreview === true && event.agentId === void 0 && event.data.parentToolCallId === void 0 && !childTools.has(event.data.toolCallId) && (hasCompleteHistory || rootTools.has(event.data.toolCallId)) && ((event.data.result?.binaryResultsForLlm?.length ?? 0) > 0 || (event.data.result?.contents?.length ?? 0) > 0)) return true;
2011
- if (taskCompletionCallIdsWithStart.has(event.data.toolCallId)) {
2012
- return true;
2013
- }
2014
- if (!hasCompleteHistory) {
2015
- return false;
2016
- }
2017
- return event.data.toolDescription?.name === "task_complete";
2018
- });
2019
- const normalizer = new ConversationNormalizer(void 0, void 0, resolveInputProvenance);
2020
- normalizer.apply(eventsForMetadata);
2021
- const items = normalizer.snapshot().filter((item) => (item.kind === "human-message" || item.kind === "assistant-message" || item.kind === "notice") && (item.actor === "human" || item.actor === "assistant" || item.actor === "system" || item.kind === "assistant-message" && item.actor === "subagent"));
2022
- const latest = items.at(-1);
2023
- const assistant = options.assistantPreview === true ? [...items].reverse().find(isContentfulAssistant) : void 0;
2024
- const human = options.assistantPreview === true ? [...items].reverse().find((item) => item.kind === "human-message" && item.actor === "human") : void 0;
2025
- const completion = [...items].reverse().find((item) => item.kind === "notice" && item.actor === "assistant" && item.severity === "success" && item.title === "Task completed");
2026
- const page = SessionTimelinePageSchema.parse({
2027
- items: [completion, latest, assistant, human].filter((item, index, all) => item !== void 0 && all.findIndex((candidate) => candidate?.id === item.id) === index).map((item) => item?.kind === "human-message" || item?.kind === "assistant-message" ? {
2028
- ...item,
2029
- content: item.id === assistant?.id || item.id === human?.id ? item.content.slice(0, 4096) : "",
2030
- attachments: item.id === assistant?.id ? item.attachments ?? [] : []
2031
- } : { ...item, content: item?.kind === "notice" && item.id === assistant?.id ? item.content.slice(0, 4096) : "" }),
2032
- hasMore: start > 0,
2033
- cursor: "",
2034
- cursorStatus: "ok"
2035
- });
2036
- options.onEventLogRead?.();
2037
- return page;
2038
- } finally {
2039
- await file.close();
2040
- }
2041
- }
2042
-
2043
- // src/adapters/copilot/timeline/timeline-history.ts
2044
1539
  var MAX_TIMELINE_RAW_EVENT_MULTIPLIER = 20;
2045
1540
  var TIMELINE_PAGE_PAYLOAD_BUDGET_BYTES = 6 * 1024 * 1024;
2046
1541
  function startsAtTurnBoundary(events, resolveInputProvenance) {
@@ -2238,25 +1733,25 @@ var TimelineHistory = class {
2238
1733
 
2239
1734
  // src/copilot-adapter.ts
2240
1735
  import {
2241
- CopilotClient as CopilotClient2,
1736
+ CopilotClient,
2242
1737
  defineTool as defineTool2,
2243
1738
  RuntimeConnection
2244
1739
  } from "@github/copilot-sdk";
2245
- import { z as z7 } from "zod";
1740
+ import { z as z5 } from "zod";
2246
1741
 
2247
1742
  // src/session-schedules.ts
2248
1743
  import { randomUUID as randomUUID3 } from "node:crypto";
2249
1744
  import { defineTool } from "@github/copilot-sdk";
2250
- import { z as z5 } from "zod";
1745
+ import { z as z3 } from "zod";
2251
1746
 
2252
1747
  // src/schedule-draft-store.ts
2253
1748
  import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
2254
- import { lstat as lstat3, mkdir as mkdir3, open as open2, readFile as readFile2, rename as rename2, rm as rm3 } from "node:fs/promises";
2255
- import { join as join3 } from "node:path";
2256
- import { z as z3 } from "zod";
2257
- var Document = z3.object({
2258
- version: z3.literal(1),
2259
- drafts: z3.array(WorkbenchScheduleDraftSchema).max(100)
1749
+ import { lstat as lstat2, mkdir as mkdir2, open, readFile, rename, rm as rm2 } from "node:fs/promises";
1750
+ import { join as join2 } from "node:path";
1751
+ import { z } from "zod";
1752
+ var Document = z.object({
1753
+ version: z.literal(1),
1754
+ drafts: z.array(WorkbenchScheduleDraftSchema).max(100)
2260
1755
  }).strict();
2261
1756
  var ScheduleDraftStore = class {
2262
1757
  constructor(directory) {
@@ -2265,7 +1760,7 @@ var ScheduleDraftStore = class {
2265
1760
  directory;
2266
1761
  #locks = /* @__PURE__ */ new Map();
2267
1762
  #path(sessionId) {
2268
- return join3(this.directory, `${createHash2("sha256").update(sessionId).digest("hex")}.json`);
1763
+ return join2(this.directory, `${createHash2("sha256").update(sessionId).digest("hex")}.json`);
2269
1764
  }
2270
1765
  async list(sessionId) {
2271
1766
  await this.#locks.get(sessionId);
@@ -2274,9 +1769,9 @@ var ScheduleDraftStore = class {
2274
1769
  async #read(sessionId) {
2275
1770
  try {
2276
1771
  const path = this.#path(sessionId);
2277
- const metadata = await lstat3(path);
1772
+ const metadata = await lstat2(path);
2278
1773
  if (metadata.isSymbolicLink() || metadata.size > 8 * 1024 * 1024) throw new Error("Invalid draft document");
2279
- const value = JSON.parse(await readFile2(path, "utf8"));
1774
+ const value = JSON.parse(await readFile(path, "utf8"));
2280
1775
  return Document.parse(value).drafts;
2281
1776
  } catch (error) {
2282
1777
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
@@ -2286,22 +1781,22 @@ var ScheduleDraftStore = class {
2286
1781
  async update(sessionId, change) {
2287
1782
  const work = (this.#locks.get(sessionId) ?? Promise.resolve()).then(async () => {
2288
1783
  const value = Document.parse({ version: 1, drafts: change(await this.#read(sessionId)) });
2289
- await mkdir3(this.directory, { recursive: true, mode: 448 });
1784
+ await mkdir2(this.directory, { recursive: true, mode: 448 });
2290
1785
  const target = this.#path(sessionId);
2291
1786
  const staging = `${target}.${randomUUID2()}.pending`;
2292
1787
  try {
2293
- const file = await open2(staging, "wx", 384);
1788
+ const file = await open(staging, "wx", 384);
2294
1789
  try {
2295
1790
  await file.writeFile(JSON.stringify(value));
2296
1791
  await file.sync();
2297
1792
  } finally {
2298
1793
  await file.close();
2299
1794
  }
2300
- await rename2(staging, target);
1795
+ await rename(staging, target);
2301
1796
  } catch (error) {
2302
1797
  throw new SessionOperationError("SCHEDULE_DRAFT_STORE_UNAVAILABLE", "Schedule drafts could not be saved", { cause: error });
2303
1798
  } finally {
2304
- await rm3(staging, { force: true });
1799
+ await rm2(staging, { force: true });
2305
1800
  }
2306
1801
  });
2307
1802
  const settled = work.then(() => void 0, () => void 0);
@@ -2315,7 +1810,7 @@ var ScheduleDraftStore = class {
2315
1810
  async remove(sessionId) {
2316
1811
  const work = (this.#locks.get(sessionId) ?? Promise.resolve()).then(async () => {
2317
1812
  try {
2318
- await rm3(this.#path(sessionId), { force: true });
1813
+ await rm2(this.#path(sessionId), { force: true });
2319
1814
  } catch (error) {
2320
1815
  throw new SessionOperationError("SCHEDULE_DRAFT_STORE_UNAVAILABLE", "Schedule drafts could not be removed", { cause: error });
2321
1816
  }
@@ -2331,25 +1826,25 @@ var ScheduleDraftStore = class {
2331
1826
  };
2332
1827
 
2333
1828
  // src/schedule-history.ts
2334
- import { z as z4 } from "zod";
2335
- var Event = z4.object({
2336
- id: z4.string().min(1).max(256),
2337
- timestamp: z4.iso.datetime({ offset: true }),
2338
- type: z4.string(),
2339
- agentId: z4.string().optional(),
2340
- data: z4.object({
2341
- source: z4.string().optional(),
2342
- content: z4.string().optional(),
2343
- interactionId: z4.string().optional(),
2344
- turnId: z4.string().optional(),
2345
- messageId: z4.string().optional(),
2346
- originatingMessageId: z4.string().optional(),
2347
- apiCallId: z4.string().optional(),
2348
- chunkIndex: z4.number().int().nonnegative().optional(),
2349
- chunkCount: z4.number().int().positive().optional(),
2350
- parentToolCallId: z4.string().optional(),
2351
- delivery: z4.string().optional(),
2352
- toolRequests: z4.array(z4.unknown()).optional()
1829
+ import { z as z2 } from "zod";
1830
+ var Event = z2.object({
1831
+ id: z2.string().min(1).max(256),
1832
+ timestamp: z2.iso.datetime({ offset: true }),
1833
+ type: z2.string(),
1834
+ agentId: z2.string().optional(),
1835
+ data: z2.object({
1836
+ source: z2.string().optional(),
1837
+ content: z2.string().optional(),
1838
+ interactionId: z2.string().optional(),
1839
+ turnId: z2.string().optional(),
1840
+ messageId: z2.string().optional(),
1841
+ originatingMessageId: z2.string().optional(),
1842
+ apiCallId: z2.string().optional(),
1843
+ chunkIndex: z2.number().int().nonnegative().optional(),
1844
+ chunkCount: z2.number().int().positive().optional(),
1845
+ parentToolCallId: z2.string().optional(),
1846
+ delivery: z2.string().optional(),
1847
+ toolRequests: z2.array(z2.unknown()).optional()
2353
1848
  }).passthrough()
2354
1849
  });
2355
1850
  var MAX_EVENTS = 2e4;
@@ -2415,13 +1910,13 @@ function projectScheduleHistory(input) {
2415
1910
 
2416
1911
  // src/session-schedules.ts
2417
1912
  var NativeEntry = WorkbenchScheduleEntrySchema.omit({ timezone: true, at: true }).extend({
2418
- tz: z5.string().max(128).optional(),
2419
- at: z5.number().int().nonnegative().max(864e13).optional()
1913
+ tz: z3.string().max(128).optional(),
1914
+ at: z3.number().int().nonnegative().max(864e13).optional()
2420
1915
  }).strip();
2421
- var NativeList = z5.object({ entries: z5.array(NativeEntry).max(256) });
2422
- var CommandCatalog = z5.object({ commands: z5.array(z5.object({
2423
- name: z5.string().max(256),
2424
- kind: z5.enum(["builtin", "skill", "client"])
1916
+ var NativeList = z3.object({ entries: z3.array(NativeEntry).max(256) });
1917
+ var CommandCatalog = z3.object({ commands: z3.array(z3.object({
1918
+ name: z3.string().max(256),
1919
+ kind: z3.enum(["builtin", "skill", "client"])
2425
1920
  })).max(512) });
2426
1921
  function unavailable(code, message) {
2427
1922
  return new SessionOperationError(code, message);
@@ -2684,7 +2179,7 @@ var SessionSchedules = class {
2684
2179
  this.#check(sessionId, connection);
2685
2180
  assertAccess?.();
2686
2181
  try {
2687
- const result = z5.object({ entry: NativeEntry.optional() }).parse(await schedule.stop({ id }));
2182
+ const result = z3.object({ entry: NativeEntry.optional() }).parse(await schedule.stop({ id }));
2688
2183
  assertAccess?.();
2689
2184
  if (result.entry !== void 0 && result.entry.id !== id) throw new Error("Native schedule identity mismatch");
2690
2185
  this.#check(sessionId, connection);
@@ -2711,6 +2206,341 @@ var SessionSchedules = class {
2711
2206
  }
2712
2207
  };
2713
2208
 
2209
+ // src/session-analytics.ts
2210
+ import { Worker } from "node:worker_threads";
2211
+ var MAX_PENDING_EVENTS = 512;
2212
+ var MAX_PENDING_BYTES = 4 * 1024 * 1024;
2213
+ var MAX_TRACKED_SESSIONS = 1e4;
2214
+ var SessionAnalytics = class {
2215
+ constructor(directory, onError) {
2216
+ this.directory = directory;
2217
+ this.onError = onError;
2218
+ }
2219
+ directory;
2220
+ onError;
2221
+ #pending = [];
2222
+ #gaps = /* @__PURE__ */ new Map();
2223
+ #failures = /* @__PURE__ */ new Map();
2224
+ #tracked = /* @__PURE__ */ new Set();
2225
+ #removed = /* @__PURE__ */ new Set();
2226
+ #requests = /* @__PURE__ */ new Map();
2227
+ #worker;
2228
+ #sequence = 0;
2229
+ #pendingBytes = 0;
2230
+ #draining;
2231
+ #batchTimer;
2232
+ #indexTimer;
2233
+ #indexing;
2234
+ #closed = false;
2235
+ start() {
2236
+ this.#closed = false;
2237
+ }
2238
+ #failWorker(worker, error) {
2239
+ if (this.#worker !== worker) return;
2240
+ this.#worker = void 0;
2241
+ if (this.#requests.size === 0) this.onError(this.#tracked.values().next().value ?? "analytics", error);
2242
+ for (const pending of this.#requests.values()) {
2243
+ clearTimeout(pending.timer);
2244
+ pending.reject(error);
2245
+ }
2246
+ this.#requests.clear();
2247
+ void worker.terminate();
2248
+ }
2249
+ #thread() {
2250
+ if (this.#closed) throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics collector is closed");
2251
+ if (this.#worker !== void 0) return this.#worker;
2252
+ const source = import.meta.url.endsWith(".ts");
2253
+ const worker = new Worker(source ? new URL("./session-analytics-worker.ts", import.meta.url) : new URL("./session-analytics-worker.js", import.meta.resolve("@agentknight/sdk/runtime")), {
2254
+ workerData: { directory: this.directory },
2255
+ execArgv: source ? ["--import", "tsx"] : []
2256
+ });
2257
+ const fail = (error) => this.#failWorker(worker, error);
2258
+ worker.on("message", (value) => {
2259
+ const parsed = AnalyticsReplySchema.safeParse(value);
2260
+ if (!parsed.success) {
2261
+ fail(new Error("Invalid analytics worker response", { cause: parsed.error }));
2262
+ return;
2263
+ }
2264
+ const pending = this.#requests.get(parsed.data.id);
2265
+ if (pending === void 0) return;
2266
+ this.#requests.delete(parsed.data.id);
2267
+ clearTimeout(pending.timer);
2268
+ if (parsed.data.error !== void 0) pending.reject(new SessionOperationError(parsed.data.error.code, parsed.data.error.message));
2269
+ else pending.resolve(parsed.data.result);
2270
+ if (this.#requests.size === 0) worker.unref();
2271
+ });
2272
+ worker.on("error", fail);
2273
+ worker.on("exit", (code) => fail(new Error(`Analytics worker exited (${code})`)));
2274
+ this.#worker = worker;
2275
+ worker.unref();
2276
+ return worker;
2277
+ }
2278
+ #request(command) {
2279
+ return new Promise((resolve2, reject) => {
2280
+ const worker = this.#thread();
2281
+ if (this.#requests.size >= 16 && command.operation !== "observe" && command.operation !== "close") {
2282
+ reject(new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics worker is busy; retry"));
2283
+ return;
2284
+ }
2285
+ const id = ++this.#sequence;
2286
+ const timer = setTimeout(() => this.#failWorker(
2287
+ worker,
2288
+ new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics worker timed out; retry")
2289
+ ), 3e4);
2290
+ timer.unref();
2291
+ this.#requests.set(id, { resolve: resolve2, reject, timer });
2292
+ worker.ref();
2293
+ try {
2294
+ worker.postMessage({ id, command });
2295
+ } catch (error) {
2296
+ this.#requests.delete(id);
2297
+ clearTimeout(timer);
2298
+ if (this.#requests.size === 0) worker.unref();
2299
+ reject(error);
2300
+ }
2301
+ });
2302
+ }
2303
+ #gap(sessionId, timestamp, count = 1) {
2304
+ const previous = this.#gaps.get(sessionId);
2305
+ this.#gaps.set(sessionId, {
2306
+ sessionId,
2307
+ since: Math.min(previous?.since ?? timestamp, timestamp),
2308
+ count: (previous?.count ?? 0) + count
2309
+ });
2310
+ }
2311
+ recordGap(sessionIds) {
2312
+ for (const id of sessionIds) {
2313
+ if (!this.#closed && !this.#removed.has(id)) this.#gap(id, Date.now(), 0);
2314
+ }
2315
+ if (this.#gaps.size > 0) void this.#drain();
2316
+ }
2317
+ observe(sessionId, event) {
2318
+ if (this.#closed || this.#removed.has(sessionId)) return;
2319
+ if (event.type !== "assistant.usage" && event.type !== "user.message" && event.type !== "assistant.message" && event.type !== "session.skills_loaded" && event.type !== "session.usage_info" && event.type !== "session.compaction_complete") return;
2320
+ if (event.agentId !== void 0 && event.type !== "assistant.usage") return;
2321
+ let data;
2322
+ let bytes = 1024 + (sessionId.length + event.id.length + event.timestamp.length + (event.agentId?.length ?? 0)) * 2;
2323
+ if (event.type === "user.message") {
2324
+ if (event.data.isAutopilotContinuation === true || event.data.source === "tool") return;
2325
+ data = {
2326
+ content: event.data.content.slice(0, 8193),
2327
+ messageId: event.data.messageId,
2328
+ source: event.data.source,
2329
+ isAutopilotContinuation: event.data.isAutopilotContinuation
2330
+ };
2331
+ bytes += (Math.min(event.data.content.length, 8193) + (event.data.messageId?.length ?? 0)) * 2;
2332
+ } else if (event.type === "assistant.message") {
2333
+ if (event.data.parentToolCallId !== void 0) return;
2334
+ data = { messageId: event.data.messageId, content: event.data.content.slice(0, 8193) };
2335
+ bytes += (Math.min(event.data.content.length, 8193) + (event.data.messageId?.length ?? 0)) * 2;
2336
+ } else if (event.type === "session.skills_loaded") {
2337
+ const skills = event.data.skills.slice(0, 513).map((skill) => ({
2338
+ name: skill.name,
2339
+ description: skill.description,
2340
+ source: skill.source,
2341
+ enabled: skill.enabled,
2342
+ userInvocable: skill.userInvocable,
2343
+ commandName: skill.commandName
2344
+ }));
2345
+ data = { skills };
2346
+ bytes += skills.reduce((size, skill) => size + (skill.name.length + (skill.description?.length ?? 0) + skill.source.length + (skill.commandName?.length ?? 0)) * 2 + 256, 0);
2347
+ } else if (event.type === "session.usage_info") {
2348
+ data = {
2349
+ currentTokens: event.data.currentTokens,
2350
+ tokenLimit: event.data.tokenLimit,
2351
+ messagesLength: event.data.messagesLength
2352
+ };
2353
+ } else if (event.type === "session.compaction_complete") {
2354
+ data = {
2355
+ success: event.data.success,
2356
+ preCompactionTokens: event.data.preCompactionTokens,
2357
+ postCompactionTokens: event.data.postCompactionTokens,
2358
+ tokensRemoved: event.data.tokensRemoved,
2359
+ messagesRemoved: event.data.messagesRemoved,
2360
+ trigger: event.data.trigger,
2361
+ tokenAccountingBasis: event.data.tokenAccountingBasis,
2362
+ compactionTokensUsed: event.data.compactionTokensUsed === void 0 ? void 0 : {
2363
+ duration: event.data.compactionTokensUsed.duration,
2364
+ inputTokens: event.data.compactionTokensUsed.inputTokens,
2365
+ outputTokens: event.data.compactionTokensUsed.outputTokens
2366
+ }
2367
+ };
2368
+ } else {
2369
+ const accounting = event.data.accounting;
2370
+ data = {
2371
+ model: event.data.model,
2372
+ inputTokens: event.data.inputTokens,
2373
+ outputTokens: event.data.outputTokens,
2374
+ cacheReadTokens: event.data.cacheReadTokens,
2375
+ apiCallId: event.data.apiCallId,
2376
+ requestBodyBytes: event.data.requestBodyBytes,
2377
+ requestBodyWireBytes: event.data.requestBodyWireBytes,
2378
+ duration: event.data.duration,
2379
+ outputTtftMs: event.data.outputTtftMs,
2380
+ accounting: accounting === void 0 ? void 0 : { sourceSessionId: accounting.sourceSessionId, usageId: accounting.usageId }
2381
+ };
2382
+ bytes += (event.data.model.length + (event.data.apiCallId?.length ?? 0) + (accounting?.sourceSessionId.length ?? 0) + (accounting?.usageId.length ?? 0)) * 2;
2383
+ }
2384
+ if (this.#pending.length >= MAX_PENDING_EVENTS || this.#pendingBytes + bytes > MAX_PENDING_BYTES) {
2385
+ this.#gap(sessionId, Date.parse(event.timestamp));
2386
+ const error = new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics queue is full; coverage is incomplete");
2387
+ if (!this.#failures.has(sessionId)) this.onError(sessionId, error);
2388
+ this.#failures.set(sessionId, error);
2389
+ return;
2390
+ }
2391
+ this.#pending.push({ bytes, observation: { sessionId, event: {
2392
+ id: event.id,
2393
+ timestamp: event.timestamp,
2394
+ type: event.type,
2395
+ data,
2396
+ ...event.agentId === void 0 ? {} : { agentId: event.agentId }
2397
+ } } });
2398
+ this.#pendingBytes += bytes;
2399
+ if (this.#batchTimer === void 0 && this.#draining === void 0) {
2400
+ this.#batchTimer = setTimeout(() => {
2401
+ this.#batchTimer = void 0;
2402
+ void this.#drain();
2403
+ }, 25);
2404
+ this.#batchTimer.unref();
2405
+ }
2406
+ }
2407
+ #drain() {
2408
+ if (this.#draining !== void 0) return this.#draining;
2409
+ if (this.#batchTimer !== void 0) clearTimeout(this.#batchTimer);
2410
+ this.#batchTimer = void 0;
2411
+ const work = (async () => {
2412
+ while (this.#pending.length > 0 || this.#gaps.size > 0) {
2413
+ const batch = this.#pending.splice(0, 32);
2414
+ this.#pendingBytes -= batch.reduce((sum, item) => sum + item.bytes, 0);
2415
+ const observations = batch.map((item) => item.observation);
2416
+ const gaps = [...this.#gaps.values()];
2417
+ this.#gaps.clear();
2418
+ const sessions = /* @__PURE__ */ new Set([...observations.map((item) => item.sessionId), ...gaps.map((item) => item.sessionId)]);
2419
+ try {
2420
+ await this.#request({ operation: "observe", observations, gaps });
2421
+ for (const id of sessions) this.#failures.delete(id);
2422
+ } catch (error) {
2423
+ for (const id of sessions) {
2424
+ const previous = gaps.find((gap) => gap.sessionId === id);
2425
+ const earliest = Math.min(Date.now(), ...observations.filter((item) => item.sessionId === id).map((item) => Date.parse(item.event.timestamp)));
2426
+ this.#gap(
2427
+ id,
2428
+ Math.min(previous?.since ?? earliest, earliest),
2429
+ (previous?.count ?? 0) + observations.filter((item) => item.sessionId === id).length
2430
+ );
2431
+ this.#failures.set(id, error);
2432
+ this.onError(id, error);
2433
+ }
2434
+ break;
2435
+ }
2436
+ }
2437
+ })();
2438
+ this.#draining = work.finally(() => {
2439
+ this.#draining = void 0;
2440
+ });
2441
+ return this.#draining;
2442
+ }
2443
+ track(sessionIds) {
2444
+ if (this.#closed) return;
2445
+ for (const id of sessionIds) {
2446
+ if (this.#removed.has(id) || this.#tracked.has(id)) continue;
2447
+ if (this.#tracked.size >= MAX_TRACKED_SESSIONS) {
2448
+ this.onError(id, new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics session capacity exceeded"));
2449
+ break;
2450
+ }
2451
+ this.#tracked.add(id);
2452
+ }
2453
+ this.#scheduleIndex(0);
2454
+ }
2455
+ #scheduleIndex(delay) {
2456
+ if (this.#closed || this.#indexTimer !== void 0 || this.#indexing !== void 0 || this.#tracked.size === 0) return;
2457
+ this.#indexTimer = setTimeout(() => {
2458
+ this.#indexTimer = void 0;
2459
+ let behind = false;
2460
+ this.#indexing = (async () => {
2461
+ for (const id of this.#tracked) {
2462
+ if (this.#closed) break;
2463
+ try {
2464
+ const progress = AnalyticsIndexResultSchema.parse(await this.#request({
2465
+ operation: "index",
2466
+ sessionId: id,
2467
+ environment: this.#environment(process.env),
2468
+ allowMissingEventLog: false
2469
+ }));
2470
+ behind ||= progress.catchUp;
2471
+ } catch (error) {
2472
+ this.onError(id, error);
2473
+ }
2474
+ await this.#drain();
2475
+ }
2476
+ })().finally(() => {
2477
+ this.#indexing = void 0;
2478
+ this.#scheduleIndex(behind ? 250 : 3e4);
2479
+ });
2480
+ }, delay);
2481
+ this.#indexTimer.unref();
2482
+ }
2483
+ #environment(environment) {
2484
+ return environment.COPILOT_HOME === void 0 ? {} : { COPILOT_HOME: environment.COPILOT_HOME };
2485
+ }
2486
+ async remove(sessionId) {
2487
+ this.#removed.add(sessionId);
2488
+ this.#tracked.delete(sessionId);
2489
+ await this.flush();
2490
+ await this.#request({ operation: "remove", sessionId });
2491
+ this.#failures.delete(sessionId);
2492
+ this.#gaps.delete(sessionId);
2493
+ }
2494
+ async flush() {
2495
+ await this.#drain();
2496
+ }
2497
+ async close() {
2498
+ if (this.#closed) return;
2499
+ if (this.#indexTimer !== void 0) clearTimeout(this.#indexTimer);
2500
+ this.#indexTimer = void 0;
2501
+ this.#tracked.clear();
2502
+ await this.#indexing;
2503
+ await this.flush();
2504
+ const worker = this.#worker;
2505
+ try {
2506
+ if (worker !== void 0) await this.#request({ operation: "close" });
2507
+ } finally {
2508
+ this.#closed = true;
2509
+ if (this.#batchTimer !== void 0) clearTimeout(this.#batchTimer);
2510
+ this.#worker = void 0;
2511
+ if (worker !== void 0) await worker.terminate();
2512
+ }
2513
+ }
2514
+ async read(sessionId, request, environment = process.env, allowMissingEventLog) {
2515
+ if (this.#removed.has(sessionId)) throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Session analytics were deleted");
2516
+ await this.flush();
2517
+ if (this.#failures.has(sessionId)) {
2518
+ throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics recording failed", { cause: this.#failures.get(sessionId) });
2519
+ }
2520
+ const result = await this.#request({
2521
+ operation: "read",
2522
+ sessionId,
2523
+ request,
2524
+ environment: this.#environment(environment),
2525
+ allowMissingEventLog: allowMissingEventLog?.() === true
2526
+ });
2527
+ return SessionAnalyticsResultSchema.parse(result);
2528
+ }
2529
+ async telemetry(sessionId, allowMissingEventLog = false) {
2530
+ if (this.#removed.has(sessionId)) throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Session analytics were deleted");
2531
+ await this.flush();
2532
+ if (this.#failures.has(sessionId)) {
2533
+ throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics recording failed", { cause: this.#failures.get(sessionId) });
2534
+ }
2535
+ return WorkbenchTelemetrySchema.parse(await this.#request({
2536
+ operation: "telemetry",
2537
+ sessionId,
2538
+ environment: this.#environment(process.env),
2539
+ allowMissingEventLog
2540
+ }));
2541
+ }
2542
+ };
2543
+
2714
2544
  // src/adapters/copilot/interactions/interaction-broker.ts
2715
2545
  import "@github/copilot-sdk";
2716
2546
  import { randomUUID as randomUUID4 } from "node:crypto";
@@ -2977,13 +2807,13 @@ var InteractionBroker = class {
2977
2807
  async #awaitInteractionRelease(operation, sessionId) {
2978
2808
  this.#releasingSessions.set(sessionId, (this.#releasingSessions.get(sessionId) ?? 0) + 1);
2979
2809
  let timer;
2980
- const timeout = new Promise((resolve4) => {
2810
+ const timeout = new Promise((resolve2) => {
2981
2811
  timer = setTimeout(() => {
2982
2812
  this.ports.callbacks()?.onSyncError(
2983
2813
  sessionId,
2984
2814
  new Error("Timed out while releasing a pending mobile interaction")
2985
2815
  );
2986
- resolve4(false);
2816
+ resolve2(false);
2987
2817
  }, INTERACTION_RELEASE_TIMEOUT_MS);
2988
2818
  });
2989
2819
  try {
@@ -3014,12 +2844,12 @@ var InteractionBroker = class {
3014
2844
  );
3015
2845
  }
3016
2846
  const interactionRequestId = randomUUID4();
3017
- return new Promise((resolve4, reject) => {
2847
+ return new Promise((resolve2, reject) => {
3018
2848
  const cancel = () => {
3019
2849
  if (unavailable2 === void 0) {
3020
2850
  reject(new Error(`Mobile ${request.kind} interaction was cancelled`));
3021
2851
  } else {
3022
- resolve4(unavailable2);
2852
+ resolve2(unavailable2);
3023
2853
  }
3024
2854
  };
3025
2855
  const timer = this.#persistentInteractionSessions.has(sessionId) ? void 0 : setTimeout(() => {
@@ -3041,7 +2871,7 @@ var InteractionBroker = class {
3041
2871
  clearTimeout(timer);
3042
2872
  }
3043
2873
  this.#pendingInteractions.delete(interactionRequestId);
3044
- resolve4(converted.value);
2874
+ resolve2(converted.value);
3045
2875
  return Promise.resolve(true);
3046
2876
  }
3047
2877
  });
@@ -3163,16 +2993,16 @@ var InteractionBroker = class {
3163
2993
  );
3164
2994
  }
3165
2995
  const permissionRequestId = randomUUID4();
3166
- return new Promise((resolve4) => {
2996
+ return new Promise((resolve2) => {
3167
2997
  const timer = setTimeout(() => {
3168
2998
  this.#pendingPermissions.delete(permissionRequestId);
3169
- resolve4({ kind: "user-not-available" });
2999
+ resolve2({ kind: "user-not-available" });
3170
3000
  }, 5 * 60 * 1e3);
3171
3001
  this.#pendingPermissions.set(permissionRequestId, {
3172
3002
  sessionId,
3173
3003
  timer,
3174
3004
  approveOnce,
3175
- resolve: resolve4
3005
+ resolve: resolve2
3176
3006
  });
3177
3007
  callbacks.onPermissionRequest(
3178
3008
  sessionId,
@@ -3684,12 +3514,12 @@ var McpAuthCoordinator = class {
3684
3514
 
3685
3515
  // src/peer-session.ts
3686
3516
  import { randomUUID as randomUUID5 } from "node:crypto";
3687
- import { z as z6 } from "zod";
3688
- var PeerTurnTextSchema = z6.string().min(1).max(16e3).refine((text) => text.trim().length > 0);
3689
- var PeerTurnPromptSchema = z6.string().min(1).max(1e5).refine((text) => text.trim().length > 0);
3690
- var PeerTurnToolSchema = z6.object({ content: PeerTurnTextSchema }).strict();
3517
+ import { z as z4 } from "zod";
3518
+ var PeerTurnTextSchema = z4.string().min(1).max(16e3).refine((text) => text.trim().length > 0);
3519
+ var PeerTurnPromptSchema = z4.string().min(1).max(1e5).refine((text) => text.trim().length > 0);
3520
+ var PeerTurnToolSchema = z4.object({ content: PeerTurnTextSchema }).strict();
3691
3521
  function awaitPeerOperation(operation, signal) {
3692
- return new Promise((resolve4, reject) => {
3522
+ return new Promise((resolve2, reject) => {
3693
3523
  const aborted = () => {
3694
3524
  cleanup();
3695
3525
  reject(signal.reason);
@@ -3699,7 +3529,7 @@ function awaitPeerOperation(operation, signal) {
3699
3529
  operation.then(
3700
3530
  (value) => {
3701
3531
  cleanup();
3702
- resolve4(value);
3532
+ resolve2(value);
3703
3533
  },
3704
3534
  (error) => {
3705
3535
  cleanup();
@@ -3715,8 +3545,8 @@ var PeerSessionTurn = class {
3715
3545
  const signal = options.signal;
3716
3546
  this.#signal = signal;
3717
3547
  this.#requestPeer = options.requestPeer;
3718
- this.response = new Promise((resolve4, reject) => {
3719
- this.#resolve = resolve4;
3548
+ this.response = new Promise((resolve2, reject) => {
3549
+ this.#resolve = resolve2;
3720
3550
  this.#reject = reject;
3721
3551
  });
3722
3552
  this.#cancel = () => this.fail(signal.reason ?? new Error("Peer turn cancelled"));
@@ -3770,7 +3600,7 @@ var PeerSessionTurn = class {
3770
3600
  }
3771
3601
  waitForProgress(revision) {
3772
3602
  if (revision !== this.progressRevision || this.terminal || this.closed) return Promise.resolve();
3773
- return new Promise((resolve4) => this.#progressWaiters.add(resolve4));
3603
+ return new Promise((resolve2) => this.#progressWaiters.add(resolve2));
3774
3604
  }
3775
3605
  async completeAfter(cleanup, awaitNativeSettlement = false) {
3776
3606
  const signal = AbortSignal.any([this.#signal, this.#interrupted.signal]);
@@ -3859,7 +3689,7 @@ var PeerSessionTurn = class {
3859
3689
  }
3860
3690
  #notifyProgress() {
3861
3691
  this.progressRevision += 1;
3862
- for (const resolve4 of this.#progressWaiters) resolve4();
3692
+ for (const resolve2 of this.#progressWaiters) resolve2();
3863
3693
  this.#progressWaiters.clear();
3864
3694
  }
3865
3695
  #finish(reason) {
@@ -3876,8 +3706,8 @@ var PeerSessionTurn = class {
3876
3706
 
3877
3707
  // src/copilot-adapter.ts
3878
3708
  var NativeCopilotModelOptionSchema = CopilotModelOptionSchema.extend({
3879
- supportedReasoningEfforts: z7.array(z7.string()).optional(),
3880
- defaultReasoningEffort: z7.string().optional()
3709
+ supportedReasoningEfforts: z5.array(z5.string()).optional(),
3710
+ defaultReasoningEffort: z5.string().optional()
3881
3711
  });
3882
3712
  var GIT_REMOTE_CACHE_TTL_MS = 5 * 60 * 1e3;
3883
3713
  var GIT_REMOTE_FAILURE_CACHE_TTL_MS = 30 * 1e3;
@@ -3886,9 +3716,46 @@ var require2 = createRequire(import.meta.url);
3886
3716
  function resolveCopilotRuntimePath(environment = process.env) {
3887
3717
  return environment["COPILOT_CLI_PATH"] ?? require2.resolve("@github/copilot/npm-loader.js");
3888
3718
  }
3719
+ function assertCopilotInProcessRuntime() {
3720
+ try {
3721
+ const entrypoint = process.env["COPILOT_CLI_PATH"];
3722
+ let platform = process.platform;
3723
+ if (platform === "linux") {
3724
+ const report = process.report?.getReport();
3725
+ const header = z5.object({ header: z5.object({ glibcVersionRuntime: z5.string().optional() }) }).safeParse(report);
3726
+ const musl = entrypoint?.includes(`copilot-linuxmusl-${process.arch}`) || !entrypoint?.includes(`copilot-linux-${process.arch}`) && (!header.success || header.data.header.glibcVersionRuntime === void 0);
3727
+ if (musl) platform = "linuxmusl";
3728
+ }
3729
+ const target = `${platform}-${process.arch}`;
3730
+ const files = [];
3731
+ if (entrypoint) {
3732
+ const directory = dirname2(resolve(entrypoint));
3733
+ const adjacent = join3(directory, "runtime.node");
3734
+ files.push(existsSync(adjacent) ? adjacent : join3(directory, "prebuilds", target, "runtime.node"));
3735
+ } else {
3736
+ const sdkRequire = createRequire(require2.resolve("@github/copilot-sdk"));
3737
+ const directory = dirname2(sdkRequire.resolve(`@github/copilot-sdk-${target}/package.json`));
3738
+ const prebuild = join3(directory, "prebuilds", target);
3739
+ files.push(
3740
+ join3(prebuild, "runtime.node"),
3741
+ join3(prebuild, process.platform === "win32" ? "copilot-runtime.exe" : "copilot-runtime")
3742
+ );
3743
+ }
3744
+ for (const path of files) {
3745
+ const file = statSync(path);
3746
+ if (!file.isFile() || file.size === 0) throw new Error(`Missing Copilot native runtime file: ${path}`);
3747
+ }
3748
+ } catch (error) {
3749
+ throw new Error(
3750
+ "Copilot inprocess runtime is unavailable. Unset COPILOT_SDK_DEFAULT_CONNECTION or set it to stdio to use the bundled CLI; inprocess requires a full SDK installation with its platform runtime, or COPILOT_CLI_PATH with an adjacent native runtime.",
3751
+ { cause: error }
3752
+ );
3753
+ }
3754
+ }
3889
3755
  function createCopilotClient() {
3890
- const defaultConnection = process.env["COPILOT_SDK_DEFAULT_CONNECTION"]?.toLowerCase();
3891
- const client = defaultConnection !== void 0 && defaultConnection !== "stdio" ? new CopilotClient2({ mode: "copilot-cli" }) : new CopilotClient2({
3756
+ const defaultConnection = process.env["COPILOT_SDK_DEFAULT_CONNECTION"]?.toLowerCase() || void 0;
3757
+ if (defaultConnection === "inprocess") assertCopilotInProcessRuntime();
3758
+ const client = defaultConnection !== void 0 && defaultConnection !== "stdio" ? new CopilotClient({ mode: "copilot-cli" }) : new CopilotClient({
3892
3759
  mode: "copilot-cli",
3893
3760
  connection: RuntimeConnection.forStdio({
3894
3761
  path: resolveCopilotRuntimePath()
@@ -3919,21 +3786,45 @@ function mapSessionMetadata(metadata, userId, machineId, gitRemoteUrl) {
3919
3786
  };
3920
3787
  }
3921
3788
  var GithubCopilotAdapter = class {
3922
- constructor(client = createCopilotClient(), openUrl = openExternalUrl, createClient = createCopilotClient, groupChat, peerChatEnabled = true, scheduleDirectory) {
3789
+ constructor(client = createCopilotClient(), openUrl = openExternalUrl, createClient = createCopilotClient, groupChat, peerChatEnabled = true, scheduleDirectory, analyticsDirectory) {
3923
3790
  this.openUrl = openUrl;
3924
3791
  this.peerChatEnabled = peerChatEnabled;
3792
+ if (analyticsDirectory !== void 0) {
3793
+ const analytics = new SessionAnalytics(
3794
+ analyticsDirectory,
3795
+ (id, error) => this.#callbacks?.onSyncError?.(id, error)
3796
+ );
3797
+ this.#analytics = analytics;
3798
+ Object.assign(this.workbench, { analytics: (id, request) => this.#withWorkbenchOperation(async () => {
3799
+ assertMainSessionId(id);
3800
+ this.#runtime.assertStarted();
3801
+ if (!this.supportsSessionListUpdates || this.#groups?.has(id) || this.#runtime.stopping || this.#deletingSessions.has(id) || this.#deletedSessions.has(id)) {
3802
+ throw new SessionOperationError("ANALYTICS_UNSUPPORTED", "Passive session analytics are unavailable");
3803
+ }
3804
+ return analytics.read(
3805
+ id,
3806
+ request,
3807
+ process.env,
3808
+ () => this.#provisionalSessions.get(id)?.allowMissingEventLog === true
3809
+ );
3810
+ }) });
3811
+ }
3925
3812
  this.#runtime = new CopilotClientRuntime(client, createClient, {
3926
3813
  beforeStart: async () => {
3814
+ this.#analytics?.start();
3927
3815
  await this.#groups?.start();
3928
3816
  },
3929
3817
  inventoryChanged: (sessionId) => {
3930
3818
  this.#sessions.peek(sessionId)?.timelineReads.invalidateContent();
3819
+ if (this.supportsSessionListUpdates && !this.#groups?.has(sessionId)) this.#analytics?.track([sessionId]);
3931
3820
  this.#callbacks?.onSessionInventoryChanged(sessionId);
3932
3821
  },
3933
3822
  invalidateConnections: () => {
3934
3823
  this.#schedules?.invalidate();
3935
3824
  this.#closePeerTurns(new Error("Copilot connection changed during the peer turn"));
3936
- return this.#sessions.invalidateConnections();
3825
+ const watched = this.#sessions.invalidateConnections();
3826
+ this.#analytics?.recordGap(watched);
3827
+ return watched;
3937
3828
  },
3938
3829
  stopResources: () => this.#sessions.stopResources(),
3939
3830
  resetObservation: () => {
@@ -4147,6 +4038,12 @@ var GithubCopilotAdapter = class {
4147
4038
  #callbacks;
4148
4039
  #workbench = new SessionWorkbenchRuntime({
4149
4040
  getSession: (sessionId) => this.#sessions.getSession(sessionId),
4041
+ currentSession: (sessionId) => this.#sessions.current(sessionId),
4042
+ telemetry: (sessionId) => this.#analytics?.telemetry(
4043
+ sessionId,
4044
+ this.#provisionalSessions.get(sessionId)?.allowMissingEventLog === true
4045
+ ) ?? Promise.resolve(void 0),
4046
+ storage: (sessionId) => this.#sessionStorage.storage(sessionId),
4150
4047
  getRuntime: (sessionId) => this.#sessions.getOrCreate(sessionId),
4151
4048
  assertAvailable: (sessionId) => {
4152
4049
  assertMainSessionId(sessionId);
@@ -4178,7 +4075,10 @@ var GithubCopilotAdapter = class {
4178
4075
  }
4179
4076
  });
4180
4077
  #schedules;
4078
+ #analytics;
4079
+ #sessionStorage = new SessionDirectoryLister((id) => this.getSessionDirectoryMetadata(id));
4181
4080
  workbench = {
4081
+ reasoning: (id, request) => this.#withWorkbenchOperation(() => this.#workbench.reasoning(id, request)),
4182
4082
  ask: (id, question) => this.#withWorkbenchOperation(() => this.#workbench.ask(id, question)),
4183
4083
  commands: (id) => this.#withWorkbenchOperation(() => this.#workbench.commands(id)),
4184
4084
  invokeCommand: (id, name, input) => this.#withWorkbenchOperation(() => this.#workbench.invokeCommand(id, name, input)),
@@ -4364,6 +4264,12 @@ var GithubCopilotAdapter = class {
4364
4264
  throw new GroupChatError("GROUP_CHAT_PARTICIPANT_BUSY", "Wait for the group-owned turn to stop before using its participant independently");
4365
4265
  }
4366
4266
  }
4267
+ assertPeerSession(sessionId) {
4268
+ assertMainSessionId(sessionId);
4269
+ if (!this.peerChatEnabled || this.#groups?.has(sessionId)) {
4270
+ throw new GroupChatError("GROUP_CHAT_PARTICIPANT_UNSUPPORTED", "Choose an ordinary peer-enabled Copilot session");
4271
+ }
4272
+ }
4367
4273
  runPeerTurn(sessionId, prompt, options) {
4368
4274
  try {
4369
4275
  assertMainSessionId(sessionId);
@@ -4592,7 +4498,7 @@ var GithubCopilotAdapter = class {
4592
4498
  } finally {
4593
4499
  runtime.connection.sendInProgressCount -= 1;
4594
4500
  if (runtime.connection.sendInProgressCount === 0) {
4595
- for (const resolve4 of runtime.connection.sendCompletionWaiters) resolve4();
4501
+ for (const resolve2 of runtime.connection.sendCompletionWaiters) resolve2();
4596
4502
  runtime.connection.sendCompletionWaiters.clear();
4597
4503
  }
4598
4504
  }
@@ -4645,7 +4551,10 @@ var GithubCopilotAdapter = class {
4645
4551
  throw new Error("Copilot returned metadata for a different session");
4646
4552
  }
4647
4553
  const workingDirectory = "workingDirectory" in metadata ? metadata.workingDirectory : metadata.context?.workingDirectory;
4648
- return workingDirectory === void 0 ? {} : { workingDirectory };
4554
+ return {
4555
+ ...workingDirectory === void 0 ? {} : { workingDirectory },
4556
+ ...this.supportsFileAttachments && !metadata.isRemote && "workspacePath" in metadata && metadata.workspacePath !== null ? { sessionStateDirectory: metadata.workspacePath } : {}
4557
+ };
4649
4558
  }
4650
4559
  #projectIdentity = new SessionProjectIdentityReader(
4651
4560
  (sessionId) => this.getSessionDirectoryMetadata(sessionId)
@@ -4668,6 +4577,9 @@ var GithubCopilotAdapter = class {
4668
4577
  () => listSessionMetadata(this.#runtime.client),
4669
4578
  { retryRead: true }
4670
4579
  )).filter((session) => !isResearchSessionId(session.sessionId));
4580
+ if (this.supportsSessionListUpdates) {
4581
+ this.#analytics?.track(sessions.filter((session) => !this.#groups?.has(session.sessionId)).map((session) => session.sessionId));
4582
+ }
4671
4583
  for (const metadata of sessions) {
4672
4584
  const workingDirectory = metadata.context?.workingDirectory;
4673
4585
  if (workingDirectory !== void 0) {
@@ -4702,7 +4614,7 @@ var GithubCopilotAdapter = class {
4702
4614
  }
4703
4615
  #resolveGitRemoteUrl(sessionId, workingDirectory) {
4704
4616
  if (!this.supportsSessionListUpdates) return Promise.resolve(void 0);
4705
- const directory = isAbsolute2(workingDirectory) ? resolve3(workingDirectory) : workingDirectory;
4617
+ const directory = isAbsolute(workingDirectory) ? resolve(workingDirectory) : workingDirectory;
4706
4618
  const cached = this.#gitRemoteUrls.get(directory);
4707
4619
  const now = Date.now();
4708
4620
  if (cached && cached.expiresAt > now) return cached.value;
@@ -4966,8 +4878,8 @@ var GithubCopilotAdapter = class {
4966
4878
  try {
4967
4879
  const runtime = this.#sessions.peek(sessionId);
4968
4880
  while (runtime !== void 0 && runtime.connection.sendInProgressCount > 0) {
4969
- await new Promise((resolve4) => {
4970
- runtime.connection.sendCompletionWaiters.add(resolve4);
4881
+ await new Promise((resolve2) => {
4882
+ runtime.connection.sendCompletionWaiters.add(resolve2);
4971
4883
  });
4972
4884
  }
4973
4885
  await this.#deleteSession(sessionId);
@@ -4989,6 +4901,7 @@ var GithubCopilotAdapter = class {
4989
4901
  this.#deletedSessions.add(sessionId);
4990
4902
  }
4991
4903
  await this.#schedules?.forgetSession(sessionId);
4904
+ await this.#analytics?.remove(sessionId);
4992
4905
  await this.#groups?.deleteNativeSession(sessionId);
4993
4906
  this.#sessions.delete(sessionId);
4994
4907
  this.#provisionalSessions.delete(sessionId);
@@ -5186,6 +5099,11 @@ var GithubCopilotAdapter = class {
5186
5099
  ...groupErrors,
5187
5100
  ...await this.#runtime.stop()
5188
5101
  ];
5102
+ try {
5103
+ await this.#analytics?.close();
5104
+ } catch (error) {
5105
+ errors.push(error instanceof Error ? error : new Error(String(error)));
5106
+ }
5189
5107
  await this.#interactions.clear();
5190
5108
  this.#sessions.clear();
5191
5109
  this.#upgradeSessionIds.clear();
@@ -5205,8 +5123,8 @@ var GithubCopilotAdapter = class {
5205
5123
  #createHtmlPreviewTool(sessionId, workingDirectory) {
5206
5124
  return defineTool2("present_html_preview", {
5207
5125
  description: "Present a self-contained HTML file from the current workspace on the paired mobile device.",
5208
- parameters: z7.object({
5209
- path: z7.string().trim().min(1).describe("Workspace-relative path to a UTF-8 .html or .htm file")
5126
+ parameters: z5.object({
5127
+ path: z5.string().trim().min(1).describe("Workspace-relative path to a UTF-8 .html or .htm file")
5210
5128
  }).strict(),
5211
5129
  defer: "never",
5212
5130
  handler: async ({ path }, invocation) => {
@@ -5215,21 +5133,21 @@ var GithubCopilotAdapter = class {
5215
5133
  "Open this session on the paired mobile device before presenting HTML"
5216
5134
  );
5217
5135
  }
5218
- const workspaceRoot = await realpath3(workingDirectory);
5219
- const requestedPath = resolve3(workspaceRoot, path);
5220
- const resolvedPath = await realpath3(requestedPath);
5221
- const relativePath = relative2(workspaceRoot, resolvedPath);
5222
- if (relativePath.length === 0 || relativePath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || relativePath === ".." || isAbsolute2(relativePath)) {
5136
+ const workspaceRoot = await realpath2(workingDirectory);
5137
+ const requestedPath = resolve(workspaceRoot, path);
5138
+ const resolvedPath = await realpath2(requestedPath);
5139
+ const relativePath = relative(workspaceRoot, resolvedPath);
5140
+ if (relativePath.length === 0 || relativePath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || relativePath === ".." || isAbsolute(relativePath)) {
5223
5141
  throw new Error("HTML preview path must remain inside the session workspace");
5224
5142
  }
5225
5143
  if (![".html", ".htm"].includes(extname(resolvedPath).toLowerCase())) {
5226
5144
  throw new Error("HTML preview requires a .html or .htm file");
5227
5145
  }
5228
- const file = await stat2(resolvedPath);
5146
+ const file = await stat(resolvedPath);
5229
5147
  if (!file.isFile() || file.size === 0 || file.size > MAX_HTML_PREVIEW_BYTES) {
5230
5148
  throw new Error("HTML preview must be a non-empty file no larger than 512 KiB");
5231
5149
  }
5232
- const bytes = await readFile3(resolvedPath);
5150
+ const bytes = await readFile2(resolvedPath);
5233
5151
  new TextDecoder("utf-8", { fatal: true }).decode(bytes);
5234
5152
  const sourceEventId = `html-preview:${invocation.toolCallId}`;
5235
5153
  const item = ConversationItemSchema.parse({
@@ -5264,6 +5182,7 @@ var GithubCopilotAdapter = class {
5264
5182
  }
5265
5183
  #queueLiveEvent(sessionId, event) {
5266
5184
  if (!this.#deletingSessions.has(sessionId) && !this.#deletedSessions.has(sessionId)) {
5185
+ this.#analytics?.observe(sessionId, event);
5267
5186
  this.#schedules?.observe(sessionId, event);
5268
5187
  }
5269
5188
  if (this.#schedules?.hasPlans(sessionId)) this.#interactions.persist(sessionId, true);