Skip to content
TypeScript

feat(server): send pdf attachments to claude and antigravity as documents (#21358)

maria532023a24127
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
index 16d657bc192..7dabfdee72f 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import {
+ ChatFileAttachment,
MessageId,
NodeId,
ProjectId,
@@ -14,6 +15,7 @@ import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
@@ -28,6 +30,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
+import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -277,6 +280,20 @@ describe("AntigravityAdapterV2 workspace changes", () => {
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ const promptReceived = yield* Deferred.make<Parameters<RuntimeService["prompt"]>[0]>();
+ const host = yield* ProviderHost.ProviderHost;
+ const document = ChatFileAttachment.make({
+ type: "file",
+ id: "native-pdf",
+ name: "diagram.pdf",
+ mimeType: "application/pdf",
+ sizeBytes: 9,
+ });
+ const documentPath = resolveAttachmentPath({
+ attachmentsDir: host.paths.attachmentsDir,
+ attachment: document,
+ })!;
+ yield* fileSystem.writeFileString(documentPath, "%PDF-1.7");
let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
const instanceId = ProviderInstanceId.make("antigravity-workspace-change-test");
const adapter = yield* makeAntigravityAdapterV2({
@@ -296,6 +313,23 @@ describe("AntigravityAdapterV2 workspace changes", () => {
Effect.provideService(Crypto.Crypto, crypto),
Effect.map((runtime): RuntimeService => ({
...runtime,
+ prompt: (request) =>
+ Deferred.succeed(promptReceived, request).pipe(
+ Effect.andThen(runtime.prompt(request)),
+ ),
+ start: () =>
+ runtime.start().pipe(
+ Effect.map((started) => ({
+ ...started,
+ initializeResult: {
+ ...started.initializeResult,
+ agentCapabilities: {
+ ...started.initializeResult.agentCapabilities,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
+ },
+ },
+ })),
+ ),
handleReadTextFile: (handler) =>
Effect.sync(() => {
readTextFile = handler;
@@ -366,7 +400,7 @@ describe("AntigravityAdapterV2 workspace changes", () => {
creationSource: "web",
messageId: MessageId.make("message-antigravity-workspace-change"),
text: "read b.txt",
- attachments: [],
+ attachments: [document],
},
modelSelection,
runtimePolicy: policyFor(workspaceB),
@@ -376,6 +410,19 @@ describe("AntigravityAdapterV2 workspace changes", () => {
Stream.filter((event) => event.type === "provider_turn.updated"),
Stream.runHead,
);
+ const sent = yield* Deferred.await(promptReceived);
+ assert.deepEqual(
+ sent.prompt.filter((block) => block.type === "resource_link"),
+ [
+ {
+ type: "resource_link",
+ uri: (yield* path.toFileUrl(documentPath)).href,
+ name: "diagram.pdf",
+ mimeType: "application/pdf",
+ },
+ ],
+ );
+ assert.include(JSON.stringify(sent.prompt), host.resolveAttachmentPath(document)!);
if (readTextFile === undefined) {
return yield* Effect.die("Antigravity sessions must serve client file requests");
}
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
index 3ec304b0a9a..a37781debe4 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
@@ -20,6 +20,7 @@ import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSession
import {
antigravityPermissionMode,
applyAntigravityAcpModelSelection,
+ buildAntigravityPrompt,
type AntigravityAcpRuntimeInput,
} from "../../provider/acp/AntigravityAcpSupport.ts";
import {
@@ -155,6 +156,16 @@ export function makeAntigravityAcpAdapterFlavor(
runtimeHarness: "Antigravity",
capabilities: AntigravityProviderCapabilitiesV2,
makeRuntime,
+ buildPrompt: ({ text, attachments, promptCapabilities }) =>
+ buildAntigravityPrompt({
+ input: text,
+ attachments,
+ attachmentsDir: options.host.paths.attachmentsDir,
+ promptCapabilities,
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, options.fileSystem),
+ Effect.provideService(Path.Path, options.path),
+ ),
// Loading history replays tool calls; resume avoids replay.
preferResumeSession: true,
subagentsIdleOnTurnCompletion: true,
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
index 9dc129c7aa0..5dfbffa5959 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
@@ -26,6 +26,7 @@ import type {
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ChatAttachmentId,
+ type ChatAttachment,
ChatFileAttachment,
ChatImageAttachment,
CheckpointId,
@@ -36,7 +37,7 @@ import {
NodeId,
type OrchestrationV2AppThread,
type OrchestrationV2PendingBackgroundTask,
- type OrchestrationV2ProviderThread,
+ OrchestrationV2ProviderThread,
ProjectId,
ProviderInstanceId,
type ProviderInstanceEnvironment,
@@ -1412,12 +1413,32 @@ describe("ClaudeAdapterV2 resume compaction", () => {
describe("ClaudeAdapterV2 attachments", () => {
it.effect.each([
+ ...[
+ "retained-images",
+ "retained-text",
+ "same-message-images",
+ "retained-documents",
+ "later-images",
+ "partial-images",
+ "cancelled-send",
+ "cancelled-steer",
+ ].map((budget) => ({
+ name: budget,
+ prompt: "Read this PDF.",
+ expectedText: "Read this PDF.",
+ command: undefined,
+ ultrathink: false,
+ resumed: false,
+ budget,
+ })),
{
name: "ordinary text",
prompt: "What’s in this image?",
expectedText: "Ultrathink:\nWhat’s in this image?",
command: undefined,
ultrathink: true,
+ resumed: false,
+ budget: "none",
},
{
name: "mid-sentence skill",
@@ -1425,6 +1446,8 @@ describe("ClaudeAdapterV2 attachments", () => {
expectedText: "Ultrathink:\nplease /implement fixes\n\nThen report the result",
command: "/implement fixes\n\nThen report the result",
ultrathink: true,
+ resumed: false,
+ budget: "none",
},
{
name: "prompt-leading skill",
@@ -1432,10 +1455,21 @@ describe("ClaudeAdapterV2 attachments", () => {
expectedText: "/implement fixes",
command: undefined,
ultrathink: false,
+ resumed: false,
+ budget: "none",
+ },
+ {
+ name: "resumed history without persisted counters",
+ prompt: "Inspect this file",
+ expectedText: "Ultrathink:\nInspect this file",
+ command: undefined,
+ ultrathink: true,
+ resumed: true,
+ budget: "none",
},
])(
- "preserves $name with images and files on sends and steering",
- ({ prompt, expectedText, command, ultrathink }) =>
+ "preserves $name with native PDFs, images, and paths on sends and steering",
+ ({ prompt, expectedText, command, ultrathink, resumed, budget }) =>
Effect.scoped(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -1459,6 +1493,10 @@ describe("ClaudeAdapterV2 attachments", () => {
prefix: "t3-claude-v2-attachments-",
});
const offeredMessages: Array<SDKUserMessage> = [];
+ let failOpen = false;
+ let failOffer = false;
+ let cancelAfterQueue = false;
+ const queued = yield* Deferred.make<void>();
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome },
@@ -1471,19 +1509,51 @@ describe("ClaudeAdapterV2 attachments", () => {
queryRunner: {
allocateSessionId: Effect.succeed("native-thread-claude-attachments"),
open: () =>
- Effect.succeed({
- messages: Stream.never,
- offer: (message) =>
- Effect.sync(() => {
- offeredMessages.push(message);
- }),
- setModel: () => Effect.void,
- applyFlagSettings: () => Effect.void,
- setPermissionMode: () => Effect.void,
- backgroundTasks: () => Effect.succeed(false),
- stopTask: () => Effect.void,
- interrupt: Effect.void,
- close: Effect.void,
+ Effect.gen(function* () {
+ if (failOpen) {
+ failOpen = false;
+ return yield* Effect.fail(
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
+ method: "open",
+ cause: "rejected open",
+ }),
+ );
+ }
+ const messages = yield* Queue.unbounded<SDKMessage>();
+ return {
+ messages: Stream.fromQueue(messages),
+ offer: (message, onQueued) =>
+ Effect.suspend(() => {
+ if (failOffer) {
+ failOffer = false;
+ return Effect.fail(
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
+ method: "offer",
+ cause: "rejected offer",
+ }),
+ );
+ }
+ return Effect.sync(() => {
+ offeredMessages.push(message);
+ onQueued?.();
+ }).pipe(
+ Effect.andThen(() =>
+ cancelAfterQueue
+ ? Deferred.succeed(queued, undefined).pipe(
+ Effect.andThen(Effect.never),
+ )
+ : Effect.void,
+ ),
+ );
+ }),
+ setModel: () => Effect.void,
+ applyFlagSettings: () => Effect.void,
+ setPermissionMode: () => Effect.void,
+ backgroundTasks: () => Effect.succeed(false),
+ stopTask: () => Effect.void,
+ interrupt: Effect.void,
+ close: Queue.shutdown(messages),
+ };
}),
forkSession: () => Effect.die("unused forkSession"),
subagentLaunchToolUseId: () => Effect.succeed(null),
@@ -1525,24 +1595,227 @@ describe("ClaudeAdapterV2 attachments", () => {
path.join(attachmentsDir, attachmentRelativePath(attachment)!),
Uint8Array.from([1, 2, 3, 4]),
);
+ const pdfBytes = Buffer.from(
+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 /Kids [3 0 R] >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF",
+ );
yield* fileSystem.writeFile(
path.join(attachmentsDir, attachmentRelativePath(document)!),
- Uint8Array.from([5, 6, 7, 8]),
+ pdfBytes,
);
const attemptId = RunAttemptId.make("attempt-claude-attachments");
const now = yield* DateTime.now;
- yield* runtime.startTurn(
- makeClaudeTestTurnInput({
+ const turnInput = {
+ ...makeClaudeTestTurnInput({
threadId,
providerThread,
now,
attemptId,
modelSelection,
text: prompt,
- attachments: [attachment, document],
+ attachments: resumed ? [attachment] : [attachment, document],
}),
- );
+ nativeThreadHasTurns: resumed,
+ };
+ if (budget === "cancelled-send" || budget === "cancelled-steer") {
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
+ const pages = Buffer.from(
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
+ );
+ yield* fileSystem.writeFile(
+ documentPath,
+ Buffer.concat([
+ pages,
+ Buffer.alloc(19 * 1024 * 1024 - pages.length - 5, 32),
+ Buffer.from("%%EOF"),
+ ]),
+ );
+ const message = { ...turnInput.message, attachments: [document] };
+ if (budget === "cancelled-steer") {
+ yield* runtime.startTurn({ ...turnInput, message: { ...message, attachments: [] } });
+ }
+ const deliver =
+ budget === "cancelled-send"
+ ? runtime.startTurn({ ...turnInput, message })
+ : runtime.steerTurn({
+ threadId,
+ runId: turnInput.runId,
+ providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${attemptId}`,
+ }),
+ message,
+ });
+ cancelAfterQueue = true;
+ const delivering = yield* deliver.pipe(Effect.forkChild);
+ yield* Deferred.await(queued);
+ yield* Fiber.interrupt(delivering);
+ const delivered = offeredMessages.at(-1)!.message.content;
+ assert.include(JSON.stringify(delivered), '"type":"document"');
+ cancelAfterQueue = false;
+ if (budget === "cancelled-send") {
+ yield* runtime.interruptTurn({
+ providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${attemptId}`,
+ }),
+ });
+ }
+ yield* deliver;
+ const retried = offeredMessages.at(-1)!.message.content;
+ assert.notInclude(JSON.stringify(retried), '"type":"document"');
+ assert.include(JSON.stringify(retried), documentPath);
+ assert.isBelow(Buffer.byteLength(JSON.stringify(offeredMessages)), 32_000_000);
+ return;
+ }
+ if (budget !== "none") {
+ const providerTurnId = idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${attemptId}`,
+ });
+ const imagePath = path.join(attachmentsDir, attachmentRelativePath(attachment)!);
+ // The on-disk length deliberately disagrees with sizeBytes.
+ yield* fileSystem.writeFile(imagePath, Buffer.alloc(4 * 1024 * 1024));
+ if (["later-images", "partial-images"].includes(budget)) {
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
+ yield* fileSystem.writeFile(
+ documentPath,
+ Buffer.concat([
+ pdfBytes.subarray(0, -5),
+ Buffer.alloc(
+ (budget === "later-images" ? 19 : 16) * 1024 * 1024 - pdfBytes.length,
+ 32,
+ ),
+ Buffer.from("%%EOF"),
+ ]),
+ );
+ yield* runtime.startTurn({
+ ...turnInput,
+ message: { ...turnInput.message, attachments: [document] },
+ });
+ assert.include(
+ JSON.stringify(offeredMessages[0]!.message.content),
+ '"type":"document"',
+ );
+ const message = { ...turnInput.message, attachments: [attachment, attachment] };
+ yield* runtime.interruptTurn({ providerThread, providerTurnId });
+ const laterAttemptId = RunAttemptId.make("attempt-claude-attachments-later");
+ yield* runtime.startTurn({
+ ...turnInput,
+ attemptId: laterAttemptId,
+ providerTurnOrdinal: 2,
+ nativeThreadHasTurns: true,
+ message,
+ });
+ const sent = offeredMessages.at(-1)!.message.content;
+ assert.isArray(sent);
+ assert.lengthOf(
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "image"),
+ budget === "partial-images" ? 1 : 0,
+ );
+ assert.include(JSON.stringify(sent), imagePath);
+ yield* runtime.steerTurn({
+ threadId,
+ runId: RunId.make("run-claude-attachments"),
+ providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${laterAttemptId}`,
+ }),
+ message,
+ });
+ const steered = offeredMessages.at(-1)!.message.content;
+ assert.isArray(steered);
+ assert.lengthOf(
+ typeof steered === "string"
+ ? []
+ : steered.filter((block) => block.type === "image"),
+ 0,
+ );
+ assert.include(JSON.stringify(steered), imagePath);
+ assert.isBelow(
+ Buffer.byteLength(
+ JSON.stringify(offeredMessages.map((message) => message.message)),
+ ),
+ 32_000_000,
+ );
+ return;
+ }
+ if (budget === "retained-documents") {
+ yield* fileSystem.writeFile(
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
+ Buffer.concat([
+ pdfBytes.subarray(0, pdfBytes.length - 5),
+ Buffer.alloc(10 * 1024 * 1024, 32),
+ Buffer.from("%%EOF"),
+ ]),
+ );
+ }
+ yield* runtime.startTurn({
+ ...turnInput,
+ message: {
+ ...turnInput.message,
+ text: budget === "retained-text" ? "x".repeat(10 * 1024 * 1024) : prompt,
+ attachments:
+ budget === "retained-text"
+ ? []
+ : budget === "retained-documents"
+ ? [document]
+ : [attachment, attachment],
+ },
+ });
+ const largePdf = Buffer.concat([
+ pdfBytes.subarray(0, pdfBytes.length - 5),
+ Buffer.alloc(
+ (budget === "retained-documents" ? 20 : 19) * 1024 * 1024 - pdfBytes.length,
+ 32,
+ ),
+ Buffer.from("%%EOF"),
+ ]);
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
+ yield* fileSystem.writeFile(documentPath, largePdf);
+ yield* runtime.steerTurn({
+ threadId,
+ runId: RunId.make("run-claude-attachments"),
+ providerThread,
+ providerTurnId,
+ message: {
+ ...turnInput.message,
+ attachments:
+ budget === "same-message-images"
+ ? [document, attachment, attachment]
+ : [document],
+ },
+ });
+ const sent = offeredMessages.at(-1)!.message.content;
+ assert.isArray(sent);
+ assert.lengthOf(
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"),
+ 0,
+ budget,
+ );
+ assert.include(JSON.stringify(sent), documentPath);
+ return;
+ }
+ if (!resumed) {
+ const undelivered = Buffer.from(
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
+ );
+ yield* fileSystem.writeFile(
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
+ undelivered,
+ );
+ failOpen = true;
+ assert.isTrue(Exit.isFailure(yield* runtime.startTurn(turnInput).pipe(Effect.exit)));
+ assert.lengthOf(offeredMessages, 0);
+ yield* fileSystem.writeFile(
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
+ pdfBytes,
+ );
+ }
+ yield* runtime.startTurn(turnInput);
const expectedImageBlock = {
type: "image",
@@ -1552,20 +1825,29 @@ describe("ClaudeAdapterV2 attachments", () => {
data: "AQIDBA==",
},
} as const;
+ const expectedDocumentBlock = {
+ type: "document",
+ source: {
+ type: "base64",
+ media_type: "application/pdf",
+ data: Buffer.from(pdfBytes).toString("base64"),
+ },
+ } as const;
const expectedAttachmentPath = path.join(
attachmentsDir,
attachmentRelativePath(attachment)!,
);
const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
- const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`;
+ const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]${resumed ? "" : `\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`}`;
const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes };
const expectedContent = command
? [
requestBlock,
expectedImageBlock,
+ ...(!resumed ? [expectedDocumentBlock] : []),
{ type: "text" as const, text: command + attachmentNotes },
]
- : [expectedImageBlock, requestBlock];
+ : [expectedImageBlock, ...(!resumed ? [expectedDocumentBlock] : []), requestBlock];
assert.deepEqual(offeredMessages[0]?.message.content, expectedContent);
const providerTurnId = idAllocator.derive.providerTurn({
@@ -1582,12 +1864,153 @@ describe("ClaudeAdapterV2 attachments", () => {
creationSource: "web",
messageId: MessageId.make("message-claude-attachments-steer"),
text: prompt,
- attachments: [attachment, document],
+ attachments: resumed ? [attachment] : [attachment, document],
},
});
assert.equal(offeredMessages[1]?.priority, "now");
assert.deepEqual(offeredMessages[1]?.message.content, expectedContent);
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
+ for (const scenario of [
+ "pages",
+ "bytes",
+ "invalid",
+ "invalid-page-tree",
+ "object-stream",
+ "encrypted",
+ "cyclic-tree",
+ "unterminated-string",
+ "missing-eof",
+ "escaped-name",
+ "incremental",
+ "compressed-bomb",
+ "indirect-count",
+ "indirect-type",
+ "indirect-kids",
+ "indirect-101-pages",
+ "aggregate-pages",
+ "retained-pages",
+ "delivery-failure",
+ "pasted-text",
+ "text-only",
+ ]) {
+ let attachments: ReadonlyArray<ChatAttachment> = [document];
+ if (
+ ["pages", "aggregate-pages", "retained-pages", "delivery-failure"].includes(scenario)
+ ) {
+ const pages = scenario === "pages" ? 101 : scenario === "delivery-failure" ? 30 : 60;
+ const large = Buffer.from(
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count ${pages} >> endobj\n${Array.from({ length: pages }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n%%EOF`,
+ );
+ yield* fileSystem.writeFile(documentPath, large);
+ if (scenario === "aggregate-pages") {
+ const second = {
+ ...document,
+ id: ChatAttachmentId.make("second-pdf"),
+ name: "second.pdf",
+ };
+ yield* fileSystem.copyFile(
+ documentPath,
+ path.join(attachmentsDir, attachmentRelativePath(second)!),
+ );
+ attachments = [document, second];
+ }
+ } else if (scenario.startsWith("indirect-")) {
+ const raw =
+ scenario === "indirect-count" || scenario === "indirect-101-pages"
+ ? `%PDF-1.7\n1 0 obj ${scenario === "indirect-count" ? 1 : 101} endobj\n2 0 obj << /Type /Catalog /Pages 3 0 R >> endobj\n3 0 obj << /Type /Pages /Count 1 0 R /Kids [${Array.from({ length: scenario === "indirect-count" ? 1 : 101 }, (_, i) => `${i + 4} 0 R`).join(" ")}] >> endobj\n4 0 obj << /Type /Page /Parent 3 0 R >> endobj\n${scenario === "indirect-count" ? "" : Array.from({ length: 100 }, (_, i) => `${i + 5} 0 obj << /Type 105 0 R /Parent 3 0 R >> endobj`).join("\n")}\n105 0 obj /Page endobj\n%%EOF`
+ : scenario === "indirect-type"
+ ? pdfBytes
+ .toString()
+ .replace(
+ "%%EOF",
+ "4 0 obj << /Type 5 0 R >> endobj\n5 0 obj /Annot endobj\n%%EOF",
+ )
+ : pdfBytes
+ .toString()
+ .replace("/Kids [3 0 R]", "/Kids 4 0 R")
+ .replace("%%EOF", "4 0 obj [3 0 R] endobj\n%%EOF");
+ yield* fileSystem.writeFileString(documentPath, raw);
+ } else if (scenario === "bytes") {
+ yield* fileSystem.truncate(documentPath, 20 * 1024 * 1024 + 1);
+ } else if (scenario === "invalid") {
+ yield* fileSystem.writeFileString(documentPath, "This is not a PDF");
+ } else if (scenario === "invalid-page-tree") {
+ const malformedBytes = Buffer.from(
+ "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 42 >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF",
+ );
+ yield* fileSystem.writeFile(documentPath, malformedBytes);
+ } else if (
+ ["object-stream", "encrypted", "cyclic-tree", "compressed-bomb"].includes(scenario)
+ ) {
+ const suffix =
+ scenario === "encrypted"
+ ? "/Encrypt 9 0 R"
+ : scenario === "cyclic-tree"
+ ? "/Count 0 /Kids [2 0 R]"
+ : "/Type /ObjStm /Filter /FlateDecode /Length 1000000000";
+ yield* fileSystem.writeFile(
+ documentPath,
+ Buffer.concat([
+ pdfBytes.subarray(0, pdfBytes.length - 5),
+ Buffer.from(`\n4 0 obj << ${suffix} >> stream\nx\nendstream endobj\n%%EOF`),
+ ]),
+ );
+ } else if (
+ ["unterminated-string", "missing-eof", "escaped-name", "incremental"].includes(
+ scenario,
+ )
+ ) {
+ const raw = pdfBytes.toString();
+ yield* fileSystem.writeFileString(
+ documentPath,
+ scenario === "missing-eof"
+ ? raw.slice(0, -5)
+ : scenario === "escaped-name"
+ ? raw.replace("/Type /Page ", "/Type /Pa#67e ")
+ : raw.replace(
+ "%%EOF",
+ scenario === "incremental" ? "/Prev 42\n%%EOF" : "(unfinished\n%%EOF",
+ ),
+ );
+ } else if (scenario === "pasted-text") {
+ yield* fileSystem.writeFile(documentPath, pdfBytes);
+ attachments = [{ ...document, source: { _tag: "pasted-text" } }];
+ } else {
+ attachments = [];
+ yield* fileSystem.remove(documentPath);
+ }
+ const steering = {
+ threadId,
+ runId: RunId.make("run-claude-attachments"),
+ providerThread,
+ providerTurnId,
+ message: {
+ createdBy: "user",
+ creationSource: "web",
+ messageId: MessageId.make(`message-${scenario}`),
+ text: "Continue.",
+ attachments,
+ },
+ } satisfies ProviderAdapter.ProviderAdapterV2SteerInput;
+ if (scenario === "delivery-failure") {
+ failOffer = true;
+ assert.isTrue(Exit.isFailure(yield* runtime.steerTurn(steering).pipe(Effect.exit)));
+ }
+ yield* runtime.steerTurn(steering);
+
+ const sent = offeredMessages.at(-1)!.message.content;
+ const documents =
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "document");
+ assert.lengthOf(
+ documents,
+ ["aggregate-pages", "delivery-failure"].includes(scenario) ? 1 : 0,
+ scenario,
+ );
+ if (scenario === "text-only")
+ assert.equal(sent, ultrathink ? "Ultrathink:\nContinue." : "Continue.");
+ else assert.include(JSON.stringify(sent), documentPath);
+ }
}).pipe(
Effect.provide(
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
@@ -1833,7 +2256,10 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
url: "http://127.0.0.1:43123/mcp",
headers: { Authorization: "Bearer dummy-mcp-credential" },
};
- const openWith = (cli: ReturnType<typeof makeFakeClaudeCli>) =>
+ const openWith = (
+ cli: ReturnType<typeof makeFakeClaudeCli>,
+ native?: ProviderEventLoggers.EventNdjsonLogger,
+ ) =>
Effect.gen(function* () {
const runner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner;
return yield* runner.open({
@@ -1854,13 +2280,39 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
});
}).pipe(
Effect.provide(ClaudeAdapterV2.layerQueryRunner),
- Effect.provideService(
- ProviderEventLoggers.ProviderEventLoggers,
- ProviderEventLoggers.NoOpProviderEventLoggers,
- ),
+ Effect.provideService(ProviderEventLoggers.ProviderEventLoggers, {
+ ...ProviderEventLoggers.NoOpProviderEventLoggers,
+ native,
+ }),
Effect.provide(NodeServices.layer),
);
+ it.effect("commits queued delivery before interruptible protocol logging", () =>
+ Effect.gen(function* () {
+ const logging = yield* Deferred.make<void>();
+ let committed = false;
+ const cli = makeFakeClaudeCli();
+ const session = yield* openWith(cli, {
+ filePath: "/tmp/claude-queued-delivery.log",
+ write: () =>
+ committed
+ ? Deferred.succeed(logging, undefined).pipe(Effect.andThen(Effect.never))
+ : Effect.void,
+ close: () => Effect.void,
+ });
+ const offering = yield* session
+ .offer(ClaudeAdapterV2.makeClaudeUserMessage({ text: "Inspect the attachment." }), () => {
+ committed = true;
+ })
+ .pipe(Effect.forkChild);
+ yield* Deferred.await(logging);
+ yield* Fiber.interrupt(offering);
+ assert.isTrue(committed);
+ committed = false;
+ yield* session.close;
+ }),
+ );
+
it.effect("sends MCP servers over stdin, not argv or the environment", () =>
Effect.gen(function* () {
const cli = makeFakeClaudeCli();
@@ -1974,6 +2426,9 @@ describe("ClaudeAdapterV2 native session identity", () => {
});
const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+const providerThreadJson = Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ProviderThread));
+const encodeProviderThreadJson = Schema.encodeEffect(providerThreadJson);
+const decodeProviderThreadJson = Schema.decodeUnknownEffect(providerThreadJson);
describe("ClaudeAdapterV2 background wake turns", () => {
const WAKE_NATIVE_SESSION = "native-thread-claude-wake";
@@ -2424,6 +2879,407 @@ describe("ClaudeAdapterV2 background wake turns", () => {
});
const makeWakeHarness = makeWakeHarnessWithOptions();
+ it.effect.each(["release-after", "cancel-after", "release-before", "resume-pending"] as const)(
+ "keeps attachment reservations across compaction: %s boundary",
+ (outcome) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
+ const backgrounding = yield* Deferred.make<void>();
+ const release = yield* Deferred.make<void>();
+ const harness = yield* makeWakeHarnessWithOptions({
+ backgroundTasks: () =>
+ Deferred.succeed(backgrounding, undefined).pipe(
+ Effect.andThen(Deferred.await(release)),
+ Effect.as(true),
+ ),
+ });
+ const document = ChatFileAttachment.make({
+ type: "file",
+ id: ChatAttachmentId.make("compacting-document"),
+ name: "compacting.pdf",
+ mimeType: "application/pdf",
+ sizeBytes: 19 * 1024 * 1024,
+ });
+ const pages = Buffer.from(
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 60 >> endobj\n${Array.from({ length: 60 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
+ );
+ yield* fileSystem.writeFile(
+ path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
+ Buffer.concat([
+ pages,
+ Buffer.alloc(document.sizeBytes - pages.length - 5, 32),
+ Buffer.from("%%EOF"),
+ ]),
+ );
+ const input = makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("compacting-reservation"),
+ text: "Audit with a subagent.",
+ attachments: [],
+ });
+ yield* harness.runtime.startTurn(input);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "system",
+ subtype: "task_started",
+ task_id: "compacting-task",
+ tool_use_id: "compacting-tool",
+ description: "Audit",
+ subagent_type: "general-purpose",
+ is_backgrounded: false,
+ task_type: "local_agent",
+ prompt: "Audit.",
+ uuid: "00000000-0000-4000-8000-000000000811",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ const steer = harness.runtime.steerTurn({
+ threadId: harness.threadId,
+ runId: input.runId,
+ providerThread: harness.providerThread,
+ providerTurnId: idAllocator.derive.providerTurn({
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
+ nativeTurnId: `turn:${input.attemptId}`,
+ }),
+ message: {
+ createdBy: "user",
+ creationSource: "web",
+ messageId: MessageId.make("compacting-steer"),
+ text: "Read this PDF.",
+ attachments: [document],
+ },
+ });
+ const pending = yield* Effect.forkScoped(steer);
+ yield* Deferred.await(backgrounding);
+ assert.lengthOf(harness.offeredMessages, 1);
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "system",
+ subtype: "status",
+ status: "compacting",
+ uuid: "00000000-0000-4000-8000-000000000812",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ if (outcome === "release-before") {
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(pending);
+ }
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "system",
+ subtype: "compact_boundary",
+ compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 },
+ uuid: "00000000-0000-4000-8000-000000000813",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ if (outcome === "cancel-after") {
+ yield* Fiber.interrupt(pending);
+ assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(pending)));
+ } else if (outcome === "release-after") {
+ yield* Deferred.succeed(release, undefined);
+ yield* Fiber.join(pending);
+ }
+ // Flush the budget update through the event stream before trying again.
+ yield* harness.offerAndWait(
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000814", result: "Read." }),
+ );
+ yield* Queue.take(harness.terminalReceipts);
+ const updates = harness.events.flatMap((event) =>
+ event.type === "provider_thread.updated" ? [event.providerThread] : [],
+ );
+ for (const thread of updates) {
+ yield* decodeProviderThreadJson(yield* encodeProviderThreadJson(thread));
+ }
+ const persisted = yield* decodeProviderThreadJson(
+ yield* encodeProviderThreadJson(updates.at(-1)!),
+ );
+ const usage = persisted.nativeMetadata?.claudeAttachmentBudget;
+ const undelivered = outcome === "cancel-after" || outcome === "resume-pending";
+ assert.equal(usage?.pagesUsed, undelivered ? 0 : 60);
+ if (undelivered) assert.equal(usage?.bytesUsed, 0);
+ else assert.isAbove(usage?.bytesUsed ?? 0, 25 * 1024 * 1024);
+ const next = outcome === "resume-pending" ? yield* makeWakeHarness : harness;
+ const providerThread =
+ outcome === "resume-pending"
+ ? yield* next.runtime.resumeThread({ providerThread: persisted })
+ : persisted;
+ if (outcome === "resume-pending") {
+ assert.lengthOf(harness.offeredMessages, 1);
+ yield* fileSystem.copyFile(
+ path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
+ path.join(next.attachmentsDir, attachmentRelativePath(document)!),
+ );
+ }
+ yield* next.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: next.threadId,
+ providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("after-compacting-reservation"),
+ text: "Read this PDF again.",
+ attachments: [document],
+ providerTurnOrdinal: 2,
+ nativeThreadHasTurns: true,
+ }),
+ );
+ if (outcome === "resume-pending") {
+ assert.equal(next.getOpenedOptions()?.resume, WAKE_NATIVE_SESSION);
+ }
+ const delivered = next.offeredMessages.slice(outcome === "resume-pending" ? 0 : 1);
+ const documents = delivered.flatMap((message) =>
+ Array.isArray(message.message.content)
+ ? message.message.content.filter((block) => block.type === "document")
+ : [],
+ );
+ assert.lengthOf(documents, 1);
+ assert.isBelow(
+ Buffer.byteLength(encodeJsonString(delivered.map((message) => message.message.content))),
+ 32_000_000,
+ );
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
+ const attachmentBudgetOutcomes = [
+ "resume",
+ "legacy",
+ "compacted",
+ "preserved-segment",
+ "preserved-messages",
+ "failed",
+ "stopped",
+ "fork-bytes",
+ "fork-pages",
+ ] as const;
+ it.effect.each(attachmentBudgetOutcomes)(
+ "restores retained attachment counters after %s",
+ (outcome) =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const document = ChatFileAttachment.make({
+ type: "file",
+ id: ChatAttachmentId.make("budget-document"),
+ name: "budget.pdf",
+ mimeType: "application/pdf",
+ sizeBytes: 19 * 1024 * 1024,
+ });
+ const image = ChatImageAttachment.make({
+ type: "image",
+ id: ChatAttachmentId.make("budget-image"),
+ name: "budget.png",
+ mimeType: "image/png",
+ sizeBytes: 4 * 1024 * 1024,
+ });
+ const pages = Buffer.from(
+ `%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 100 >> endobj\n${Array.from({ length: 100 }, (_, i) => `${i + 3} 0 obj << /Type /Page /Parent 2 0 R >> endobj`).join("\n")}\n`,
+ );
+ const persisted = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarness;
+ yield* fileSystem.writeFile(
+ path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
+ Buffer.concat([
+ pages,
+ Buffer.alloc(document.sizeBytes - pages.length - 5, 32),
+ Buffer.from("%%EOF"),
+ ]),
+ );
+ yield* harness.runtime.startTurn(
+ makeClaudeTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("spend-attachment-budget"),
+ text: "Read this PDF.",
+ attachments: [document],
+ }),
+ );
+ const first = harness.offeredMessages[0]?.message.content;
+ assert.isArray(first);
+ if (Array.isArray(first)) assert.equal(first[0]?.type, "document");
+ if (
+ [
+ "compacted",
+ "preserved-segment",
+ "preserved-messages",
+ "failed",
+ "stopped",
+ ].includes(outcome)
+ ) {
+ yield* harness.offerAndWait(
+ claudeSdkFrame({
+ type: "system",
+ subtype: "status",
+ status: "compacting",
+ uuid: "00000000-0000-4000-8000-000000000801",
+ session_id: WAKE_NATIVE_SESSION,
+ }),
+ );
+ yield* harness.offerAndWait(
+ claudeSdkFrame(
+ outcome === "compacted" ||
+ outcome === "preserved-segment" ||
+ outcome === "preserved-messages"
+ ? {
+ type: "system",
+ subtype: "compact_boundary",
+ compact_metadata: {
+ trigger: "auto",
+ pre_tokens: 1500,
+ post_tokens: 400,
+ ...(outcome === "preserved-segment"
+ ? {
+ preserved_segment: {
+ head_uuid: harness.promptUuid(0),
+ tail_uuid: harness.promptUuid(0),
+ anchor_uuid: "00000000-0000-4000-8000-000000000802",
+ },
+ }
+ : outcome === "preserved-messages"
+ ? {
+ preserved_messages: {
+ anchor_uuid: "00000000-0000-4000-8000-000000000802",
+ uuids: [harness.promptUuid(0)],
+ },
+ }
+ : {}),
+ },
+ uuid: "00000000-0000-4000-8000-000000000802",
+ session_id: WAKE_NATIVE_SESSION,
+ }
+ : {
+ type: "system",
+ subtype: "status",
+ status: null,
+ ...(outcome === "failed"
+ ? { compact_result: "failed", compact_error: "Could not compact." }
+ : {}),
+ uuid: "00000000-0000-4000-8000-000000000802",
+ session_id: WAKE_NATIVE_SESSION,
+ },
+ ),
+ );
+ }
+ yield* harness.offerAndWait(
+ makeResultFrame({
+ uuid: "00000000-0000-4000-8000-000000000803",
+ result: "Read.",
+ }),
+ );
+ yield* Queue.take(harness.terminalReceipts);
+ const event = harness.events.findLast(
+ (entry) => entry.type === "provider_thread.updated",
+ );
+ assert.equal(event?.type, "provider_thread.updated");
+ if (event?.type !== "provider_thread.updated")
+ return yield* Effect.die("Missing persisted thread");
+ const budget = event.providerThread.nativeMetadata?.claudeAttachmentBudget;
+ assert.isDefined(budget);
+ if (outcome === "compacted") assert.deepEqual(budget, { bytesUsed: 0, pagesUsed: 0 });
+ else {
+ assert.equal(budget?.pagesUsed, 100);
+ assert.isAbove(budget?.bytesUsed ?? 0, 25 * 1024 * 1024);
+ }
+ // Exercise the same schema boundary as the persisted provider thread.
+ return yield* decodeProviderThreadJson(
+ yield* encodeProviderThreadJson({
+ ...event.providerThread,
+ ...(outcome === "legacy" ? { nativeMetadata: null } : {}),
+ }),
+ );
+ }),
+ );
+ const fork = outcome === "fork-bytes" || outcome === "fork-pages";
+ const inherited = fork
+ ? yield* Effect.scoped(
+ Effect.gen(function* () {
+ const harness = yield* makeWakeHarnessWithOptions({
+ forkSession: () =>
+ Effect.succeed({
+ sessionId: "forked-native-session",
+ ...(outcome === "fork-bytes"
+ ? { headMessageId: "forked-assistant-head" }
+ : {}),
+ }),
+ });
+ const forked = yield* harness.runtime.forkThread({
+ sourceProviderThread: persisted,
+ targetThreadId: harness.threadId,
+ });
+ return yield* decodeProviderThreadJson(yield* encodeProviderThreadJson(forked));
+ }),
+ )
+ : persisted;
+ const resumed = yield* makeWakeHarness;
+ const providerThread = yield* resumed.runtime.resumeThread({ providerThread: inherited });
+ yield* fileSystem.writeFileString(
+ path.join(resumed.attachmentsDir, attachmentRelativePath(document)!),
+ "%PDF-1.7\n1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj\n2 0 obj << /Type /Pages /Count 1 >> endobj\n3 0 obj << /Type /Page /Parent 2 0 R >> endobj\n%%EOF",
+ );
+ yield* fileSystem.writeFile(
+ path.join(resumed.attachmentsDir, attachmentRelativePath(image)!),
+ Buffer.alloc(image.sizeBytes, 1),
+ );
+ yield* resumed.runtime.startTurn({
+ ...makeClaudeTestTurnInput({
+ threadId: resumed.threadId,
+ providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make("resume-attachment-budget"),
+ text: "Read the PDF and both images.",
+ attachments:
+ outcome === "fork-bytes"
+ ? [image, image]
+ : outcome === "fork-pages"
+ ? [document]
+ : [document, image, image],
+ }),
+ nativeThreadHasTurns: true,
+ });
+ assert.equal(
+ resumed.getOpenedOptions()?.resume,
+ fork ? "forked-native-session" : WAKE_NATIVE_SESSION,
+ );
+ const content = resumed.offeredMessages[0]?.message.content;
+ assert.isArray(content);
+ if (!Array.isArray(content)) return;
+ const native = outcome === "legacy" || outcome === "compacted";
+ assert.equal(content.filter((block) => block.type === "document").length, native ? 1 : 0);
+ assert.equal(content.filter((block) => block.type === "image").length, native ? 2 : 0);
+ assert.isBelow(Buffer.byteLength(encodeJsonString(content)), 32_000_000);
+ if (fork) {
+ assert.deepEqual(
+ inherited.nativeMetadata?.claudeAttachmentBudget,
+ persisted.nativeMetadata?.claudeAttachmentBudget,
+ );
+ assert.equal(
+ inherited.nativeMetadata?.forkHeadMessageId,
+ outcome === "fork-bytes" ? "forked-assistant-head" : undefined,
+ );
+ assert.isBelow(
+ (persisted.nativeMetadata?.claudeAttachmentBudget?.bytesUsed ?? 0) +
+ Buffer.byteLength(encodeJsonString(content)),
+ 32_000_000,
+ );
+ assert.include(encodeJsonString(content), "budget.");
+ }
+ }).pipe(
+ Effect.provide(
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
+ ),
+ ),
+ );
+
describe("Claude settings restrictions", () => {
it.effect("resolves cached managed policy from the configured home through the real SDK", () =>
Effect.gen(function* () {
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index d3cd67a3598..e15d52e07f1 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -64,6 +64,7 @@ import {
} from "@t3tools/shared/claudeCompaction";
import {
type ChatAttachment,
+ PROVIDER_SEND_TURN_MAX_FILE_BYTES,
ClaudeSettings,
TrimmedNonEmptyString,
defaultInstanceIdForDriver,
@@ -499,7 +500,10 @@ export interface ClaudeAgentSdkQueryOpenInput {
export interface ClaudeAgentSdkQuerySession {
readonly messages: Stream.Stream<SDKMessage, ClaudeAgentSdkQueryRunnerError>;
- readonly offer: (message: SDKUserMessage) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
+ readonly offer: (
+ message: SDKUserMessage,
+ onQueued?: () => void,
+ ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly setModel: (model: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
readonly applyFlagSettings: (
settings: ClaudeFlagSettings,
@@ -815,7 +819,7 @@ function makeClaudeAgentSdkProtocolLogger(input: {
};
}
-const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
+const encodeClaudeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
Schema.fromJsonString(
Schema.Struct({ sessionId: Schema.String, headMessageId: Schema.optionalKey(Schema.String) }),
@@ -830,9 +834,12 @@ const claudeConfigDirOf = (
// The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
// worker so concurrent providers keep the server's environment.
-const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
- input: ClaudeAgentSdkSessionForkInput,
-) {
+const runClaudeWorker = Effect.fn("runClaudeWorker")(function* (input: {
+ readonly method: "forkSession";
+ readonly sessionId: string;
+ readonly options?: ForkSessionOptions;
+ readonly environment: NodeJS.ProcessEnv;
+}) {
const path = yield* Path.Path;
const fromSource = import.meta.url.endsWith(".ts");
// A single executable hosts the worker itself; it has no sibling script.
@@ -852,22 +859,30 @@ const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(functio
executablePath,
ChildProcess.make(
executablePath,
- [
- ...workerArguments,
- "forkSession",
- input.sessionId,
- encodeClaudeHistoryOptions(input.options),
- ],
- { env: { ...input.environment, ELECTRON_RUN_AS_NODE: "1" } },
+ [...workerArguments, input.method, input.sessionId, encodeClaudeJson(input.options ?? {})],
+ {
+ env: {
+ ...input.environment,
+ ELECTRON_RUN_AS_NODE: "1",
+ },
+ },
),
).pipe(Effect.timeout("30 seconds"));
if (result.code !== 0) {
return yield* new ClaudeAgentSdkQueryRunnerError({
- method: "forkSession",
+ method: input.method,
cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`,
});
}
- return yield* decodeClaudeHistoryFork(result.stdout);
+ return result.stdout;
+});
+
+const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
+ input: ClaudeAgentSdkSessionForkInput,
+) {
+ return yield* runClaudeWorker({ ...input, method: "forkSession" }).pipe(
+ Effect.flatMap(decodeClaudeHistoryFork),
+ );
});
export const layerQueryRunner: Layer.Layer<
@@ -1015,8 +1030,12 @@ export const layerQueryRunner: Layer.Layer<
}),
),
),
- offer: (message) =>
- Queue.offer(promptQueue, message).pipe(
+ offer: (message, onQueued) =>
+ Effect.uninterruptibleMask((restore) =>
+ restore(Queue.offer(promptQueue, message)).pipe(
+ Effect.tap(() => Effect.sync(() => onQueued?.())),
+ ),
+ ).pipe(
Effect.asVoid,
Effect.tap(() =>
logProtocolEvent({
@@ -1884,6 +1903,138 @@ export function makeClaudeUserMessage(input: {
};
}
+// Never decode streams just to enforce a provider limit. Only accept an explicit,
+// uncompressed page tree whose /Count agrees with the visible page objects.
+const estimateClaudePdfPages = (bytes: Buffer): number | null => {
+ if (bytes.length > 20 * 1024 * 1024 || bytes.subarray(0, 5).toString() !== "%PDF-") return null;
+ if (!bytes.subarray(-1024).includes("%%EOF")) return null;
+ let pages = 0;
+ let count = 0;
+ let catalog = false;
+ let pageTree = false;
+ let previous = "";
+ const delimiter = (byte: number) =>
+ byte <= 32 || "()<>[]{}/%".includes(String.fromCharCode(byte));
+ for (let i = 0; i < bytes.length;) {
+ const byte = bytes[i]!;
+ if (byte === 37) {
+ while (i < bytes.length && bytes[i] !== 10 && bytes[i] !== 13) i++;
+ continue;
+ }
+ if (byte <= 32) {
+ i++;
+ continue;
+ }
+ if (previous === "/Type" && byte !== 47) return null;
+ if (previous === "/Kids") {
+ if (byte !== 91) return null;
+ previous = "";
+ }
+ if (byte === 40) {
+ let depth = 1;
+ for (i++; i < bytes.length && depth > 0; i++) {
+ if (bytes[i] === 92) i++;
+ else if (bytes[i] === 40) depth++;
+ else if (bytes[i] === 41) depth--;
+ }
+ if (depth !== 0) return null;
+ previous = "";
+ continue;
+ }
+ if (byte === 60 && bytes[i + 1] !== 60) {
+ i = bytes.indexOf(62, i + 1);
+ if (i < 0) return null;
+ i++;
+ previous = "";
+ continue;
+ }
+ if (byte === 60 && bytes[i + 1] === 60) {
+ i += 2;
+ previous = "";
+ continue;
+ }
+ if (delimiter(byte) && byte !== 47) {
+ i++;
+ continue;
+ }
+ const start = i++;
+ while (i < bytes.length && !delimiter(bytes[i]!)) i++;
+ if (i - start > 64) return null;
+ const token = bytes.toString("latin1", start, i);
+ if (token.includes("#") || ["/ObjStm", "/XRef", "/Encrypt", "/Prev"].includes(token))
+ return null;
+ if (token === "stream") {
+ i = bytes.indexOf("endstream", i);
+ if (i < 0) return null;
+ i += 9;
+ previous = "";
+ continue;
+ }
+ if (previous === "/Type") {
+ if (token === "/Page") pages++;
+ if (token === "/Catalog") catalog = true;
+ if (token === "/Pages") pageTree = true;
+ }
+ if (previous === "/Count") {
+ if (!/^[1-9]\d{0,8}$/.test(token)) return null;
+ let next = i;
+ while (next < bytes.length) {
+ if (bytes[next]! <= 32) next++;
+ else if (bytes[next] === 37) {
+ while (next < bytes.length && bytes[next] !== 10 && bytes[next] !== 13) next++;
+ } else break;
+ }
+ // A second scalar is an indirect reference, not a direct page count.
+ if (next < bytes.length && !delimiter(bytes[next]!)) return null;
+ count = Math.max(count, Number(token));
+ }
+ previous = token;
+ }
+ return catalog && pageTree && pages > 0 && count === pages ? pages : null;
+};
+
+const CLAUDE_ATTACHMENT_MAX_BYTES = 28 * 1024 * 1024;
+const CLAUDE_ATTACHMENT_MAX_PAGES = 100;
+
+const makeClaudeAttachmentBudget = (used?: { pagesUsed: number; bytesUsed: number }) => ({
+ committed: { pages: used?.pagesUsed ?? 0, bytes: used?.bytesUsed ?? 0 },
+ pending: { pages: 0, bytes: 0 },
+ compacting: null as { pages: number; bytes: number } | null,
+ get remainingPages() {
+ return CLAUDE_ATTACHMENT_MAX_PAGES - this.committed.pages - this.pending.pages;
+ },
+ get remainingBytes() {
+ return CLAUDE_ATTACHMENT_MAX_BYTES - this.committed.bytes - this.pending.bytes;
+ },
+});
+
+const reserveClaudePdfBudget = (
+ budget: ReturnType<typeof makeClaudeAttachmentBudget>,
+ persist: Effect.Effect<void>,
+) =>
+ Effect.acquireRelease(
+ Effect.sync(() => ({
+ budget,
+ pages: 0,
+ bytes: 0,
+ delivered: false,
+ commit() {
+ if (this.delivered) return;
+ this.delivered = true;
+ budget.pending.pages -= this.pages;
+ budget.pending.bytes -= this.bytes;
+ budget.committed.pages += this.pages;
+ budget.committed.bytes += this.bytes;
+ },
+ })),
+ (reservation) =>
+ Effect.sync(() => {
+ if (reservation.delivered) return;
+ budget.pending.pages -= reservation.pages;
+ budget.pending.bytes -= reservation.bytes;
+ }).pipe(Effect.andThen(persist)),
+ );
+
const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: {
readonly text: string;
readonly attachments: ReadonlyArray<ChatAttachment>;
@@ -1891,15 +2042,20 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
readonly uuid?: SDKUserMessage["uuid"];
readonly attachmentsDir: string;
readonly fileSystem: FileSystem.FileSystem;
+ readonly pdfReservation: Effect.Success<ReturnType<typeof reserveClaudePdfBudget>>;
readonly skills?: ReadonlyMap<string, ClaudeSkillTarget>;
}) {
if (input.attachments.length === 0) {
- return makeClaudeUserMessage({
+ const message = makeClaudeUserMessage({
text: input.text,
...(input.skills === undefined ? {} : { skills: input.skills }),
...(input.priority === undefined ? {} : { priority: input.priority }),
...(input.uuid === undefined ? {} : { uuid: input.uuid }),
});
+ const bytes = Buffer.byteLength(encodeClaudeJson(message.message.content));
+ input.pdfReservation.budget.pending.bytes += bytes;
+ input.pdfReservation.bytes += bytes;
+ return message;
}
const textWithAttachmentPaths = providerMessageTextWithAttachmentPaths({
@@ -1914,21 +2070,39 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
? undefined
: planClaudeSkillDispatch(textWithAttachmentPaths, input.skills);
const content: Array<ClaudeUserContentBlock> = [];
+ // Base64 adds a third to the payload. Leave room below Anthropic's 32 MB
+ // request limit for text, instructions, and SDK framing. The SDK does not
+ // expose document/context-window capabilities, so use the 100-page limit
+ // that also applies to models with less than a 1M-token context window.
if (dispatch?.leadingText !== undefined) {
content.push({ type: "text", text: dispatch.leadingText });
}
- for (const attachment of input.attachments) {
- if (attachment.type === "file") {
- continue;
- }
+ // Reserve all text and actual image bytes before considering any document,
+ // including images that follow it in attachment order.
+ const images = new Map<number, ClaudeUserContentBlock>();
+ const textBytes = Buffer.byteLength(
+ encodeClaudeJson(
+ dispatch
+ ? [
+ ...(dispatch.leadingText === undefined
+ ? []
+ : [{ type: "text", text: dispatch.leadingText }]),
+ { type: "text", text: dispatch.commandText },
+ ]
+ : [{ type: "text", text: textWithAttachmentPaths }],
+ ),
+ );
+ input.pdfReservation.budget.pending.bytes += textBytes;
+ input.pdfReservation.bytes += textBytes;
+ for (const [index, attachment] of input.attachments.entries()) {
+ if (attachment.type !== "image") continue;
if (!isSupportedClaudeImageMimeType(attachment.mimeType)) {
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
driver: CLAUDE_PROVIDER,
detail: `Unsupported Claude image attachment type '${attachment.mimeType}'`,
});
}
-
const attachmentPath = resolveAttachmentPath({
attachmentsDir: input.attachmentsDir,
attachment,
@@ -1939,7 +2113,6 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
detail: `Invalid attachment id '${attachment.id}'`,
});
}
-
const bytes = yield* input.fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
@@ -1951,14 +2124,76 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
}),
),
);
- content.push({
+ const retainedBytes = 4 * Math.ceil(bytes.length / 3) + 128;
+ if (retainedBytes > input.pdfReservation.budget.remainingBytes) continue;
+ input.pdfReservation.budget.pending.bytes += retainedBytes;
+ input.pdfReservation.bytes += retainedBytes;
+ const block: ClaudeUserContentBlock = {
type: "image",
source: {
type: "base64",
media_type: attachment.mimeType,
data: Buffer.from(bytes).toString("base64"),
},
- });
+ };
+ images.set(index, block);
+ }
+ for (const [index, attachment] of input.attachments.entries()) {
+ if (attachment.type === "file") {
+ if (
+ input.pdfReservation.budget.remainingPages <= 0 ||
+ attachment.mimeType.toLowerCase().split(";", 1)[0]?.trim() !== "application/pdf" ||
+ ("source" in attachment && attachment.source?._tag === "pasted-text")
+ )
+ continue;
+ const attachmentPath = resolveAttachmentPath({
+ attachmentsDir: input.attachmentsDir,
+ attachment,
+ });
+ if (attachmentPath === null) continue;
+ const remainingBytes = Math.min(
+ PROVIDER_SEND_TURN_MAX_FILE_BYTES,
+ 20 * 1024 * 1024,
+ Math.floor(((input.pdfReservation.budget.remainingBytes - 1024) * 3) / 4),
+ );
+ const info = yield* input.fileSystem
+ .stat(attachmentPath)
+ .pipe(Effect.orElseSucceed(() => null));
+ if (info?.type !== "File" || Number(info.size) > remainingBytes || remainingBytes <= 0)
+ continue;
+ const bytes = yield* input.fileSystem
+ .stream(attachmentPath, { bytesToRead: remainingBytes + 1 })
+ .pipe(
+ Stream.runCollect,
+ Effect.map((chunks) => Buffer.concat(chunks)),
+ Effect.orElseSucceed(() => null),
+ );
+ if (bytes === null || bytes.length > remainingBytes) continue;
+ const pageCount = estimateClaudePdfPages(bytes);
+ if (pageCount === null) {
+ yield* Effect.logDebug("Claude PDF page count is unknown; keeping attachment path-only.");
+ continue;
+ }
+ const retainedBytes = 4 * Math.ceil(bytes.length / 3) + 128;
+ if (
+ pageCount <= 0 ||
+ pageCount > input.pdfReservation.budget.remainingPages ||
+ retainedBytes > input.pdfReservation.budget.remainingBytes
+ )
+ continue;
+ input.pdfReservation.budget.pending.pages += pageCount;
+ input.pdfReservation.pages += pageCount;
+ const block: ClaudeUserContentBlock = {
+ type: "document",
+ source: { type: "base64", media_type: "application/pdf", data: bytes.toString("base64") },
+ };
+ input.pdfReservation.budget.pending.bytes += retainedBytes;
+ input.pdfReservation.bytes += retainedBytes;
+ content.push(block);
+ continue;
+ }
+ const image = images.get(index);
+ if (image !== undefined) content.push(image);
}
// Images must precede the command block for skill expansion.
@@ -3921,6 +4156,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
adapterOptions: ClaudeAdapterV2Options,
) {
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
const { attachmentsDir, fileSystem, path, crypto, idAllocator, queryRunner } = adapterOptions;
const subagentModelCatalog = scopeClaudeModelCatalog(
@@ -4170,6 +4406,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
);
});
const openedNativeThreads = yield* Ref.make(new Set<string>());
+ const pdfBudgets = new Map<string, ReturnType<typeof makeClaudeAttachmentBudget>>();
const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>());
// Claude 5 task tools edit one list per native session, across turns.
const taskListsByNativeThread = yield* Ref.make(
@@ -4382,8 +4619,44 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
const runtimeContext = yield* Effect.context<never>();
const runPromise = Effect.runPromiseWith(runtimeContext);
- const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
- Queue.offer(events, event).pipe(Effect.asVoid);
+ const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => {
+ if (event.type === "provider_thread.updated") {
+ const budget = pdfBudgets.get(event.providerThread.nativeThreadRef?.nativeId ?? "");
+ if (budget !== undefined) {
+ event = {
+ ...event,
+ providerThread: {
+ ...event.providerThread,
+ nativeMetadata: {
+ ...event.providerThread.nativeMetadata,
+ claudeAttachmentBudget: {
+ bytesUsed: budget.committed.bytes,
+ pagesUsed: budget.committed.pages,
+ },
+ },
+ },
+ };
+ }
+ }
+ return Queue.offer(events, event).pipe(Effect.asVoid);
+ };
+
+ const persistAttachmentBudget = Effect.fnUntraced(function* (nativeThreadId: string) {
+ const providerThread = (yield* Ref.get(lastProviderThreadByNativeThread)).get(
+ nativeThreadId,
+ );
+ if (providerThread === undefined) return;
+ const active = yield* Ref.get(activeTurn);
+ yield* emitProviderEvent({
+ type: "provider_thread.updated",
+ driver: CLAUDE_PROVIDER,
+ providerThread: {
+ ...providerThread,
+ status: active?.nativeThreadId === nativeThreadId ? "active" : providerThread.status,
+ updatedAt: yield* DateTime.now,
+ },
+ });
+ });
// Usage without input is a placeholder, not a context measurement.
const emitContextUsage = Effect.fnUntraced(function* (
@@ -7819,7 +8092,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
driver: CLAUDE_PROVIDER,
turnItem: context.compaction,
});
- if (message.compact_result !== "success") context.compaction = null;
+ if (message.compact_result !== "success") {
+ context.compaction = null;
+ const budget = pdfBudgets.get(context.nativeThreadId);
+ if (budget !== undefined) budget.compacting = null;
+ }
}
}
@@ -7859,6 +8136,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
updatedAt: now,
} satisfies OrchestrationV2TurnItem);
if (message.subtype === "status") {
+ const budget = pdfBudgets.get(context.nativeThreadId);
+ // Offers made while compaction runs are outside the history it
+ // removes. Pending reservations must survive its boundary too.
+ if (budget !== undefined) budget.compacting = { ...budget.committed };
context.compaction = compaction;
yield* emitProviderEvent({
type: "turn_item.updated",
@@ -7867,6 +8148,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
});
return;
}
+ const budget = pdfBudgets.get(context.nativeThreadId);
+ if (budget !== undefined) {
+ // Aggregate persisted usage cannot identify attachments in a
+ // preserved segment. Retain it conservatively on partial compacts.
+ if (
+ message.compact_metadata.preserved_segment === undefined &&
+ message.compact_metadata.preserved_messages === undefined
+ ) {
+ const compacted = budget.compacting ?? { ...budget.committed };
+ budget.committed.pages -= compacted.pages;
+ budget.committed.bytes -= compacted.bytes;
+ }
+ budget.compacting = null;
+ yield* persistAttachmentBudget(context.nativeThreadId);
+ }
if (context.streamUsage !== null) context.streamUsage.usage = null;
const postTokens = message.compact_metadata.post_tokens;
const afterTokenCount =
@@ -9520,6 +9816,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (!goalsByNativeThread.has(nativeThreadId)) {
goalsByNativeThread.set(nativeThreadId, turnInput.providerThread.goal ?? null);
}
+ if (!pdfBudgets.has(nativeThreadId)) {
+ // Older sessions did not record retained attachments. Keep their
+ // existing native-image allowance rather than disabling images.
+ const used = turnInput.providerThread.nativeMetadata?.claudeAttachmentBudget;
+ pdfBudgets.set(nativeThreadId, makeClaudeAttachmentBudget(used));
+ }
+ const pdfReservation = yield* reserveClaudePdfBudget(
+ pdfBudgets.get(nativeThreadId)!,
+ persistAttachmentBudget(nativeThreadId),
+ );
const userMessage =
promptUuid === null
? null
@@ -9531,9 +9837,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
attachments: turnInput.message.attachments,
attachmentsDir,
fileSystem,
+ pdfReservation,
skills: yield* userInvocableSkills(turnInput.runtimePolicy.cwd),
uuid: promptUuid,
- });
+ }).pipe(
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ Effect.provideService(Path.Path, path),
+ );
const querySession = yield* openQuery(turnInput, nativeThreadId);
const context: ActiveClaudeTurnContext = {
input: turnInput,
@@ -9642,7 +9952,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
if (userMessage !== null) {
yield* attachTurn;
yield* startUserTurnForWakeReports(nativeThreadId);
- yield* querySession.query.offer(userMessage);
+ yield* Effect.uninterruptibleMask((restore) =>
+ restore(
+ querySession.query.offer(userMessage, () => {
+ pdfReservation.commit();
+ }),
+ ).pipe(
+ Effect.tap(() =>
+ Effect.sync(() => {
+ pdfReservation.commit();
+ }),
+ ),
+ ),
+ );
return;
}
// Transcript reads suspend replay; hold SDK frames until the buffer is applied to preserve order.
@@ -9768,6 +10090,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
},
(effect, turnInput) =>
effect.pipe(
+ Effect.scoped,
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterTurnStartError({
@@ -9951,6 +10274,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`,
});
}
+ const pdfReservation = yield* reserveClaudePdfBudget(
+ pdfBudgets.get(existing.nativeThreadId) ??
+ makeClaudeAttachmentBudget({
+ pagesUsed: CLAUDE_ATTACHMENT_MAX_PAGES,
+ bytesUsed: CLAUDE_ATTACHMENT_MAX_BYTES,
+ }),
+ persistAttachmentBudget(existing.nativeThreadId),
+ );
const userMessage = yield* makeClaudeUserMessageWithAttachments({
text: applyClaudePromptEffortPrefix(
turnInput.message.text,
@@ -9960,8 +10291,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
priority: "now",
attachmentsDir,
fileSystem,
+ pdfReservation,
skills: yield* userInvocableSkills(currentTurn.input.runtimePolicy.cwd),
- });
+ }).pipe(
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ Effect.provideService(Path.Path, path),
+ );
yield* backgroundForegroundSubagents(existing, backgroundDeadline);
// The turn can end while the moves are answered. A steer offered
// then would start a new turn the orchestrator never asked for, so
@@ -9980,10 +10315,23 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
next.add(turnInput.providerTurnId);
return next;
});
- yield* existing.query.offer(userMessage);
+ yield* Effect.uninterruptibleMask((restore) =>
+ restore(
+ existing.query.offer(userMessage, () => {
+ pdfReservation.commit();
+ }),
+ ).pipe(
+ Effect.tap(() =>
+ Effect.sync(() => {
+ pdfReservation.commit();
+ }),
+ ),
+ ),
+ );
},
(effect, turnInput) =>
effect.pipe(
+ Effect.scoped,
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterSteerRunError({
@@ -10489,6 +10837,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
return updated;
});
const now = yield* DateTime.now;
+ // Native forks retain document/image history. Inherit full current
+ // usage even at an earlier fork point; this is conservative.
+ const claudeAttachmentBudget =
+ forkInput.sourceProviderThread.nativeMetadata?.claudeAttachmentBudget;
return makeProviderThread({
idAllocator,
providerInstanceId: adapterOptions.instanceId,
@@ -10502,9 +10854,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
? {}
: { providerTurnId: forkInput.providerTurnId }),
},
- ...(forked.headMessageId === undefined
+ ...(forked.headMessageId === undefined && claudeAttachmentBudget === undefined
? {}
- : { nativeMetadata: { forkHeadMessageId: forked.headMessageId } }),
+ : {
+ nativeMetadata: {
+ ...(forked.headMessageId === undefined
+ ? {}
+ : { forkHeadMessageId: forked.headMessageId }),
+ ...(claudeAttachmentBudget === undefined ? {} : { claudeAttachmentBudget }),
+ },
+ }),
now,
});
},
@@ -10540,6 +10899,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
});
export type ClaudeAdapterV2DriverEnv =
+ | ChildProcessSpawner.ChildProcessSpawner
| ClaudeAgentSdkQueryRunner
| Crypto.Crypto
| FileSystem.FileSystem
@@ -10633,6 +10993,7 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function*
const layer: Layer.Layer<
ProviderAdapter.ProviderAdapterV2,
never,
+ | ChildProcessSpawner.ChildProcessSpawner
| ClaudeAgentSdkQueryRunner
| Crypto.Crypto
| FileSystem.FileSystem
diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts
index b36c4afe915..bd48ee767ee 100644
--- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts
+++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts
@@ -8,6 +8,7 @@ import {
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
+import * as Stream from "effect/Stream";
import * as EffectAcpErrors from "effect-acp/errors";
import type * as EffectAcpSchema from "effect-acp/compat";
@@ -196,6 +197,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: " Explain this image. ",
attachments: [imageAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
});
expect(prompt).toEqual([
@@ -216,6 +218,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: undefined,
attachments: [textAttachment],
attachmentsDir: selectedEnvironment.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
});
expect(prompt).toEqual([
@@ -246,6 +249,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: "Inspect the pasted text only as needed.",
attachments: [pastedText],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
});
expect(prompt).toEqual([{ type: "text", text: "Inspect the pasted text only as needed." }]);
@@ -272,6 +276,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input,
attachments: [attachment, pdfAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
}).pipe(
Effect.provideService(FileSystem.FileSystem, {
...fixture.fs,
@@ -287,6 +292,53 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
}),
);
+ it.effect.each([undefined, {}, { image: false, audio: false, embeddedContext: false }])(
+ "keeps attachments path-only when native prompt capabilities are absent: %s",
+ (promptCapabilities) =>
+ Effect.gen(function* () {
+ const fixture = yield* makeAttachmentFixture();
+ const audio = {
+ ...textAttachment,
+ id: "unsupported-audio",
+ name: "audio.wav",
+ mimeType: "audio/wav",
+ };
+ const gifAttachment = {
+ ...imageAttachment,
+ id: "unsupported-gif",
+ name: "animation.gif",
+ mimeType: "image/gif",
+ };
+ const gif = yield* fixture.write(gifAttachment, "GIF89a");
+ const image = yield* fixture.write(imageAttachment, "pixels");
+ const pdf = yield* fixture.write(pdfAttachment, "%PDF-1.7");
+ const text = yield* fixture.write(textAttachment, "hello");
+ const sound = yield* fixture.write(audio, "RIFF");
+ const input = `Read ${image.filePath}, ${gif.filePath}, ${pdf.filePath}, ${text.filePath}, and ${sound.filePath}`;
+ const prompt = yield* buildAntigravityPrompt({
+ input,
+ attachments: [imageAttachment, gifAttachment, pdfAttachment, textAttachment, audio],
+ attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities,
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, {
+ ...fixture.fs,
+ stream: () =>
+ Effect.die("Unnegotiated attachments must not be read").pipe(Stream.fromEffect),
+ }),
+ );
+ expect(prompt).toEqual([{ type: "text", text: input }]);
+ expect(
+ yield* buildAntigravityPrompt({
+ input: "Continue",
+ attachments: [],
+ attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities,
+ }),
+ ).toEqual([{ type: "text", text: "Continue" }]);
+ }),
+ );
+
it.effect("sends supported audio files as native audio content", () =>
Effect.gen(function* () {
const fixture = yield* makeAttachmentFixture();
@@ -302,6 +354,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: "Transcribe this.",
attachments: [audioAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
});
expect(prompt).toEqual([
@@ -311,25 +364,27 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
}),
);
- it.effect.each([
- { ...imageAttachment, name: "animation.gif", mimeType: "image/gif" },
- ] satisfies ReadonlyArray<ChatAttachment>)(
- "rejects $name instead of silently dropping it from a valid prompt",
- (attachment) =>
+ it.effect.each([undefined, {}, { image: false }, { image: true }])(
+ "keeps unsupported image formats path-only with capabilities %s",
+ (promptCapabilities) =>
Effect.gen(function* () {
const fixture = yield* makeAttachmentFixture();
- yield* fixture.write(imageAttachment, new Uint8Array([1, 2, 3]));
- const error = yield* buildAntigravityPrompt({
- input: "Analyze every attachment.",
- attachments: [imageAttachment, attachment],
+ const attachment = { ...imageAttachment, name: "animation.gif", mimeType: "image/gif" };
+ const upload = yield* fixture.write(attachment, "GIF89a");
+ const input = `Analyze the image at ${upload.filePath}`;
+ const prompt = yield* buildAntigravityPrompt({
+ input,
+ attachments: [attachment],
attachmentsDir: fixture.attachmentsDir,
- }).pipe(Effect.flip);
+ promptCapabilities,
+ }).pipe(
+ Effect.provideService(FileSystem.FileSystem, {
+ ...fixture.fs,
+ stream: () => Effect.die("Unsupported images must not be read").pipe(Stream.fromEffect),
+ }),
+ );
- expect(error).toMatchObject({
- _tag: "AcpRequestError",
- code: -32602,
- errorMessage: expect.stringContaining(`does not support '${attachment.name}'`),
- });
+ expect(prompt).toEqual([{ type: "text", text: input }]);
}),
);
@@ -342,6 +397,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: "Read this attachment.",
attachments: [imageAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
}).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "AcpRequestError",
@@ -367,6 +423,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: `Read ${first.filePath} and ${second.filePath}`,
attachments: [pdfAttachment, secondAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
};
const prompt = yield* buildAntigravityPrompt(input);
expect(prompt).toEqual([
@@ -408,6 +465,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: "Inspect both attachments.",
attachments: [pdfAttachment, imageAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
}).pipe(Effect.flip);
expect(error).toMatchObject({
_tag: "AcpRequestError",
@@ -426,6 +484,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: undefined,
attachments: [pdfAttachment, textAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
}).pipe(
Effect.provideService(FileSystem.FileSystem, {
...fixture.fs,
@@ -459,6 +518,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: undefined,
attachments: [textAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
}).pipe(Effect.flip);
expect(error).toMatchObject({
@@ -476,6 +536,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
input: "Read this image.",
attachments: [imageAttachment],
attachmentsDir: fixture.attachmentsDir,
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
}).pipe(Effect.flip);
expect(error).toMatchObject({
diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts
index 0b3ef2603dc..8ddbf575c8f 100644
--- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts
+++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts
@@ -231,6 +231,7 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
readonly input: ProviderSendTurnInput["input"];
readonly attachments: ProviderSendTurnInput["attachments"];
readonly attachmentsDir: string;
+ readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
}): Effect.fn.Return<
ReadonlyArray<EffectAcpSchema.ContentBlock>,
EffectAcpErrors.AcpError,
@@ -259,12 +260,14 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
TEXT_MIME_TYPES.has(mimeType) ||
TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase()));
const isPathOnly =
- attachment.type === "file" && (isPastedText || (!audio && !pdf && !textFile));
- if (attachment.type === "image" && !image) {
- return yield* EffectAcpErrors.AcpRequestError.invalidParams(
- `Antigravity does not support '${attachment.name}' (${attachment.mimeType}). Attach a BMP, JPEG, PNG, WebP, PDF, audio, or text file.`,
- );
- }
+ (attachment.type === "image" && (!image || input.promptCapabilities?.image !== true)) ||
+ (attachment.type === "file" &&
+ (isPastedText ||
+ (audio
+ ? input.promptCapabilities?.audio !== true
+ : pdf || textFile
+ ? input.promptCapabilities?.embeddedContext !== true
+ : true)));
const attachmentPath = resolveAttachmentPath({
attachmentsDir: input.attachmentsDir,
attachment,
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index b36fc971f87..c5d59f817ed 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -918,6 +918,9 @@ export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({
updatedAt: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
itemIdentityVersion: Schema.optional(Schema.Literal(2)),
forkHeadMessageId: Schema.optional(TrimmedNonEmptyString),
+ claudeAttachmentBudget: Schema.optional(
+ Schema.Struct({ bytesUsed: NonNegativeInt, pagesUsed: NonNegativeInt }),
+ ),
});
export type OrchestrationV2ProviderThreadNativeMetadata =
typeof OrchestrationV2ProviderThreadNativeMetadata.Type;
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index 3ac79ddc614..bf39035f1f4 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -217,6 +217,11 @@ class AcpModelSelectionError extends Schema.TaggedError<AcpModelSelectionError>(
}
export interface AcpAdapterV2Flavor {
+ readonly buildPrompt?: (input: {
+ readonly text: string;
+ readonly attachments: ReadonlyArray<ChatAttachment>;
+ readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
+ }) => Effect.Effect<ReadonlyArray<EffectAcpSchema.ContentBlock>, EffectAcpErrors.AcpError>;
readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;
/**
* Runs before attachment paths, T3 instructions and native slash-command detection,
@@ -7130,7 +7135,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
detail: "ACP driver did not negotiate image prompt support",
});
}
- for (const attachment of imageAttachments) {
+ if (flavor.buildPrompt) {
+ const setup = yield* Ref.get(activeSessionSetup);
+ const blocks = yield* flavor
+ .buildPrompt({
+ text,
+ attachments: turnInput.message.attachments,
+ promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities,
+ })
+ .pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProviderAdapter.ProviderAdapterProtocolError({
+ driver,
+ detail: "Failed to build ACP attachment prompt",
+ payload: cause,
+ }),
+ ),
+ );
+ prompt.splice(0, prompt.length, ...blocks);
+ }
+ for (const attachment of flavor.buildPrompt ? [] : imageAttachments) {
const path = host.resolveAttachmentPath(attachment as ChatAttachment);
if (path === null) {
return yield* new ProviderAdapter.ProviderAdapterProtocolError({