@agentknight/sdk 0.9.56 → 0.9.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,25 +3,26 @@ import {
3
3
  } from "./chunk-T6226JFS.js";
4
4
  import {
5
5
  latestPreviewItems
6
- } from "./chunk-5J7BK2Y7.js";
6
+ } from "./chunk-NDEJOXSX.js";
7
7
  import {
8
8
  UnsupportedAgentOperationError,
9
9
  validateSessionName
10
- } from "./chunk-L3A736SO.js";
10
+ } from "./chunk-5DVJ7Y5W.js";
11
+ import "./chunk-3OIHMMDF.js";
11
12
  import {
12
13
  ConversationItemSchema,
13
14
  InteractionRequestSchema,
14
15
  InteractionResponseSchema,
15
16
  SESSION_TIMELINE_PAGE_SIZE,
16
17
  SessionSummarySchema
17
- } from "./chunk-K5CMKBW6.js";
18
+ } from "./chunk-LO4ZRE77.js";
18
19
 
19
20
  // src/claude-adapter.ts
20
21
  import { randomUUID as randomUUID2 } from "node:crypto";
21
- import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
22
- import { homedir } from "node:os";
23
- import { isAbsolute, join, resolve } from "node:path";
24
- 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";
25
26
 
26
27
  // src/adapters/claude/input.ts
27
28
  var ClaudeInput = class {
@@ -472,39 +473,180 @@ var ClaudeProcess = class {
472
473
  }
473
474
  };
474
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
+
475
617
  // src/claude-adapter.ts
476
618
  var CLAUDE_DEFAULT_MODEL_ID = "claude:agent-default";
477
- var UuidSchema = z4.custom((value) => z4.uuid().safeParse(value).success);
478
- var ReceiptSchema = z4.object({
619
+ var UuidSchema = z5.custom((value) => z5.uuid().safeParse(value).success);
620
+ var ReceiptSchema = z5.object({
479
621
  id: UuidSchema,
480
- prompt: z4.string().min(1).max(1e5),
481
- mode: z4.enum(["enqueue", "immediate"]),
482
- submittedAt: z4.iso.datetime(),
483
- operationId: z4.string().min(1).max(256).optional(),
484
- 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"])
485
627
  });
486
- var StoredSchema = z4.object({
487
- version: z4.literal(1),
628
+ var StoredSchema = z5.object({
629
+ version: z5.literal(1),
488
630
  summary: SessionSummarySchema,
489
631
  nativeId: UuidSchema.optional(),
490
- modelId: z4.string().min(1).max(256),
491
- nativeDirectory: z4.string().min(1).optional(),
492
- items: z4.array(ConversationItemSchema),
493
- receipts: z4.array(ReceiptSchema),
494
- 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()
495
637
  }).refine((stored) => stored.nativeDirectory === void 0 || stored.nativeId !== void 0 && stored.summary.sessionId === `claude:native:${stored.nativeId}`, {
496
638
  message: "Invalid Claude native session identity"
497
639
  });
498
- var MessageSchema = z4.object({
499
- type: z4.string(),
500
- subtype: z4.string().optional(),
501
- uuid: z4.string().optional(),
502
- session_id: z4.string().optional(),
503
- state: z4.string().optional(),
504
- user_message_uuid: z4.string().optional(),
505
- user_message_uuids: z4.array(z4.string()).optional(),
506
- parent_tool_use_id: z4.string().nullable().optional(),
507
- 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()
508
650
  }).passthrough();
509
651
  var ClaudeCodingAgentAdapter = class {
510
652
  agentId = "claude";
@@ -540,7 +682,7 @@ var ClaudeCodingAgentAdapter = class {
540
682
  if (options.nativeSessionOwner !== void 0) {
541
683
  SessionSummarySchema.pick({ userId: true, machineId: true }).parse(options.nativeSessionOwner);
542
684
  }
543
- this.#directory = join(resolve(options.dataDirectory), "claude");
685
+ this.#directory = join2(resolve(options.dataDirectory), "claude");
544
686
  this.#interactions = new ClaudeInteractions(() => this.#callbacks, timeout);
545
687
  }
546
688
  setSessionCallbacks(callbacks) {
@@ -553,10 +695,10 @@ var ClaudeCodingAgentAdapter = class {
553
695
  }
554
696
  async #start() {
555
697
  await mkdir(this.#directory, { recursive: true, mode: 448 });
556
- await mkdir(join(this.#directory, "native"), { recursive: true, mode: 448 });
698
+ await mkdir(join2(this.#directory, "native"), { recursive: true, mode: 448 });
557
699
  for (const file of await readdir(this.#directory)) {
558
700
  if (!/^[a-f0-9]{64}\.json$/.test(file)) continue;
559
- const raw = JSON.parse(await readFile(join(this.#directory, file), "utf8"));
701
+ const raw = JSON.parse(await readFile2(join2(this.#directory, file), "utf8"));
560
702
  const stored = StoredSchema.parse(raw);
561
703
  if (!stored.summary.sessionId.startsWith("claude:") || `${identity(stored.summary.sessionId)}.json` !== file) {
562
704
  throw new Error("Invalid Claude session ownership record");
@@ -587,6 +729,7 @@ var ClaudeCodingAgentAdapter = class {
587
729
  active: void 0,
588
730
  input: void 0,
589
731
  query: void 0,
732
+ command: void 0,
590
733
  controller: void 0,
591
734
  work: void 0,
592
735
  dispatch: void 0,
@@ -634,13 +777,13 @@ var ClaudeCodingAgentAdapter = class {
634
777
  }
635
778
  async #scanNative(owner) {
636
779
  const sdk = await this.#nativeSessions();
637
- const sessions = z4.array(z4.object({
780
+ const sessions = z5.array(z5.object({
638
781
  sessionId: UuidSchema,
639
- summary: z4.string(),
640
- customTitle: z4.string().optional(),
641
- lastModified: z4.number(),
642
- createdAt: z4.number().optional(),
643
- 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()
644
787
  })).parse(await sdk.listSessions({ includeProgrammatic: true }));
645
788
  this.#ready();
646
789
  const next = /* @__PURE__ */ new Map();
@@ -673,7 +816,7 @@ var ClaudeCodingAgentAdapter = class {
673
816
  version: 1,
674
817
  summary,
675
818
  nativeId: native.sessionId,
676
- nativeDirectory: resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude")),
819
+ nativeDirectory: resolve(env.CLAUDE_CONFIG_DIR || join2(homedir2(), ".claude")),
677
820
  modelId: CLAUDE_DEFAULT_MODEL_ID,
678
821
  items: [],
679
822
  receipts: [],
@@ -693,12 +836,13 @@ var ClaudeCodingAgentAdapter = class {
693
836
  if (session.work || session.operations || session.cancellations || session.aborting || session.stored.unsafe || session.error) continue;
694
837
  this.#sessions.delete(id);
695
838
  this.#retiredSessions.add(id);
696
- await rm(join(this.#directory, `${identity(id)}.json`));
839
+ await rm(join2(this.#directory, `${identity(id)}.json`));
697
840
  }
698
841
  }
699
842
  }
700
843
  async listModels() {
701
844
  this.#ready();
845
+ await resolveClaudeExecutable(this.#options.command, this.#options.env);
702
846
  return [{ id: CLAUDE_DEFAULT_MODEL_ID, name: "Claude agent default", isDefault: true }];
703
847
  }
704
848
  getSessionCapabilities() {
@@ -753,7 +897,9 @@ var ClaudeCodingAgentAdapter = class {
753
897
  async createSession(options) {
754
898
  this.#ready();
755
899
  this.#validate(options);
756
- 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();
757
903
  const now = (/* @__PURE__ */ new Date()).toISOString();
758
904
  const summary = SessionSummarySchema.parse({
759
905
  sessionId: `claude:${randomUUID2()}`,
@@ -828,14 +974,14 @@ var ClaudeCodingAgentAdapter = class {
828
974
  const sdk = await this.#nativeSessions();
829
975
  const nativeId = UuidSchema.parse(session.stored.nativeId);
830
976
  const raw = await sdk.getSessionMessages(nativeId, this.#nativeReadOptions(session));
831
- const messages = z4.array(z4.object({
832
- type: z4.enum(["user", "assistant", "system"]),
833
- uuid: z4.string(),
977
+ const messages = z5.array(z5.object({
978
+ type: z5.enum(["user", "assistant", "system"]),
979
+ uuid: z5.string(),
834
980
  session_id: UuidSchema,
835
- message: z4.unknown(),
836
- timestamp: z4.iso.datetime().optional(),
837
- parent_tool_use_id: z4.string().nullable(),
838
- 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()
839
985
  }).passthrough()).parse(raw);
840
986
  this.#known(session.stored.summary.sessionId);
841
987
  const items = [];
@@ -845,8 +991,8 @@ var ClaudeCodingAgentAdapter = class {
845
991
  if (message.session_id !== nativeId) throw new Error("Claude returned history for another native session");
846
992
  if (message.parent_agent_id || message.parent_tool_use_id) continue;
847
993
  if (message.type === "user") {
848
- const body = z4.object({ content: z4.unknown() }).parse(message.message);
849
- 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;
850
996
  }
851
997
  timeline.project({ ...message, timestamp: message.timestamp ?? session.stored.summary.createdAt }, turnId);
852
998
  }
@@ -881,7 +1027,7 @@ var ClaudeCodingAgentAdapter = class {
881
1027
  if (session.stored.nativeDirectory) {
882
1028
  this.#environment(session);
883
1029
  const directory = session.stored.summary.workingDirectory;
884
- 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");
885
1031
  }
886
1032
  const duplicate = operationId === void 0 ? void 0 : session.stored.receipts.find((entry) => entry.operationId === operationId);
887
1033
  if (duplicate) {
@@ -889,6 +1035,11 @@ var ClaudeCodingAgentAdapter = class {
889
1035
  if (duplicate.state === "failed" || duplicate.state === "cancelled") throw new Error("Claude operation already ended; it was not retried");
890
1036
  return { messageId: duplicate.id, deliveryState: duplicate.state === "queued" ? "queued" : "processing", submittedAt: duplicate.submittedAt };
891
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
+ }
892
1043
  if (mode === "immediate" && session.busy) {
893
1044
  await this.#cancel(session, false);
894
1045
  if (session.aborting || this.#stopping || session.epoch !== epoch + 1) throw new Error("Claude prompt cancelled before acceptance");
@@ -953,7 +1104,7 @@ var ClaudeCodingAgentAdapter = class {
953
1104
  #environment(session) {
954
1105
  return prepareClaudeEnvironment(
955
1106
  this.#options.env ?? process.env,
956
- session.stored.nativeDirectory ?? join(this.#directory, "native")
1107
+ session.stored.nativeDirectory ?? join2(this.#directory, "native")
957
1108
  );
958
1109
  }
959
1110
  async #consume(session, epoch) {
@@ -980,7 +1131,7 @@ var ClaudeCodingAgentAdapter = class {
980
1131
  abortController: controller,
981
1132
  spawnClaudeCodeProcess: ownedProcess.spawn,
982
1133
  ...session.stored.nativeId ? { resume: session.stored.nativeId } : {},
983
- ...this.#options.command ? { pathToClaudeCodeExecutable: this.#options.command } : {},
1134
+ ...session.command === void 0 ? {} : { pathToClaudeCodeExecutable: session.command },
984
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)
985
1136
  }
986
1137
  });
@@ -1007,7 +1158,7 @@ var ClaudeCodingAgentAdapter = class {
1007
1158
  for (const receiptId of confirmations) this.#confirm(session, receiptId);
1008
1159
  session.timeline.project(raw, turnId);
1009
1160
  if (message.type === "result") {
1010
- const isError = z4.boolean().parse(message.is_error);
1161
+ const isError = z5.boolean().parse(message.is_error);
1011
1162
  session.resultSeen = true;
1012
1163
  if (session.active) session.active.state = isError ? "failed" : "completed";
1013
1164
  if (isError) {
@@ -1016,7 +1167,7 @@ var ClaudeCodingAgentAdapter = class {
1016
1167
  }
1017
1168
  }
1018
1169
  if (message.type === "system" && message.subtype === "background_tasks_changed") {
1019
- const background = z4.object({ tasks: z4.array(z4.unknown()) }).safeParse(message);
1170
+ const background = z5.object({ tasks: z5.array(z5.unknown()) }).safeParse(message);
1020
1171
  session.background = !background.success || background.data.tasks.length > 0;
1021
1172
  }
1022
1173
  if (message.type === "system" && message.subtype === "session_state_changed" && (message.state === "running" || message.state === "requires_action")) {
@@ -1189,7 +1340,7 @@ var ClaudeCodingAgentAdapter = class {
1189
1340
  #save(session) {
1190
1341
  if (!this.#sessions.has(session.stored.summary.sessionId)) return Promise.resolve();
1191
1342
  const data = JSON.stringify(StoredSchema.parse(session.stored));
1192
- const file = join(this.#directory, `${identity(session.stored.summary.sessionId)}.json`);
1343
+ const file = join2(this.#directory, `${identity(session.stored.summary.sessionId)}.json`);
1193
1344
  session.saves++;
1194
1345
  const work = session.saving.then(async () => {
1195
1346
  const temporary = `${file}.${randomUUID2()}.tmp`;
@@ -1,15 +1,16 @@
1
1
  import {
2
2
  latestPreviewItems
3
- } from "./chunk-5J7BK2Y7.js";
3
+ } from "./chunk-NDEJOXSX.js";
4
4
  import {
5
5
  UnsupportedAgentOperationError
6
- } from "./chunk-L3A736SO.js";
6
+ } from "./chunk-5DVJ7Y5W.js";
7
+ import "./chunk-3OIHMMDF.js";
7
8
  import {
8
9
  ConversationItemSchema,
9
10
  InteractionRequestSchema,
10
11
  SESSION_TIMELINE_PAGE_SIZE,
11
12
  SessionSummarySchema
12
- } from "./chunk-K5CMKBW6.js";
13
+ } from "./chunk-LO4ZRE77.js";
13
14
 
14
15
  // src/codex-adapter.ts
15
16
  import { randomUUID } from "node:crypto";