@agentknight/sdk 0.9.55 → 0.9.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,4 @@
1
1
  import {
2
- ConversationNormalizer,
3
2
  LiveTimelineProjection,
4
3
  NotGitDirectoryError,
5
4
  PromptPreparationError,
@@ -9,7 +8,6 @@ import {
9
8
  SessionRuntimeRegistry,
10
9
  SessionWorkbenchRuntime,
11
10
  isClosedCopilotConnection,
12
- isDisplayableHumanMessage,
13
11
  isDisposedCopilotSession,
14
12
  isSessionRestoreFailure,
15
13
  measureOperationStage,
@@ -18,26 +16,39 @@ import {
18
16
  recordTimelineSyncDiagnostic,
19
17
  resolveGitProjectIdentity,
20
18
  sanitizeGitRemoteUrl
21
- } from "./chunk-6ZPE7VIE.js";
19
+ } from "./chunk-OOCAIULD.js";
22
20
  import "./chunk-IJPJQF7S.js";
21
+ import {
22
+ AnalyticsIndexResultSchema,
23
+ AnalyticsReplySchema,
24
+ CopilotSessionCompatibilityClient,
25
+ openSessionEventLog,
26
+ readSessionUpdatePage,
27
+ resolveCopilotSessionDirectory,
28
+ resumeWithCopilotSessionCompatibility
29
+ } from "./chunk-ZLKFFKAX.js";
30
+ import {
31
+ ConversationNormalizer,
32
+ isDisplayableHumanMessage
33
+ } from "./chunk-LT5ULDVT.js";
23
34
  import {
24
35
  assertMainSessionId,
25
36
  isResearchSessionId
26
- } from "./chunk-E7QL4CBT.js";
37
+ } from "./chunk-WPVH7HKC.js";
27
38
  import {
28
39
  GroupChatError,
29
40
  GroupChatMessageSchema,
30
41
  GroupChatRuntime
31
- } from "./chunk-HFVA7ZOD.js";
32
- import {
33
- isContentfulAssistant
34
- } from "./chunk-5J7BK2Y7.js";
42
+ } from "./chunk-EDZPP6SJ.js";
43
+ import "./chunk-IPJWNGNK.js";
35
44
  import {
36
45
  AgentSessionRenameError,
37
- SessionOperationError,
38
46
  TimelinePageBudgetError,
39
47
  validateSessionName
40
- } from "./chunk-L3A736SO.js";
48
+ } from "./chunk-3LEPYV7Y.js";
49
+ import {
50
+ SessionOperationError
51
+ } from "./chunk-7ZYBES47.js";
41
52
  import {
42
53
  ConversationItemSchema,
43
54
  CopilotModelOptionSchema,
@@ -47,6 +58,7 @@ import {
47
58
  PromptImageAttachmentSchema,
48
59
  ReasoningEffortSchema,
49
60
  SESSION_TIMELINE_PAGE_SIZE,
61
+ SessionAnalyticsResultSchema,
50
62
  SessionAvatarPersonaSchema,
51
63
  SessionReasoningEffortSchema,
52
64
  SessionRemoteStatusSchema,
@@ -58,283 +70,13 @@ import {
58
70
  WorkbenchScheduleEntrySchema,
59
71
  WorkbenchScheduleProposalSchema,
60
72
  WorkbenchScheduleSnapshotSchema
61
- } from "./chunk-K5CMKBW6.js";
73
+ } from "./chunk-KBI5IWPR.js";
62
74
 
63
75
  // src/copilot-adapter.ts
64
76
  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";
77
+ import { readFile as readFile2, realpath as realpath2, stat } from "node:fs/promises";
66
78
  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
- }
79
+ import { basename as basename2, extname, isAbsolute, relative, resolve } from "node:path";
338
80
 
339
81
  // src/adapters/copilot/runtime/client-runtime.ts
340
82
  var CopilotClientRuntime = class {
@@ -560,8 +302,8 @@ var SessionConfiguration = class {
560
302
  const runtime = this.ports.state(sessionId);
561
303
  const previous = runtime.configuration.transition;
562
304
  let release = () => void 0;
563
- const current = new Promise((resolve4) => {
564
- release = resolve4;
305
+ const current = new Promise((resolve2) => {
306
+ release = resolve2;
565
307
  });
566
308
  runtime.configuration.transition = current;
567
309
  await previous;
@@ -796,8 +538,8 @@ import "@github/copilot-sdk";
796
538
 
797
539
  // src/prompt-attachments.ts
798
540
  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";
541
+ import { lstat, mkdir, realpath, rm, writeFile } from "node:fs/promises";
542
+ import { basename, dirname, join } from "node:path";
801
543
  function validatePromptAttachments(images, files) {
802
544
  const validateBytes = (attachment) => {
803
545
  const bytes = Buffer.from(attachment.data, "base64");
@@ -827,9 +569,9 @@ function hasCode(error, code) {
827
569
  return error instanceof Error && "code" in error && error.code === code;
828
570
  }
829
571
  async function uploadDirectory(sessionDirectory, create) {
830
- const home = dirname2(dirname2(sessionDirectory));
572
+ const home = dirname(dirname(sessionDirectory));
831
573
  if (create) {
832
- await mkdir2(home, { recursive: true, mode: 448 });
574
+ await mkdir(home, { recursive: true, mode: 448 });
833
575
  }
834
576
  let directory;
835
577
  try {
@@ -839,10 +581,10 @@ async function uploadDirectory(sessionDirectory, create) {
839
581
  throw error;
840
582
  }
841
583
  for (const segment of ["session-state", basename(sessionDirectory), "agentknight-uploads"]) {
842
- directory = join2(directory, segment);
584
+ directory = join(directory, segment);
843
585
  if (create) {
844
586
  try {
845
- await mkdir2(directory, { mode: 448 });
587
+ await mkdir(directory, { mode: 448 });
846
588
  } catch (error) {
847
589
  if (!hasCode(error, "EEXIST")) throw error;
848
590
  }
@@ -863,20 +605,20 @@ async function stagePromptAttachments(sessionId, validated) {
863
605
  if (validated.files.length === 0) return validated.images;
864
606
  const root = await uploadDirectory(resolveCopilotSessionDirectory(sessionId), true);
865
607
  if (root === void 0) throw new Error("Attachment storage is unavailable");
866
- const batchDirectory = join2(root, randomUUID());
867
- await mkdir2(batchDirectory, { mode: 448 });
608
+ const batchDirectory = join(root, randomUUID());
609
+ await mkdir(batchDirectory, { mode: 448 });
868
610
  try {
869
611
  const attachments = [...validated.images];
870
612
  for (const [index, { attachment, bytes }] of validated.files.entries()) {
871
613
  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 });
614
+ const path = join(batchDirectory, `${index}-${name || "file"}`);
615
+ await writeFile(path, bytes, { flag: "wx", mode: 384, flush: true });
874
616
  attachments.push({ type: "file", path, displayName: attachment.name });
875
617
  }
876
618
  return attachments;
877
619
  } catch (error) {
878
620
  try {
879
- await rm2(batchDirectory, { recursive: true, force: true });
621
+ await rm(batchDirectory, { recursive: true, force: true });
880
622
  } catch (cleanupError) {
881
623
  throw new AggregateError([error, cleanupError], "Failed to stage and clean up prompt attachments");
882
624
  }
@@ -886,7 +628,7 @@ async function stagePromptAttachments(sessionId, validated) {
886
628
  async function deletePromptAttachments(sessionDirectory) {
887
629
  const directory = await uploadDirectory(sessionDirectory, false);
888
630
  if (directory !== void 0) {
889
- await rm2(directory, { recursive: true, force: true });
631
+ await rm(directory, { recursive: true, force: true });
890
632
  }
891
633
  }
892
634
 
@@ -953,8 +695,8 @@ var SessionConnections = class {
953
695
  async reloadSessionWhenSendCompletes(sessionId, options = {}, expectedSession) {
954
696
  const runtime = this.#sessionRuntimes.getOrCreate(sessionId);
955
697
  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);
698
+ await new Promise((resolve2) => {
699
+ runtime.connection.sendCompletionWaiters.add(resolve2);
958
700
  });
959
701
  if (this.ports.runtime().stopping) {
960
702
  throw new Error("Copilot adapter is stopping");
@@ -1187,8 +929,8 @@ var SessionConnections = class {
1187
929
  const remaining = runtime.connection.sendInProgressCount - 1;
1188
930
  if (remaining === 0) {
1189
931
  runtime.connection.sendInProgressCount = 0;
1190
- for (const resolve4 of runtime.connection.sendCompletionWaiters) {
1191
- resolve4();
932
+ for (const resolve2 of runtime.connection.sendCompletionWaiters) {
933
+ resolve2();
1192
934
  }
1193
935
  runtime.connection.sendCompletionWaiters.clear();
1194
936
  } else {
@@ -1527,8 +1269,8 @@ var TimelineImageAssets = class {
1527
1269
  }
1528
1270
  }
1529
1271
  if (normalizer.pendingImageAssetIds().length > 0) {
1530
- await new Promise((resolve4) => {
1531
- setTimeout(resolve4, IMAGE_ASSET_LIVE_GRACE_MS);
1272
+ await new Promise((resolve2) => {
1273
+ setTimeout(resolve2, IMAGE_ASSET_LIVE_GRACE_MS);
1532
1274
  });
1533
1275
  }
1534
1276
  const unresolvedAssetIds = normalizer.pendingImageAssetIds();
@@ -1791,256 +1533,6 @@ var PlanSnapshots = class {
1791
1533
 
1792
1534
  // src/adapters/copilot/timeline/timeline-history.ts
1793
1535
  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
1536
  var MAX_TIMELINE_RAW_EVENT_MULTIPLIER = 20;
2045
1537
  var TIMELINE_PAGE_PAYLOAD_BUDGET_BYTES = 6 * 1024 * 1024;
2046
1538
  function startsAtTurnBoundary(events, resolveInputProvenance) {
@@ -2238,25 +1730,25 @@ var TimelineHistory = class {
2238
1730
 
2239
1731
  // src/copilot-adapter.ts
2240
1732
  import {
2241
- CopilotClient as CopilotClient2,
1733
+ CopilotClient,
2242
1734
  defineTool as defineTool2,
2243
1735
  RuntimeConnection
2244
1736
  } from "@github/copilot-sdk";
2245
- import { z as z7 } from "zod";
1737
+ import { z as z5 } from "zod";
2246
1738
 
2247
1739
  // src/session-schedules.ts
2248
1740
  import { randomUUID as randomUUID3 } from "node:crypto";
2249
1741
  import { defineTool } from "@github/copilot-sdk";
2250
- import { z as z5 } from "zod";
1742
+ import { z as z3 } from "zod";
2251
1743
 
2252
1744
  // src/schedule-draft-store.ts
2253
1745
  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)
1746
+ import { lstat as lstat2, mkdir as mkdir2, open, readFile, rename, rm as rm2 } from "node:fs/promises";
1747
+ import { join as join2 } from "node:path";
1748
+ import { z } from "zod";
1749
+ var Document = z.object({
1750
+ version: z.literal(1),
1751
+ drafts: z.array(WorkbenchScheduleDraftSchema).max(100)
2260
1752
  }).strict();
2261
1753
  var ScheduleDraftStore = class {
2262
1754
  constructor(directory) {
@@ -2265,7 +1757,7 @@ var ScheduleDraftStore = class {
2265
1757
  directory;
2266
1758
  #locks = /* @__PURE__ */ new Map();
2267
1759
  #path(sessionId) {
2268
- return join3(this.directory, `${createHash2("sha256").update(sessionId).digest("hex")}.json`);
1760
+ return join2(this.directory, `${createHash2("sha256").update(sessionId).digest("hex")}.json`);
2269
1761
  }
2270
1762
  async list(sessionId) {
2271
1763
  await this.#locks.get(sessionId);
@@ -2274,9 +1766,9 @@ var ScheduleDraftStore = class {
2274
1766
  async #read(sessionId) {
2275
1767
  try {
2276
1768
  const path = this.#path(sessionId);
2277
- const metadata = await lstat3(path);
1769
+ const metadata = await lstat2(path);
2278
1770
  if (metadata.isSymbolicLink() || metadata.size > 8 * 1024 * 1024) throw new Error("Invalid draft document");
2279
- const value = JSON.parse(await readFile2(path, "utf8"));
1771
+ const value = JSON.parse(await readFile(path, "utf8"));
2280
1772
  return Document.parse(value).drafts;
2281
1773
  } catch (error) {
2282
1774
  if (error instanceof Error && "code" in error && error.code === "ENOENT") return [];
@@ -2286,22 +1778,22 @@ var ScheduleDraftStore = class {
2286
1778
  async update(sessionId, change) {
2287
1779
  const work = (this.#locks.get(sessionId) ?? Promise.resolve()).then(async () => {
2288
1780
  const value = Document.parse({ version: 1, drafts: change(await this.#read(sessionId)) });
2289
- await mkdir3(this.directory, { recursive: true, mode: 448 });
1781
+ await mkdir2(this.directory, { recursive: true, mode: 448 });
2290
1782
  const target = this.#path(sessionId);
2291
1783
  const staging = `${target}.${randomUUID2()}.pending`;
2292
1784
  try {
2293
- const file = await open2(staging, "wx", 384);
1785
+ const file = await open(staging, "wx", 384);
2294
1786
  try {
2295
1787
  await file.writeFile(JSON.stringify(value));
2296
1788
  await file.sync();
2297
1789
  } finally {
2298
1790
  await file.close();
2299
1791
  }
2300
- await rename2(staging, target);
1792
+ await rename(staging, target);
2301
1793
  } catch (error) {
2302
1794
  throw new SessionOperationError("SCHEDULE_DRAFT_STORE_UNAVAILABLE", "Schedule drafts could not be saved", { cause: error });
2303
1795
  } finally {
2304
- await rm3(staging, { force: true });
1796
+ await rm2(staging, { force: true });
2305
1797
  }
2306
1798
  });
2307
1799
  const settled = work.then(() => void 0, () => void 0);
@@ -2315,7 +1807,7 @@ var ScheduleDraftStore = class {
2315
1807
  async remove(sessionId) {
2316
1808
  const work = (this.#locks.get(sessionId) ?? Promise.resolve()).then(async () => {
2317
1809
  try {
2318
- await rm3(this.#path(sessionId), { force: true });
1810
+ await rm2(this.#path(sessionId), { force: true });
2319
1811
  } catch (error) {
2320
1812
  throw new SessionOperationError("SCHEDULE_DRAFT_STORE_UNAVAILABLE", "Schedule drafts could not be removed", { cause: error });
2321
1813
  }
@@ -2331,25 +1823,25 @@ var ScheduleDraftStore = class {
2331
1823
  };
2332
1824
 
2333
1825
  // 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()
1826
+ import { z as z2 } from "zod";
1827
+ var Event = z2.object({
1828
+ id: z2.string().min(1).max(256),
1829
+ timestamp: z2.iso.datetime({ offset: true }),
1830
+ type: z2.string(),
1831
+ agentId: z2.string().optional(),
1832
+ data: z2.object({
1833
+ source: z2.string().optional(),
1834
+ content: z2.string().optional(),
1835
+ interactionId: z2.string().optional(),
1836
+ turnId: z2.string().optional(),
1837
+ messageId: z2.string().optional(),
1838
+ originatingMessageId: z2.string().optional(),
1839
+ apiCallId: z2.string().optional(),
1840
+ chunkIndex: z2.number().int().nonnegative().optional(),
1841
+ chunkCount: z2.number().int().positive().optional(),
1842
+ parentToolCallId: z2.string().optional(),
1843
+ delivery: z2.string().optional(),
1844
+ toolRequests: z2.array(z2.unknown()).optional()
2353
1845
  }).passthrough()
2354
1846
  });
2355
1847
  var MAX_EVENTS = 2e4;
@@ -2415,13 +1907,13 @@ function projectScheduleHistory(input) {
2415
1907
 
2416
1908
  // src/session-schedules.ts
2417
1909
  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()
1910
+ tz: z3.string().max(128).optional(),
1911
+ at: z3.number().int().nonnegative().max(864e13).optional()
2420
1912
  }).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"])
1913
+ var NativeList = z3.object({ entries: z3.array(NativeEntry).max(256) });
1914
+ var CommandCatalog = z3.object({ commands: z3.array(z3.object({
1915
+ name: z3.string().max(256),
1916
+ kind: z3.enum(["builtin", "skill", "client"])
2425
1917
  })).max(512) });
2426
1918
  function unavailable(code, message) {
2427
1919
  return new SessionOperationError(code, message);
@@ -2502,7 +1994,10 @@ var SessionSchedules = class {
2502
1994
  }
2503
1995
  return { connection, session, schedule: session.rpc.schedule, invoke: session.rpc.commands.invoke };
2504
1996
  }
2505
- async snapshot(sessionId) {
1997
+ snapshot(sessionId) {
1998
+ return this.#snapshot(sessionId, true);
1999
+ }
2000
+ async #snapshot(sessionId, readHistory) {
2506
2001
  this.options.assertAvailable(sessionId);
2507
2002
  const connection = this.options.current(sessionId);
2508
2003
  const drafts = await this.#drafts.list(sessionId);
@@ -2519,7 +2014,10 @@ var SessionSchedules = class {
2519
2014
  });
2520
2015
  }
2521
2016
  const { session, schedule } = await this.#active(sessionId);
2522
- const [native, history] = await Promise.all([schedule.list(), session.getEvents?.()]);
2017
+ const [native, history] = await Promise.all([
2018
+ schedule.list(),
2019
+ readHistory ? session.getEvents?.() : void 0
2020
+ ]);
2523
2021
  this.#check(sessionId, connection);
2524
2022
  const entries = NativeList.parse(native).entries.map(({ tz, at, ...entry }) => ({
2525
2023
  ...entry,
@@ -2533,7 +2031,10 @@ var SessionSchedules = class {
2533
2031
  sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
2534
2032
  timezone: new Intl.DateTimeFormat("en").resolvedOptions().timeZone,
2535
2033
  ...workingDirectory === void 0 ? {} : { workingDirectory },
2536
- ...projectScheduleHistory(history ?? [])
2034
+ ...readHistory ? projectScheduleHistory(history ?? []) : {
2035
+ results: this.#cache.get(sessionId)?.results ?? [],
2036
+ historyTruncated: true
2037
+ }
2537
2038
  });
2538
2039
  if (entries.length > 0) this.#activePlans.add(sessionId);
2539
2040
  else this.#activePlans.delete(sessionId);
@@ -2675,11 +2176,13 @@ var SessionSchedules = class {
2675
2176
  this.#check(sessionId, connection);
2676
2177
  assertAccess?.();
2677
2178
  try {
2678
- const result = z5.object({ entry: NativeEntry.optional() }).parse(await schedule.stop({ id }));
2179
+ const result = z3.object({ entry: NativeEntry.optional() }).parse(await schedule.stop({ id }));
2679
2180
  assertAccess?.();
2680
2181
  if (result.entry !== void 0 && result.entry.id !== id) throw new Error("Native schedule identity mismatch");
2681
2182
  this.#check(sessionId, connection);
2682
- const snapshot = await this.snapshot(sessionId);
2183
+ const snapshot = await this.#snapshot(sessionId, false);
2184
+ this.#check(sessionId, connection);
2185
+ assertAccess?.();
2683
2186
  if (snapshot.entries.some((entry) => entry.id === id)) throw new Error("Native schedule is still present");
2684
2187
  this.options.changed(sessionId);
2685
2188
  return { snapshot, removed: result.entry !== void 0 };
@@ -2700,6 +2203,303 @@ var SessionSchedules = class {
2700
2203
  }
2701
2204
  };
2702
2205
 
2206
+ // src/session-analytics.ts
2207
+ import { Worker } from "node:worker_threads";
2208
+ var MAX_PENDING_EVENTS = 512;
2209
+ var MAX_PENDING_BYTES = 4 * 1024 * 1024;
2210
+ var MAX_TRACKED_SESSIONS = 1e4;
2211
+ var SessionAnalytics = class {
2212
+ constructor(directory, onError) {
2213
+ this.directory = directory;
2214
+ this.onError = onError;
2215
+ }
2216
+ directory;
2217
+ onError;
2218
+ #pending = [];
2219
+ #gaps = /* @__PURE__ */ new Map();
2220
+ #failures = /* @__PURE__ */ new Map();
2221
+ #tracked = /* @__PURE__ */ new Set();
2222
+ #removed = /* @__PURE__ */ new Set();
2223
+ #requests = /* @__PURE__ */ new Map();
2224
+ #worker;
2225
+ #sequence = 0;
2226
+ #pendingBytes = 0;
2227
+ #draining;
2228
+ #batchTimer;
2229
+ #indexTimer;
2230
+ #indexing;
2231
+ #closed = false;
2232
+ start() {
2233
+ this.#closed = false;
2234
+ }
2235
+ #failWorker(worker, error) {
2236
+ if (this.#worker !== worker) return;
2237
+ this.#worker = void 0;
2238
+ if (this.#requests.size === 0) this.onError(this.#tracked.values().next().value ?? "analytics", error);
2239
+ for (const pending of this.#requests.values()) {
2240
+ clearTimeout(pending.timer);
2241
+ pending.reject(error);
2242
+ }
2243
+ this.#requests.clear();
2244
+ void worker.terminate();
2245
+ }
2246
+ #thread() {
2247
+ if (this.#closed) throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics collector is closed");
2248
+ if (this.#worker !== void 0) return this.#worker;
2249
+ const source = import.meta.url.endsWith(".ts");
2250
+ 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")), {
2251
+ workerData: { directory: this.directory },
2252
+ execArgv: source ? ["--import", "tsx"] : []
2253
+ });
2254
+ const fail = (error) => this.#failWorker(worker, error);
2255
+ worker.on("message", (value) => {
2256
+ const parsed = AnalyticsReplySchema.safeParse(value);
2257
+ if (!parsed.success) {
2258
+ fail(new Error("Invalid analytics worker response", { cause: parsed.error }));
2259
+ return;
2260
+ }
2261
+ const pending = this.#requests.get(parsed.data.id);
2262
+ if (pending === void 0) return;
2263
+ this.#requests.delete(parsed.data.id);
2264
+ clearTimeout(pending.timer);
2265
+ if (parsed.data.error !== void 0) pending.reject(new SessionOperationError(parsed.data.error.code, parsed.data.error.message));
2266
+ else pending.resolve(parsed.data.result);
2267
+ if (this.#requests.size === 0) worker.unref();
2268
+ });
2269
+ worker.on("error", fail);
2270
+ worker.on("exit", (code) => fail(new Error(`Analytics worker exited (${code})`)));
2271
+ this.#worker = worker;
2272
+ worker.unref();
2273
+ return worker;
2274
+ }
2275
+ #request(command) {
2276
+ return new Promise((resolve2, reject) => {
2277
+ const worker = this.#thread();
2278
+ if (this.#requests.size >= 16 && command.operation !== "observe" && command.operation !== "close") {
2279
+ reject(new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics worker is busy; retry"));
2280
+ return;
2281
+ }
2282
+ const id = ++this.#sequence;
2283
+ const timer = setTimeout(() => this.#failWorker(
2284
+ worker,
2285
+ new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics worker timed out; retry")
2286
+ ), 3e4);
2287
+ timer.unref();
2288
+ this.#requests.set(id, { resolve: resolve2, reject, timer });
2289
+ worker.ref();
2290
+ try {
2291
+ worker.postMessage({ id, command });
2292
+ } catch (error) {
2293
+ this.#requests.delete(id);
2294
+ clearTimeout(timer);
2295
+ if (this.#requests.size === 0) worker.unref();
2296
+ reject(error);
2297
+ }
2298
+ });
2299
+ }
2300
+ #gap(sessionId, timestamp, count = 1) {
2301
+ const previous = this.#gaps.get(sessionId);
2302
+ this.#gaps.set(sessionId, {
2303
+ sessionId,
2304
+ since: Math.min(previous?.since ?? timestamp, timestamp),
2305
+ count: (previous?.count ?? 0) + count
2306
+ });
2307
+ }
2308
+ recordGap(sessionIds) {
2309
+ for (const id of sessionIds) {
2310
+ if (!this.#closed && !this.#removed.has(id)) this.#gap(id, Date.now(), 0);
2311
+ }
2312
+ if (this.#gaps.size > 0) void this.#drain();
2313
+ }
2314
+ observe(sessionId, event) {
2315
+ if (this.#closed || this.#removed.has(sessionId)) return;
2316
+ if (event.type !== "assistant.usage" && event.type !== "user.message" && event.type !== "assistant.message" && event.type !== "session.skills_loaded") return;
2317
+ if (event.agentId !== void 0 && event.type !== "assistant.usage") return;
2318
+ let data;
2319
+ let bytes = 1024 + (sessionId.length + event.id.length + event.timestamp.length + (event.agentId?.length ?? 0)) * 2;
2320
+ if (event.type === "user.message") {
2321
+ if (event.data.isAutopilotContinuation === true || event.data.source === "tool") return;
2322
+ data = {
2323
+ content: event.data.content.slice(0, 8193),
2324
+ messageId: event.data.messageId,
2325
+ source: event.data.source,
2326
+ isAutopilotContinuation: event.data.isAutopilotContinuation
2327
+ };
2328
+ bytes += (Math.min(event.data.content.length, 8193) + (event.data.messageId?.length ?? 0)) * 2;
2329
+ } else if (event.type === "assistant.message") {
2330
+ if (event.data.parentToolCallId !== void 0) return;
2331
+ data = { messageId: event.data.messageId, content: event.data.content.slice(0, 8193) };
2332
+ bytes += (Math.min(event.data.content.length, 8193) + (event.data.messageId?.length ?? 0)) * 2;
2333
+ } else if (event.type === "session.skills_loaded") {
2334
+ const skills = event.data.skills.slice(0, 513).map((skill) => ({
2335
+ name: skill.name,
2336
+ description: skill.description,
2337
+ source: skill.source,
2338
+ enabled: skill.enabled,
2339
+ userInvocable: skill.userInvocable,
2340
+ commandName: skill.commandName
2341
+ }));
2342
+ data = { skills };
2343
+ bytes += skills.reduce((size, skill) => size + (skill.name.length + (skill.description?.length ?? 0) + skill.source.length + (skill.commandName?.length ?? 0)) * 2 + 256, 0);
2344
+ } else {
2345
+ const accounting = event.data.accounting;
2346
+ data = {
2347
+ model: event.data.model,
2348
+ inputTokens: event.data.inputTokens,
2349
+ outputTokens: event.data.outputTokens,
2350
+ cacheReadTokens: event.data.cacheReadTokens,
2351
+ apiCallId: event.data.apiCallId,
2352
+ accounting: accounting === void 0 ? void 0 : { sourceSessionId: accounting.sourceSessionId, usageId: accounting.usageId }
2353
+ };
2354
+ bytes += (event.data.model.length + (event.data.apiCallId?.length ?? 0) + (accounting?.sourceSessionId.length ?? 0) + (accounting?.usageId.length ?? 0)) * 2;
2355
+ }
2356
+ if (this.#pending.length >= MAX_PENDING_EVENTS || this.#pendingBytes + bytes > MAX_PENDING_BYTES) {
2357
+ this.#gap(sessionId, Date.parse(event.timestamp));
2358
+ const error = new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics queue is full; coverage is incomplete");
2359
+ if (!this.#failures.has(sessionId)) this.onError(sessionId, error);
2360
+ this.#failures.set(sessionId, error);
2361
+ return;
2362
+ }
2363
+ this.#pending.push({ bytes, observation: { sessionId, event: {
2364
+ id: event.id,
2365
+ timestamp: event.timestamp,
2366
+ type: event.type,
2367
+ data,
2368
+ ...event.agentId === void 0 ? {} : { agentId: event.agentId }
2369
+ } } });
2370
+ this.#pendingBytes += bytes;
2371
+ if (this.#batchTimer === void 0 && this.#draining === void 0) {
2372
+ this.#batchTimer = setTimeout(() => {
2373
+ this.#batchTimer = void 0;
2374
+ void this.#drain();
2375
+ }, 25);
2376
+ this.#batchTimer.unref();
2377
+ }
2378
+ }
2379
+ #drain() {
2380
+ if (this.#draining !== void 0) return this.#draining;
2381
+ if (this.#batchTimer !== void 0) clearTimeout(this.#batchTimer);
2382
+ this.#batchTimer = void 0;
2383
+ const work = (async () => {
2384
+ while (this.#pending.length > 0 || this.#gaps.size > 0) {
2385
+ const batch = this.#pending.splice(0, 32);
2386
+ this.#pendingBytes -= batch.reduce((sum, item) => sum + item.bytes, 0);
2387
+ const observations = batch.map((item) => item.observation);
2388
+ const gaps = [...this.#gaps.values()];
2389
+ this.#gaps.clear();
2390
+ const sessions = /* @__PURE__ */ new Set([...observations.map((item) => item.sessionId), ...gaps.map((item) => item.sessionId)]);
2391
+ try {
2392
+ await this.#request({ operation: "observe", observations, gaps });
2393
+ for (const id of sessions) this.#failures.delete(id);
2394
+ } catch (error) {
2395
+ for (const id of sessions) {
2396
+ const previous = gaps.find((gap) => gap.sessionId === id);
2397
+ const earliest = Math.min(Date.now(), ...observations.filter((item) => item.sessionId === id).map((item) => Date.parse(item.event.timestamp)));
2398
+ this.#gap(
2399
+ id,
2400
+ Math.min(previous?.since ?? earliest, earliest),
2401
+ (previous?.count ?? 0) + observations.filter((item) => item.sessionId === id).length
2402
+ );
2403
+ this.#failures.set(id, error);
2404
+ this.onError(id, error);
2405
+ }
2406
+ break;
2407
+ }
2408
+ }
2409
+ })();
2410
+ this.#draining = work.finally(() => {
2411
+ this.#draining = void 0;
2412
+ });
2413
+ return this.#draining;
2414
+ }
2415
+ track(sessionIds) {
2416
+ if (this.#closed) return;
2417
+ for (const id of sessionIds) {
2418
+ if (this.#removed.has(id) || this.#tracked.has(id)) continue;
2419
+ if (this.#tracked.size >= MAX_TRACKED_SESSIONS) {
2420
+ this.onError(id, new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics session capacity exceeded"));
2421
+ break;
2422
+ }
2423
+ this.#tracked.add(id);
2424
+ }
2425
+ this.#scheduleIndex(0);
2426
+ }
2427
+ #scheduleIndex(delay) {
2428
+ if (this.#closed || this.#indexTimer !== void 0 || this.#indexing !== void 0 || this.#tracked.size === 0) return;
2429
+ this.#indexTimer = setTimeout(() => {
2430
+ this.#indexTimer = void 0;
2431
+ let behind = false;
2432
+ this.#indexing = (async () => {
2433
+ for (const id of this.#tracked) {
2434
+ if (this.#closed) break;
2435
+ try {
2436
+ const progress = AnalyticsIndexResultSchema.parse(await this.#request({
2437
+ operation: "index",
2438
+ sessionId: id,
2439
+ environment: this.#environment(process.env),
2440
+ allowMissingEventLog: false
2441
+ }));
2442
+ behind ||= progress.catchUp;
2443
+ } catch (error) {
2444
+ this.onError(id, error);
2445
+ }
2446
+ await this.#drain();
2447
+ }
2448
+ })().finally(() => {
2449
+ this.#indexing = void 0;
2450
+ this.#scheduleIndex(behind ? 250 : 3e4);
2451
+ });
2452
+ }, delay);
2453
+ this.#indexTimer.unref();
2454
+ }
2455
+ #environment(environment) {
2456
+ return environment.COPILOT_HOME === void 0 ? {} : { COPILOT_HOME: environment.COPILOT_HOME };
2457
+ }
2458
+ async remove(sessionId) {
2459
+ this.#removed.add(sessionId);
2460
+ this.#tracked.delete(sessionId);
2461
+ await this.flush();
2462
+ await this.#request({ operation: "remove", sessionId });
2463
+ this.#failures.delete(sessionId);
2464
+ this.#gaps.delete(sessionId);
2465
+ }
2466
+ async flush() {
2467
+ await this.#drain();
2468
+ }
2469
+ async close() {
2470
+ if (this.#closed) return;
2471
+ if (this.#indexTimer !== void 0) clearTimeout(this.#indexTimer);
2472
+ this.#indexTimer = void 0;
2473
+ this.#tracked.clear();
2474
+ await this.#indexing;
2475
+ await this.flush();
2476
+ const worker = this.#worker;
2477
+ try {
2478
+ if (worker !== void 0) await this.#request({ operation: "close" });
2479
+ } finally {
2480
+ this.#closed = true;
2481
+ if (this.#batchTimer !== void 0) clearTimeout(this.#batchTimer);
2482
+ this.#worker = void 0;
2483
+ if (worker !== void 0) await worker.terminate();
2484
+ }
2485
+ }
2486
+ async read(sessionId, request, environment = process.env, allowMissingEventLog) {
2487
+ if (this.#removed.has(sessionId)) throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Session analytics were deleted");
2488
+ await this.flush();
2489
+ if (this.#failures.has(sessionId)) {
2490
+ throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics recording failed", { cause: this.#failures.get(sessionId) });
2491
+ }
2492
+ const result = await this.#request({
2493
+ operation: "read",
2494
+ sessionId,
2495
+ request,
2496
+ environment: this.#environment(environment),
2497
+ allowMissingEventLog: allowMissingEventLog?.() === true
2498
+ });
2499
+ return SessionAnalyticsResultSchema.parse(result);
2500
+ }
2501
+ };
2502
+
2703
2503
  // src/adapters/copilot/interactions/interaction-broker.ts
2704
2504
  import "@github/copilot-sdk";
2705
2505
  import { randomUUID as randomUUID4 } from "node:crypto";
@@ -2966,13 +2766,13 @@ var InteractionBroker = class {
2966
2766
  async #awaitInteractionRelease(operation, sessionId) {
2967
2767
  this.#releasingSessions.set(sessionId, (this.#releasingSessions.get(sessionId) ?? 0) + 1);
2968
2768
  let timer;
2969
- const timeout = new Promise((resolve4) => {
2769
+ const timeout = new Promise((resolve2) => {
2970
2770
  timer = setTimeout(() => {
2971
2771
  this.ports.callbacks()?.onSyncError(
2972
2772
  sessionId,
2973
2773
  new Error("Timed out while releasing a pending mobile interaction")
2974
2774
  );
2975
- resolve4(false);
2775
+ resolve2(false);
2976
2776
  }, INTERACTION_RELEASE_TIMEOUT_MS);
2977
2777
  });
2978
2778
  try {
@@ -3003,12 +2803,12 @@ var InteractionBroker = class {
3003
2803
  );
3004
2804
  }
3005
2805
  const interactionRequestId = randomUUID4();
3006
- return new Promise((resolve4, reject) => {
2806
+ return new Promise((resolve2, reject) => {
3007
2807
  const cancel = () => {
3008
2808
  if (unavailable2 === void 0) {
3009
2809
  reject(new Error(`Mobile ${request.kind} interaction was cancelled`));
3010
2810
  } else {
3011
- resolve4(unavailable2);
2811
+ resolve2(unavailable2);
3012
2812
  }
3013
2813
  };
3014
2814
  const timer = this.#persistentInteractionSessions.has(sessionId) ? void 0 : setTimeout(() => {
@@ -3030,7 +2830,7 @@ var InteractionBroker = class {
3030
2830
  clearTimeout(timer);
3031
2831
  }
3032
2832
  this.#pendingInteractions.delete(interactionRequestId);
3033
- resolve4(converted.value);
2833
+ resolve2(converted.value);
3034
2834
  return Promise.resolve(true);
3035
2835
  }
3036
2836
  });
@@ -3152,16 +2952,16 @@ var InteractionBroker = class {
3152
2952
  );
3153
2953
  }
3154
2954
  const permissionRequestId = randomUUID4();
3155
- return new Promise((resolve4) => {
2955
+ return new Promise((resolve2) => {
3156
2956
  const timer = setTimeout(() => {
3157
2957
  this.#pendingPermissions.delete(permissionRequestId);
3158
- resolve4({ kind: "user-not-available" });
2958
+ resolve2({ kind: "user-not-available" });
3159
2959
  }, 5 * 60 * 1e3);
3160
2960
  this.#pendingPermissions.set(permissionRequestId, {
3161
2961
  sessionId,
3162
2962
  timer,
3163
2963
  approveOnce,
3164
- resolve: resolve4
2964
+ resolve: resolve2
3165
2965
  });
3166
2966
  callbacks.onPermissionRequest(
3167
2967
  sessionId,
@@ -3673,12 +3473,12 @@ var McpAuthCoordinator = class {
3673
3473
 
3674
3474
  // src/peer-session.ts
3675
3475
  import { randomUUID as randomUUID5 } from "node:crypto";
3676
- import { z as z6 } from "zod";
3677
- var PeerTurnTextSchema = z6.string().min(1).max(16e3).refine((text) => text.trim().length > 0);
3678
- var PeerTurnPromptSchema = z6.string().min(1).max(1e5).refine((text) => text.trim().length > 0);
3679
- var PeerTurnToolSchema = z6.object({ content: PeerTurnTextSchema }).strict();
3476
+ import { z as z4 } from "zod";
3477
+ var PeerTurnTextSchema = z4.string().min(1).max(16e3).refine((text) => text.trim().length > 0);
3478
+ var PeerTurnPromptSchema = z4.string().min(1).max(1e5).refine((text) => text.trim().length > 0);
3479
+ var PeerTurnToolSchema = z4.object({ content: PeerTurnTextSchema }).strict();
3680
3480
  function awaitPeerOperation(operation, signal) {
3681
- return new Promise((resolve4, reject) => {
3481
+ return new Promise((resolve2, reject) => {
3682
3482
  const aborted = () => {
3683
3483
  cleanup();
3684
3484
  reject(signal.reason);
@@ -3688,7 +3488,7 @@ function awaitPeerOperation(operation, signal) {
3688
3488
  operation.then(
3689
3489
  (value) => {
3690
3490
  cleanup();
3691
- resolve4(value);
3491
+ resolve2(value);
3692
3492
  },
3693
3493
  (error) => {
3694
3494
  cleanup();
@@ -3704,8 +3504,8 @@ var PeerSessionTurn = class {
3704
3504
  const signal = options.signal;
3705
3505
  this.#signal = signal;
3706
3506
  this.#requestPeer = options.requestPeer;
3707
- this.response = new Promise((resolve4, reject) => {
3708
- this.#resolve = resolve4;
3507
+ this.response = new Promise((resolve2, reject) => {
3508
+ this.#resolve = resolve2;
3709
3509
  this.#reject = reject;
3710
3510
  });
3711
3511
  this.#cancel = () => this.fail(signal.reason ?? new Error("Peer turn cancelled"));
@@ -3759,7 +3559,7 @@ var PeerSessionTurn = class {
3759
3559
  }
3760
3560
  waitForProgress(revision) {
3761
3561
  if (revision !== this.progressRevision || this.terminal || this.closed) return Promise.resolve();
3762
- return new Promise((resolve4) => this.#progressWaiters.add(resolve4));
3562
+ return new Promise((resolve2) => this.#progressWaiters.add(resolve2));
3763
3563
  }
3764
3564
  async completeAfter(cleanup, awaitNativeSettlement = false) {
3765
3565
  const signal = AbortSignal.any([this.#signal, this.#interrupted.signal]);
@@ -3848,7 +3648,7 @@ var PeerSessionTurn = class {
3848
3648
  }
3849
3649
  #notifyProgress() {
3850
3650
  this.progressRevision += 1;
3851
- for (const resolve4 of this.#progressWaiters) resolve4();
3651
+ for (const resolve2 of this.#progressWaiters) resolve2();
3852
3652
  this.#progressWaiters.clear();
3853
3653
  }
3854
3654
  #finish(reason) {
@@ -3865,8 +3665,8 @@ var PeerSessionTurn = class {
3865
3665
 
3866
3666
  // src/copilot-adapter.ts
3867
3667
  var NativeCopilotModelOptionSchema = CopilotModelOptionSchema.extend({
3868
- supportedReasoningEfforts: z7.array(z7.string()).optional(),
3869
- defaultReasoningEffort: z7.string().optional()
3668
+ supportedReasoningEfforts: z5.array(z5.string()).optional(),
3669
+ defaultReasoningEffort: z5.string().optional()
3870
3670
  });
3871
3671
  var GIT_REMOTE_CACHE_TTL_MS = 5 * 60 * 1e3;
3872
3672
  var GIT_REMOTE_FAILURE_CACHE_TTL_MS = 30 * 1e3;
@@ -3877,7 +3677,7 @@ function resolveCopilotRuntimePath(environment = process.env) {
3877
3677
  }
3878
3678
  function createCopilotClient() {
3879
3679
  const defaultConnection = process.env["COPILOT_SDK_DEFAULT_CONNECTION"]?.toLowerCase();
3880
- const client = defaultConnection !== void 0 && defaultConnection !== "stdio" ? new CopilotClient2({ mode: "copilot-cli" }) : new CopilotClient2({
3680
+ const client = defaultConnection !== void 0 && defaultConnection !== "stdio" ? new CopilotClient({ mode: "copilot-cli" }) : new CopilotClient({
3881
3681
  mode: "copilot-cli",
3882
3682
  connection: RuntimeConnection.forStdio({
3883
3683
  path: resolveCopilotRuntimePath()
@@ -3908,21 +3708,45 @@ function mapSessionMetadata(metadata, userId, machineId, gitRemoteUrl) {
3908
3708
  };
3909
3709
  }
3910
3710
  var GithubCopilotAdapter = class {
3911
- constructor(client = createCopilotClient(), openUrl = openExternalUrl, createClient = createCopilotClient, groupChat, peerChatEnabled = true, scheduleDirectory) {
3711
+ constructor(client = createCopilotClient(), openUrl = openExternalUrl, createClient = createCopilotClient, groupChat, peerChatEnabled = true, scheduleDirectory, analyticsDirectory) {
3912
3712
  this.openUrl = openUrl;
3913
3713
  this.peerChatEnabled = peerChatEnabled;
3714
+ if (analyticsDirectory !== void 0) {
3715
+ const analytics = new SessionAnalytics(
3716
+ analyticsDirectory,
3717
+ (id, error) => this.#callbacks?.onSyncError?.(id, error)
3718
+ );
3719
+ this.#analytics = analytics;
3720
+ Object.assign(this.workbench, { analytics: (id, request) => this.#withWorkbenchOperation(async () => {
3721
+ assertMainSessionId(id);
3722
+ this.#runtime.assertStarted();
3723
+ if (!this.supportsSessionListUpdates || this.#groups?.has(id) || this.#runtime.stopping || this.#deletingSessions.has(id) || this.#deletedSessions.has(id)) {
3724
+ throw new SessionOperationError("ANALYTICS_UNSUPPORTED", "Passive session analytics are unavailable");
3725
+ }
3726
+ return analytics.read(
3727
+ id,
3728
+ request,
3729
+ process.env,
3730
+ () => this.#provisionalSessions.get(id)?.allowMissingEventLog === true
3731
+ );
3732
+ }) });
3733
+ }
3914
3734
  this.#runtime = new CopilotClientRuntime(client, createClient, {
3915
3735
  beforeStart: async () => {
3736
+ this.#analytics?.start();
3916
3737
  await this.#groups?.start();
3917
3738
  },
3918
3739
  inventoryChanged: (sessionId) => {
3919
3740
  this.#sessions.peek(sessionId)?.timelineReads.invalidateContent();
3741
+ if (this.supportsSessionListUpdates && !this.#groups?.has(sessionId)) this.#analytics?.track([sessionId]);
3920
3742
  this.#callbacks?.onSessionInventoryChanged(sessionId);
3921
3743
  },
3922
3744
  invalidateConnections: () => {
3923
3745
  this.#schedules?.invalidate();
3924
3746
  this.#closePeerTurns(new Error("Copilot connection changed during the peer turn"));
3925
- return this.#sessions.invalidateConnections();
3747
+ const watched = this.#sessions.invalidateConnections();
3748
+ this.#analytics?.recordGap(watched);
3749
+ return watched;
3926
3750
  },
3927
3751
  stopResources: () => this.#sessions.stopResources(),
3928
3752
  resetObservation: () => {
@@ -4167,6 +3991,7 @@ var GithubCopilotAdapter = class {
4167
3991
  }
4168
3992
  });
4169
3993
  #schedules;
3994
+ #analytics;
4170
3995
  workbench = {
4171
3996
  ask: (id, question) => this.#withWorkbenchOperation(() => this.#workbench.ask(id, question)),
4172
3997
  commands: (id) => this.#withWorkbenchOperation(() => this.#workbench.commands(id)),
@@ -4581,7 +4406,7 @@ var GithubCopilotAdapter = class {
4581
4406
  } finally {
4582
4407
  runtime.connection.sendInProgressCount -= 1;
4583
4408
  if (runtime.connection.sendInProgressCount === 0) {
4584
- for (const resolve4 of runtime.connection.sendCompletionWaiters) resolve4();
4409
+ for (const resolve2 of runtime.connection.sendCompletionWaiters) resolve2();
4585
4410
  runtime.connection.sendCompletionWaiters.clear();
4586
4411
  }
4587
4412
  }
@@ -4657,6 +4482,9 @@ var GithubCopilotAdapter = class {
4657
4482
  () => listSessionMetadata(this.#runtime.client),
4658
4483
  { retryRead: true }
4659
4484
  )).filter((session) => !isResearchSessionId(session.sessionId));
4485
+ if (this.supportsSessionListUpdates) {
4486
+ this.#analytics?.track(sessions.filter((session) => !this.#groups?.has(session.sessionId)).map((session) => session.sessionId));
4487
+ }
4660
4488
  for (const metadata of sessions) {
4661
4489
  const workingDirectory = metadata.context?.workingDirectory;
4662
4490
  if (workingDirectory !== void 0) {
@@ -4691,7 +4519,7 @@ var GithubCopilotAdapter = class {
4691
4519
  }
4692
4520
  #resolveGitRemoteUrl(sessionId, workingDirectory) {
4693
4521
  if (!this.supportsSessionListUpdates) return Promise.resolve(void 0);
4694
- const directory = isAbsolute2(workingDirectory) ? resolve3(workingDirectory) : workingDirectory;
4522
+ const directory = isAbsolute(workingDirectory) ? resolve(workingDirectory) : workingDirectory;
4695
4523
  const cached = this.#gitRemoteUrls.get(directory);
4696
4524
  const now = Date.now();
4697
4525
  if (cached && cached.expiresAt > now) return cached.value;
@@ -4955,8 +4783,8 @@ var GithubCopilotAdapter = class {
4955
4783
  try {
4956
4784
  const runtime = this.#sessions.peek(sessionId);
4957
4785
  while (runtime !== void 0 && runtime.connection.sendInProgressCount > 0) {
4958
- await new Promise((resolve4) => {
4959
- runtime.connection.sendCompletionWaiters.add(resolve4);
4786
+ await new Promise((resolve2) => {
4787
+ runtime.connection.sendCompletionWaiters.add(resolve2);
4960
4788
  });
4961
4789
  }
4962
4790
  await this.#deleteSession(sessionId);
@@ -4978,6 +4806,7 @@ var GithubCopilotAdapter = class {
4978
4806
  this.#deletedSessions.add(sessionId);
4979
4807
  }
4980
4808
  await this.#schedules?.forgetSession(sessionId);
4809
+ await this.#analytics?.remove(sessionId);
4981
4810
  await this.#groups?.deleteNativeSession(sessionId);
4982
4811
  this.#sessions.delete(sessionId);
4983
4812
  this.#provisionalSessions.delete(sessionId);
@@ -5175,6 +5004,11 @@ var GithubCopilotAdapter = class {
5175
5004
  ...groupErrors,
5176
5005
  ...await this.#runtime.stop()
5177
5006
  ];
5007
+ try {
5008
+ await this.#analytics?.close();
5009
+ } catch (error) {
5010
+ errors.push(error instanceof Error ? error : new Error(String(error)));
5011
+ }
5178
5012
  await this.#interactions.clear();
5179
5013
  this.#sessions.clear();
5180
5014
  this.#upgradeSessionIds.clear();
@@ -5194,8 +5028,8 @@ var GithubCopilotAdapter = class {
5194
5028
  #createHtmlPreviewTool(sessionId, workingDirectory) {
5195
5029
  return defineTool2("present_html_preview", {
5196
5030
  description: "Present a self-contained HTML file from the current workspace on the paired mobile device.",
5197
- parameters: z7.object({
5198
- path: z7.string().trim().min(1).describe("Workspace-relative path to a UTF-8 .html or .htm file")
5031
+ parameters: z5.object({
5032
+ path: z5.string().trim().min(1).describe("Workspace-relative path to a UTF-8 .html or .htm file")
5199
5033
  }).strict(),
5200
5034
  defer: "never",
5201
5035
  handler: async ({ path }, invocation) => {
@@ -5204,21 +5038,21 @@ var GithubCopilotAdapter = class {
5204
5038
  "Open this session on the paired mobile device before presenting HTML"
5205
5039
  );
5206
5040
  }
5207
- const workspaceRoot = await realpath3(workingDirectory);
5208
- const requestedPath = resolve3(workspaceRoot, path);
5209
- const resolvedPath = await realpath3(requestedPath);
5210
- const relativePath = relative2(workspaceRoot, resolvedPath);
5211
- if (relativePath.length === 0 || relativePath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || relativePath === ".." || isAbsolute2(relativePath)) {
5041
+ const workspaceRoot = await realpath2(workingDirectory);
5042
+ const requestedPath = resolve(workspaceRoot, path);
5043
+ const resolvedPath = await realpath2(requestedPath);
5044
+ const relativePath = relative(workspaceRoot, resolvedPath);
5045
+ if (relativePath.length === 0 || relativePath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) || relativePath === ".." || isAbsolute(relativePath)) {
5212
5046
  throw new Error("HTML preview path must remain inside the session workspace");
5213
5047
  }
5214
5048
  if (![".html", ".htm"].includes(extname(resolvedPath).toLowerCase())) {
5215
5049
  throw new Error("HTML preview requires a .html or .htm file");
5216
5050
  }
5217
- const file = await stat2(resolvedPath);
5051
+ const file = await stat(resolvedPath);
5218
5052
  if (!file.isFile() || file.size === 0 || file.size > MAX_HTML_PREVIEW_BYTES) {
5219
5053
  throw new Error("HTML preview must be a non-empty file no larger than 512 KiB");
5220
5054
  }
5221
- const bytes = await readFile3(resolvedPath);
5055
+ const bytes = await readFile2(resolvedPath);
5222
5056
  new TextDecoder("utf-8", { fatal: true }).decode(bytes);
5223
5057
  const sourceEventId = `html-preview:${invocation.toolCallId}`;
5224
5058
  const item = ConversationItemSchema.parse({
@@ -5253,6 +5087,7 @@ var GithubCopilotAdapter = class {
5253
5087
  }
5254
5088
  #queueLiveEvent(sessionId, event) {
5255
5089
  if (!this.#deletingSessions.has(sessionId) && !this.#deletedSessions.has(sessionId)) {
5090
+ this.#analytics?.observe(sessionId, event);
5256
5091
  this.#schedules?.observe(sessionId, event);
5257
5092
  }
5258
5093
  if (this.#schedules?.hasPlans(sessionId)) this.#interactions.persist(sessionId, true);