@agentknight/sdk 0.9.68 → 0.9.72
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.
- package/dist/chunks/{acp-adapter-RZX5SUB3.js → acp-adapter-PCNN2NAJ.js} +41 -4
- package/dist/chunks/{chunk-Y6NCJB55.js → chunk-23BKGY5J.js} +4 -4
- package/dist/chunks/{chunk-UHRUQM4D.js → chunk-2UHBY25U.js} +1 -1
- package/dist/chunks/{chunk-CFQQOAQV.js → chunk-36KL4FSH.js} +2 -2
- package/dist/chunks/{chunk-FY4XTWUF.js → chunk-5BDFZ3AS.js} +4 -13
- package/dist/chunks/{chunk-DWTXWVIA.js → chunk-5FJJZCP6.js} +683 -629
- package/dist/chunks/{chunk-B777YB6E.js → chunk-DXHAKWGO.js} +2 -2
- package/dist/chunks/{chunk-35OF2ZNS.js → chunk-E5VHBC55.js} +14 -0
- package/dist/chunks/{chunk-MB3H6HEI.js → chunk-FQ26TSDG.js} +2 -2
- package/dist/chunks/{chunk-Q5OUZJCZ.js → chunk-GRUDMHEJ.js} +1 -1
- package/dist/chunks/{chunk-AWVC5NX4.js → chunk-I42IONUU.js} +1 -1
- package/dist/chunks/{chunk-4XT65OSG.js → chunk-KPHWVNKP.js} +46 -3
- package/dist/chunks/{chunk-EDYVCZIR.js → chunk-PAJZL5ST.js} +7 -2
- package/dist/chunks/{chunk-LCA2MWOQ.js → chunk-TFUSRA2B.js} +2 -2
- package/dist/chunks/chunk-UTF7KLMJ.js +11 -0
- package/dist/chunks/chunk-VEJLENEQ.js +174 -0
- package/dist/chunks/chunk-VOR4AECB.js +78 -0
- package/dist/chunks/{claude-adapter-FQSQIYUY.js → claude-adapter-A4LPYQ2Z.js} +296 -223
- package/dist/chunks/{codex-adapter-TOXSRT2W.js → codex-adapter-AFGS7MPX.js} +249 -66
- package/dist/chunks/{copilot-adapter-KUCX7XQW.js → copilot-adapter-NXJTI2HY.js} +27 -70
- package/dist/chunks/{managed-agent-adapter-LGBRXDGP.js → managed-agent-adapter-4C2PWD4V.js} +9 -7
- package/dist/chunks/{pi-adapter-RXNZSE4F.js → pi-adapter-EZOIK5RA.js} +7 -9
- package/dist/configuration.js +4 -4
- package/dist/index.d.ts +153 -8
- package/dist/index.js +183 -57
- package/dist/runtime.js +2 -2
- package/dist/session-analytics-worker.js +6 -7
- package/package.json +2 -3
- package/dist/chunks/chunk-IXGVSREH.js +0 -48
- package/dist/chunks/chunk-T6226JFS.js +0 -55
|
@@ -1,28 +1,40 @@
|
|
|
1
1
|
import {
|
|
2
|
-
hasClaudeProviderConfiguration
|
|
3
|
-
|
|
2
|
+
hasClaudeProviderConfiguration,
|
|
3
|
+
resolveClaudeExecutable
|
|
4
|
+
} from "./chunk-VEJLENEQ.js";
|
|
4
5
|
import {
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
prepareNativePrompt,
|
|
7
|
+
projectNativeImage
|
|
8
|
+
} from "./chunk-VOR4AECB.js";
|
|
9
|
+
import "./chunk-UTF7KLMJ.js";
|
|
10
|
+
import "./chunk-DXHAKWGO.js";
|
|
11
|
+
import "./chunk-E5VHBC55.js";
|
|
7
12
|
import {
|
|
13
|
+
latestPreviewItems,
|
|
14
|
+
splitTimelineImages
|
|
15
|
+
} from "./chunk-KPHWVNKP.js";
|
|
16
|
+
import {
|
|
17
|
+
SessionDeletionRejectedError,
|
|
8
18
|
UnsupportedAgentOperationError,
|
|
9
19
|
validateSessionName
|
|
10
|
-
} from "./chunk-
|
|
11
|
-
import "./chunk-
|
|
20
|
+
} from "./chunk-36KL4FSH.js";
|
|
21
|
+
import "./chunk-2UHBY25U.js";
|
|
12
22
|
import {
|
|
13
23
|
ConversationItemSchema,
|
|
14
24
|
InteractionRequestSchema,
|
|
15
25
|
InteractionResponseSchema,
|
|
16
26
|
SESSION_TIMELINE_PAGE_SIZE,
|
|
17
27
|
SessionSummarySchema
|
|
18
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-5FJJZCP6.js";
|
|
19
29
|
|
|
20
30
|
// src/claude-adapter.ts
|
|
31
|
+
import { execFile } from "node:child_process";
|
|
21
32
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
22
|
-
import { mkdir, readFile
|
|
23
|
-
import { homedir
|
|
24
|
-
import { isAbsolute
|
|
25
|
-
import {
|
|
33
|
+
import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
34
|
+
import { homedir } from "node:os";
|
|
35
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
36
|
+
import { promisify } from "node:util";
|
|
37
|
+
import { z as z4 } from "zod";
|
|
26
38
|
|
|
27
39
|
// src/adapters/claude/input.ts
|
|
28
40
|
var ClaudeInput = class {
|
|
@@ -196,6 +208,20 @@ var BlockSchema = z2.object({
|
|
|
196
208
|
tool_use_id: z2.string().optional(),
|
|
197
209
|
is_error: z2.boolean().optional()
|
|
198
210
|
}).passthrough();
|
|
211
|
+
var ImageBlock = z2.object({
|
|
212
|
+
type: z2.literal("image"),
|
|
213
|
+
source: z2.object({ type: z2.literal("base64"), data: z2.string(), media_type: z2.string() })
|
|
214
|
+
});
|
|
215
|
+
function imagesFrom(value) {
|
|
216
|
+
if (!Array.isArray(value)) return [];
|
|
217
|
+
return value.flatMap((part) => {
|
|
218
|
+
const parsed = ImageBlock.safeParse(part);
|
|
219
|
+
if (!parsed.success) return [];
|
|
220
|
+
const source = parsed.data.source;
|
|
221
|
+
const image = projectNativeImage(source.data, source.media_type);
|
|
222
|
+
return image ? [image] : [];
|
|
223
|
+
});
|
|
224
|
+
}
|
|
199
225
|
var ClaudeTimeline = class {
|
|
200
226
|
constructor(sessionId, items, publish) {
|
|
201
227
|
this.sessionId = sessionId;
|
|
@@ -270,6 +296,7 @@ var ClaudeTimeline = class {
|
|
|
270
296
|
const source = message.uuid ?? turnId;
|
|
271
297
|
if (message.type === "assistant") {
|
|
272
298
|
const body = z2.object({ id: z2.string(), content: z2.array(BlockSchema) }).parse(message.message);
|
|
299
|
+
this.#images(body.id, turnId, imagesFrom(body.content));
|
|
273
300
|
body.content.forEach((block, index) => {
|
|
274
301
|
if (block.type === "text" && block.text !== void 0) {
|
|
275
302
|
this.#text(body.id, index, block.text, true, turnId);
|
|
@@ -283,21 +310,23 @@ var ClaudeTimeline = class {
|
|
|
283
310
|
const body = z2.object({ content: z2.unknown() }).parse(message.message);
|
|
284
311
|
const blocks = Array.isArray(body.content) ? body.content.map((block) => BlockSchema.parse(block)) : [];
|
|
285
312
|
const text = typeof body.content === "string" ? body.content : blocks.filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n");
|
|
313
|
+
const attachments = splitTimelineImages(imagesFrom(blocks), (image) => image.byteLength ?? 0)[0] ?? [];
|
|
286
314
|
const uuid = message.uuid;
|
|
287
|
-
if (text && uuid && !this.items.some((item) => item.id === sourceId(uuid))) {
|
|
315
|
+
if ((text || attachments.length) && uuid && !this.items.some((item) => item.id === sourceId(uuid))) {
|
|
288
316
|
this.upsert({
|
|
289
317
|
...this.base(uuid, turnId),
|
|
290
318
|
sourceMessageIds: [sourceId(uuid)],
|
|
291
319
|
kind: "human-message",
|
|
292
320
|
actor: "human",
|
|
293
321
|
content: text,
|
|
294
|
-
attachments
|
|
322
|
+
attachments
|
|
295
323
|
});
|
|
296
324
|
}
|
|
297
325
|
if (!Array.isArray(body.content)) return;
|
|
298
326
|
for (const block of blocks) {
|
|
299
327
|
if (block.type === "tool_result" && block.tool_use_id) {
|
|
300
328
|
this.#tool(block.tool_use_id, void 0, block.is_error ? "failed" : "completed", turnId);
|
|
329
|
+
this.#images(block.tool_use_id, turnId, imagesFrom(block.content));
|
|
301
330
|
}
|
|
302
331
|
}
|
|
303
332
|
} else if (message.type === "tool_progress") {
|
|
@@ -359,6 +388,20 @@ var ClaudeTimeline = class {
|
|
|
359
388
|
final
|
|
360
389
|
});
|
|
361
390
|
}
|
|
391
|
+
#images(source, turnId, images) {
|
|
392
|
+
const unique = [...new Map(images.map((image) => [image.sha256, image])).values()];
|
|
393
|
+
splitTimelineImages(unique, (image) => image.byteLength ?? 0).forEach((attachments, index) => {
|
|
394
|
+
const id = identity(`${this.sessionId}:images:${source}:${index}`);
|
|
395
|
+
this.upsert({
|
|
396
|
+
...this.base(id, turnId),
|
|
397
|
+
kind: "assistant-message",
|
|
398
|
+
actor: "assistant",
|
|
399
|
+
content: "",
|
|
400
|
+
final: true,
|
|
401
|
+
attachments
|
|
402
|
+
});
|
|
403
|
+
});
|
|
404
|
+
}
|
|
362
405
|
#tool(toolId, name, status, turnId) {
|
|
363
406
|
const id = identity(`${this.sessionId}:tool:${toolId}`);
|
|
364
407
|
const previous = this.items.find((item) => item.id === id);
|
|
@@ -473,180 +516,41 @@ var ClaudeProcess = class {
|
|
|
473
516
|
}
|
|
474
517
|
};
|
|
475
518
|
|
|
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
|
-
|
|
617
519
|
// src/claude-adapter.ts
|
|
618
520
|
var CLAUDE_DEFAULT_MODEL_ID = "claude:agent-default";
|
|
619
|
-
var UuidSchema =
|
|
620
|
-
var ReceiptSchema =
|
|
521
|
+
var UuidSchema = z4.custom((value) => z4.uuid().safeParse(value).success);
|
|
522
|
+
var ReceiptSchema = z4.object({
|
|
621
523
|
id: UuidSchema,
|
|
622
|
-
prompt:
|
|
623
|
-
mode:
|
|
624
|
-
submittedAt:
|
|
625
|
-
operationId:
|
|
626
|
-
state:
|
|
524
|
+
prompt: z4.string().max(1e5),
|
|
525
|
+
mode: z4.enum(["enqueue", "immediate"]),
|
|
526
|
+
submittedAt: z4.iso.datetime(),
|
|
527
|
+
operationId: z4.string().min(1).max(256).optional(),
|
|
528
|
+
state: z4.enum(["queued", "submitted", "confirmed", "completed", "cancelled", "failed"])
|
|
627
529
|
});
|
|
628
|
-
var
|
|
629
|
-
|
|
530
|
+
var modelCatalog = z4.array(z4.object({ value: z4.string().min(1).max(240), displayName: z4.string().min(1).max(260) })).max(250);
|
|
531
|
+
var defaultModel = { id: CLAUDE_DEFAULT_MODEL_ID, name: "Claude agent default", isDefault: true };
|
|
532
|
+
var StoredSchema = z4.object({
|
|
533
|
+
version: z4.literal(1),
|
|
630
534
|
summary: SessionSummarySchema,
|
|
631
535
|
nativeId: UuidSchema.optional(),
|
|
632
|
-
modelId:
|
|
633
|
-
nativeDirectory:
|
|
634
|
-
items:
|
|
635
|
-
receipts:
|
|
636
|
-
unsafe:
|
|
536
|
+
modelId: z4.string().min(1).max(256),
|
|
537
|
+
nativeDirectory: z4.string().min(1).optional(),
|
|
538
|
+
items: z4.array(ConversationItemSchema),
|
|
539
|
+
receipts: z4.array(ReceiptSchema),
|
|
540
|
+
unsafe: z4.boolean()
|
|
637
541
|
}).refine((stored) => stored.nativeDirectory === void 0 || stored.nativeId !== void 0 && stored.summary.sessionId === `claude:native:${stored.nativeId}`, {
|
|
638
542
|
message: "Invalid Claude native session identity"
|
|
639
543
|
});
|
|
640
|
-
var MessageSchema =
|
|
641
|
-
type:
|
|
642
|
-
subtype:
|
|
643
|
-
uuid:
|
|
644
|
-
session_id:
|
|
645
|
-
state:
|
|
646
|
-
user_message_uuid:
|
|
647
|
-
user_message_uuids:
|
|
648
|
-
parent_tool_use_id:
|
|
649
|
-
is_error:
|
|
544
|
+
var MessageSchema = z4.object({
|
|
545
|
+
type: z4.string(),
|
|
546
|
+
subtype: z4.string().optional(),
|
|
547
|
+
uuid: z4.string().optional(),
|
|
548
|
+
session_id: z4.string().optional(),
|
|
549
|
+
state: z4.string().optional(),
|
|
550
|
+
user_message_uuid: z4.string().optional(),
|
|
551
|
+
user_message_uuids: z4.array(z4.string()).optional(),
|
|
552
|
+
parent_tool_use_id: z4.string().nullable().optional(),
|
|
553
|
+
is_error: z4.boolean().optional()
|
|
650
554
|
}).passthrough();
|
|
651
555
|
var ClaudeCodingAgentAdapter = class {
|
|
652
556
|
agentId = "claude";
|
|
@@ -655,8 +559,11 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
655
559
|
supportsReasoningEffort = false;
|
|
656
560
|
supportsSessionListUpdates = true;
|
|
657
561
|
supportsAssistantPreview = true;
|
|
658
|
-
supportsSessionDelete =
|
|
659
|
-
supportsFileAttachments =
|
|
562
|
+
supportsSessionDelete = true;
|
|
563
|
+
supportsFileAttachments = true;
|
|
564
|
+
#models = [defaultModel];
|
|
565
|
+
#modelRefresh;
|
|
566
|
+
#modelAbort;
|
|
660
567
|
groupChatEnabled = false;
|
|
661
568
|
#options;
|
|
662
569
|
#directory;
|
|
@@ -682,7 +589,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
682
589
|
if (options.nativeSessionOwner !== void 0) {
|
|
683
590
|
SessionSummarySchema.pick({ userId: true, machineId: true }).parse(options.nativeSessionOwner);
|
|
684
591
|
}
|
|
685
|
-
this.#directory =
|
|
592
|
+
this.#directory = join(resolve(options.dataDirectory), "claude");
|
|
686
593
|
this.#interactions = new ClaudeInteractions(() => this.#callbacks, timeout);
|
|
687
594
|
}
|
|
688
595
|
setSessionCallbacks(callbacks) {
|
|
@@ -695,10 +602,10 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
695
602
|
}
|
|
696
603
|
async #start() {
|
|
697
604
|
await mkdir(this.#directory, { recursive: true, mode: 448 });
|
|
698
|
-
await mkdir(
|
|
605
|
+
await mkdir(join(this.#directory, "native"), { recursive: true, mode: 448 });
|
|
699
606
|
for (const file of await readdir(this.#directory)) {
|
|
700
607
|
if (!/^[a-f0-9]{64}\.json$/.test(file)) continue;
|
|
701
|
-
const raw = JSON.parse(await
|
|
608
|
+
const raw = JSON.parse(await readFile(join(this.#directory, file), "utf8"));
|
|
702
609
|
const stored = StoredSchema.parse(raw);
|
|
703
610
|
if (!stored.summary.sessionId.startsWith("claude:") || `${identity(stored.summary.sessionId)}.json` !== file) {
|
|
704
611
|
throw new Error("Invalid Claude session ownership record");
|
|
@@ -764,7 +671,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
764
671
|
return "claude:host-owned";
|
|
765
672
|
}
|
|
766
673
|
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);
|
|
674
|
+
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
675
|
}
|
|
769
676
|
async listSessions(userId, machineId) {
|
|
770
677
|
this.#ready();
|
|
@@ -777,13 +684,13 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
777
684
|
}
|
|
778
685
|
async #scanNative(owner) {
|
|
779
686
|
const sdk = await this.#nativeSessions();
|
|
780
|
-
const sessions =
|
|
687
|
+
const sessions = z4.array(z4.object({
|
|
781
688
|
sessionId: UuidSchema,
|
|
782
|
-
summary:
|
|
783
|
-
customTitle:
|
|
784
|
-
lastModified:
|
|
785
|
-
createdAt:
|
|
786
|
-
cwd:
|
|
689
|
+
summary: z4.string(),
|
|
690
|
+
customTitle: z4.string().optional(),
|
|
691
|
+
lastModified: z4.number(),
|
|
692
|
+
createdAt: z4.number().optional(),
|
|
693
|
+
cwd: z4.string().optional()
|
|
787
694
|
})).parse(await sdk.listSessions({ includeProgrammatic: true }));
|
|
788
695
|
this.#ready();
|
|
789
696
|
const next = /* @__PURE__ */ new Map();
|
|
@@ -816,7 +723,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
816
723
|
version: 1,
|
|
817
724
|
summary,
|
|
818
725
|
nativeId: native.sessionId,
|
|
819
|
-
nativeDirectory: resolve(env.CLAUDE_CONFIG_DIR ||
|
|
726
|
+
nativeDirectory: resolve(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude")),
|
|
820
727
|
modelId: CLAUDE_DEFAULT_MODEL_ID,
|
|
821
728
|
items: [],
|
|
822
729
|
receipts: [],
|
|
@@ -836,17 +743,82 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
836
743
|
if (session.work || session.operations || session.cancellations || session.aborting || session.stored.unsafe || session.error) continue;
|
|
837
744
|
this.#sessions.delete(id);
|
|
838
745
|
this.#retiredSessions.add(id);
|
|
839
|
-
await rm(
|
|
746
|
+
await rm(join(this.#directory, `${identity(id)}.json`));
|
|
840
747
|
}
|
|
841
748
|
}
|
|
842
749
|
}
|
|
843
|
-
async listModels() {
|
|
750
|
+
async listModels(id) {
|
|
844
751
|
this.#ready();
|
|
845
|
-
|
|
846
|
-
|
|
752
|
+
const session = id === void 0 ? void 0 : this.#known(id);
|
|
753
|
+
const path = await resolveClaudeExecutable(this.#options.command, this.#options.env);
|
|
754
|
+
this.#ready();
|
|
755
|
+
if (this.#models.length === 1 && !this.#options.sdk && !this.#modelRefresh) {
|
|
756
|
+
this.#modelRefresh = this.#refreshModels(path).finally(() => {
|
|
757
|
+
this.#modelRefresh = void 0;
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
await this.#modelRefresh;
|
|
761
|
+
const selected = session?.stored.modelId;
|
|
762
|
+
return selected && !this.#models.some((model) => model.id === selected) ? [...this.#models, { id: selected, name: selected, isDefault: false }] : [...this.#models];
|
|
847
763
|
}
|
|
848
|
-
|
|
849
|
-
|
|
764
|
+
async #refreshModels(path) {
|
|
765
|
+
const controller = new AbortController();
|
|
766
|
+
this.#modelAbort = controller;
|
|
767
|
+
const timer = setTimeout(() => controller.abort(new Error("Claude model discovery timed out")), 5e3);
|
|
768
|
+
const owned = new ClaudeProcess();
|
|
769
|
+
let query;
|
|
770
|
+
try {
|
|
771
|
+
const cwd = join(this.#directory, "native");
|
|
772
|
+
const env = prepareClaudeEnvironment(this.#options.env ?? process.env, cwd);
|
|
773
|
+
const sdk = await import("@anthropic-ai/claude-agent-sdk");
|
|
774
|
+
this.#ready();
|
|
775
|
+
controller.signal.throwIfAborted();
|
|
776
|
+
const input = new ClaudeInput();
|
|
777
|
+
try {
|
|
778
|
+
query = sdk.query({
|
|
779
|
+
prompt: input,
|
|
780
|
+
options: {
|
|
781
|
+
cwd,
|
|
782
|
+
env,
|
|
783
|
+
pathToClaudeCodeExecutable: path,
|
|
784
|
+
spawnClaudeCodeProcess: owned.spawn,
|
|
785
|
+
abortController: controller,
|
|
786
|
+
persistSession: false,
|
|
787
|
+
settingSources: [],
|
|
788
|
+
tools: []
|
|
789
|
+
}
|
|
790
|
+
});
|
|
791
|
+
this.#rememberModels(await query.supportedModels?.());
|
|
792
|
+
} finally {
|
|
793
|
+
input.close();
|
|
794
|
+
}
|
|
795
|
+
} catch (error) {
|
|
796
|
+
this.#options.onDiagnostic?.(`Claude model list unavailable: ${error instanceof Error ? error.message : "unknown error"}`);
|
|
797
|
+
} finally {
|
|
798
|
+
clearTimeout(timer);
|
|
799
|
+
controller.abort();
|
|
800
|
+
query?.close();
|
|
801
|
+
try {
|
|
802
|
+
await owned.finish(this.#options.processExitTimeoutMs ?? 5e3);
|
|
803
|
+
} finally {
|
|
804
|
+
this.#modelAbort = void 0;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
#rememberModels(raw) {
|
|
809
|
+
const parsed = modelCatalog.safeParse(raw);
|
|
810
|
+
if (!parsed.success) return;
|
|
811
|
+
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()];
|
|
812
|
+
}
|
|
813
|
+
getSessionCapabilities(id) {
|
|
814
|
+
return {
|
|
815
|
+
agentModes: this.agentModes,
|
|
816
|
+
supportsReasoningEffort: false,
|
|
817
|
+
supportsFileAttachments: true,
|
|
818
|
+
agentName: "Claude",
|
|
819
|
+
supportsPlanRead: false,
|
|
820
|
+
supportsSessionDelete: id === void 0 || !this.#known(id).stored.nativeDirectory
|
|
821
|
+
};
|
|
850
822
|
}
|
|
851
823
|
async getSessionConfiguration(id) {
|
|
852
824
|
return { modelId: this.#known(id).stored.modelId, agentMode: "interactive", reasoningEffort: "default" };
|
|
@@ -870,8 +842,54 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
870
842
|
return this.getSessionRemoteStatus(id);
|
|
871
843
|
}
|
|
872
844
|
async deleteSession(id) {
|
|
873
|
-
this.#known(id);
|
|
874
|
-
|
|
845
|
+
const session = this.#known(id);
|
|
846
|
+
const reject = (message) => {
|
|
847
|
+
throw new SessionDeletionRejectedError(message);
|
|
848
|
+
};
|
|
849
|
+
if (session.stored.nativeDirectory) reject("Delete sessions created in standalone Claude Code there");
|
|
850
|
+
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");
|
|
851
|
+
session.operations++;
|
|
852
|
+
const work = session.lock.then(async () => {
|
|
853
|
+
const { nativeId, summary } = session.stored;
|
|
854
|
+
const dir = summary.workingDirectory;
|
|
855
|
+
if (nativeId && !dir) return reject("Claude session has no known project directory");
|
|
856
|
+
if (session.work) {
|
|
857
|
+
try {
|
|
858
|
+
await this.#cancel(session, false);
|
|
859
|
+
} catch {
|
|
860
|
+
return reject("Claude process exit could not be verified");
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
this.#known(id);
|
|
864
|
+
if (nativeId && dir) {
|
|
865
|
+
const config = join(this.#directory, "native");
|
|
866
|
+
const injected = this.#options.nativeSessions?.deleteOwnedSession;
|
|
867
|
+
if (injected) await injected(nativeId, dir, config);
|
|
868
|
+
else await promisify(execFile)(process.execPath, [
|
|
869
|
+
"--input-type=module",
|
|
870
|
+
"-e",
|
|
871
|
+
"const [sdk, id, dir] = process.argv.slice(1); await (await import(sdk)).deleteSession(id, {dir});",
|
|
872
|
+
import.meta.resolve("@anthropic-ai/claude-agent-sdk"),
|
|
873
|
+
nativeId,
|
|
874
|
+
dir
|
|
875
|
+
], {
|
|
876
|
+
env: { CLAUDE_CONFIG_DIR: config, SystemRoot: process.env.SystemRoot },
|
|
877
|
+
timeout: 1e4,
|
|
878
|
+
windowsHide: true
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
await session.saving;
|
|
882
|
+
await rm(join(this.#directory, `${identity(id)}.json`));
|
|
883
|
+
this.#sessions.delete(id);
|
|
884
|
+
this.#retiredSessions.add(id);
|
|
885
|
+
this.#callbacks?.onSessionInventoryChanged(id);
|
|
886
|
+
});
|
|
887
|
+
session.lock = work.then(() => void 0, () => void 0);
|
|
888
|
+
try {
|
|
889
|
+
await work;
|
|
890
|
+
} finally {
|
|
891
|
+
session.operations--;
|
|
892
|
+
}
|
|
875
893
|
}
|
|
876
894
|
async readSessionPlan(id) {
|
|
877
895
|
this.#known(id);
|
|
@@ -892,12 +910,12 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
892
910
|
if (options.agentMode !== void 0 && options.agentMode !== "interactive") this.#unsupported("agent modes");
|
|
893
911
|
if (options.reasoningEffort !== void 0 && options.reasoningEffort !== "default") this.#unsupported("reasoning controls");
|
|
894
912
|
if (options.configOption !== void 0) this.#unsupported("configuration options");
|
|
895
|
-
if (options.modelId !== void 0 && options.modelId
|
|
913
|
+
if (options.modelId !== void 0 && !this.#models.some((model) => model.id === options.modelId)) this.#unsupported("model selection");
|
|
896
914
|
}
|
|
897
915
|
async createSession(options) {
|
|
898
916
|
this.#ready();
|
|
899
917
|
this.#validate(options);
|
|
900
|
-
if (!
|
|
918
|
+
if (!isAbsolute(options.workingDirectory)) throw new Error("Claude working directory must be absolute");
|
|
901
919
|
await resolveClaudeExecutable(this.#options.command, this.#options.env);
|
|
902
920
|
this.#ready();
|
|
903
921
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
@@ -918,9 +936,31 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
918
936
|
return structuredClone(summary);
|
|
919
937
|
}
|
|
920
938
|
async configureSession(id, options) {
|
|
921
|
-
this.#known(id);
|
|
939
|
+
const session = this.#known(id);
|
|
922
940
|
this.#validate(options);
|
|
923
|
-
|
|
941
|
+
const model = options.modelId;
|
|
942
|
+
if (model === void 0 || model === session.stored.modelId) return this.getSessionConfiguration(id);
|
|
943
|
+
if (session.busy || session.background || session.operations || session.queue.length || session.aborting) {
|
|
944
|
+
throw new Error("Wait for the Claude session to become idle before changing models");
|
|
945
|
+
}
|
|
946
|
+
session.operations++;
|
|
947
|
+
const change = session.lock.then(async () => {
|
|
948
|
+
this.#known(id);
|
|
949
|
+
if (session.work) {
|
|
950
|
+
if (!session.query?.setModel) this.#unsupported("changing the active model");
|
|
951
|
+
await session.query.setModel(model === CLAUDE_DEFAULT_MODEL_ID ? void 0 : model);
|
|
952
|
+
}
|
|
953
|
+
if (this.#discovered.delete(id)) this.#sessions.set(id, session);
|
|
954
|
+
session.stored.modelId = model;
|
|
955
|
+
await this.#save(session);
|
|
956
|
+
return this.getSessionConfiguration(id);
|
|
957
|
+
});
|
|
958
|
+
session.lock = change.then(() => void 0, () => void 0);
|
|
959
|
+
try {
|
|
960
|
+
return await change;
|
|
961
|
+
} finally {
|
|
962
|
+
session.operations--;
|
|
963
|
+
}
|
|
924
964
|
}
|
|
925
965
|
async renameSession(id, name, assertAccess) {
|
|
926
966
|
const session = this.#known(id);
|
|
@@ -974,14 +1014,14 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
974
1014
|
const sdk = await this.#nativeSessions();
|
|
975
1015
|
const nativeId = UuidSchema.parse(session.stored.nativeId);
|
|
976
1016
|
const raw = await sdk.getSessionMessages(nativeId, this.#nativeReadOptions(session));
|
|
977
|
-
const messages =
|
|
978
|
-
type:
|
|
979
|
-
uuid:
|
|
1017
|
+
const messages = z4.array(z4.object({
|
|
1018
|
+
type: z4.enum(["user", "assistant", "system"]),
|
|
1019
|
+
uuid: z4.string(),
|
|
980
1020
|
session_id: UuidSchema,
|
|
981
|
-
message:
|
|
982
|
-
timestamp:
|
|
983
|
-
parent_tool_use_id:
|
|
984
|
-
parent_agent_id:
|
|
1021
|
+
message: z4.unknown(),
|
|
1022
|
+
timestamp: z4.iso.datetime().optional(),
|
|
1023
|
+
parent_tool_use_id: z4.string().nullable(),
|
|
1024
|
+
parent_agent_id: z4.string().nullable()
|
|
985
1025
|
}).passthrough()).parse(raw);
|
|
986
1026
|
this.#known(session.stored.summary.sessionId);
|
|
987
1027
|
const items = [];
|
|
@@ -991,8 +1031,8 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
991
1031
|
if (message.session_id !== nativeId) throw new Error("Claude returned history for another native session");
|
|
992
1032
|
if (message.parent_agent_id || message.parent_tool_use_id) continue;
|
|
993
1033
|
if (message.type === "user") {
|
|
994
|
-
const body =
|
|
995
|
-
if (typeof body.content === "string" || Array.isArray(body.content) && body.content.some((block) =>
|
|
1034
|
+
const body = z4.object({ content: z4.unknown() }).parse(message.message);
|
|
1035
|
+
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;
|
|
996
1036
|
}
|
|
997
1037
|
timeline.project({ ...message, timestamp: message.timestamp ?? session.stored.summary.createdAt }, turnId);
|
|
998
1038
|
}
|
|
@@ -1003,6 +1043,10 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1003
1043
|
if (previous.kind === "human-message" && candidate.kind === "human-message" && previous.operationId) {
|
|
1004
1044
|
candidate.operationId = previous.operationId;
|
|
1005
1045
|
}
|
|
1046
|
+
if (previous.kind === "human-message" && candidate.kind === "human-message" && previous.attachments?.length) {
|
|
1047
|
+
candidate.content = previous.content;
|
|
1048
|
+
candidate.attachments = previous.attachments;
|
|
1049
|
+
}
|
|
1006
1050
|
if (JSON.stringify(candidate) !== JSON.stringify(previous)) candidate.revision++;
|
|
1007
1051
|
return candidate;
|
|
1008
1052
|
});
|
|
@@ -1012,14 +1056,13 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1012
1056
|
}
|
|
1013
1057
|
async sendPrompt(id, prompt, mode, attachments = [], _persistInteractions = true, files = [], operationId, avatar) {
|
|
1014
1058
|
const session = this.#known(id);
|
|
1015
|
-
if (attachments.length || files.length) this.#unsupported("attachments");
|
|
1016
1059
|
if (avatar !== void 0) this.#unsupported("avatar personas");
|
|
1017
|
-
if (!prompt.trim() || prompt.length > 1e5) throw new Error("Invalid Claude prompt");
|
|
1060
|
+
if (!prompt.trim() && !attachments.length && !files.length || prompt.length > 1e5) throw new Error("Invalid Claude prompt");
|
|
1018
1061
|
if (session.aborting) throw new Error("Claude cancellation is still settling");
|
|
1019
1062
|
session.operations++;
|
|
1020
1063
|
const epoch = session.epoch;
|
|
1021
1064
|
const run = session.lock.then(async () => {
|
|
1022
|
-
this.#
|
|
1065
|
+
this.#known(id);
|
|
1023
1066
|
if (session.epoch !== epoch || session.aborting) throw new Error("Claude prompt cancelled before acceptance");
|
|
1024
1067
|
if (session.error instanceof ClaudeProcessTerminationError) throw session.error;
|
|
1025
1068
|
if (session.error) throw new Error("Claude session persistence failed", { cause: session.error });
|
|
@@ -1027,14 +1070,18 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1027
1070
|
if (session.stored.nativeDirectory) {
|
|
1028
1071
|
this.#environment(session);
|
|
1029
1072
|
const directory = session.stored.summary.workingDirectory;
|
|
1030
|
-
if (!directory || !
|
|
1073
|
+
if (!directory || !isAbsolute(directory)) throw new Error("Claude native session working directory is unavailable; open it in the CLI first");
|
|
1031
1074
|
}
|
|
1032
1075
|
const duplicate = operationId === void 0 ? void 0 : session.stored.receipts.find((entry) => entry.operationId === operationId);
|
|
1033
1076
|
if (duplicate) {
|
|
1034
|
-
if (duplicate.prompt !== prompt || duplicate.mode !== mode
|
|
1077
|
+
if (duplicate.prompt !== prompt || duplicate.mode !== mode || attachments.length || files.length) {
|
|
1078
|
+
throw new Error("Claude operation ID already has different or unverified content");
|
|
1079
|
+
}
|
|
1035
1080
|
if (duplicate.state === "failed" || duplicate.state === "cancelled") throw new Error("Claude operation already ended; it was not retried");
|
|
1036
1081
|
return { messageId: duplicate.id, deliveryState: duplicate.state === "queued" ? "queued" : "processing", submittedAt: duplicate.submittedAt };
|
|
1037
1082
|
}
|
|
1083
|
+
const media = await prepareNativePrompt(this.#directory, identity(id), prompt, attachments, files);
|
|
1084
|
+
if (session.epoch !== epoch || this.#stopping) throw new Error("Claude prompt cancelled before acceptance");
|
|
1038
1085
|
if (!session.work || mode === "immediate" && session.busy) {
|
|
1039
1086
|
session.command = await resolveClaudeExecutable(this.#options.command, this.#options.env);
|
|
1040
1087
|
this.#ready();
|
|
@@ -1062,6 +1109,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1062
1109
|
...operationId === void 0 ? {} : { operationId }
|
|
1063
1110
|
});
|
|
1064
1111
|
session.stored.receipts.push(receipt);
|
|
1112
|
+
if (media.attachments.length) (session.media ??= /* @__PURE__ */ new Map()).set(receipt.id, media);
|
|
1065
1113
|
if (mode === "immediate") session.queue.unshift(receipt);
|
|
1066
1114
|
else session.queue.push(receipt);
|
|
1067
1115
|
await this.#save(session);
|
|
@@ -1104,7 +1152,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1104
1152
|
#environment(session) {
|
|
1105
1153
|
return prepareClaudeEnvironment(
|
|
1106
1154
|
this.#options.env ?? process.env,
|
|
1107
|
-
session.stored.nativeDirectory ??
|
|
1155
|
+
session.stored.nativeDirectory ?? join(this.#directory, "native")
|
|
1108
1156
|
);
|
|
1109
1157
|
}
|
|
1110
1158
|
async #consume(session, epoch) {
|
|
@@ -1130,6 +1178,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1130
1178
|
permissionMode: "default",
|
|
1131
1179
|
abortController: controller,
|
|
1132
1180
|
spawnClaudeCodeProcess: ownedProcess.spawn,
|
|
1181
|
+
...session.stored.modelId === CLAUDE_DEFAULT_MODEL_ID ? {} : { model: session.stored.modelId },
|
|
1133
1182
|
...session.stored.nativeId ? { resume: session.stored.nativeId } : {},
|
|
1134
1183
|
...session.command === void 0 ? {} : { pathToClaudeCodeExecutable: session.command },
|
|
1135
1184
|
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 +1195,11 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1146
1195
|
const nativeId = UuidSchema.parse(message.session_id);
|
|
1147
1196
|
if (session.stored.nativeId && session.stored.nativeId !== nativeId) throw new Error("Claude resumed a different native session");
|
|
1148
1197
|
session.stored.nativeId = nativeId;
|
|
1198
|
+
if (query.supportedModels && this.#models.length === 1) {
|
|
1199
|
+
void query.supportedModels().then((models) => {
|
|
1200
|
+
if (!this.#stopping && epoch === session.epoch) this.#rememberModels(models);
|
|
1201
|
+
}).catch(() => this.#options.onDiagnostic?.("Claude did not report its model catalog"));
|
|
1202
|
+
}
|
|
1149
1203
|
} else if (message.session_id && session.stored.nativeId && message.session_id !== session.stored.nativeId) {
|
|
1150
1204
|
throw new Error("Claude emitted a foreign session");
|
|
1151
1205
|
}
|
|
@@ -1158,7 +1212,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1158
1212
|
for (const receiptId of confirmations) this.#confirm(session, receiptId);
|
|
1159
1213
|
session.timeline.project(raw, turnId);
|
|
1160
1214
|
if (message.type === "result") {
|
|
1161
|
-
const isError =
|
|
1215
|
+
const isError = z4.boolean().parse(message.is_error);
|
|
1162
1216
|
session.resultSeen = true;
|
|
1163
1217
|
if (session.active) session.active.state = isError ? "failed" : "completed";
|
|
1164
1218
|
if (isError) {
|
|
@@ -1167,7 +1221,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1167
1221
|
}
|
|
1168
1222
|
}
|
|
1169
1223
|
if (message.type === "system" && message.subtype === "background_tasks_changed") {
|
|
1170
|
-
const background =
|
|
1224
|
+
const background = z4.object({ tasks: z4.array(z4.unknown()) }).safeParse(message);
|
|
1171
1225
|
session.background = !background.success || background.data.tasks.length > 0;
|
|
1172
1226
|
}
|
|
1173
1227
|
if (message.type === "system" && message.subtype === "session_state_changed" && (message.state === "running" || message.state === "requires_action")) {
|
|
@@ -1176,6 +1230,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1176
1230
|
}
|
|
1177
1231
|
if (message.type === "system" && message.subtype === "session_state_changed" && message.state === "idle" && session.resultSeen) {
|
|
1178
1232
|
session.timeline.finish();
|
|
1233
|
+
if (session.active) session.media?.delete(session.active.id);
|
|
1179
1234
|
session.active = void 0;
|
|
1180
1235
|
session.busy = false;
|
|
1181
1236
|
session.resultSeen = false;
|
|
@@ -1239,10 +1294,18 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1239
1294
|
receipt.state = "submitted";
|
|
1240
1295
|
await this.#save(session);
|
|
1241
1296
|
if (epoch !== session.epoch || this.#stopping) return;
|
|
1297
|
+
const media = session.media?.get(receipt.id);
|
|
1298
|
+
const content = media?.images.length ? [
|
|
1299
|
+
...media.text ? [{ type: "text", text: media.text }] : [],
|
|
1300
|
+
...media.images.map(({ data, mimeType }) => ({
|
|
1301
|
+
type: "image",
|
|
1302
|
+
source: { type: "base64", data, media_type: mimeType }
|
|
1303
|
+
}))
|
|
1304
|
+
] : media?.text ?? receipt.prompt;
|
|
1242
1305
|
session.input.push({
|
|
1243
1306
|
type: "user",
|
|
1244
1307
|
uuid: receipt.id,
|
|
1245
|
-
message: { role: "user", content
|
|
1308
|
+
message: { role: "user", content },
|
|
1246
1309
|
parent_tool_use_id: null,
|
|
1247
1310
|
priority: receipt.mode === "enqueue" ? "later" : "next",
|
|
1248
1311
|
client_composed: true,
|
|
@@ -1253,6 +1316,8 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1253
1316
|
#confirm(session, id) {
|
|
1254
1317
|
const receipt = session.stored.receipts.find((entry) => entry.id === id);
|
|
1255
1318
|
if (!receipt || receipt.state !== "submitted" && receipt.state !== "confirmed") return;
|
|
1319
|
+
const previous = session.stored.items.find((item) => item.id === receipt.id);
|
|
1320
|
+
const attachments = session.media?.get(receipt.id)?.attachments ?? (previous?.kind === "human-message" ? previous.attachments : []);
|
|
1256
1321
|
receipt.state = "confirmed";
|
|
1257
1322
|
session.timeline.upsert({
|
|
1258
1323
|
...session.timeline.base(receipt.id, receipt.id),
|
|
@@ -1261,9 +1326,10 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1261
1326
|
kind: "human-message",
|
|
1262
1327
|
actor: "human",
|
|
1263
1328
|
content: receipt.prompt,
|
|
1264
|
-
attachments
|
|
1329
|
+
attachments,
|
|
1265
1330
|
...receipt.operationId ? { operationId: receipt.operationId } : {}
|
|
1266
1331
|
});
|
|
1332
|
+
session.media?.delete(receipt.id);
|
|
1267
1333
|
}
|
|
1268
1334
|
#retire(session, clearQueue) {
|
|
1269
1335
|
if (session.active && !session.stored.nativeId) session.stored.unsafe = true;
|
|
@@ -1271,10 +1337,12 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1271
1337
|
session.active.state = "cancelled";
|
|
1272
1338
|
session.timeline.notice(session.active.id, "Prompt interrupted; it was not retried.", "warning");
|
|
1273
1339
|
}
|
|
1340
|
+
if (session.active) session.media?.delete(session.active.id);
|
|
1274
1341
|
session.active = void 0;
|
|
1275
1342
|
if (clearQueue) {
|
|
1276
1343
|
for (const receipt of session.queue) {
|
|
1277
1344
|
receipt.state = "cancelled";
|
|
1345
|
+
session.media?.delete(receipt.id);
|
|
1278
1346
|
session.timeline.notice(receipt.id, "Queued prompt cancelled before delivery.", "warning");
|
|
1279
1347
|
}
|
|
1280
1348
|
session.queue = [];
|
|
@@ -1340,7 +1408,7 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1340
1408
|
#save(session) {
|
|
1341
1409
|
if (!this.#sessions.has(session.stored.summary.sessionId)) return Promise.resolve();
|
|
1342
1410
|
const data = JSON.stringify(StoredSchema.parse(session.stored));
|
|
1343
|
-
const file =
|
|
1411
|
+
const file = join(this.#directory, `${identity(session.stored.summary.sessionId)}.json`);
|
|
1344
1412
|
session.saves++;
|
|
1345
1413
|
const work = session.saving.then(async () => {
|
|
1346
1414
|
const temporary = `${file}.${randomUUID2()}.tmp`;
|
|
@@ -1362,10 +1430,15 @@ var ClaudeCodingAgentAdapter = class {
|
|
|
1362
1430
|
stop() {
|
|
1363
1431
|
if (this.#stopPromise) return this.#stopPromise;
|
|
1364
1432
|
this.#stopping = true;
|
|
1433
|
+
this.#modelAbort?.abort();
|
|
1365
1434
|
this.#stopPromise = this.#stop();
|
|
1366
1435
|
return this.#stopPromise;
|
|
1367
1436
|
}
|
|
1368
1437
|
async #stop() {
|
|
1438
|
+
if (this.#modelRefresh) {
|
|
1439
|
+
const [result] = await Promise.allSettled([this.#modelRefresh]);
|
|
1440
|
+
if (result?.status === "rejected") this.#options.onDiagnostic?.("Claude model discovery could not be stopped cleanly");
|
|
1441
|
+
}
|
|
1369
1442
|
if (this.#starting && !this.#started) {
|
|
1370
1443
|
const [result] = await Promise.allSettled([this.#starting]);
|
|
1371
1444
|
if (result?.status === "rejected") {
|