@agentknight/sdk 0.9.57 → 0.9.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. package/dist/chunks/{acp-adapter-WYDK3PLS.js → acp-adapter-OGD5QSNI.js} +4 -4
  2. package/dist/chunks/{chunk-WPVH7HKC.js → chunk-2MERNOK6.js} +1 -1
  3. package/dist/chunks/{chunk-7ZYBES47.js → chunk-3OIHMMDF.js} +1 -1
  4. package/dist/chunks/{chunk-3LEPYV7Y.js → chunk-5DVJ7Y5W.js} +2 -2
  5. package/dist/chunks/{chunk-USI66MEF.js → chunk-AREU4R62.js} +3 -2
  6. package/dist/chunks/{chunk-ZLKFFKAX.js → chunk-DP5KVGWF.js} +4 -3
  7. package/dist/chunks/{chunk-DAKDVZ7X.js → chunk-FDUJP3WA.js} +2 -2
  8. package/dist/chunks/{chunk-KBI5IWPR.js → chunk-LO4ZRE77.js} +747 -513
  9. package/dist/chunks/{chunk-OOCAIULD.js → chunk-LWJNDBIM.js} +431 -21
  10. package/dist/chunks/{chunk-IPJWNGNK.js → chunk-NDEJOXSX.js} +1 -1
  11. package/dist/chunks/{chunk-EDZPP6SJ.js → chunk-X3ZG6WMN.js} +2 -3
  12. package/dist/chunks/{chunk-LT5ULDVT.js → chunk-ZDKBJFA2.js} +1 -1
  13. package/dist/chunks/{claude-adapter-GCH36EZ6.js → claude-adapter-DGZBZSWJ.js} +209 -59
  14. package/dist/chunks/{codex-adapter-CXD4SVCE.js → codex-adapter-2W7RRER3.js} +4 -4
  15. package/dist/chunks/{copilot-adapter-SYFGOAGE.js → copilot-adapter-ZEHU6CFQ.js} +109 -14
  16. package/dist/chunks/{managed-agent-adapter-ODCNYYO6.js → managed-agent-adapter-CGJPJZ2Z.js} +20 -6
  17. package/dist/chunks/{pi-adapter-XLY46UDL.js → pi-adapter-WOVSWBGG.js} +4 -4
  18. package/dist/configuration.js +4 -4
  19. package/dist/index.d.ts +126 -1
  20. package/dist/index.js +1447 -562
  21. package/dist/runtime.js +2 -2
  22. package/dist/session-analytics-worker.js +162 -51
  23. package/package.json +1 -1
@@ -3,26 +3,26 @@ import {
3
3
  } from "./chunk-T6226JFS.js";
4
4
  import {
5
5
  latestPreviewItems
6
- } from "./chunk-IPJWNGNK.js";
6
+ } from "./chunk-NDEJOXSX.js";
7
7
  import {
8
8
  UnsupportedAgentOperationError,
9
9
  validateSessionName
10
- } from "./chunk-3LEPYV7Y.js";
11
- import "./chunk-7ZYBES47.js";
10
+ } from "./chunk-5DVJ7Y5W.js";
11
+ import "./chunk-3OIHMMDF.js";
12
12
  import {
13
13
  ConversationItemSchema,
14
14
  InteractionRequestSchema,
15
15
  InteractionResponseSchema,
16
16
  SESSION_TIMELINE_PAGE_SIZE,
17
17
  SessionSummarySchema
18
- } from "./chunk-KBI5IWPR.js";
18
+ } from "./chunk-LO4ZRE77.js";
19
19
 
20
20
  // src/claude-adapter.ts
21
21
  import { randomUUID as randomUUID2 } from "node:crypto";
22
- import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
23
- import { homedir } from "node:os";
24
- import { isAbsolute, join, resolve } from "node:path";
25
- import { z as z4 } from "zod";
22
+ import { mkdir, readFile as readFile2, readdir, rename, rm, writeFile } from "node:fs/promises";
23
+ import { homedir as homedir2 } from "node:os";
24
+ import { isAbsolute as isAbsolute2, join as join2, resolve } from "node:path";
25
+ import { z as z5 } from "zod";
26
26
 
27
27
  // src/adapters/claude/input.ts
28
28
  var ClaudeInput = class {
@@ -473,39 +473,180 @@ var ClaudeProcess = class {
473
473
  }
474
474
  };
475
475
 
476
+ // src/adapters/claude/runtime.ts
477
+ import { execFile } from "node:child_process";
478
+ import { constants } from "node:fs";
479
+ import { access, open, readFile, realpath, stat } from "node:fs/promises";
480
+ import { createRequire } from "node:module";
481
+ import { homedir } from "node:os";
482
+ import { delimiter, dirname, extname, isAbsolute, join, relative, sep } from "node:path";
483
+ import { z as z4 } from "zod";
484
+ var packageName = "@anthropic-ai/claude-agent-sdk";
485
+ var require2 = createRequire(import.meta.url);
486
+ var metadataSchema = z4.object({ claudeCodeVersion: z4.string().regex(/^\d+\.\d+\.\d+$/) });
487
+ var configurationHint = "Set AGENTKNIGHT_CLAUDE_COMMAND (SDK: command / managed claudeCommand) to an absolute native executable.";
488
+ function missing(error) {
489
+ return error instanceof Error && "code" in error && ["ENOENT", "ENOTDIR", "MODULE_NOT_FOUND"].includes(String(error.code));
490
+ }
491
+ function absolute(path) {
492
+ return !path.includes("\0") && isAbsolute(path) && (process.platform !== "win32" || /^(?:[a-z]:[\\/]|\\\\[^\\/]+[\\/][^\\/]+[\\/])/i.test(path));
493
+ }
494
+ async function executable(path) {
495
+ try {
496
+ await access(path, process.platform === "win32" ? constants.F_OK : constants.X_OK);
497
+ return (await stat(path)).isFile();
498
+ } catch (error) {
499
+ if (missing(error)) return false;
500
+ throw error;
501
+ }
502
+ }
503
+ async function nativeExecutable(path) {
504
+ if (process.platform === "win32" && extname(path).toLowerCase() !== ".exe") return false;
505
+ if (!await executable(path)) return false;
506
+ const file = await open(path, "r");
507
+ try {
508
+ const header = Buffer.alloc(4);
509
+ const { bytesRead } = await file.read(header, 0, header.length, 0);
510
+ if (bytesRead !== 4) return false;
511
+ if (process.platform === "win32") return header.subarray(0, 2).toString() === "MZ";
512
+ return [
513
+ "7f454c46",
514
+ "feedface",
515
+ "cefaedfe",
516
+ "feedfacf",
517
+ "cffaedfe",
518
+ "cafebabe",
519
+ "bebafeca",
520
+ "cafebabf",
521
+ "bfbafeca"
522
+ ].includes(header.toString("hex"));
523
+ } finally {
524
+ await file.close();
525
+ }
526
+ }
527
+ async function bundledExecutable(entry) {
528
+ const sdkRequire = createRequire(entry);
529
+ const platform = process.platform;
530
+ let platforms = [`${platform}-${process.arch}`];
531
+ if (platform === "linux") {
532
+ const report = process.report?.getReport();
533
+ const glibc = z4.object({ header: z4.object({ glibcVersionRuntime: z4.string().optional() }) }).safeParse(report);
534
+ const base = `linux-${process.arch}`;
535
+ platforms = glibc.success && glibc.data.header.glibcVersionRuntime !== void 0 ? [base, `${base}-musl`] : [`${base}-musl`, base];
536
+ } else if (platform === "android") {
537
+ platforms = [`linux-${process.arch}-android`];
538
+ }
539
+ for (const target of platforms) {
540
+ try {
541
+ if (await executable(sdkRequire.resolve(`${packageName}-${target}/claude${platform === "win32" ? ".exe" : ""}`))) return true;
542
+ } catch (error) {
543
+ if (!missing(error)) throw error;
544
+ }
545
+ }
546
+ return false;
547
+ }
548
+ function inside(directory, path) {
549
+ const child = relative(directory, path);
550
+ return child === "" || !isAbsolute(child) && child !== ".." && !child.startsWith(`..${sep}`);
551
+ }
552
+ async function findExternal(environment) {
553
+ const name = process.platform === "win32" ? "claude.exe" : "claude";
554
+ try {
555
+ const installed = await realpath(join(homedir(), ".local", "bin", name));
556
+ if (await nativeExecutable(installed)) return installed;
557
+ } catch (error) {
558
+ if (!missing(error)) throw error;
559
+ }
560
+ const cwd = await realpath(process.cwd());
561
+ for (const directory of (environment.PATH ?? "").split(delimiter)) {
562
+ if (!absolute(directory) || inside(cwd, directory)) continue;
563
+ try {
564
+ const path = await realpath(join(directory, name));
565
+ if (!inside(cwd, path) && await nativeExecutable(path)) return path;
566
+ } catch (error) {
567
+ if (!missing(error)) throw error;
568
+ }
569
+ }
570
+ return void 0;
571
+ }
572
+ async function version(path, environment) {
573
+ return new Promise((resolve2, reject) => {
574
+ const child = execFile(path, ["--version"], {
575
+ env: environment,
576
+ shell: false,
577
+ windowsHide: true,
578
+ timeout: 5e3,
579
+ maxBuffer: 4096,
580
+ killSignal: "SIGKILL"
581
+ }, (error, stdout) => {
582
+ if (error) reject(new Error(`Claude --version failed. ${configurationHint}`, { cause: error }));
583
+ else resolve2(stdout.trim());
584
+ });
585
+ child.stdin?.end();
586
+ });
587
+ }
588
+ async function resolveClaudeExecutable(command, environment = process.env) {
589
+ let entry;
590
+ let expected;
591
+ try {
592
+ entry = require2.resolve(packageName);
593
+ const raw = JSON.parse(await readFile(join(dirname(entry), "package.json"), "utf8"));
594
+ expected = metadataSchema.parse(raw).claudeCodeVersion;
595
+ } catch (error) {
596
+ throw new Error("Claude SDK installation is missing or invalid. Reinstall AgentKnight with optional dependencies enabled.", { cause: error });
597
+ }
598
+ if (command === void 0 && await bundledExecutable(entry)) return void 0;
599
+ let path;
600
+ if (command !== void 0) {
601
+ if (!absolute(command)) throw new Error(configurationHint);
602
+ path = await realpath(command).catch((error) => {
603
+ throw new Error(`Claude executable is unavailable. ${configurationHint}`, { cause: error });
604
+ });
605
+ if (!await nativeExecutable(path)) throw new Error(`Claude requires a native executable, not a script or shell shim. ${configurationHint}`);
606
+ } else {
607
+ path = await findExternal(environment);
608
+ }
609
+ if (path === void 0) throw new Error(`Claude Code ${expected} is not installed. ${configurationHint}`);
610
+ const actual = await version(path, environment);
611
+ if (actual !== `${expected} (Claude Code)`) {
612
+ throw new Error(`This SDK requires Claude Code ${expected}; the local CLI is incompatible or unrecognized. ${configurationHint}`);
613
+ }
614
+ return path;
615
+ }
616
+
476
617
  // src/claude-adapter.ts
477
618
  var CLAUDE_DEFAULT_MODEL_ID = "claude:agent-default";
478
- var UuidSchema = z4.custom((value) => z4.uuid().safeParse(value).success);
479
- var ReceiptSchema = z4.object({
619
+ var UuidSchema = z5.custom((value) => z5.uuid().safeParse(value).success);
620
+ var ReceiptSchema = z5.object({
480
621
  id: UuidSchema,
481
- prompt: z4.string().min(1).max(1e5),
482
- mode: z4.enum(["enqueue", "immediate"]),
483
- submittedAt: z4.iso.datetime(),
484
- operationId: z4.string().min(1).max(256).optional(),
485
- state: z4.enum(["queued", "submitted", "confirmed", "completed", "cancelled", "failed"])
622
+ prompt: z5.string().min(1).max(1e5),
623
+ mode: z5.enum(["enqueue", "immediate"]),
624
+ submittedAt: z5.iso.datetime(),
625
+ operationId: z5.string().min(1).max(256).optional(),
626
+ state: z5.enum(["queued", "submitted", "confirmed", "completed", "cancelled", "failed"])
486
627
  });
487
- var StoredSchema = z4.object({
488
- version: z4.literal(1),
628
+ var StoredSchema = z5.object({
629
+ version: z5.literal(1),
489
630
  summary: SessionSummarySchema,
490
631
  nativeId: UuidSchema.optional(),
491
- modelId: z4.string().min(1).max(256),
492
- nativeDirectory: z4.string().min(1).optional(),
493
- items: z4.array(ConversationItemSchema),
494
- receipts: z4.array(ReceiptSchema),
495
- unsafe: z4.boolean()
632
+ modelId: z5.string().min(1).max(256),
633
+ nativeDirectory: z5.string().min(1).optional(),
634
+ items: z5.array(ConversationItemSchema),
635
+ receipts: z5.array(ReceiptSchema),
636
+ unsafe: z5.boolean()
496
637
  }).refine((stored) => stored.nativeDirectory === void 0 || stored.nativeId !== void 0 && stored.summary.sessionId === `claude:native:${stored.nativeId}`, {
497
638
  message: "Invalid Claude native session identity"
498
639
  });
499
- var MessageSchema = z4.object({
500
- type: z4.string(),
501
- subtype: z4.string().optional(),
502
- uuid: z4.string().optional(),
503
- session_id: z4.string().optional(),
504
- state: z4.string().optional(),
505
- user_message_uuid: z4.string().optional(),
506
- user_message_uuids: z4.array(z4.string()).optional(),
507
- parent_tool_use_id: z4.string().nullable().optional(),
508
- is_error: z4.boolean().optional()
640
+ var MessageSchema = z5.object({
641
+ type: z5.string(),
642
+ subtype: z5.string().optional(),
643
+ uuid: z5.string().optional(),
644
+ session_id: z5.string().optional(),
645
+ state: z5.string().optional(),
646
+ user_message_uuid: z5.string().optional(),
647
+ user_message_uuids: z5.array(z5.string()).optional(),
648
+ parent_tool_use_id: z5.string().nullable().optional(),
649
+ is_error: z5.boolean().optional()
509
650
  }).passthrough();
510
651
  var ClaudeCodingAgentAdapter = class {
511
652
  agentId = "claude";
@@ -541,7 +682,7 @@ var ClaudeCodingAgentAdapter = class {
541
682
  if (options.nativeSessionOwner !== void 0) {
542
683
  SessionSummarySchema.pick({ userId: true, machineId: true }).parse(options.nativeSessionOwner);
543
684
  }
544
- this.#directory = join(resolve(options.dataDirectory), "claude");
685
+ this.#directory = join2(resolve(options.dataDirectory), "claude");
545
686
  this.#interactions = new ClaudeInteractions(() => this.#callbacks, timeout);
546
687
  }
547
688
  setSessionCallbacks(callbacks) {
@@ -554,10 +695,10 @@ var ClaudeCodingAgentAdapter = class {
554
695
  }
555
696
  async #start() {
556
697
  await mkdir(this.#directory, { recursive: true, mode: 448 });
557
- await mkdir(join(this.#directory, "native"), { recursive: true, mode: 448 });
698
+ await mkdir(join2(this.#directory, "native"), { recursive: true, mode: 448 });
558
699
  for (const file of await readdir(this.#directory)) {
559
700
  if (!/^[a-f0-9]{64}\.json$/.test(file)) continue;
560
- const raw = JSON.parse(await readFile(join(this.#directory, file), "utf8"));
701
+ const raw = JSON.parse(await readFile2(join2(this.#directory, file), "utf8"));
561
702
  const stored = StoredSchema.parse(raw);
562
703
  if (!stored.summary.sessionId.startsWith("claude:") || `${identity(stored.summary.sessionId)}.json` !== file) {
563
704
  throw new Error("Invalid Claude session ownership record");
@@ -588,6 +729,7 @@ var ClaudeCodingAgentAdapter = class {
588
729
  active: void 0,
589
730
  input: void 0,
590
731
  query: void 0,
732
+ command: void 0,
591
733
  controller: void 0,
592
734
  work: void 0,
593
735
  dispatch: void 0,
@@ -635,13 +777,13 @@ var ClaudeCodingAgentAdapter = class {
635
777
  }
636
778
  async #scanNative(owner) {
637
779
  const sdk = await this.#nativeSessions();
638
- const sessions = z4.array(z4.object({
780
+ const sessions = z5.array(z5.object({
639
781
  sessionId: UuidSchema,
640
- summary: z4.string(),
641
- customTitle: z4.string().optional(),
642
- lastModified: z4.number(),
643
- createdAt: z4.number().optional(),
644
- cwd: z4.string().optional()
782
+ summary: z5.string(),
783
+ customTitle: z5.string().optional(),
784
+ lastModified: z5.number(),
785
+ createdAt: z5.number().optional(),
786
+ cwd: z5.string().optional()
645
787
  })).parse(await sdk.listSessions({ includeProgrammatic: true }));
646
788
  this.#ready();
647
789
  const next = /* @__PURE__ */ new Map();
@@ -674,7 +816,7 @@ var ClaudeCodingAgentAdapter = class {
674
816
  version: 1,
675
817
  summary,
676
818
  nativeId: native.sessionId,
677
- nativeDirectory: resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude")),
819
+ nativeDirectory: resolve(env.CLAUDE_CONFIG_DIR || join2(homedir2(), ".claude")),
678
820
  modelId: CLAUDE_DEFAULT_MODEL_ID,
679
821
  items: [],
680
822
  receipts: [],
@@ -694,12 +836,13 @@ var ClaudeCodingAgentAdapter = class {
694
836
  if (session.work || session.operations || session.cancellations || session.aborting || session.stored.unsafe || session.error) continue;
695
837
  this.#sessions.delete(id);
696
838
  this.#retiredSessions.add(id);
697
- await rm(join(this.#directory, `${identity(id)}.json`));
839
+ await rm(join2(this.#directory, `${identity(id)}.json`));
698
840
  }
699
841
  }
700
842
  }
701
843
  async listModels() {
702
844
  this.#ready();
845
+ await resolveClaudeExecutable(this.#options.command, this.#options.env);
703
846
  return [{ id: CLAUDE_DEFAULT_MODEL_ID, name: "Claude agent default", isDefault: true }];
704
847
  }
705
848
  getSessionCapabilities() {
@@ -754,7 +897,9 @@ var ClaudeCodingAgentAdapter = class {
754
897
  async createSession(options) {
755
898
  this.#ready();
756
899
  this.#validate(options);
757
- if (!isAbsolute(options.workingDirectory)) throw new Error("Claude working directory must be absolute");
900
+ if (!isAbsolute2(options.workingDirectory)) throw new Error("Claude working directory must be absolute");
901
+ await resolveClaudeExecutable(this.#options.command, this.#options.env);
902
+ this.#ready();
758
903
  const now = (/* @__PURE__ */ new Date()).toISOString();
759
904
  const summary = SessionSummarySchema.parse({
760
905
  sessionId: `claude:${randomUUID2()}`,
@@ -829,14 +974,14 @@ var ClaudeCodingAgentAdapter = class {
829
974
  const sdk = await this.#nativeSessions();
830
975
  const nativeId = UuidSchema.parse(session.stored.nativeId);
831
976
  const raw = await sdk.getSessionMessages(nativeId, this.#nativeReadOptions(session));
832
- const messages = z4.array(z4.object({
833
- type: z4.enum(["user", "assistant", "system"]),
834
- uuid: z4.string(),
977
+ const messages = z5.array(z5.object({
978
+ type: z5.enum(["user", "assistant", "system"]),
979
+ uuid: z5.string(),
835
980
  session_id: UuidSchema,
836
- message: z4.unknown(),
837
- timestamp: z4.iso.datetime().optional(),
838
- parent_tool_use_id: z4.string().nullable(),
839
- parent_agent_id: z4.string().nullable()
981
+ message: z5.unknown(),
982
+ timestamp: z5.iso.datetime().optional(),
983
+ parent_tool_use_id: z5.string().nullable(),
984
+ parent_agent_id: z5.string().nullable()
840
985
  }).passthrough()).parse(raw);
841
986
  this.#known(session.stored.summary.sessionId);
842
987
  const items = [];
@@ -846,8 +991,8 @@ var ClaudeCodingAgentAdapter = class {
846
991
  if (message.session_id !== nativeId) throw new Error("Claude returned history for another native session");
847
992
  if (message.parent_agent_id || message.parent_tool_use_id) continue;
848
993
  if (message.type === "user") {
849
- const body = z4.object({ content: z4.unknown() }).parse(message.message);
850
- if (typeof body.content === "string" || Array.isArray(body.content) && body.content.some((block) => z4.object({ type: z4.literal("text") }).safeParse(block).success)) turnId = message.uuid;
994
+ const body = z5.object({ content: z5.unknown() }).parse(message.message);
995
+ if (typeof body.content === "string" || Array.isArray(body.content) && body.content.some((block) => z5.object({ type: z5.literal("text") }).safeParse(block).success)) turnId = message.uuid;
851
996
  }
852
997
  timeline.project({ ...message, timestamp: message.timestamp ?? session.stored.summary.createdAt }, turnId);
853
998
  }
@@ -882,7 +1027,7 @@ var ClaudeCodingAgentAdapter = class {
882
1027
  if (session.stored.nativeDirectory) {
883
1028
  this.#environment(session);
884
1029
  const directory = session.stored.summary.workingDirectory;
885
- if (!directory || !isAbsolute(directory)) throw new Error("Claude native session working directory is unavailable; open it in the CLI first");
1030
+ if (!directory || !isAbsolute2(directory)) throw new Error("Claude native session working directory is unavailable; open it in the CLI first");
886
1031
  }
887
1032
  const duplicate = operationId === void 0 ? void 0 : session.stored.receipts.find((entry) => entry.operationId === operationId);
888
1033
  if (duplicate) {
@@ -890,6 +1035,11 @@ var ClaudeCodingAgentAdapter = class {
890
1035
  if (duplicate.state === "failed" || duplicate.state === "cancelled") throw new Error("Claude operation already ended; it was not retried");
891
1036
  return { messageId: duplicate.id, deliveryState: duplicate.state === "queued" ? "queued" : "processing", submittedAt: duplicate.submittedAt };
892
1037
  }
1038
+ if (!session.work || mode === "immediate" && session.busy) {
1039
+ session.command = await resolveClaudeExecutable(this.#options.command, this.#options.env);
1040
+ this.#ready();
1041
+ if (session.epoch !== epoch || session.aborting) throw new Error("Claude prompt cancelled before acceptance");
1042
+ }
893
1043
  if (mode === "immediate" && session.busy) {
894
1044
  await this.#cancel(session, false);
895
1045
  if (session.aborting || this.#stopping || session.epoch !== epoch + 1) throw new Error("Claude prompt cancelled before acceptance");
@@ -954,7 +1104,7 @@ var ClaudeCodingAgentAdapter = class {
954
1104
  #environment(session) {
955
1105
  return prepareClaudeEnvironment(
956
1106
  this.#options.env ?? process.env,
957
- session.stored.nativeDirectory ?? join(this.#directory, "native")
1107
+ session.stored.nativeDirectory ?? join2(this.#directory, "native")
958
1108
  );
959
1109
  }
960
1110
  async #consume(session, epoch) {
@@ -981,7 +1131,7 @@ var ClaudeCodingAgentAdapter = class {
981
1131
  abortController: controller,
982
1132
  spawnClaudeCodeProcess: ownedProcess.spawn,
983
1133
  ...session.stored.nativeId ? { resume: session.stored.nativeId } : {},
984
- ...this.#options.command ? { pathToClaudeCodeExecutable: this.#options.command } : {},
1134
+ ...session.command === void 0 ? {} : { pathToClaudeCodeExecutable: session.command },
985
1135
  canUseTool: (tool, args, context) => epoch !== session.epoch || controller.signal.aborted ? Promise.resolve({ behavior: "deny", message: "Stale Claude query" }) : this.#interactions.request(id, tool, args, context.signal)
986
1136
  }
987
1137
  });
@@ -1008,7 +1158,7 @@ var ClaudeCodingAgentAdapter = class {
1008
1158
  for (const receiptId of confirmations) this.#confirm(session, receiptId);
1009
1159
  session.timeline.project(raw, turnId);
1010
1160
  if (message.type === "result") {
1011
- const isError = z4.boolean().parse(message.is_error);
1161
+ const isError = z5.boolean().parse(message.is_error);
1012
1162
  session.resultSeen = true;
1013
1163
  if (session.active) session.active.state = isError ? "failed" : "completed";
1014
1164
  if (isError) {
@@ -1017,7 +1167,7 @@ var ClaudeCodingAgentAdapter = class {
1017
1167
  }
1018
1168
  }
1019
1169
  if (message.type === "system" && message.subtype === "background_tasks_changed") {
1020
- const background = z4.object({ tasks: z4.array(z4.unknown()) }).safeParse(message);
1170
+ const background = z5.object({ tasks: z5.array(z5.unknown()) }).safeParse(message);
1021
1171
  session.background = !background.success || background.data.tasks.length > 0;
1022
1172
  }
1023
1173
  if (message.type === "system" && message.subtype === "session_state_changed" && (message.state === "running" || message.state === "requires_action")) {
@@ -1190,7 +1340,7 @@ var ClaudeCodingAgentAdapter = class {
1190
1340
  #save(session) {
1191
1341
  if (!this.#sessions.has(session.stored.summary.sessionId)) return Promise.resolve();
1192
1342
  const data = JSON.stringify(StoredSchema.parse(session.stored));
1193
- const file = join(this.#directory, `${identity(session.stored.summary.sessionId)}.json`);
1343
+ const file = join2(this.#directory, `${identity(session.stored.summary.sessionId)}.json`);
1194
1344
  session.saves++;
1195
1345
  const work = session.saving.then(async () => {
1196
1346
  const temporary = `${file}.${randomUUID2()}.tmp`;
@@ -1,16 +1,16 @@
1
1
  import {
2
2
  latestPreviewItems
3
- } from "./chunk-IPJWNGNK.js";
3
+ } from "./chunk-NDEJOXSX.js";
4
4
  import {
5
5
  UnsupportedAgentOperationError
6
- } from "./chunk-3LEPYV7Y.js";
7
- import "./chunk-7ZYBES47.js";
6
+ } from "./chunk-5DVJ7Y5W.js";
7
+ import "./chunk-3OIHMMDF.js";
8
8
  import {
9
9
  ConversationItemSchema,
10
10
  InteractionRequestSchema,
11
11
  SESSION_TIMELINE_PAGE_SIZE,
12
12
  SessionSummarySchema
13
- } from "./chunk-KBI5IWPR.js";
13
+ } from "./chunk-LO4ZRE77.js";
14
14
 
15
15
  // src/codex-adapter.ts
16
16
  import { randomUUID } from "node:crypto";
@@ -3,6 +3,7 @@ import {
3
3
  NotGitDirectoryError,
4
4
  PromptPreparationError,
5
5
  SESSION_PROJECT_IDENTITY_CONCURRENCY,
6
+ SessionDirectoryLister,
6
7
  SessionProjectIdentityError,
7
8
  SessionProjectIdentityReader,
8
9
  SessionRuntimeRegistry,
@@ -16,7 +17,7 @@ import {
16
17
  recordTimelineSyncDiagnostic,
17
18
  resolveGitProjectIdentity,
18
19
  sanitizeGitRemoteUrl
19
- } from "./chunk-OOCAIULD.js";
20
+ } from "./chunk-LWJNDBIM.js";
20
21
  import "./chunk-IJPJQF7S.js";
21
22
  import {
22
23
  AnalyticsIndexResultSchema,
@@ -26,29 +27,29 @@ import {
26
27
  readSessionUpdatePage,
27
28
  resolveCopilotSessionDirectory,
28
29
  resumeWithCopilotSessionCompatibility
29
- } from "./chunk-ZLKFFKAX.js";
30
+ } from "./chunk-DP5KVGWF.js";
30
31
  import {
31
32
  ConversationNormalizer,
32
33
  isDisplayableHumanMessage
33
- } from "./chunk-LT5ULDVT.js";
34
+ } from "./chunk-ZDKBJFA2.js";
34
35
  import {
35
36
  assertMainSessionId,
36
37
  isResearchSessionId
37
- } from "./chunk-WPVH7HKC.js";
38
+ } from "./chunk-2MERNOK6.js";
38
39
  import {
39
40
  GroupChatError,
40
41
  GroupChatMessageSchema,
41
42
  GroupChatRuntime
42
- } from "./chunk-EDZPP6SJ.js";
43
- import "./chunk-IPJWNGNK.js";
43
+ } from "./chunk-X3ZG6WMN.js";
44
+ import "./chunk-NDEJOXSX.js";
44
45
  import {
45
46
  AgentSessionRenameError,
46
47
  TimelinePageBudgetError,
47
48
  validateSessionName
48
- } from "./chunk-3LEPYV7Y.js";
49
+ } from "./chunk-5DVJ7Y5W.js";
49
50
  import {
50
51
  SessionOperationError
51
- } from "./chunk-7ZYBES47.js";
52
+ } from "./chunk-3OIHMMDF.js";
52
53
  import {
53
54
  ConversationItemSchema,
54
55
  CopilotModelOptionSchema,
@@ -69,14 +70,16 @@ import {
69
70
  WorkbenchScheduleDraftSchema,
70
71
  WorkbenchScheduleEntrySchema,
71
72
  WorkbenchScheduleProposalSchema,
72
- WorkbenchScheduleSnapshotSchema
73
- } from "./chunk-KBI5IWPR.js";
73
+ WorkbenchScheduleSnapshotSchema,
74
+ WorkbenchTelemetrySchema
75
+ } from "./chunk-LO4ZRE77.js";
74
76
 
75
77
  // src/copilot-adapter.ts
76
78
  import { createHash as createHash4, randomUUID as randomUUID6 } from "node:crypto";
79
+ import { existsSync, statSync } from "node:fs";
77
80
  import { readFile as readFile2, realpath as realpath2, stat } from "node:fs/promises";
78
81
  import { createRequire } from "node:module";
79
- import { basename as basename2, extname, isAbsolute, relative, resolve } from "node:path";
82
+ import { basename as basename2, dirname as dirname2, extname, isAbsolute, join as join3, relative, resolve } from "node:path";
80
83
 
81
84
  // src/adapters/copilot/runtime/client-runtime.ts
82
85
  var CopilotClientRuntime = class {
@@ -2313,7 +2316,7 @@ var SessionAnalytics = class {
2313
2316
  }
2314
2317
  observe(sessionId, event) {
2315
2318
  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;
2319
+ if (event.type !== "assistant.usage" && event.type !== "user.message" && event.type !== "assistant.message" && event.type !== "session.skills_loaded" && event.type !== "session.usage_info" && event.type !== "session.compaction_complete") return;
2317
2320
  if (event.agentId !== void 0 && event.type !== "assistant.usage") return;
2318
2321
  let data;
2319
2322
  let bytes = 1024 + (sessionId.length + event.id.length + event.timestamp.length + (event.agentId?.length ?? 0)) * 2;
@@ -2341,6 +2344,27 @@ var SessionAnalytics = class {
2341
2344
  }));
2342
2345
  data = { skills };
2343
2346
  bytes += skills.reduce((size, skill) => size + (skill.name.length + (skill.description?.length ?? 0) + skill.source.length + (skill.commandName?.length ?? 0)) * 2 + 256, 0);
2347
+ } else if (event.type === "session.usage_info") {
2348
+ data = {
2349
+ currentTokens: event.data.currentTokens,
2350
+ tokenLimit: event.data.tokenLimit,
2351
+ messagesLength: event.data.messagesLength
2352
+ };
2353
+ } else if (event.type === "session.compaction_complete") {
2354
+ data = {
2355
+ success: event.data.success,
2356
+ preCompactionTokens: event.data.preCompactionTokens,
2357
+ postCompactionTokens: event.data.postCompactionTokens,
2358
+ tokensRemoved: event.data.tokensRemoved,
2359
+ messagesRemoved: event.data.messagesRemoved,
2360
+ trigger: event.data.trigger,
2361
+ tokenAccountingBasis: event.data.tokenAccountingBasis,
2362
+ compactionTokensUsed: event.data.compactionTokensUsed === void 0 ? void 0 : {
2363
+ duration: event.data.compactionTokensUsed.duration,
2364
+ inputTokens: event.data.compactionTokensUsed.inputTokens,
2365
+ outputTokens: event.data.compactionTokensUsed.outputTokens
2366
+ }
2367
+ };
2344
2368
  } else {
2345
2369
  const accounting = event.data.accounting;
2346
2370
  data = {
@@ -2349,6 +2373,10 @@ var SessionAnalytics = class {
2349
2373
  outputTokens: event.data.outputTokens,
2350
2374
  cacheReadTokens: event.data.cacheReadTokens,
2351
2375
  apiCallId: event.data.apiCallId,
2376
+ requestBodyBytes: event.data.requestBodyBytes,
2377
+ requestBodyWireBytes: event.data.requestBodyWireBytes,
2378
+ duration: event.data.duration,
2379
+ outputTtftMs: event.data.outputTtftMs,
2352
2380
  accounting: accounting === void 0 ? void 0 : { sourceSessionId: accounting.sourceSessionId, usageId: accounting.usageId }
2353
2381
  };
2354
2382
  bytes += (event.data.model.length + (event.data.apiCallId?.length ?? 0) + (accounting?.sourceSessionId.length ?? 0) + (accounting?.usageId.length ?? 0)) * 2;
@@ -2498,6 +2526,19 @@ var SessionAnalytics = class {
2498
2526
  });
2499
2527
  return SessionAnalyticsResultSchema.parse(result);
2500
2528
  }
2529
+ async telemetry(sessionId, allowMissingEventLog = false) {
2530
+ if (this.#removed.has(sessionId)) throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Session analytics were deleted");
2531
+ await this.flush();
2532
+ if (this.#failures.has(sessionId)) {
2533
+ throw new SessionOperationError("ANALYTICS_UNAVAILABLE", "Analytics recording failed", { cause: this.#failures.get(sessionId) });
2534
+ }
2535
+ return WorkbenchTelemetrySchema.parse(await this.#request({
2536
+ operation: "telemetry",
2537
+ sessionId,
2538
+ environment: this.#environment(process.env),
2539
+ allowMissingEventLog
2540
+ }));
2541
+ }
2501
2542
  };
2502
2543
 
2503
2544
  // src/adapters/copilot/interactions/interaction-broker.ts
@@ -3675,8 +3716,45 @@ var require2 = createRequire(import.meta.url);
3675
3716
  function resolveCopilotRuntimePath(environment = process.env) {
3676
3717
  return environment["COPILOT_CLI_PATH"] ?? require2.resolve("@github/copilot/npm-loader.js");
3677
3718
  }
3719
+ function assertCopilotInProcessRuntime() {
3720
+ try {
3721
+ const entrypoint = process.env["COPILOT_CLI_PATH"];
3722
+ let platform = process.platform;
3723
+ if (platform === "linux") {
3724
+ const report = process.report?.getReport();
3725
+ const header = z5.object({ header: z5.object({ glibcVersionRuntime: z5.string().optional() }) }).safeParse(report);
3726
+ const musl = entrypoint?.includes(`copilot-linuxmusl-${process.arch}`) || !entrypoint?.includes(`copilot-linux-${process.arch}`) && (!header.success || header.data.header.glibcVersionRuntime === void 0);
3727
+ if (musl) platform = "linuxmusl";
3728
+ }
3729
+ const target = `${platform}-${process.arch}`;
3730
+ const files = [];
3731
+ if (entrypoint) {
3732
+ const directory = dirname2(resolve(entrypoint));
3733
+ const adjacent = join3(directory, "runtime.node");
3734
+ files.push(existsSync(adjacent) ? adjacent : join3(directory, "prebuilds", target, "runtime.node"));
3735
+ } else {
3736
+ const sdkRequire = createRequire(require2.resolve("@github/copilot-sdk"));
3737
+ const directory = dirname2(sdkRequire.resolve(`@github/copilot-sdk-${target}/package.json`));
3738
+ const prebuild = join3(directory, "prebuilds", target);
3739
+ files.push(
3740
+ join3(prebuild, "runtime.node"),
3741
+ join3(prebuild, process.platform === "win32" ? "copilot-runtime.exe" : "copilot-runtime")
3742
+ );
3743
+ }
3744
+ for (const path of files) {
3745
+ const file = statSync(path);
3746
+ if (!file.isFile() || file.size === 0) throw new Error(`Missing Copilot native runtime file: ${path}`);
3747
+ }
3748
+ } catch (error) {
3749
+ throw new Error(
3750
+ "Copilot inprocess runtime is unavailable. Unset COPILOT_SDK_DEFAULT_CONNECTION or set it to stdio to use the bundled CLI; inprocess requires a full SDK installation with its platform runtime, or COPILOT_CLI_PATH with an adjacent native runtime.",
3751
+ { cause: error }
3752
+ );
3753
+ }
3754
+ }
3678
3755
  function createCopilotClient() {
3679
- const defaultConnection = process.env["COPILOT_SDK_DEFAULT_CONNECTION"]?.toLowerCase();
3756
+ const defaultConnection = process.env["COPILOT_SDK_DEFAULT_CONNECTION"]?.toLowerCase() || void 0;
3757
+ if (defaultConnection === "inprocess") assertCopilotInProcessRuntime();
3680
3758
  const client = defaultConnection !== void 0 && defaultConnection !== "stdio" ? new CopilotClient({ mode: "copilot-cli" }) : new CopilotClient({
3681
3759
  mode: "copilot-cli",
3682
3760
  connection: RuntimeConnection.forStdio({
@@ -3960,6 +4038,12 @@ var GithubCopilotAdapter = class {
3960
4038
  #callbacks;
3961
4039
  #workbench = new SessionWorkbenchRuntime({
3962
4040
  getSession: (sessionId) => this.#sessions.getSession(sessionId),
4041
+ currentSession: (sessionId) => this.#sessions.current(sessionId),
4042
+ telemetry: (sessionId) => this.#analytics?.telemetry(
4043
+ sessionId,
4044
+ this.#provisionalSessions.get(sessionId)?.allowMissingEventLog === true
4045
+ ) ?? Promise.resolve(void 0),
4046
+ storage: (sessionId) => this.#sessionStorage.storage(sessionId),
3963
4047
  getRuntime: (sessionId) => this.#sessions.getOrCreate(sessionId),
3964
4048
  assertAvailable: (sessionId) => {
3965
4049
  assertMainSessionId(sessionId);
@@ -3992,7 +4076,9 @@ var GithubCopilotAdapter = class {
3992
4076
  });
3993
4077
  #schedules;
3994
4078
  #analytics;
4079
+ #sessionStorage = new SessionDirectoryLister((id) => this.getSessionDirectoryMetadata(id));
3995
4080
  workbench = {
4081
+ reasoning: (id, request) => this.#withWorkbenchOperation(() => this.#workbench.reasoning(id, request)),
3996
4082
  ask: (id, question) => this.#withWorkbenchOperation(() => this.#workbench.ask(id, question)),
3997
4083
  commands: (id) => this.#withWorkbenchOperation(() => this.#workbench.commands(id)),
3998
4084
  invokeCommand: (id, name, input) => this.#withWorkbenchOperation(() => this.#workbench.invokeCommand(id, name, input)),
@@ -4178,6 +4264,12 @@ var GithubCopilotAdapter = class {
4178
4264
  throw new GroupChatError("GROUP_CHAT_PARTICIPANT_BUSY", "Wait for the group-owned turn to stop before using its participant independently");
4179
4265
  }
4180
4266
  }
4267
+ assertPeerSession(sessionId) {
4268
+ assertMainSessionId(sessionId);
4269
+ if (!this.peerChatEnabled || this.#groups?.has(sessionId)) {
4270
+ throw new GroupChatError("GROUP_CHAT_PARTICIPANT_UNSUPPORTED", "Choose an ordinary peer-enabled Copilot session");
4271
+ }
4272
+ }
4181
4273
  runPeerTurn(sessionId, prompt, options) {
4182
4274
  try {
4183
4275
  assertMainSessionId(sessionId);
@@ -4459,7 +4551,10 @@ var GithubCopilotAdapter = class {
4459
4551
  throw new Error("Copilot returned metadata for a different session");
4460
4552
  }
4461
4553
  const workingDirectory = "workingDirectory" in metadata ? metadata.workingDirectory : metadata.context?.workingDirectory;
4462
- return workingDirectory === void 0 ? {} : { workingDirectory };
4554
+ return {
4555
+ ...workingDirectory === void 0 ? {} : { workingDirectory },
4556
+ ...this.supportsFileAttachments && !metadata.isRemote && "workspacePath" in metadata && metadata.workspacePath !== null ? { sessionStateDirectory: metadata.workspacePath } : {}
4557
+ };
4463
4558
  }
4464
4559
  #projectIdentity = new SessionProjectIdentityReader(
4465
4560
  (sessionId) => this.getSessionDirectoryMetadata(sessionId)