@agentknight/sdk 0.9.64 → 0.9.69

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/chunks/{acp-adapter-MBYKOCA2.js → acp-adapter-VJ2OUSBS.js} +41 -4
  2. package/dist/chunks/{chunk-3AMFPDE5.js → chunk-2D34UDII.js} +4 -13
  3. package/dist/chunks/chunk-35OF2ZNS.js +275 -0
  4. package/dist/chunks/{chunk-A4YCCQ3I.js → chunk-5QYL6NKJ.js} +1 -1
  5. package/dist/chunks/chunk-ES2N66EH.js +109 -0
  6. package/dist/chunks/{chunk-P2PH5KMV.js → chunk-F5YCEWE4.js} +9 -0
  7. package/dist/chunks/{chunk-7CNBPLNE.js → chunk-IRYEOV62.js} +5 -2
  8. package/dist/chunks/{chunk-7OGTK7KB.js → chunk-J63A5OLO.js} +1 -1
  9. package/dist/chunks/chunk-LA6A4TUM.js +302 -0
  10. package/dist/chunks/{chunk-ZNQ2I5EF.js → chunk-LU73CEHE.js} +11 -132
  11. package/dist/chunks/chunk-MB34W52S.js +78 -0
  12. package/dist/chunks/{chunk-CHKNC6PD.js → chunk-MH7FDSTY.js} +1 -1
  13. package/dist/chunks/{chunk-ALUQLM54.js → chunk-Q5NNNSU2.js} +2 -2
  14. package/dist/chunks/chunk-UTF7KLMJ.js +11 -0
  15. package/dist/chunks/chunk-WAPJZKUK.js +115 -0
  16. package/dist/chunks/{chunk-SIFCCGXF.js → chunk-ZAU2MYQI.js} +2 -2
  17. package/dist/chunks/{claude-adapter-D3JWXMNX.js → claude-adapter-FZNLF5XN.js} +240 -27
  18. package/dist/chunks/{codex-adapter-655KHW7H.js → codex-adapter-5ZVOAT6O.js} +249 -66
  19. package/dist/chunks/{copilot-adapter-EZUXHBE3.js → copilot-adapter-V6RAQ4WK.js} +58 -149
  20. package/dist/chunks/{managed-agent-adapter-RIXRCURU.js → managed-agent-adapter-THUSTKRW.js} +35 -24
  21. package/dist/chunks/{pi-adapter-LAD5GOCP.js → pi-adapter-EHCSR5I2.js} +329 -54
  22. package/dist/configuration.js +4 -4
  23. package/dist/index.d.ts +15 -8
  24. package/dist/index.js +37 -35
  25. package/dist/runtime.js +2 -2
  26. package/dist/session-analytics-worker.js +6 -5
  27. package/package.json +3 -3
  28. package/dist/chunks/chunk-CM5LVXVL.js +0 -572
  29. package/dist/chunks/chunk-H4SHMWQ6.js +0 -48
@@ -1,572 +0,0 @@
1
- import {
2
- ConversationNormalizer
3
- } from "./chunk-ZNQ2I5EF.js";
4
- import {
5
- isContentfulAssistant
6
- } from "./chunk-H4SHMWQ6.js";
7
- import {
8
- SessionAnalyticsRequestSchema,
9
- SessionTimelinePageSchema
10
- } from "./chunk-P2PH5KMV.js";
11
-
12
- // src/copilot-session-compatibility.ts
13
- import {
14
- appendFile,
15
- mkdir,
16
- readFile,
17
- readdir,
18
- rename,
19
- rm,
20
- stat,
21
- writeFile
22
- } from "node:fs/promises";
23
- import { homedir } from "node:os";
24
- import {
25
- dirname,
26
- isAbsolute,
27
- join,
28
- relative,
29
- resolve,
30
- sep
31
- } from "node:path";
32
- import {
33
- CopilotClient
34
- } from "@github/copilot-sdk";
35
- import { z } from "zod";
36
- var SessionIdSchema = z.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u);
37
- var PermissionModeSchema = z.enum(["manual", "allow-all"]);
38
- var PermissionEventSchema = z.object({
39
- type: z.literal("session.permissions_changed"),
40
- data: z.object({
41
- previousMode: PermissionModeSchema,
42
- mode: PermissionModeSchema,
43
- previousAllowAllPermissions: z.boolean().optional(),
44
- allowAllPermissions: z.boolean().optional()
45
- }).passthrough()
46
- }).passthrough();
47
- var PERMISSION_EVENT_MARKER = '"type":"session.permissions_changed"';
48
- var PERMISSION_SCHEMA_MISMATCH = /Session file is corrupted \(line \d+: (?:missing field `previousAllowAllPermissions`|(?:data\.)?previousAllowAllPermissions: Required)\)/u;
49
- var VIRTUAL_SESSION_STATE_PATH = process.platform === "win32" ? "C:\\agentknight-session-state" : "/agentknight-session-state";
50
- function normalizeCopilotSessionEvents(content) {
51
- const output = [];
52
- let migratedEventCount = 0;
53
- let outputCursor = 0;
54
- let searchCursor = 0;
55
- let marker = content.indexOf(PERMISSION_EVENT_MARKER, searchCursor);
56
- while (marker !== -1) {
57
- const lineStart = content.lastIndexOf("\n", marker - 1) + 1;
58
- const nextNewline = content.indexOf("\n", marker);
59
- const lineEnd = nextNewline === -1 ? content.length : nextNewline;
60
- const hasCarriageReturn = lineEnd > lineStart && content.charCodeAt(lineEnd - 1) === 13;
61
- const jsonEnd = hasCarriageReturn ? lineEnd - 1 : lineEnd;
62
- const parsed = PermissionEventSchema.safeParse(
63
- JSON.parse(content.slice(lineStart, jsonEnd))
64
- );
65
- if (parsed.success && parsed.data.data.previousAllowAllPermissions === void 0 && parsed.data.data.allowAllPermissions === void 0) {
66
- output.push(
67
- content.slice(outputCursor, lineStart),
68
- JSON.stringify({
69
- ...parsed.data,
70
- data: {
71
- ...parsed.data.data,
72
- previousAllowAllPermissions: parsed.data.data.previousMode === "allow-all",
73
- allowAllPermissions: parsed.data.data.mode === "allow-all"
74
- }
75
- }),
76
- hasCarriageReturn ? "\r" : ""
77
- );
78
- outputCursor = lineEnd;
79
- migratedEventCount += 1;
80
- }
81
- searchCursor = lineEnd;
82
- marker = content.indexOf(PERMISSION_EVENT_MARKER, searchCursor);
83
- }
84
- if (migratedEventCount === 0) {
85
- return { content, migratedEventCount };
86
- }
87
- output.push(content.slice(outputCursor));
88
- return { content: output.join(""), migratedEventCount };
89
- }
90
- async function resumeWithCopilotSessionCompatibility(resume, resumeCompatibleSession) {
91
- try {
92
- return await resume();
93
- } catch (resumeError) {
94
- if (!(resumeError instanceof Error) || !PERMISSION_SCHEMA_MISMATCH.test(resumeError.message)) {
95
- throw resumeError;
96
- }
97
- return resumeCompatibleSession();
98
- }
99
- }
100
- var CopilotSessionCompatibilityClient = class {
101
- #environment;
102
- #workingDirectory;
103
- #client;
104
- #starting;
105
- constructor(environment = process.env, workingDirectory = process.cwd()) {
106
- this.#environment = environment;
107
- this.#workingDirectory = workingDirectory;
108
- }
109
- async resumeSession(sessionId, config) {
110
- const safeSessionId = SessionIdSchema.parse(sessionId);
111
- const client = await this.#getClient();
112
- return client.resumeSession(safeSessionId, {
113
- ...config,
114
- // The overlay provides files only; disabling Session Store avoids routing
115
- // SQLite through a provider that intentionally does not implement it.
116
- enableSessionStore: false,
117
- createSessionFsProvider: () => createLocalSessionProvider(
118
- safeSessionId,
119
- this.#environment,
120
- VIRTUAL_SESSION_STATE_PATH
121
- )
122
- });
123
- }
124
- async stop() {
125
- const client = this.#client;
126
- const starting = this.#starting;
127
- this.#client = void 0;
128
- this.#starting = void 0;
129
- if (client !== void 0) {
130
- return client.stop();
131
- }
132
- if (starting === void 0) {
133
- return [];
134
- }
135
- try {
136
- return (await starting).stop();
137
- } catch (error) {
138
- return [error instanceof Error ? error : new Error(String(error))];
139
- }
140
- }
141
- async forceStop() {
142
- const client = this.#client;
143
- const starting = this.#starting;
144
- this.#client = void 0;
145
- this.#starting = void 0;
146
- if (client !== void 0) {
147
- await client.forceStop();
148
- } else if (starting !== void 0) {
149
- await (await starting).forceStop();
150
- }
151
- }
152
- #getClient() {
153
- if (this.#client !== void 0) {
154
- return Promise.resolve(this.#client);
155
- }
156
- if (this.#starting !== void 0) {
157
- return this.#starting;
158
- }
159
- const client = new CopilotClient({
160
- mode: "copilot-cli",
161
- sessionFs: {
162
- conventions: process.platform === "win32" ? "windows" : "posix",
163
- initialCwd: this.#workingDirectory,
164
- sessionStatePath: VIRTUAL_SESSION_STATE_PATH
165
- }
166
- });
167
- const starting = client.start().then(
168
- () => {
169
- if (this.#starting === starting) {
170
- this.#client = client;
171
- this.#starting = void 0;
172
- }
173
- return client;
174
- },
175
- async (error) => {
176
- if (this.#starting === starting) {
177
- this.#starting = void 0;
178
- }
179
- await client.forceStop();
180
- throw error;
181
- }
182
- );
183
- this.#starting = starting;
184
- return starting;
185
- }
186
- };
187
- function resolveCopilotSessionDirectory(sessionId, environment = process.env) {
188
- const safeSessionId = SessionIdSchema.parse(sessionId);
189
- if (safeSessionId.endsWith(".") || /^(?:con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/iu.test(safeSessionId)) {
190
- throw new Error("Expected a safe Copilot session identifier");
191
- }
192
- const configuredHome = environment.COPILOT_HOME?.trim();
193
- const copilotHome = resolve(
194
- configuredHome === void 0 || configuredHome.length === 0 ? join(homedir(), ".copilot") : configuredHome
195
- );
196
- return join(copilotHome, "session-state", safeSessionId);
197
- }
198
- function createLocalSessionProvider(sessionId, environment, virtualSessionStatePath) {
199
- const sessionDirectory = resolveCopilotSessionDirectory(sessionId, environment);
200
- const virtualRoot = resolve(virtualSessionStatePath);
201
- const resolveProviderPath = (path) => {
202
- const resolvedPath = resolve(path);
203
- const relativeToVirtualRoot = relative(virtualRoot, resolvedPath);
204
- const isWithinVirtualRoot = relativeToVirtualRoot === "" || !relativeToVirtualRoot.startsWith(`..${sep}`) && relativeToVirtualRoot !== ".." && !isAbsolute(relativeToVirtualRoot);
205
- const actualPath = isWithinVirtualRoot ? resolve(sessionDirectory, relativeToVirtualRoot) : resolvedPath;
206
- return {
207
- actualPath,
208
- isEventLog: isWithinVirtualRoot && relativeToVirtualRoot.replaceAll("\\", "/") === "events.jsonl"
209
- };
210
- };
211
- return {
212
- async readFile(path) {
213
- const resolved = resolveProviderPath(path);
214
- const content = await readFile(resolved.actualPath, "utf8");
215
- return resolved.isEventLog ? normalizeCopilotSessionEvents(content).content : content;
216
- },
217
- async writeFile(path, content, mode) {
218
- const { actualPath } = resolveProviderPath(path);
219
- await mkdir(dirname(actualPath), { recursive: true });
220
- await writeFile(actualPath, content, { encoding: "utf8", mode });
221
- },
222
- async appendFile(path, content, mode) {
223
- const { actualPath } = resolveProviderPath(path);
224
- await mkdir(dirname(actualPath), { recursive: true });
225
- await appendFile(actualPath, content, { encoding: "utf8", mode });
226
- },
227
- async exists(path) {
228
- const { actualPath } = resolveProviderPath(path);
229
- try {
230
- await stat(actualPath);
231
- return true;
232
- } catch (error) {
233
- if (isNodeError(error, "ENOENT")) {
234
- return false;
235
- }
236
- throw error;
237
- }
238
- },
239
- async stat(path) {
240
- const { actualPath } = resolveProviderPath(path);
241
- const value = await stat(actualPath);
242
- return {
243
- isFile: value.isFile(),
244
- isDirectory: value.isDirectory(),
245
- size: value.size,
246
- mtime: value.mtime.toISOString(),
247
- birthtime: value.birthtime.toISOString()
248
- };
249
- },
250
- async mkdir(path, recursive, mode) {
251
- const { actualPath } = resolveProviderPath(path);
252
- await mkdir(actualPath, { recursive, mode });
253
- },
254
- async readdir(path) {
255
- const { actualPath } = resolveProviderPath(path);
256
- return readdir(actualPath);
257
- },
258
- async readdirWithTypes(path) {
259
- const { actualPath } = resolveProviderPath(path);
260
- return (await readdir(actualPath, { withFileTypes: true })).map(
261
- (entry) => ({
262
- name: entry.name,
263
- type: entry.isDirectory() ? "directory" : "file"
264
- })
265
- );
266
- },
267
- async rm(path, recursive, force) {
268
- const { actualPath } = resolveProviderPath(path);
269
- await rm(actualPath, { recursive, force });
270
- },
271
- async rename(source, destination) {
272
- const { actualPath: sourcePath } = resolveProviderPath(source);
273
- const { actualPath: destinationPath } = resolveProviderPath(destination);
274
- await rename(sourcePath, destinationPath);
275
- }
276
- };
277
- }
278
- function isNodeError(error, code) {
279
- return error instanceof Error && "code" in error && error.code === code;
280
- }
281
-
282
- // src/session-analytics-messages.ts
283
- import { z as z2 } from "zod";
284
- var AnalyticsEventSchema = z2.object({
285
- id: z2.string().min(1).max(1024),
286
- timestamp: z2.iso.datetime({ offset: true }),
287
- type: z2.string(),
288
- agentId: z2.string().optional(),
289
- data: z2.record(z2.string(), z2.unknown())
290
- });
291
- var SessionId = z2.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/u);
292
- var Observation = z2.object({ sessionId: SessionId, event: AnalyticsEventSchema });
293
- var Gap = z2.object({ sessionId: SessionId, since: z2.number(), count: z2.number().int().nonnegative() });
294
- var History = {
295
- sessionId: SessionId,
296
- environment: z2.object({ COPILOT_HOME: z2.string().optional() }),
297
- allowMissingEventLog: z2.boolean()
298
- };
299
- var AnalyticsCommandSchema = z2.discriminatedUnion("operation", [
300
- z2.object({ operation: z2.literal("observe"), observations: z2.array(Observation).max(32), gaps: z2.array(Gap) }),
301
- z2.object({ operation: z2.literal("index"), ...History }),
302
- z2.object({ operation: z2.literal("read"), ...History, request: SessionAnalyticsRequestSchema }),
303
- z2.object({ operation: z2.literal("telemetry"), ...History }),
304
- z2.object({ operation: z2.literal("remove"), sessionId: SessionId }),
305
- z2.object({ operation: z2.literal("close") })
306
- ]);
307
- var AnalyticsReplySchema = z2.object({
308
- id: z2.number().int(),
309
- result: z2.unknown().optional(),
310
- error: z2.object({ code: z2.string(), message: z2.string() }).optional()
311
- });
312
- var AnalyticsIndexResultSchema = z2.object({ complete: z2.boolean(), catchUp: z2.boolean() });
313
-
314
- // src/session-update-reader.ts
315
- import { lstat, open, realpath } from "node:fs/promises";
316
- import { resolve as resolve2 } from "node:path";
317
- import { z as z3 } from "zod";
318
- var MAX_HEAD_BYTES = 8 * 1024 * 1024;
319
- var EnvelopeSchema = z3.object({
320
- id: z3.string(),
321
- type: z3.string(),
322
- timestamp: z3.iso.datetime({ offset: true }),
323
- agentId: z3.string().optional(),
324
- data: z3.unknown()
325
- });
326
- var HumanSchema = z3.object({
327
- content: z3.string(),
328
- messageId: z3.string().optional(),
329
- interactionId: z3.string().optional(),
330
- source: z3.string().optional(),
331
- isAutopilotContinuation: z3.boolean().optional()
332
- });
333
- var AssistantSchema = z3.object({
334
- messageId: z3.string(),
335
- content: z3.string(),
336
- parentToolCallId: z3.string().optional(),
337
- apiCallId: z3.string().optional(),
338
- chunkIndex: z3.number().int().nonnegative().optional(),
339
- chunkCount: z3.number().int().positive().optional(),
340
- interactionId: z3.string().optional(),
341
- turnId: z3.string().optional()
342
- });
343
- var ToolStartSchema = z3.object({
344
- toolCallId: z3.string(),
345
- toolName: z3.string(),
346
- parentToolCallId: z3.string().optional()
347
- });
348
- var ImageSchema = z3.object({
349
- type: z3.literal("image"),
350
- data: z3.string(),
351
- mimeType: z3.string()
352
- });
353
- var ImageReferenceSchema = z3.object({
354
- type: z3.literal("image"),
355
- assetId: z3.string(),
356
- mimeType: z3.string(),
357
- byteLength: z3.number()
358
- });
359
- var ToolCompleteSchema = z3.object({
360
- toolCallId: z3.string(),
361
- success: z3.boolean(),
362
- result: z3.object({
363
- content: z3.string().optional(),
364
- binaryResultsForLlm: z3.array(z3.unknown()).optional(),
365
- contents: z3.array(z3.unknown()).optional()
366
- }).optional(),
367
- toolDescription: z3.object({ name: z3.string() }).optional(),
368
- parentToolCallId: z3.string().optional()
369
- });
370
- var NoticeSchema = z3.object({ message: z3.string() });
371
- var NotificationSchema = z3.object({ kind: z3.object({ type: z3.string() }).passthrough() });
372
- var ShellCompletedSchema = z3.object({
373
- type: z3.literal("shell_completed"),
374
- shellId: z3.string(),
375
- exitCode: z3.number().int().optional()
376
- });
377
- function metadataEvent(value, preview = false) {
378
- const event = EnvelopeSchema.parse(value);
379
- const toolEvent = event.type === "tool.execution_start" || event.type === "tool.execution_complete";
380
- if (event.agentId !== void 0 && !toolEvent) return void 0;
381
- const base = {
382
- id: event.id,
383
- timestamp: event.timestamp,
384
- parentId: null,
385
- ...event.agentId === void 0 ? {} : { agentId: event.agentId }
386
- };
387
- switch (event.type) {
388
- case "session.binary_asset": {
389
- if (!preview) return void 0;
390
- const parsed = ImageSchema.extend({ assetId: z3.string(), byteLength: z3.number() }).safeParse(event.data);
391
- return parsed.success ? { ...base, type: "session.binary_asset", data: parsed.data } : void 0;
392
- }
393
- case "user.message": {
394
- const data = HumanSchema.parse(event.data);
395
- if (data.isAutopilotContinuation === true) return void 0;
396
- return { ...base, type: "user.message", data: {
397
- content: data.content,
398
- ...data.messageId === void 0 ? {} : { messageId: data.messageId },
399
- ...data.interactionId === void 0 ? {} : { interactionId: data.interactionId },
400
- ...data.source === void 0 ? {} : { source: data.source }
401
- } };
402
- }
403
- case "assistant.message": {
404
- const data = AssistantSchema.parse(event.data);
405
- if (data.parentToolCallId !== void 0) return void 0;
406
- return { ...base, type: "assistant.message", data: {
407
- messageId: data.messageId,
408
- content: data.content,
409
- ...data.apiCallId === void 0 ? {} : { apiCallId: data.apiCallId },
410
- ...data.chunkIndex === void 0 ? {} : { chunkIndex: data.chunkIndex },
411
- ...data.chunkCount === void 0 ? {} : { chunkCount: data.chunkCount },
412
- ...data.interactionId === void 0 ? {} : { interactionId: data.interactionId },
413
- ...data.turnId === void 0 ? {} : { turnId: data.turnId }
414
- } };
415
- }
416
- case "tool.execution_start": {
417
- const data = ToolStartSchema.parse(event.data);
418
- return preview || data.toolName === "task_complete" ? {
419
- ...base,
420
- type: "tool.execution_start",
421
- data: {
422
- toolCallId: data.toolCallId,
423
- toolName: data.toolName,
424
- ...data.parentToolCallId === void 0 ? {} : { parentToolCallId: data.parentToolCallId }
425
- }
426
- } : void 0;
427
- }
428
- case "tool.execution_complete": {
429
- const data = ToolCompleteSchema.parse(event.data);
430
- const images = preview ? data.result?.binaryResultsForLlm?.flatMap((value2) => {
431
- const parsed = z3.union([ImageSchema, ImageReferenceSchema]).safeParse(value2);
432
- return parsed.success ? [parsed.data] : [];
433
- }) ?? [] : [];
434
- const contents = preview ? data.result?.contents?.flatMap((value2) => {
435
- const parsed = ImageSchema.safeParse(value2);
436
- return parsed.success ? [parsed.data] : [];
437
- }) ?? [] : [];
438
- return {
439
- ...base,
440
- type: "tool.execution_complete",
441
- data: {
442
- toolCallId: data.toolCallId,
443
- success: data.success,
444
- ...data.result === void 0 ? {} : { result: {
445
- content: data.result.content ?? "",
446
- binaryResultsForLlm: images,
447
- contents
448
- } },
449
- ...data.toolDescription === void 0 ? {} : { toolDescription: data.toolDescription },
450
- ...data.parentToolCallId === void 0 ? {} : { parentToolCallId: data.parentToolCallId }
451
- }
452
- };
453
- }
454
- case "session.error": {
455
- const data = NoticeSchema.extend({ errorType: z3.string() }).parse(event.data);
456
- return { ...base, type: "session.error", data };
457
- }
458
- case "session.warning": {
459
- const data = NoticeSchema.extend({ warningType: z3.string() }).parse(event.data);
460
- return { ...base, type: "session.warning", data };
461
- }
462
- case "system.notification": {
463
- const { kind } = NotificationSchema.parse(event.data);
464
- if (kind.type !== "shell_completed") return void 0;
465
- const shell = ShellCompletedSchema.parse(kind);
466
- return {
467
- ...base,
468
- type: "system.notification",
469
- data: {
470
- content: "",
471
- kind: {
472
- type: "shell_completed",
473
- shellId: shell.shellId,
474
- ...shell.exitCode === void 0 ? {} : { exitCode: shell.exitCode }
475
- }
476
- }
477
- };
478
- }
479
- default:
480
- return void 0;
481
- }
482
- }
483
- async function openSessionEventLog(sessionId, environment = process.env, options = {}) {
484
- const directory = await realpath(resolveCopilotSessionDirectory(sessionId, environment));
485
- const expectedPath = resolve2(directory, "events.jsonl");
486
- if (options.allowMissingEventLog?.() === true) {
487
- try {
488
- await lstat(expectedPath);
489
- } catch (error) {
490
- if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
491
- await realpath(directory);
492
- if (options.allowMissingEventLog?.() !== true) throw error;
493
- return void 0;
494
- }
495
- }
496
- const path = await realpath(expectedPath);
497
- if (path !== expectedPath) throw new Error("Session event log must not be a symbolic link");
498
- return open(path, "r");
499
- }
500
- async function readSessionUpdatePage(sessionId, environment = process.env, resolveInputProvenance, options = {}) {
501
- const file = await openSessionEventLog(sessionId, environment, options);
502
- if (file === void 0) return { items: [], cursor: "", hasMore: false, cursorStatus: "ok" };
503
- try {
504
- const { size } = await file.stat();
505
- if (size === 0) {
506
- options.onEventLogRead?.();
507
- return { items: [], cursor: "", hasMore: false, cursorStatus: "ok" };
508
- }
509
- const start = Math.max(0, size - MAX_HEAD_BYTES);
510
- const buffer = Buffer.alloc(size - start);
511
- const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
512
- const text = buffer.subarray(0, bytesRead).toString("utf8");
513
- const first = start === 0 ? 0 : text.indexOf("\n") + 1;
514
- const end = text.lastIndexOf("\n");
515
- if (first === 0 && start > 0 || end < first) {
516
- throw new Error("Session event log has no complete records in its metadata window");
517
- }
518
- 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);
519
- const toolStarts = events.filter((event) => event.type === "tool.execution_start");
520
- const taskCompletionCallIdsWithStart = new Set(events.flatMap((event) => event.type === "tool.execution_start" && event.data.toolName === "task_complete" ? [event.data.toolCallId] : []));
521
- const rootTools = new Set(toolStarts.filter((event) => event.agentId === void 0 && event.data.parentToolCallId === void 0).map((event) => event.data.toolCallId));
522
- const childTools = new Set(toolStarts.filter((event) => event.agentId !== void 0 || event.data.parentToolCallId !== void 0).map((event) => event.data.toolCallId));
523
- const hasCompleteHistory = start === 0;
524
- const eventsForMetadata = events.filter((event) => {
525
- if (event.type === "tool.execution_start" && event.data.toolName !== "task_complete") return false;
526
- if (event.type !== "tool.execution_complete") {
527
- return true;
528
- }
529
- 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;
530
- if (taskCompletionCallIdsWithStart.has(event.data.toolCallId)) {
531
- return true;
532
- }
533
- if (!hasCompleteHistory) {
534
- return false;
535
- }
536
- return event.data.toolDescription?.name === "task_complete";
537
- });
538
- const normalizer = new ConversationNormalizer(void 0, void 0, resolveInputProvenance);
539
- normalizer.apply(eventsForMetadata);
540
- 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"));
541
- const latest = items.at(-1);
542
- const assistant = options.assistantPreview === true ? [...items].reverse().find(isContentfulAssistant) : void 0;
543
- const human = options.assistantPreview === true ? [...items].reverse().find((item) => item.kind === "human-message" && item.actor === "human") : void 0;
544
- const completion = [...items].reverse().find((item) => item.kind === "notice" && item.actor === "assistant" && item.severity === "success" && item.title === "Task completed");
545
- const page = SessionTimelinePageSchema.parse({
546
- 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" ? {
547
- ...item,
548
- content: item.id === assistant?.id || item.id === human?.id ? item.content.slice(0, 4096) : "",
549
- attachments: item.id === assistant?.id ? item.attachments ?? [] : []
550
- } : { ...item, content: item?.kind === "notice" && item.id === assistant?.id ? item.content.slice(0, 4096) : "" }),
551
- hasMore: start > 0,
552
- cursor: "",
553
- cursorStatus: "ok"
554
- });
555
- options.onEventLogRead?.();
556
- return page;
557
- } finally {
558
- await file.close();
559
- }
560
- }
561
-
562
- export {
563
- resumeWithCopilotSessionCompatibility,
564
- CopilotSessionCompatibilityClient,
565
- resolveCopilotSessionDirectory,
566
- openSessionEventLog,
567
- readSessionUpdatePage,
568
- AnalyticsEventSchema,
569
- AnalyticsCommandSchema,
570
- AnalyticsReplySchema,
571
- AnalyticsIndexResultSchema
572
- };
@@ -1,48 +0,0 @@
1
- import {
2
- SessionAssistantPreviewSchema,
3
- SessionUserPreviewSchema
4
- } from "./chunk-P2PH5KMV.js";
5
-
6
- // src/assistant-preview.ts
7
- function isContentfulAssistant(item) {
8
- return item.actor === "assistant" && (item.kind === "notice" && item.severity === "success" && item.title === "Task completed" && item.content.trim().length > 0 || item.kind === "assistant-message" && (item.content.trim().length > 0 || (item.attachments ?? []).some((attachment) => attachment.kind === "image")));
9
- }
10
- function userPreview(item) {
11
- if (item.kind !== "human-message" || item.actor !== "human") return void 0;
12
- return SessionUserPreviewSchema.parse({
13
- id: item.id,
14
- revision: item.revision,
15
- timestamp: item.timestamp,
16
- text: item.content.slice(0, 4096)
17
- });
18
- }
19
- function latestPreviewItems(items) {
20
- const latest = [...items].reverse();
21
- return [
22
- latest.find((item) => item.kind === "human-message" && item.actor === "human"),
23
- latest.find(isContentfulAssistant)
24
- ].filter((item) => item !== void 0);
25
- }
26
- function assistantPreview(item, referenceItem) {
27
- if (!isContentfulAssistant(item)) return void 0;
28
- const referenced = referenceItem(item);
29
- const attachments = referenced.kind === "assistant-message" ? (referenced.attachments ?? []).filter((attachment) => attachment.kind === "image" && attachment.imageRef === "sha256").slice(0, 4) : [];
30
- if (item.content.trim().length === 0 && attachments.length === 0) return void 0;
31
- return SessionAssistantPreviewSchema.parse({
32
- id: item.id,
33
- revision: item.revision,
34
- timestamp: item.timestamp,
35
- sourceEventIds: item.sourceEventIds.slice(-1),
36
- text: item.content.trim().slice(0, 4096),
37
- final: item.kind === "assistant-message" ? item.final : true,
38
- ...item.kind === "notice" ? { kind: "task-completion" } : {},
39
- attachments
40
- });
41
- }
42
-
43
- export {
44
- isContentfulAssistant,
45
- userPreview,
46
- latestPreviewItems,
47
- assistantPreview
48
- };