@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
@@ -0,0 +1,115 @@
1
+ import {
2
+ INLINE_IMAGE_MAX_BYTES,
3
+ SessionAssistantPreviewSchema,
4
+ SessionUserPreviewSchema
5
+ } from "./chunk-F5YCEWE4.js";
6
+
7
+ // src/assistant-preview.ts
8
+ function isContentfulAssistant(item) {
9
+ 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")));
10
+ }
11
+ function userPreview(item) {
12
+ if (item.kind !== "human-message" || item.actor !== "human") return void 0;
13
+ return SessionUserPreviewSchema.parse({
14
+ id: item.id,
15
+ revision: item.revision,
16
+ timestamp: item.timestamp,
17
+ text: item.content.slice(0, 4096)
18
+ });
19
+ }
20
+ function latestPreviewItems(items) {
21
+ const latest = [...items].reverse();
22
+ return [
23
+ latest.find((item) => item.kind === "human-message" && item.actor === "human"),
24
+ latest.find(isContentfulAssistant)
25
+ ].filter((item) => item !== void 0);
26
+ }
27
+ function assistantPreview(item, referenceItem) {
28
+ if (!isContentfulAssistant(item)) return void 0;
29
+ const referenced = referenceItem(item);
30
+ const attachments = referenced.kind === "assistant-message" ? (referenced.attachments ?? []).filter((attachment) => attachment.kind === "image" && attachment.imageRef === "sha256").slice(0, 4) : [];
31
+ if (item.content.trim().length === 0 && attachments.length === 0) return void 0;
32
+ return SessionAssistantPreviewSchema.parse({
33
+ id: item.id,
34
+ revision: item.revision,
35
+ timestamp: item.timestamp,
36
+ sourceEventIds: item.sourceEventIds.slice(-1),
37
+ text: item.content.trim().slice(0, 4096),
38
+ final: item.kind === "assistant-message" ? item.final : true,
39
+ ...item.kind === "notice" ? { kind: "task-completion" } : {},
40
+ attachments
41
+ });
42
+ }
43
+
44
+ // src/timeline-image-content.ts
45
+ import { createHash } from "node:crypto";
46
+ var imageMimeTypes = /* @__PURE__ */ new Set(["image/gif", "image/jpeg", "image/png", "image/webp"]);
47
+ function normalizeImageMimeType(value) {
48
+ const lower = value.toLowerCase();
49
+ return lower === "image/jpg" ? "image/jpeg" : lower;
50
+ }
51
+ function hasImageSignature(bytes, mimeType) {
52
+ switch (mimeType) {
53
+ case "image/png":
54
+ return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
55
+ case "image/jpeg":
56
+ return bytes.subarray(0, 3).equals(Buffer.from([255, 216, 255]));
57
+ case "image/gif":
58
+ return ["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString("ascii"));
59
+ case "image/webp":
60
+ return bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
61
+ default:
62
+ return false;
63
+ }
64
+ }
65
+ function decodeTimelineImage(value, mimeType, source) {
66
+ if (!imageMimeTypes.has(mimeType)) return { failure: { source, reason: "mime-unsupported", mimeType } };
67
+ const dataUrl = /^data:([^;,]+);base64,(.*)$/isu.exec(value);
68
+ const payload = dataUrl?.[2] ?? value;
69
+ if (dataUrl && normalizeImageMimeType(dataUrl[1] ?? "") !== mimeType || !/^[A-Za-z0-9+/_-]+={0,2}$/u.test(payload) || payload.length % 4 === 1) {
70
+ return { failure: { source, reason: "data-invalid", mimeType } };
71
+ }
72
+ const byteLength = Math.floor(payload.replace(/=+$/u, "").length * 3 / 4);
73
+ if (byteLength > INLINE_IMAGE_MAX_BYTES) {
74
+ return { failure: { source, reason: "data-too-large", mimeType, actualByteLength: byteLength } };
75
+ }
76
+ const normalized = payload.replaceAll("-", "+").replaceAll("_", "/");
77
+ const bytes = Buffer.from(normalized, "base64");
78
+ const data = bytes.toString("base64");
79
+ if (data.replace(/=+$/u, "") !== normalized.replace(/=+$/u, "")) {
80
+ return { failure: { source, reason: "data-invalid", mimeType } };
81
+ }
82
+ if (bytes.length === 0) return { failure: { source, reason: "data-empty", mimeType, actualByteLength: 0 } };
83
+ if (!hasImageSignature(bytes, mimeType)) {
84
+ return { failure: { source, reason: "signature-mismatch", mimeType, actualByteLength: bytes.length } };
85
+ }
86
+ return { data, byteLength: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") };
87
+ }
88
+ function splitTimelineImages(images, size) {
89
+ const groups = [];
90
+ let group = [];
91
+ let bytes = 0;
92
+ for (const image of images) {
93
+ const length = size(image);
94
+ if (group.length > 0 && (group.length >= 4 || bytes + length > INLINE_IMAGE_MAX_BYTES)) {
95
+ groups.push(group);
96
+ group = [];
97
+ bytes = 0;
98
+ }
99
+ group.push(image);
100
+ bytes += length;
101
+ }
102
+ if (group.length > 0) groups.push(group);
103
+ return groups;
104
+ }
105
+
106
+ export {
107
+ normalizeImageMimeType,
108
+ hasImageSignature,
109
+ decodeTimelineImage,
110
+ splitTimelineImages,
111
+ isContentfulAssistant,
112
+ userPreview,
113
+ latestPreviewItems,
114
+ assistantPreview
115
+ };
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  CODING_AGENT_IDS
3
- } from "./chunk-7CNBPLNE.js";
3
+ } from "./chunk-IRYEOV62.js";
4
4
  import {
5
5
  BYTES_PER_KIB,
6
6
  LEGACY_SECURE_MESSAGE_MAX_CIPHERTEXT_LENGTH
7
- } from "./chunk-P2PH5KMV.js";
7
+ } from "./chunk-F5YCEWE4.js";
8
8
 
9
9
  // src/agent-selection.ts
10
10
  import { z } from "zod";
@@ -2,26 +2,37 @@ import {
2
2
  hasClaudeProviderConfiguration
3
3
  } from "./chunk-T6226JFS.js";
4
4
  import {
5
- latestPreviewItems
6
- } from "./chunk-H4SHMWQ6.js";
5
+ prepareNativePrompt,
6
+ projectNativeImage
7
+ } from "./chunk-MB34W52S.js";
8
+ import "./chunk-UTF7KLMJ.js";
9
+ import "./chunk-ES2N66EH.js";
10
+ import "./chunk-35OF2ZNS.js";
7
11
  import {
12
+ latestPreviewItems,
13
+ splitTimelineImages
14
+ } from "./chunk-WAPJZKUK.js";
15
+ import {
16
+ SessionDeletionRejectedError,
8
17
  UnsupportedAgentOperationError,
9
18
  validateSessionName
10
- } from "./chunk-7CNBPLNE.js";
11
- import "./chunk-7OGTK7KB.js";
19
+ } from "./chunk-IRYEOV62.js";
20
+ import "./chunk-J63A5OLO.js";
12
21
  import {
13
22
  ConversationItemSchema,
14
23
  InteractionRequestSchema,
15
24
  InteractionResponseSchema,
16
25
  SESSION_TIMELINE_PAGE_SIZE,
17
26
  SessionSummarySchema
18
- } from "./chunk-P2PH5KMV.js";
27
+ } from "./chunk-F5YCEWE4.js";
19
28
 
20
29
  // src/claude-adapter.ts
30
+ import { execFile as execFile2 } from "node:child_process";
21
31
  import { randomUUID as randomUUID2 } from "node:crypto";
22
32
  import { mkdir, readFile as readFile2, readdir, rename, rm, writeFile } from "node:fs/promises";
23
33
  import { homedir as homedir2 } from "node:os";
24
34
  import { isAbsolute as isAbsolute2, join as join2, resolve } from "node:path";
35
+ import { promisify } from "node:util";
25
36
  import { z as z5 } from "zod";
26
37
 
27
38
  // src/adapters/claude/input.ts
@@ -196,6 +207,20 @@ var BlockSchema = z2.object({
196
207
  tool_use_id: z2.string().optional(),
197
208
  is_error: z2.boolean().optional()
198
209
  }).passthrough();
210
+ var ImageBlock = z2.object({
211
+ type: z2.literal("image"),
212
+ source: z2.object({ type: z2.literal("base64"), data: z2.string(), media_type: z2.string() })
213
+ });
214
+ function imagesFrom(value) {
215
+ if (!Array.isArray(value)) return [];
216
+ return value.flatMap((part) => {
217
+ const parsed = ImageBlock.safeParse(part);
218
+ if (!parsed.success) return [];
219
+ const source = parsed.data.source;
220
+ const image = projectNativeImage(source.data, source.media_type);
221
+ return image ? [image] : [];
222
+ });
223
+ }
199
224
  var ClaudeTimeline = class {
200
225
  constructor(sessionId, items, publish) {
201
226
  this.sessionId = sessionId;
@@ -270,6 +295,7 @@ var ClaudeTimeline = class {
270
295
  const source = message.uuid ?? turnId;
271
296
  if (message.type === "assistant") {
272
297
  const body = z2.object({ id: z2.string(), content: z2.array(BlockSchema) }).parse(message.message);
298
+ this.#images(body.id, turnId, imagesFrom(body.content));
273
299
  body.content.forEach((block, index) => {
274
300
  if (block.type === "text" && block.text !== void 0) {
275
301
  this.#text(body.id, index, block.text, true, turnId);
@@ -283,21 +309,23 @@ var ClaudeTimeline = class {
283
309
  const body = z2.object({ content: z2.unknown() }).parse(message.message);
284
310
  const blocks = Array.isArray(body.content) ? body.content.map((block) => BlockSchema.parse(block)) : [];
285
311
  const text = typeof body.content === "string" ? body.content : blocks.filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n");
312
+ const attachments = splitTimelineImages(imagesFrom(blocks), (image) => image.byteLength ?? 0)[0] ?? [];
286
313
  const uuid = message.uuid;
287
- if (text && uuid && !this.items.some((item) => item.id === sourceId(uuid))) {
314
+ if ((text || attachments.length) && uuid && !this.items.some((item) => item.id === sourceId(uuid))) {
288
315
  this.upsert({
289
316
  ...this.base(uuid, turnId),
290
317
  sourceMessageIds: [sourceId(uuid)],
291
318
  kind: "human-message",
292
319
  actor: "human",
293
320
  content: text,
294
- attachments: []
321
+ attachments
295
322
  });
296
323
  }
297
324
  if (!Array.isArray(body.content)) return;
298
325
  for (const block of blocks) {
299
326
  if (block.type === "tool_result" && block.tool_use_id) {
300
327
  this.#tool(block.tool_use_id, void 0, block.is_error ? "failed" : "completed", turnId);
328
+ this.#images(block.tool_use_id, turnId, imagesFrom(block.content));
301
329
  }
302
330
  }
303
331
  } else if (message.type === "tool_progress") {
@@ -359,6 +387,20 @@ var ClaudeTimeline = class {
359
387
  final
360
388
  });
361
389
  }
390
+ #images(source, turnId, images) {
391
+ const unique = [...new Map(images.map((image) => [image.sha256, image])).values()];
392
+ splitTimelineImages(unique, (image) => image.byteLength ?? 0).forEach((attachments, index) => {
393
+ const id = identity(`${this.sessionId}:images:${source}:${index}`);
394
+ this.upsert({
395
+ ...this.base(id, turnId),
396
+ kind: "assistant-message",
397
+ actor: "assistant",
398
+ content: "",
399
+ final: true,
400
+ attachments
401
+ });
402
+ });
403
+ }
362
404
  #tool(toolId, name, status, turnId) {
363
405
  const id = identity(`${this.sessionId}:tool:${toolId}`);
364
406
  const previous = this.items.find((item) => item.id === id);
@@ -619,12 +661,14 @@ var CLAUDE_DEFAULT_MODEL_ID = "claude:agent-default";
619
661
  var UuidSchema = z5.custom((value) => z5.uuid().safeParse(value).success);
620
662
  var ReceiptSchema = z5.object({
621
663
  id: UuidSchema,
622
- prompt: z5.string().min(1).max(1e5),
664
+ prompt: z5.string().max(1e5),
623
665
  mode: z5.enum(["enqueue", "immediate"]),
624
666
  submittedAt: z5.iso.datetime(),
625
667
  operationId: z5.string().min(1).max(256).optional(),
626
668
  state: z5.enum(["queued", "submitted", "confirmed", "completed", "cancelled", "failed"])
627
669
  });
670
+ var modelCatalog = z5.array(z5.object({ value: z5.string().min(1).max(240), displayName: z5.string().min(1).max(260) })).max(250);
671
+ var defaultModel = { id: CLAUDE_DEFAULT_MODEL_ID, name: "Claude agent default", isDefault: true };
628
672
  var StoredSchema = z5.object({
629
673
  version: z5.literal(1),
630
674
  summary: SessionSummarySchema,
@@ -655,8 +699,11 @@ var ClaudeCodingAgentAdapter = class {
655
699
  supportsReasoningEffort = false;
656
700
  supportsSessionListUpdates = true;
657
701
  supportsAssistantPreview = true;
658
- supportsSessionDelete = false;
659
- supportsFileAttachments = false;
702
+ supportsSessionDelete = true;
703
+ supportsFileAttachments = true;
704
+ #models = [defaultModel];
705
+ #modelRefresh;
706
+ #modelAbort;
660
707
  groupChatEnabled = false;
661
708
  #options;
662
709
  #directory;
@@ -764,7 +811,7 @@ var ClaudeCodingAgentAdapter = class {
764
811
  return "claude:host-owned";
765
812
  }
766
813
  async canUpgrade() {
767
- return this.#started && !this.#stopping && this.#interactions.size === 0 && [...this.#sessions.values()].every((s) => (!s.work || s.query !== void 0) && !s.dispatch && !s.active && !s.busy && !s.background && !s.cancellations && !s.operations && !s.aborting && !s.queue.length && !s.saves && !s.error);
814
+ return this.#started && !this.#stopping && !this.#modelRefresh && this.#interactions.size === 0 && [...this.#sessions.values()].every((s) => (!s.work || s.query !== void 0) && !s.dispatch && !s.active && !s.busy && !s.background && !s.cancellations && !s.operations && !s.aborting && !s.queue.length && !s.saves && !s.error);
768
815
  }
769
816
  async listSessions(userId, machineId) {
770
817
  this.#ready();
@@ -840,13 +887,78 @@ var ClaudeCodingAgentAdapter = class {
840
887
  }
841
888
  }
842
889
  }
843
- async listModels() {
890
+ async listModels(id) {
844
891
  this.#ready();
845
- await resolveClaudeExecutable(this.#options.command, this.#options.env);
846
- return [{ id: CLAUDE_DEFAULT_MODEL_ID, name: "Claude agent default", isDefault: true }];
892
+ const session = id === void 0 ? void 0 : this.#known(id);
893
+ const path = await resolveClaudeExecutable(this.#options.command, this.#options.env);
894
+ this.#ready();
895
+ if (this.#models.length === 1 && !this.#options.sdk && !this.#modelRefresh) {
896
+ this.#modelRefresh = this.#refreshModels(path).finally(() => {
897
+ this.#modelRefresh = void 0;
898
+ });
899
+ }
900
+ await this.#modelRefresh;
901
+ const selected = session?.stored.modelId;
902
+ return selected && !this.#models.some((model) => model.id === selected) ? [...this.#models, { id: selected, name: selected, isDefault: false }] : [...this.#models];
847
903
  }
848
- getSessionCapabilities() {
849
- return { agentModes: this.agentModes, supportsReasoningEffort: false, supportsFileAttachments: false, agentName: "Claude", supportsPlanRead: false };
904
+ async #refreshModels(path) {
905
+ const controller = new AbortController();
906
+ this.#modelAbort = controller;
907
+ const timer = setTimeout(() => controller.abort(new Error("Claude model discovery timed out")), 5e3);
908
+ const owned = new ClaudeProcess();
909
+ let query;
910
+ try {
911
+ const cwd = join2(this.#directory, "native");
912
+ const env = prepareClaudeEnvironment(this.#options.env ?? process.env, cwd);
913
+ const sdk = await import("@anthropic-ai/claude-agent-sdk");
914
+ this.#ready();
915
+ controller.signal.throwIfAborted();
916
+ const input = new ClaudeInput();
917
+ try {
918
+ query = sdk.query({
919
+ prompt: input,
920
+ options: {
921
+ cwd,
922
+ env,
923
+ ...path === void 0 ? {} : { pathToClaudeCodeExecutable: path },
924
+ spawnClaudeCodeProcess: owned.spawn,
925
+ abortController: controller,
926
+ persistSession: false,
927
+ settingSources: [],
928
+ tools: []
929
+ }
930
+ });
931
+ this.#rememberModels(await query.supportedModels?.());
932
+ } finally {
933
+ input.close();
934
+ }
935
+ } catch (error) {
936
+ this.#options.onDiagnostic?.(`Claude model list unavailable: ${error instanceof Error ? error.message : "unknown error"}`);
937
+ } finally {
938
+ clearTimeout(timer);
939
+ controller.abort();
940
+ query?.close();
941
+ try {
942
+ await owned.finish(this.#options.processExitTimeoutMs ?? 5e3);
943
+ } finally {
944
+ this.#modelAbort = void 0;
945
+ }
946
+ }
947
+ }
948
+ #rememberModels(raw) {
949
+ const parsed = modelCatalog.safeParse(raw);
950
+ if (!parsed.success) return;
951
+ this.#models = [defaultModel, ...new Map(parsed.data.filter(({ value }) => value !== CLAUDE_DEFAULT_MODEL_ID).map(({ value, displayName }) => [value, { id: value, name: displayName, isDefault: false }])).values()];
952
+ }
953
+ getSessionCapabilities(id) {
954
+ return {
955
+ agentModes: this.agentModes,
956
+ supportsReasoningEffort: false,
957
+ supportsFileAttachments: true,
958
+ agentName: "Claude",
959
+ supportsPlanRead: false,
960
+ supportsSessionDelete: id === void 0 || !this.#known(id).stored.nativeDirectory
961
+ };
850
962
  }
851
963
  async getSessionConfiguration(id) {
852
964
  return { modelId: this.#known(id).stored.modelId, agentMode: "interactive", reasoningEffort: "default" };
@@ -870,8 +982,54 @@ var ClaudeCodingAgentAdapter = class {
870
982
  return this.getSessionRemoteStatus(id);
871
983
  }
872
984
  async deleteSession(id) {
873
- this.#known(id);
874
- return this.#unsupported("native session deletion");
985
+ const session = this.#known(id);
986
+ const reject = (message) => {
987
+ throw new SessionDeletionRejectedError(message);
988
+ };
989
+ if (session.stored.nativeDirectory) reject("Delete sessions created in standalone Claude Code there");
990
+ if (session.busy || session.background || session.queue.length || session.operations || session.aborting || session.cancellations || session.error || session.stored.unsafe) reject("Claude session is active or cannot be verified idle");
991
+ session.operations++;
992
+ const work = session.lock.then(async () => {
993
+ const { nativeId, summary } = session.stored;
994
+ const dir = summary.workingDirectory;
995
+ if (nativeId && !dir) return reject("Claude session has no known project directory");
996
+ if (session.work) {
997
+ try {
998
+ await this.#cancel(session, false);
999
+ } catch {
1000
+ return reject("Claude process exit could not be verified");
1001
+ }
1002
+ }
1003
+ this.#known(id);
1004
+ if (nativeId && dir) {
1005
+ const config = join2(this.#directory, "native");
1006
+ const injected = this.#options.nativeSessions?.deleteOwnedSession;
1007
+ if (injected) await injected(nativeId, dir, config);
1008
+ else await promisify(execFile2)(process.execPath, [
1009
+ "--input-type=module",
1010
+ "-e",
1011
+ "const [sdk, id, dir] = process.argv.slice(1); await (await import(sdk)).deleteSession(id, {dir});",
1012
+ import.meta.resolve("@anthropic-ai/claude-agent-sdk"),
1013
+ nativeId,
1014
+ dir
1015
+ ], {
1016
+ env: { CLAUDE_CONFIG_DIR: config, SystemRoot: process.env.SystemRoot },
1017
+ timeout: 1e4,
1018
+ windowsHide: true
1019
+ });
1020
+ }
1021
+ await session.saving;
1022
+ await rm(join2(this.#directory, `${identity(id)}.json`));
1023
+ this.#sessions.delete(id);
1024
+ this.#retiredSessions.add(id);
1025
+ this.#callbacks?.onSessionInventoryChanged(id);
1026
+ });
1027
+ session.lock = work.then(() => void 0, () => void 0);
1028
+ try {
1029
+ await work;
1030
+ } finally {
1031
+ session.operations--;
1032
+ }
875
1033
  }
876
1034
  async readSessionPlan(id) {
877
1035
  this.#known(id);
@@ -892,7 +1050,7 @@ var ClaudeCodingAgentAdapter = class {
892
1050
  if (options.agentMode !== void 0 && options.agentMode !== "interactive") this.#unsupported("agent modes");
893
1051
  if (options.reasoningEffort !== void 0 && options.reasoningEffort !== "default") this.#unsupported("reasoning controls");
894
1052
  if (options.configOption !== void 0) this.#unsupported("configuration options");
895
- if (options.modelId !== void 0 && options.modelId !== CLAUDE_DEFAULT_MODEL_ID) this.#unsupported("model selection");
1053
+ if (options.modelId !== void 0 && !this.#models.some((model) => model.id === options.modelId)) this.#unsupported("model selection");
896
1054
  }
897
1055
  async createSession(options) {
898
1056
  this.#ready();
@@ -918,9 +1076,31 @@ var ClaudeCodingAgentAdapter = class {
918
1076
  return structuredClone(summary);
919
1077
  }
920
1078
  async configureSession(id, options) {
921
- this.#known(id);
1079
+ const session = this.#known(id);
922
1080
  this.#validate(options);
923
- return this.getSessionConfiguration(id);
1081
+ const model = options.modelId;
1082
+ if (model === void 0 || model === session.stored.modelId) return this.getSessionConfiguration(id);
1083
+ if (session.busy || session.background || session.operations || session.queue.length || session.aborting) {
1084
+ throw new Error("Wait for the Claude session to become idle before changing models");
1085
+ }
1086
+ session.operations++;
1087
+ const change = session.lock.then(async () => {
1088
+ this.#known(id);
1089
+ if (session.work) {
1090
+ if (!session.query?.setModel) this.#unsupported("changing the active model");
1091
+ await session.query.setModel(model === CLAUDE_DEFAULT_MODEL_ID ? void 0 : model);
1092
+ }
1093
+ if (this.#discovered.delete(id)) this.#sessions.set(id, session);
1094
+ session.stored.modelId = model;
1095
+ await this.#save(session);
1096
+ return this.getSessionConfiguration(id);
1097
+ });
1098
+ session.lock = change.then(() => void 0, () => void 0);
1099
+ try {
1100
+ return await change;
1101
+ } finally {
1102
+ session.operations--;
1103
+ }
924
1104
  }
925
1105
  async renameSession(id, name, assertAccess) {
926
1106
  const session = this.#known(id);
@@ -1003,6 +1183,10 @@ var ClaudeCodingAgentAdapter = class {
1003
1183
  if (previous.kind === "human-message" && candidate.kind === "human-message" && previous.operationId) {
1004
1184
  candidate.operationId = previous.operationId;
1005
1185
  }
1186
+ if (previous.kind === "human-message" && candidate.kind === "human-message" && previous.attachments?.length) {
1187
+ candidate.content = previous.content;
1188
+ candidate.attachments = previous.attachments;
1189
+ }
1006
1190
  if (JSON.stringify(candidate) !== JSON.stringify(previous)) candidate.revision++;
1007
1191
  return candidate;
1008
1192
  });
@@ -1012,14 +1196,13 @@ var ClaudeCodingAgentAdapter = class {
1012
1196
  }
1013
1197
  async sendPrompt(id, prompt, mode, attachments = [], _persistInteractions = true, files = [], operationId, avatar) {
1014
1198
  const session = this.#known(id);
1015
- if (attachments.length || files.length) this.#unsupported("attachments");
1016
1199
  if (avatar !== void 0) this.#unsupported("avatar personas");
1017
- if (!prompt.trim() || prompt.length > 1e5) throw new Error("Invalid Claude prompt");
1200
+ if (!prompt.trim() && !attachments.length && !files.length || prompt.length > 1e5) throw new Error("Invalid Claude prompt");
1018
1201
  if (session.aborting) throw new Error("Claude cancellation is still settling");
1019
1202
  session.operations++;
1020
1203
  const epoch = session.epoch;
1021
1204
  const run = session.lock.then(async () => {
1022
- this.#ready();
1205
+ this.#known(id);
1023
1206
  if (session.epoch !== epoch || session.aborting) throw new Error("Claude prompt cancelled before acceptance");
1024
1207
  if (session.error instanceof ClaudeProcessTerminationError) throw session.error;
1025
1208
  if (session.error) throw new Error("Claude session persistence failed", { cause: session.error });
@@ -1031,10 +1214,14 @@ var ClaudeCodingAgentAdapter = class {
1031
1214
  }
1032
1215
  const duplicate = operationId === void 0 ? void 0 : session.stored.receipts.find((entry) => entry.operationId === operationId);
1033
1216
  if (duplicate) {
1034
- if (duplicate.prompt !== prompt || duplicate.mode !== mode) throw new Error("Claude operation ID already has different content");
1217
+ if (duplicate.prompt !== prompt || duplicate.mode !== mode || attachments.length || files.length) {
1218
+ throw new Error("Claude operation ID already has different or unverified content");
1219
+ }
1035
1220
  if (duplicate.state === "failed" || duplicate.state === "cancelled") throw new Error("Claude operation already ended; it was not retried");
1036
1221
  return { messageId: duplicate.id, deliveryState: duplicate.state === "queued" ? "queued" : "processing", submittedAt: duplicate.submittedAt };
1037
1222
  }
1223
+ const media = await prepareNativePrompt(this.#directory, identity(id), prompt, attachments, files);
1224
+ if (session.epoch !== epoch || this.#stopping) throw new Error("Claude prompt cancelled before acceptance");
1038
1225
  if (!session.work || mode === "immediate" && session.busy) {
1039
1226
  session.command = await resolveClaudeExecutable(this.#options.command, this.#options.env);
1040
1227
  this.#ready();
@@ -1062,6 +1249,7 @@ var ClaudeCodingAgentAdapter = class {
1062
1249
  ...operationId === void 0 ? {} : { operationId }
1063
1250
  });
1064
1251
  session.stored.receipts.push(receipt);
1252
+ if (media.attachments.length) (session.media ??= /* @__PURE__ */ new Map()).set(receipt.id, media);
1065
1253
  if (mode === "immediate") session.queue.unshift(receipt);
1066
1254
  else session.queue.push(receipt);
1067
1255
  await this.#save(session);
@@ -1130,6 +1318,7 @@ var ClaudeCodingAgentAdapter = class {
1130
1318
  permissionMode: "default",
1131
1319
  abortController: controller,
1132
1320
  spawnClaudeCodeProcess: ownedProcess.spawn,
1321
+ ...session.stored.modelId === CLAUDE_DEFAULT_MODEL_ID ? {} : { model: session.stored.modelId },
1133
1322
  ...session.stored.nativeId ? { resume: session.stored.nativeId } : {},
1134
1323
  ...session.command === void 0 ? {} : { pathToClaudeCodeExecutable: session.command },
1135
1324
  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)
@@ -1146,6 +1335,11 @@ var ClaudeCodingAgentAdapter = class {
1146
1335
  const nativeId = UuidSchema.parse(message.session_id);
1147
1336
  if (session.stored.nativeId && session.stored.nativeId !== nativeId) throw new Error("Claude resumed a different native session");
1148
1337
  session.stored.nativeId = nativeId;
1338
+ if (query.supportedModels && this.#models.length === 1) {
1339
+ void query.supportedModels().then((models) => {
1340
+ if (!this.#stopping && epoch === session.epoch) this.#rememberModels(models);
1341
+ }).catch(() => this.#options.onDiagnostic?.("Claude did not report its model catalog"));
1342
+ }
1149
1343
  } else if (message.session_id && session.stored.nativeId && message.session_id !== session.stored.nativeId) {
1150
1344
  throw new Error("Claude emitted a foreign session");
1151
1345
  }
@@ -1176,6 +1370,7 @@ var ClaudeCodingAgentAdapter = class {
1176
1370
  }
1177
1371
  if (message.type === "system" && message.subtype === "session_state_changed" && message.state === "idle" && session.resultSeen) {
1178
1372
  session.timeline.finish();
1373
+ if (session.active) session.media?.delete(session.active.id);
1179
1374
  session.active = void 0;
1180
1375
  session.busy = false;
1181
1376
  session.resultSeen = false;
@@ -1239,10 +1434,18 @@ var ClaudeCodingAgentAdapter = class {
1239
1434
  receipt.state = "submitted";
1240
1435
  await this.#save(session);
1241
1436
  if (epoch !== session.epoch || this.#stopping) return;
1437
+ const media = session.media?.get(receipt.id);
1438
+ const content = media?.images.length ? [
1439
+ ...media.text ? [{ type: "text", text: media.text }] : [],
1440
+ ...media.images.map(({ data, mimeType }) => ({
1441
+ type: "image",
1442
+ source: { type: "base64", data, media_type: mimeType }
1443
+ }))
1444
+ ] : media?.text ?? receipt.prompt;
1242
1445
  session.input.push({
1243
1446
  type: "user",
1244
1447
  uuid: receipt.id,
1245
- message: { role: "user", content: receipt.prompt },
1448
+ message: { role: "user", content },
1246
1449
  parent_tool_use_id: null,
1247
1450
  priority: receipt.mode === "enqueue" ? "later" : "next",
1248
1451
  client_composed: true,
@@ -1253,6 +1456,8 @@ var ClaudeCodingAgentAdapter = class {
1253
1456
  #confirm(session, id) {
1254
1457
  const receipt = session.stored.receipts.find((entry) => entry.id === id);
1255
1458
  if (!receipt || receipt.state !== "submitted" && receipt.state !== "confirmed") return;
1459
+ const previous = session.stored.items.find((item) => item.id === receipt.id);
1460
+ const attachments = session.media?.get(receipt.id)?.attachments ?? (previous?.kind === "human-message" ? previous.attachments : []);
1256
1461
  receipt.state = "confirmed";
1257
1462
  session.timeline.upsert({
1258
1463
  ...session.timeline.base(receipt.id, receipt.id),
@@ -1261,9 +1466,10 @@ var ClaudeCodingAgentAdapter = class {
1261
1466
  kind: "human-message",
1262
1467
  actor: "human",
1263
1468
  content: receipt.prompt,
1264
- attachments: [],
1469
+ attachments,
1265
1470
  ...receipt.operationId ? { operationId: receipt.operationId } : {}
1266
1471
  });
1472
+ session.media?.delete(receipt.id);
1267
1473
  }
1268
1474
  #retire(session, clearQueue) {
1269
1475
  if (session.active && !session.stored.nativeId) session.stored.unsafe = true;
@@ -1271,10 +1477,12 @@ var ClaudeCodingAgentAdapter = class {
1271
1477
  session.active.state = "cancelled";
1272
1478
  session.timeline.notice(session.active.id, "Prompt interrupted; it was not retried.", "warning");
1273
1479
  }
1480
+ if (session.active) session.media?.delete(session.active.id);
1274
1481
  session.active = void 0;
1275
1482
  if (clearQueue) {
1276
1483
  for (const receipt of session.queue) {
1277
1484
  receipt.state = "cancelled";
1485
+ session.media?.delete(receipt.id);
1278
1486
  session.timeline.notice(receipt.id, "Queued prompt cancelled before delivery.", "warning");
1279
1487
  }
1280
1488
  session.queue = [];
@@ -1362,10 +1570,15 @@ var ClaudeCodingAgentAdapter = class {
1362
1570
  stop() {
1363
1571
  if (this.#stopPromise) return this.#stopPromise;
1364
1572
  this.#stopping = true;
1573
+ this.#modelAbort?.abort();
1365
1574
  this.#stopPromise = this.#stop();
1366
1575
  return this.#stopPromise;
1367
1576
  }
1368
1577
  async #stop() {
1578
+ if (this.#modelRefresh) {
1579
+ const [result] = await Promise.allSettled([this.#modelRefresh]);
1580
+ if (result?.status === "rejected") this.#options.onDiagnostic?.("Claude model discovery could not be stopped cleanly");
1581
+ }
1369
1582
  if (this.#starting && !this.#started) {
1370
1583
  const [result] = await Promise.allSettled([this.#starting]);
1371
1584
  if (result?.status === "rejected") {