@agentknight/sdk 0.9.62 → 0.9.68

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 (28) hide show
  1. package/dist/chunks/{acp-adapter-MBYKOCA2.js → acp-adapter-RZX5SUB3.js} +4 -4
  2. package/dist/chunks/chunk-35OF2ZNS.js +275 -0
  3. package/dist/chunks/chunk-4XT65OSG.js +72 -0
  4. package/dist/chunks/{chunk-A4YCCQ3I.js → chunk-AWVC5NX4.js} +1 -1
  5. package/dist/chunks/chunk-B777YB6E.js +109 -0
  6. package/dist/chunks/{chunk-7CNBPLNE.js → chunk-CFQQOAQV.js} +5 -2
  7. package/dist/chunks/{chunk-P2PH5KMV.js → chunk-DWTXWVIA.js} +6 -0
  8. package/dist/chunks/{chunk-ZNQ2I5EF.js → chunk-EDYVCZIR.js} +11 -132
  9. package/dist/chunks/{chunk-3AMFPDE5.js → chunk-FY4XTWUF.js} +4 -4
  10. package/dist/chunks/{chunk-H4SHMWQ6.js → chunk-IXGVSREH.js} +1 -1
  11. package/dist/chunks/{chunk-SIFCCGXF.js → chunk-LCA2MWOQ.js} +2 -2
  12. package/dist/chunks/{chunk-ALUQLM54.js → chunk-MB3H6HEI.js} +2 -2
  13. package/dist/chunks/{chunk-CHKNC6PD.js → chunk-Q5OUZJCZ.js} +1 -1
  14. package/dist/chunks/{chunk-7OGTK7KB.js → chunk-UHRUQM4D.js} +1 -1
  15. package/dist/chunks/chunk-VIWTNPVC.js +66 -0
  16. package/dist/chunks/chunk-Y6NCJB55.js +302 -0
  17. package/dist/chunks/{claude-adapter-D3JWXMNX.js → claude-adapter-FQSQIYUY.js} +4 -4
  18. package/dist/chunks/{codex-adapter-655KHW7H.js → codex-adapter-TOXSRT2W.js} +4 -4
  19. package/dist/chunks/{copilot-adapter-EZUXHBE3.js → copilot-adapter-KUCX7XQW.js} +56 -148
  20. package/dist/chunks/{managed-agent-adapter-BOJNEJ75.js → managed-agent-adapter-LGBRXDGP.js} +33 -24
  21. package/dist/chunks/{pi-adapter-LAD5GOCP.js → pi-adapter-RXNZSE4F.js} +330 -53
  22. package/dist/configuration.js +5 -5
  23. package/dist/index.js +20 -31
  24. package/dist/runtime.js +2 -2
  25. package/dist/session-analytics-worker.js +7 -5
  26. package/package.json +1 -1
  27. package/dist/chunks/chunk-CM5LVXVL.js +0 -572
  28. package/dist/chunks/chunk-XPHAIOKN.js +0 -64
@@ -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,64 +0,0 @@
1
- // src/coding-agent-presentation.ts
2
- var copilotIcon = '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path fill="currentColor" d="M23.922 16.992c-.861 1.495-5.859 5.023-11.922 5.023-6.063 0-11.061-3.528-11.922-5.023A.641.641 0 0 1 0 16.736v-2.869a.841.841 0 0 1 .053-.22c.372-.935 1.347-2.292 2.605-2.656.167-.429.414-1.055.644-1.517a10.195 10.195 0 0 1-.052-1.086c0-1.331.282-2.499 1.132-3.368.397-.406.89-.717 1.474-.952 1.399-1.136 3.392-2.093 6.122-2.093 2.731 0 4.767.957 6.166 2.093.584.235 1.077.546 1.474.952.85.869 1.132 2.037 1.132 3.368 0 .368-.014.733-.052 1.086.23.462.477 1.088.644 1.517 1.258.364 2.233 1.721 2.605 2.656a.832.832 0 0 1 .053.22v2.869a.641.641 0 0 1-.078.256ZM12.172 11h-.344a4.323 4.323 0 0 1-.355.508C10.703 12.455 9.555 13 7.965 13c-1.725 0-2.989-.359-3.782-1.259a2.005 2.005 0 0 1-.085-.104L4 11.741v6.585c1.435.779 4.514 2.179 8 2.179 3.486 0 6.565-1.4 8-2.179v-6.585l-.098-.104s-.033.045-.085.104c-.793.9-2.057 1.259-3.782 1.259-1.59 0-2.738-.545-3.508-1.492a4.323 4.323 0 0 1-.355-.508h-.016.016Zm.641-2.935c.136 1.057.403 1.913.878 2.497.442.544 1.134.938 2.344.938 1.573 0 2.292-.337 2.657-.751.384-.435.558-1.15.558-2.361 0-1.14-.243-1.847-.705-2.319-.477-.488-1.319-.862-2.824-1.025-1.487-.161-2.192.138-2.533.529-.269.307-.437.808-.438 1.578v.021c0 .265.021.562.063.893Zm-1.626 0c.042-.331.063-.628.063-.894v-.02c-.001-.77-.169-1.271-.438-1.578-.341-.391-1.046-.69-2.533-.529-1.505.163-2.347.537-2.824 1.025-.462.472-.705 1.179-.705 2.319 0 1.211.175 1.926.558 2.361.365.414 1.084.751 2.657.751 1.21 0 1.902-.394 2.344-.938.475-.584.742-1.44.878-2.497Z"/><path fill="currentColor" d="M14.5 14.25a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Zm-5 0a1 1 0 0 1 1 1v2a1 1 0 0 1-2 0v-2a1 1 0 0 1 1-1Z"/></svg>';
3
- var piIcon = '<span class="agent-pi-icon" aria-hidden="true">\u03C0</span>';
4
- var genericIcon = '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><g fill="none" stroke="currentColor" stroke-width="2"><rect x="4" y="6" width="16" height="14" rx="3"/><path d="M12 2v4M8 15h8"/><path d="M8 10v2m8-2v2"/></g></svg>';
5
- var presentations = {
6
- copilot: { name: "GitHub Copilot", icon: copilotIcon },
7
- pi: { name: "PI", icon: piIcon },
8
- codex: { name: "Codex", icon: genericIcon },
9
- claude: { name: "Claude Code", icon: genericIcon },
10
- acp: { name: "ACP", icon: genericIcon }
11
- };
12
- var fallback = { name: "Agent", icon: genericIcon };
13
- function codingAgentPresentation(agentId) {
14
- return Object.hasOwn(presentations, agentId) ? presentations[agentId] : fallback;
15
- }
16
-
17
- // src/device-identity.ts
18
- import { z } from "zod";
19
- var DeviceIdentitySchema = z.object({
20
- schemaVersion: z.literal(2),
21
- machineId: z.uuid(),
22
- stableDeviceId: z.uuid(),
23
- machineName: z.string().trim().min(1).max(120),
24
- createdAt: z.iso.datetime({ offset: true })
25
- });
26
-
27
- // src/relay-authorization.ts
28
- async function relayRequestToken(config) {
29
- if (config.relayAuthorization === void 0) return config.relayToken;
30
- const credential = await config.relayAuthorization.getAccessToken();
31
- if (!Number.isSafeInteger(credential.expiresAt) || credential.expiresAt <= Date.now() || !/^[\x21-\x7e]{1,32768}$/u.test(credential.token)) {
32
- throw new Error("Relay authorization expired or is invalid. Sign in again.");
33
- }
34
- return credential.token;
35
- }
36
-
37
- export {
38
- codingAgentPresentation,
39
- DeviceIdentitySchema,
40
- relayRequestToken
41
- };
42
- /*!
43
- * Copilot artwork: https://github.com/primer/octicons
44
- * MIT License
45
- * Copyright (c) 2026 GitHub Inc.
46
- *
47
- * Permission is hereby granted, free of charge, to any person obtaining a copy
48
- * of this software and associated documentation files (the "Software"), to deal
49
- * in the Software without restriction, including without limitation the rights
50
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
51
- * copies of the Software, and to permit persons to whom the Software is
52
- * furnished to do so, subject to the following conditions:
53
- *
54
- * The above copyright notice and this permission notice shall be included in all
55
- * copies or substantial portions of the Software.
56
- *
57
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
58
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
59
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
60
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
61
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
62
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
63
- * SOFTWARE.
64
- */