The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 17:00 UTC
feat(server): send pdf attachments to claude and antigravity as documents (#21358)
maria committed
Oct 25, 2026 at 19:12 UTC
532023a241278d43a3acaab39191c1c6ad30fc73
8 files changed
+1453
-86
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts
+48
-1
@@ -1,6 +1,7 @@
1
import * as NodeServices from "@effect/platform-node/NodeServices";
2
import { assert, describe, it } from "@effect/vitest";
3
import {
4
+ ChatFileAttachment,
5
MessageId,
6
NodeId,
7
ProjectId,
@@ -14,6 +15,7 @@ import { resolveSelfInvocation } from "@t3tools/shared/nodeRuntime";
15
import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput";
16
import * as Crypto from "effect/Crypto";
17
import * as DateTime from "effect/DateTime";
18
+import * as Deferred from "effect/Deferred";
19
import * as Effect from "effect/Effect";
20
import * as Exit from "effect/Exit";
21
import * as FileSystem from "effect/FileSystem";
@@ -28,6 +30,7 @@ import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderS
30
import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost";
31
import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime";
32
import { makeAntigravityAcpRuntime } from "../../provider/acp/AntigravityAcpSupport.ts";
33
+import { resolveAttachmentPath } from "../../attachmentStore.ts";
34
import { normalizeAntigravitySessionUpdate } from "../../provider/acp/AntigravityProtocol.ts";
35
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
36
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -277,6 +280,20 @@ describe("AntigravityAdapterV2 workspace changes", () => {
280
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
281
);
282
type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
283
+ const promptReceived = yield* Deferred.make<Parameters<RuntimeService["prompt"]>[0]>();
284
+ const host = yield* ProviderHost.ProviderHost;
285
+ const document = ChatFileAttachment.make({
286
+ type: "file",
287
+ id: "native-pdf",
288
+ name: "diagram.pdf",
289
+ mimeType: "application/pdf",
290
+ sizeBytes: 9,
291
+ });
292
+ const documentPath = resolveAttachmentPath({
293
+ attachmentsDir: host.paths.attachmentsDir,
294
+ attachment: document,
295
+ })!;
296
+ yield* fileSystem.writeFileString(documentPath, "%PDF-1.7");
297
let readTextFile: Parameters<RuntimeService["handleReadTextFile"]>[0] | undefined;
298
const instanceId = ProviderInstanceId.make("antigravity-workspace-change-test");
299
const adapter = yield* makeAntigravityAdapterV2({
@@ -296,6 +313,23 @@ describe("AntigravityAdapterV2 workspace changes", () => {
313
Effect.provideService(Crypto.Crypto, crypto),
314
Effect.map((runtime): RuntimeService => ({
315
...runtime,
316
+ prompt: (request) =>
317
+ Deferred.succeed(promptReceived, request).pipe(
318
+ Effect.andThen(runtime.prompt(request)),
319
+ ),
320
+ start: () =>
321
+ runtime.start().pipe(
322
+ Effect.map((started) => ({
323
+ ...started,
324
+ initializeResult: {
325
+ ...started.initializeResult,
326
+ agentCapabilities: {
327
+ ...started.initializeResult.agentCapabilities,
328
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
329
+ },
330
+ },
331
+ })),
332
+ ),
333
handleReadTextFile: (handler) =>
334
Effect.sync(() => {
335
readTextFile = handler;
@@ -366,7 +400,7 @@ describe("AntigravityAdapterV2 workspace changes", () => {
400
creationSource: "web",
401
messageId: MessageId.make("message-antigravity-workspace-change"),
402
text: "read b.txt",
369
- attachments: [],
403
+ attachments: [document],
404
},
405
modelSelection,
406
runtimePolicy: policyFor(workspaceB),
@@ -376,6 +410,19 @@ describe("AntigravityAdapterV2 workspace changes", () => {
410
Stream.filter((event) => event.type === "provider_turn.updated"),
411
Stream.runHead,
412
);
413
+ const sent = yield* Deferred.await(promptReceived);
414
+ assert.deepEqual(
415
+ sent.prompt.filter((block) => block.type === "resource_link"),
416
+ [
417
+ {
418
+ type: "resource_link",
419
+ uri: (yield* path.toFileUrl(documentPath)).href,
420
+ name: "diagram.pdf",
421
+ mimeType: "application/pdf",
422
+ },
423
+ ],
424
+ );
425
+ assert.include(JSON.stringify(sent.prompt), host.resolveAttachmentPath(document)!);
426
if (readTextFile === undefined) {
427
return yield* Effect.die("Antigravity sessions must serve client file requests");
428
}
apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+11
@@ -20,6 +20,7 @@ import type * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSession
20
import {
21
antigravityPermissionMode,
22
applyAntigravityAcpModelSelection,
23
+ buildAntigravityPrompt,
24
type AntigravityAcpRuntimeInput,
25
} from "../../provider/acp/AntigravityAcpSupport.ts";
26
import {
@@ -155,6 +156,16 @@ export function makeAntigravityAcpAdapterFlavor(
156
runtimeHarness: "Antigravity",
157
capabilities: AntigravityProviderCapabilitiesV2,
158
makeRuntime,
159
+ buildPrompt: ({ text, attachments, promptCapabilities }) =>
160
+ buildAntigravityPrompt({
161
+ input: text,
162
+ attachments,
163
+ attachmentsDir: options.host.paths.attachmentsDir,
164
+ promptCapabilities,
165
+ }).pipe(
166
+ Effect.provideService(FileSystem.FileSystem, options.fileSystem),
167
+ Effect.provideService(Path.Path, options.path),
168
+ ),
169
// Loading history replays tool calls; resume avoids replay.
170
preferResumeSession: true,
171
subagentsIdleOnTurnCompletion: true,
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+885
-29
@@ -26,6 +26,7 @@ import type {
26
import * as NodeServices from "@effect/platform-node/NodeServices";
27
import {
28
ChatAttachmentId,
29
+ type ChatAttachment,
30
ChatFileAttachment,
31
ChatImageAttachment,
32
CheckpointId,
@@ -36,7 +37,7 @@ import {
37
NodeId,
38
type OrchestrationV2AppThread,
39
type OrchestrationV2PendingBackgroundTask,
39
- type OrchestrationV2ProviderThread,
40
+ OrchestrationV2ProviderThread,
41
ProjectId,
42
ProviderInstanceId,
43
type ProviderInstanceEnvironment,
@@ -1412,12 +1413,32 @@ describe("ClaudeAdapterV2 resume compaction", () => {
1413
1414
describe("ClaudeAdapterV2 attachments", () => {
1415
it.effect.each([
1416
+ ...[
1417
+ "retained-images",
1418
+ "retained-text",
1419
+ "same-message-images",
1420
+ "retained-documents",
1421
+ "later-images",
1422
+ "partial-images",
1423
+ "cancelled-send",
1424
+ "cancelled-steer",
1425
+ ].map((budget) => ({
1426
+ name: budget,
1427
+ prompt: "Read this PDF.",
1428
+ expectedText: "Read this PDF.",
1429
+ command: undefined,
1430
+ ultrathink: false,
1431
+ resumed: false,
1432
+ budget,
1433
+ })),
1434
{
1435
name: "ordinary text",
1436
prompt: "What’s in this image?",
1437
expectedText: "Ultrathink:\nWhat’s in this image?",
1438
command: undefined,
1439
ultrathink: true,
1440
+ resumed: false,
1441
+ budget: "none",
1442
},
1443
{
1444
name: "mid-sentence skill",
@@ -1425,6 +1446,8 @@ describe("ClaudeAdapterV2 attachments", () => {
1446
expectedText: "Ultrathink:\nplease /implement fixes\n\nThen report the result",
1447
command: "/implement fixes\n\nThen report the result",
1448
ultrathink: true,
1449
+ resumed: false,
1450
+ budget: "none",
1451
},
1452
{
1453
name: "prompt-leading skill",
@@ -1432,10 +1455,21 @@ describe("ClaudeAdapterV2 attachments", () => {
1455
expectedText: "/implement fixes",
1456
command: undefined,
1457
ultrathink: false,
1458
+ resumed: false,
1459
+ budget: "none",
1460
+ },
1461
+ {
1462
+ name: "resumed history without persisted counters",
1463
+ prompt: "Inspect this file",
1464
+ expectedText: "Ultrathink:\nInspect this file",
1465
+ command: undefined,
1466
+ ultrathink: true,
1467
+ resumed: true,
1468
+ budget: "none",
1469
},
1470
])(
1437
- "preserves $name with images and files on sends and steering",
1438
- ({ prompt, expectedText, command, ultrathink }) =>
1471
+ "preserves $name with native PDFs, images, and paths on sends and steering",
1472
+ ({ prompt, expectedText, command, ultrathink, resumed, budget }) =>
1473
Effect.scoped(
1474
Effect.gen(function* () {
1475
const fileSystem = yield* FileSystem.FileSystem;
@@ -1459,6 +1493,10 @@ describe("ClaudeAdapterV2 attachments", () => {
1493
prefix: "t3-claude-v2-attachments-",
1494
});
1495
const offeredMessages: Array<SDKUserMessage> = [];
1496
+ let failOpen = false;
1497
+ let failOffer = false;
1498
+ let cancelAfterQueue = false;
1499
+ const queued = yield* Deferred.make<void>();
1500
const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1501
instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,
1502
settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome },
@@ -1471,19 +1509,51 @@ describe("ClaudeAdapterV2 attachments", () => {
1509
queryRunner: {
1510
allocateSessionId: Effect.succeed("native-thread-claude-attachments"),
1511
open: () =>
1474
- Effect.succeed({
1475
- messages: Stream.never,
1476
- offer: (message) =>
1477
- Effect.sync(() => {
1478
- offeredMessages.push(message);
1479
- }),
1480
- setModel: () => Effect.void,
1481
- applyFlagSettings: () => Effect.void,
1482
- setPermissionMode: () => Effect.void,
1483
- backgroundTasks: () => Effect.succeed(false),
1484
- stopTask: () => Effect.void,
1485
- interrupt: Effect.void,
1486
- close: Effect.void,
1512
+ Effect.gen(function* () {
1513
+ if (failOpen) {
1514
+ failOpen = false;
1515
+ return yield* Effect.fail(
1516
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
1517
+ method: "open",
1518
+ cause: "rejected open",
1519
+ }),
1520
+ );
1521
+ }
1522
+ const messages = yield* Queue.unbounded<SDKMessage>();
1523
+ return {
1524
+ messages: Stream.fromQueue(messages),
1525
+ offer: (message, onQueued) =>
1526
+ Effect.suspend(() => {
1527
+ if (failOffer) {
1528
+ failOffer = false;
1529
+ return Effect.fail(
1530
+ new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({
1531
+ method: "offer",
1532
+ cause: "rejected offer",
1533
+ }),
1534
+ );
1535
+ }
1536
+ return Effect.sync(() => {
1537
+ offeredMessages.push(message);
1538
+ onQueued?.();
1539
+ }).pipe(
1540
+ Effect.andThen(() =>
1541
+ cancelAfterQueue
1542
+ ? Deferred.succeed(queued, undefined).pipe(
1543
+ Effect.andThen(Effect.never),
1544
+ )
1545
+ : Effect.void,
1546
+ ),
1547
+ );
1548
+ }),
1549
+ setModel: () => Effect.void,
1550
+ applyFlagSettings: () => Effect.void,
1551
+ setPermissionMode: () => Effect.void,
1552
+ backgroundTasks: () => Effect.succeed(false),
1553
+ stopTask: () => Effect.void,
1554
+ interrupt: Effect.void,
1555
+ close: Queue.shutdown(messages),
1556
+ };
1557
}),
1558
forkSession: () => Effect.die("unused forkSession"),
1559
subagentLaunchToolUseId: () => Effect.succeed(null),
@@ -1525,24 +1595,227 @@ describe("ClaudeAdapterV2 attachments", () => {
1595
path.join(attachmentsDir, attachmentRelativePath(attachment)!),
1596
Uint8Array.from([1, 2, 3, 4]),
1597
);
1598
+ const pdfBytes = Buffer.from(
1599
+ "%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",
1600
+ );
1601
yield* fileSystem.writeFile(
1602
path.join(attachmentsDir, attachmentRelativePath(document)!),
1530
- Uint8Array.from([5, 6, 7, 8]),
1603
+ pdfBytes,
1604
);
1605
const attemptId = RunAttemptId.make("attempt-claude-attachments");
1606
const now = yield* DateTime.now;
1607
1535
- yield* runtime.startTurn(
1536
- makeClaudeTestTurnInput({
1608
+ const turnInput = {
1609
+ ...makeClaudeTestTurnInput({
1610
threadId,
1611
providerThread,
1612
now,
1613
attemptId,
1614
modelSelection,
1615
text: prompt,
1543
- attachments: [attachment, document],
1616
+ attachments: resumed ? [attachment] : [attachment, document],
1617
}),
1545
- );
1618
+ nativeThreadHasTurns: resumed,
1619
+ };
1620
+ if (budget === "cancelled-send" || budget === "cancelled-steer") {
1621
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
1622
+ const pages = Buffer.from(
1623
+ `%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`,
1624
+ );
1625
+ yield* fileSystem.writeFile(
1626
+ documentPath,
1627
+ Buffer.concat([
1628
+ pages,
1629
+ Buffer.alloc(19 * 1024 * 1024 - pages.length - 5, 32),
1630
+ Buffer.from("%%EOF"),
1631
+ ]),
1632
+ );
1633
+ const message = { ...turnInput.message, attachments: [document] };
1634
+ if (budget === "cancelled-steer") {
1635
+ yield* runtime.startTurn({ ...turnInput, message: { ...message, attachments: [] } });
1636
+ }
1637
+ const deliver =
1638
+ budget === "cancelled-send"
1639
+ ? runtime.startTurn({ ...turnInput, message })
1640
+ : runtime.steerTurn({
1641
+ threadId,
1642
+ runId: turnInput.runId,
1643
+ providerThread,
1644
+ providerTurnId: idAllocator.derive.providerTurn({
1645
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1646
+ nativeTurnId: `turn:${attemptId}`,
1647
+ }),
1648
+ message,
1649
+ });
1650
+ cancelAfterQueue = true;
1651
+ const delivering = yield* deliver.pipe(Effect.forkChild);
1652
+ yield* Deferred.await(queued);
1653
+ yield* Fiber.interrupt(delivering);
1654
+ const delivered = offeredMessages.at(-1)!.message.content;
1655
+ assert.include(JSON.stringify(delivered), '"type":"document"');
1656
+ cancelAfterQueue = false;
1657
+ if (budget === "cancelled-send") {
1658
+ yield* runtime.interruptTurn({
1659
+ providerThread,
1660
+ providerTurnId: idAllocator.derive.providerTurn({
1661
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1662
+ nativeTurnId: `turn:${attemptId}`,
1663
+ }),
1664
+ });
1665
+ }
1666
+ yield* deliver;
1667
+ const retried = offeredMessages.at(-1)!.message.content;
1668
+ assert.notInclude(JSON.stringify(retried), '"type":"document"');
1669
+ assert.include(JSON.stringify(retried), documentPath);
1670
+ assert.isBelow(Buffer.byteLength(JSON.stringify(offeredMessages)), 32_000_000);
1671
+ return;
1672
+ }
1673
+ if (budget !== "none") {
1674
+ const providerTurnId = idAllocator.derive.providerTurn({
1675
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1676
+ nativeTurnId: `turn:${attemptId}`,
1677
+ });
1678
+ const imagePath = path.join(attachmentsDir, attachmentRelativePath(attachment)!);
1679
+ // The on-disk length deliberately disagrees with sizeBytes.
1680
+ yield* fileSystem.writeFile(imagePath, Buffer.alloc(4 * 1024 * 1024));
1681
+ if (["later-images", "partial-images"].includes(budget)) {
1682
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
1683
+ yield* fileSystem.writeFile(
1684
+ documentPath,
1685
+ Buffer.concat([
1686
+ pdfBytes.subarray(0, -5),
1687
+ Buffer.alloc(
1688
+ (budget === "later-images" ? 19 : 16) * 1024 * 1024 - pdfBytes.length,
1689
+ 32,
1690
+ ),
1691
+ Buffer.from("%%EOF"),
1692
+ ]),
1693
+ );
1694
+ yield* runtime.startTurn({
1695
+ ...turnInput,
1696
+ message: { ...turnInput.message, attachments: [document] },
1697
+ });
1698
+ assert.include(
1699
+ JSON.stringify(offeredMessages[0]!.message.content),
1700
+ '"type":"document"',
1701
+ );
1702
+ const message = { ...turnInput.message, attachments: [attachment, attachment] };
1703
+ yield* runtime.interruptTurn({ providerThread, providerTurnId });
1704
+ const laterAttemptId = RunAttemptId.make("attempt-claude-attachments-later");
1705
+ yield* runtime.startTurn({
1706
+ ...turnInput,
1707
+ attemptId: laterAttemptId,
1708
+ providerTurnOrdinal: 2,
1709
+ nativeThreadHasTurns: true,
1710
+ message,
1711
+ });
1712
+ const sent = offeredMessages.at(-1)!.message.content;
1713
+ assert.isArray(sent);
1714
+ assert.lengthOf(
1715
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "image"),
1716
+ budget === "partial-images" ? 1 : 0,
1717
+ );
1718
+ assert.include(JSON.stringify(sent), imagePath);
1719
+ yield* runtime.steerTurn({
1720
+ threadId,
1721
+ runId: RunId.make("run-claude-attachments"),
1722
+ providerThread,
1723
+ providerTurnId: idAllocator.derive.providerTurn({
1724
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1725
+ nativeTurnId: `turn:${laterAttemptId}`,
1726
+ }),
1727
+ message,
1728
+ });
1729
+ const steered = offeredMessages.at(-1)!.message.content;
1730
+ assert.isArray(steered);
1731
+ assert.lengthOf(
1732
+ typeof steered === "string"
1733
+ ? []
1734
+ : steered.filter((block) => block.type === "image"),
1735
+ 0,
1736
+ );
1737
+ assert.include(JSON.stringify(steered), imagePath);
1738
+ assert.isBelow(
1739
+ Buffer.byteLength(
1740
+ JSON.stringify(offeredMessages.map((message) => message.message)),
1741
+ ),
1742
+ 32_000_000,
1743
+ );
1744
+ return;
1745
+ }
1746
+ if (budget === "retained-documents") {
1747
+ yield* fileSystem.writeFile(
1748
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
1749
+ Buffer.concat([
1750
+ pdfBytes.subarray(0, pdfBytes.length - 5),
1751
+ Buffer.alloc(10 * 1024 * 1024, 32),
1752
+ Buffer.from("%%EOF"),
1753
+ ]),
1754
+ );
1755
+ }
1756
+ yield* runtime.startTurn({
1757
+ ...turnInput,
1758
+ message: {
1759
+ ...turnInput.message,
1760
+ text: budget === "retained-text" ? "x".repeat(10 * 1024 * 1024) : prompt,
1761
+ attachments:
1762
+ budget === "retained-text"
1763
+ ? []
1764
+ : budget === "retained-documents"
1765
+ ? [document]
1766
+ : [attachment, attachment],
1767
+ },
1768
+ });
1769
+ const largePdf = Buffer.concat([
1770
+ pdfBytes.subarray(0, pdfBytes.length - 5),
1771
+ Buffer.alloc(
1772
+ (budget === "retained-documents" ? 20 : 19) * 1024 * 1024 - pdfBytes.length,
1773
+ 32,
1774
+ ),
1775
+ Buffer.from("%%EOF"),
1776
+ ]);
1777
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
1778
+ yield* fileSystem.writeFile(documentPath, largePdf);
1779
+ yield* runtime.steerTurn({
1780
+ threadId,
1781
+ runId: RunId.make("run-claude-attachments"),
1782
+ providerThread,
1783
+ providerTurnId,
1784
+ message: {
1785
+ ...turnInput.message,
1786
+ attachments:
1787
+ budget === "same-message-images"
1788
+ ? [document, attachment, attachment]
1789
+ : [document],
1790
+ },
1791
+ });
1792
+ const sent = offeredMessages.at(-1)!.message.content;
1793
+ assert.isArray(sent);
1794
+ assert.lengthOf(
1795
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "document"),
1796
+ 0,
1797
+ budget,
1798
+ );
1799
+ assert.include(JSON.stringify(sent), documentPath);
1800
+ return;
1801
+ }
1802
+ if (!resumed) {
1803
+ const undelivered = Buffer.from(
1804
+ `%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`,
1805
+ );
1806
+ yield* fileSystem.writeFile(
1807
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
1808
+ undelivered,
1809
+ );
1810
+ failOpen = true;
1811
+ assert.isTrue(Exit.isFailure(yield* runtime.startTurn(turnInput).pipe(Effect.exit)));
1812
+ assert.lengthOf(offeredMessages, 0);
1813
+ yield* fileSystem.writeFile(
1814
+ path.join(attachmentsDir, attachmentRelativePath(document)!),
1815
+ pdfBytes,
1816
+ );
1817
+ }
1818
+ yield* runtime.startTurn(turnInput);
1819
1820
const expectedImageBlock = {
1821
type: "image",
@@ -1552,20 +1825,29 @@ describe("ClaudeAdapterV2 attachments", () => {
1825
data: "AQIDBA==",
1826
},
1827
} as const;
1828
+ const expectedDocumentBlock = {
1829
+ type: "document",
1830
+ source: {
1831
+ type: "base64",
1832
+ media_type: "application/pdf",
1833
+ data: Buffer.from(pdfBytes).toString("base64"),
1834
+ },
1835
+ } as const;
1836
const expectedAttachmentPath = path.join(
1837
attachmentsDir,
1838
attachmentRelativePath(attachment)!,
1839
);
1840
const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
1560
- const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`;
1841
+ const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]${resumed ? "" : `\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`}`;
1842
const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes };
1843
const expectedContent = command
1844
? [
1845
requestBlock,
1846
expectedImageBlock,
1847
+ ...(!resumed ? [expectedDocumentBlock] : []),
1848
{ type: "text" as const, text: command + attachmentNotes },
1849
]
1568
- : [expectedImageBlock, requestBlock];
1850
+ : [expectedImageBlock, ...(!resumed ? [expectedDocumentBlock] : []), requestBlock];
1851
assert.deepEqual(offeredMessages[0]?.message.content, expectedContent);
1852
1853
const providerTurnId = idAllocator.derive.providerTurn({
@@ -1582,12 +1864,153 @@ describe("ClaudeAdapterV2 attachments", () => {
1864
creationSource: "web",
1865
messageId: MessageId.make("message-claude-attachments-steer"),
1866
text: prompt,
1585
- attachments: [attachment, document],
1867
+ attachments: resumed ? [attachment] : [attachment, document],
1868
},
1869
});
1870
1871
assert.equal(offeredMessages[1]?.priority, "now");
1872
assert.deepEqual(offeredMessages[1]?.message.content, expectedContent);
1873
+ const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
1874
+ for (const scenario of [
1875
+ "pages",
1876
+ "bytes",
1877
+ "invalid",
1878
+ "invalid-page-tree",
1879
+ "object-stream",
1880
+ "encrypted",
1881
+ "cyclic-tree",
1882
+ "unterminated-string",
1883
+ "missing-eof",
1884
+ "escaped-name",
1885
+ "incremental",
1886
+ "compressed-bomb",
1887
+ "indirect-count",
1888
+ "indirect-type",
1889
+ "indirect-kids",
1890
+ "indirect-101-pages",
1891
+ "aggregate-pages",
1892
+ "retained-pages",
1893
+ "delivery-failure",
1894
+ "pasted-text",
1895
+ "text-only",
1896
+ ]) {
1897
+ let attachments: ReadonlyArray<ChatAttachment> = [document];
1898
+ if (
1899
+ ["pages", "aggregate-pages", "retained-pages", "delivery-failure"].includes(scenario)
1900
+ ) {
1901
+ const pages = scenario === "pages" ? 101 : scenario === "delivery-failure" ? 30 : 60;
1902
+ const large = Buffer.from(
1903
+ `%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`,
1904
+ );
1905
+ yield* fileSystem.writeFile(documentPath, large);
1906
+ if (scenario === "aggregate-pages") {
1907
+ const second = {
1908
+ ...document,
1909
+ id: ChatAttachmentId.make("second-pdf"),
1910
+ name: "second.pdf",
1911
+ };
1912
+ yield* fileSystem.copyFile(
1913
+ documentPath,
1914
+ path.join(attachmentsDir, attachmentRelativePath(second)!),
1915
+ );
1916
+ attachments = [document, second];
1917
+ }
1918
+ } else if (scenario.startsWith("indirect-")) {
1919
+ const raw =
1920
+ scenario === "indirect-count" || scenario === "indirect-101-pages"
1921
+ ? `%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`
1922
+ : scenario === "indirect-type"
1923
+ ? pdfBytes
1924
+ .toString()
1925
+ .replace(
1926
+ "%%EOF",
1927
+ "4 0 obj << /Type 5 0 R >> endobj\n5 0 obj /Annot endobj\n%%EOF",
1928
+ )
1929
+ : pdfBytes
1930
+ .toString()
1931
+ .replace("/Kids [3 0 R]", "/Kids 4 0 R")
1932
+ .replace("%%EOF", "4 0 obj [3 0 R] endobj\n%%EOF");
1933
+ yield* fileSystem.writeFileString(documentPath, raw);
1934
+ } else if (scenario === "bytes") {
1935
+ yield* fileSystem.truncate(documentPath, 20 * 1024 * 1024 + 1);
1936
+ } else if (scenario === "invalid") {
1937
+ yield* fileSystem.writeFileString(documentPath, "This is not a PDF");
1938
+ } else if (scenario === "invalid-page-tree") {
1939
+ const malformedBytes = Buffer.from(
1940
+ "%PDF-1.7\n1 0 obj\n<< /Type /Catalog /Pages 42 >>\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF",
1941
+ );
1942
+ yield* fileSystem.writeFile(documentPath, malformedBytes);
1943
+ } else if (
1944
+ ["object-stream", "encrypted", "cyclic-tree", "compressed-bomb"].includes(scenario)
1945
+ ) {
1946
+ const suffix =
1947
+ scenario === "encrypted"
1948
+ ? "/Encrypt 9 0 R"
1949
+ : scenario === "cyclic-tree"
1950
+ ? "/Count 0 /Kids [2 0 R]"
1951
+ : "/Type /ObjStm /Filter /FlateDecode /Length 1000000000";
1952
+ yield* fileSystem.writeFile(
1953
+ documentPath,
1954
+ Buffer.concat([
1955
+ pdfBytes.subarray(0, pdfBytes.length - 5),
1956
+ Buffer.from(`\n4 0 obj << ${suffix} >> stream\nx\nendstream endobj\n%%EOF`),
1957
+ ]),
1958
+ );
1959
+ } else if (
1960
+ ["unterminated-string", "missing-eof", "escaped-name", "incremental"].includes(
1961
+ scenario,
1962
+ )
1963
+ ) {
1964
+ const raw = pdfBytes.toString();
1965
+ yield* fileSystem.writeFileString(
1966
+ documentPath,
1967
+ scenario === "missing-eof"
1968
+ ? raw.slice(0, -5)
1969
+ : scenario === "escaped-name"
1970
+ ? raw.replace("/Type /Page ", "/Type /Pa#67e ")
1971
+ : raw.replace(
1972
+ "%%EOF",
1973
+ scenario === "incremental" ? "/Prev 42\n%%EOF" : "(unfinished\n%%EOF",
1974
+ ),
1975
+ );
1976
+ } else if (scenario === "pasted-text") {
1977
+ yield* fileSystem.writeFile(documentPath, pdfBytes);
1978
+ attachments = [{ ...document, source: { _tag: "pasted-text" } }];
1979
+ } else {
1980
+ attachments = [];
1981
+ yield* fileSystem.remove(documentPath);
1982
+ }
1983
+ const steering = {
1984
+ threadId,
1985
+ runId: RunId.make("run-claude-attachments"),
1986
+ providerThread,
1987
+ providerTurnId,
1988
+ message: {
1989
+ createdBy: "user",
1990
+ creationSource: "web",
1991
+ messageId: MessageId.make(`message-${scenario}`),
1992
+ text: "Continue.",
1993
+ attachments,
1994
+ },
1995
+ } satisfies ProviderAdapter.ProviderAdapterV2SteerInput;
1996
+ if (scenario === "delivery-failure") {
1997
+ failOffer = true;
1998
+ assert.isTrue(Exit.isFailure(yield* runtime.steerTurn(steering).pipe(Effect.exit)));
1999
+ }
2000
+ yield* runtime.steerTurn(steering);
2001
+
2002
+ const sent = offeredMessages.at(-1)!.message.content;
2003
+ const documents =
2004
+ typeof sent === "string" ? [] : sent.filter((block) => block.type === "document");
2005
+ assert.lengthOf(
2006
+ documents,
2007
+ ["aggregate-pages", "delivery-failure"].includes(scenario) ? 1 : 0,
2008
+ scenario,
2009
+ );
2010
+ if (scenario === "text-only")
2011
+ assert.equal(sent, ultrathink ? "Ultrathink:\nContinue." : "Continue.");
2012
+ else assert.include(JSON.stringify(sent), documentPath);
2013
+ }
2014
}).pipe(
2015
Effect.provide(
2016
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
@@ -1833,7 +2256,10 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
2256
url: "http://127.0.0.1:43123/mcp",
2257
headers: { Authorization: "Bearer dummy-mcp-credential" },
2258
};
1836
- const openWith = (cli: ReturnType<typeof makeFakeClaudeCli>) =>
2259
+ const openWith = (
2260
+ cli: ReturnType<typeof makeFakeClaudeCli>,
2261
+ native?: ProviderEventLoggers.EventNdjsonLogger,
2262
+ ) =>
2263
Effect.gen(function* () {
2264
const runner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner;
2265
return yield* runner.open({
@@ -1854,13 +2280,39 @@ describe("ClaudeAdapterV2 MCP credential channel", () => {
2280
});
2281
}).pipe(
2282
Effect.provide(ClaudeAdapterV2.layerQueryRunner),
1857
- Effect.provideService(
1858
- ProviderEventLoggers.ProviderEventLoggers,
1859
- ProviderEventLoggers.NoOpProviderEventLoggers,
1860
- ),
2283
+ Effect.provideService(ProviderEventLoggers.ProviderEventLoggers, {
2284
+ ...ProviderEventLoggers.NoOpProviderEventLoggers,
2285
+ native,
2286
+ }),
2287
Effect.provide(NodeServices.layer),
2288
);
2289
2290
+ it.effect("commits queued delivery before interruptible protocol logging", () =>
2291
+ Effect.gen(function* () {
2292
+ const logging = yield* Deferred.make<void>();
2293
+ let committed = false;
2294
+ const cli = makeFakeClaudeCli();
2295
+ const session = yield* openWith(cli, {
2296
+ filePath: "/tmp/claude-queued-delivery.log",
2297
+ write: () =>
2298
+ committed
2299
+ ? Deferred.succeed(logging, undefined).pipe(Effect.andThen(Effect.never))
2300
+ : Effect.void,
2301
+ close: () => Effect.void,
2302
+ });
2303
+ const offering = yield* session
2304
+ .offer(ClaudeAdapterV2.makeClaudeUserMessage({ text: "Inspect the attachment." }), () => {
2305
+ committed = true;
2306
+ })
2307
+ .pipe(Effect.forkChild);
2308
+ yield* Deferred.await(logging);
2309
+ yield* Fiber.interrupt(offering);
2310
+ assert.isTrue(committed);
2311
+ committed = false;
2312
+ yield* session.close;
2313
+ }),
2314
+ );
2315
+
2316
it.effect("sends MCP servers over stdin, not argv or the environment", () =>
2317
Effect.gen(function* () {
2318
const cli = makeFakeClaudeCli();
@@ -1974,6 +2426,9 @@ describe("ClaudeAdapterV2 native session identity", () => {
2426
});
2427
2428
const encodeJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
2429
+const providerThreadJson = Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ProviderThread));
2430
+const encodeProviderThreadJson = Schema.encodeEffect(providerThreadJson);
2431
+const decodeProviderThreadJson = Schema.decodeUnknownEffect(providerThreadJson);
2432
2433
describe("ClaudeAdapterV2 background wake turns", () => {
2434
const WAKE_NATIVE_SESSION = "native-thread-claude-wake";
@@ -2424,6 +2879,407 @@ describe("ClaudeAdapterV2 background wake turns", () => {
2879
});
2880
const makeWakeHarness = makeWakeHarnessWithOptions();
2881
2882
+ it.effect.each(["release-after", "cancel-after", "release-before", "resume-pending"] as const)(
2883
+ "keeps attachment reservations across compaction: %s boundary",
2884
+ (outcome) =>
2885
+ Effect.gen(function* () {
2886
+ const fileSystem = yield* FileSystem.FileSystem;
2887
+ const path = yield* Path.Path;
2888
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
2889
+ const backgrounding = yield* Deferred.make<void>();
2890
+ const release = yield* Deferred.make<void>();
2891
+ const harness = yield* makeWakeHarnessWithOptions({
2892
+ backgroundTasks: () =>
2893
+ Deferred.succeed(backgrounding, undefined).pipe(
2894
+ Effect.andThen(Deferred.await(release)),
2895
+ Effect.as(true),
2896
+ ),
2897
+ });
2898
+ const document = ChatFileAttachment.make({
2899
+ type: "file",
2900
+ id: ChatAttachmentId.make("compacting-document"),
2901
+ name: "compacting.pdf",
2902
+ mimeType: "application/pdf",
2903
+ sizeBytes: 19 * 1024 * 1024,
2904
+ });
2905
+ const pages = Buffer.from(
2906
+ `%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`,
2907
+ );
2908
+ yield* fileSystem.writeFile(
2909
+ path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
2910
+ Buffer.concat([
2911
+ pages,
2912
+ Buffer.alloc(document.sizeBytes - pages.length - 5, 32),
2913
+ Buffer.from("%%EOF"),
2914
+ ]),
2915
+ );
2916
+ const input = makeClaudeTestTurnInput({
2917
+ threadId: harness.threadId,
2918
+ providerThread: harness.providerThread,
2919
+ now: yield* DateTime.now,
2920
+ attemptId: RunAttemptId.make("compacting-reservation"),
2921
+ text: "Audit with a subagent.",
2922
+ attachments: [],
2923
+ });
2924
+ yield* harness.runtime.startTurn(input);
2925
+ yield* harness.offerAndWait(
2926
+ claudeSdkFrame({
2927
+ type: "system",
2928
+ subtype: "task_started",
2929
+ task_id: "compacting-task",
2930
+ tool_use_id: "compacting-tool",
2931
+ description: "Audit",
2932
+ subagent_type: "general-purpose",
2933
+ is_backgrounded: false,
2934
+ task_type: "local_agent",
2935
+ prompt: "Audit.",
2936
+ uuid: "00000000-0000-4000-8000-000000000811",
2937
+ session_id: WAKE_NATIVE_SESSION,
2938
+ }),
2939
+ );
2940
+ const steer = harness.runtime.steerTurn({
2941
+ threadId: harness.threadId,
2942
+ runId: input.runId,
2943
+ providerThread: harness.providerThread,
2944
+ providerTurnId: idAllocator.derive.providerTurn({
2945
+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
2946
+ nativeTurnId: `turn:${input.attemptId}`,
2947
+ }),
2948
+ message: {
2949
+ createdBy: "user",
2950
+ creationSource: "web",
2951
+ messageId: MessageId.make("compacting-steer"),
2952
+ text: "Read this PDF.",
2953
+ attachments: [document],
2954
+ },
2955
+ });
2956
+ const pending = yield* Effect.forkScoped(steer);
2957
+ yield* Deferred.await(backgrounding);
2958
+ assert.lengthOf(harness.offeredMessages, 1);
2959
+ yield* harness.offerAndWait(
2960
+ claudeSdkFrame({
2961
+ type: "system",
2962
+ subtype: "status",
2963
+ status: "compacting",
2964
+ uuid: "00000000-0000-4000-8000-000000000812",
2965
+ session_id: WAKE_NATIVE_SESSION,
2966
+ }),
2967
+ );
2968
+ if (outcome === "release-before") {
2969
+ yield* Deferred.succeed(release, undefined);
2970
+ yield* Fiber.join(pending);
2971
+ }
2972
+ yield* harness.offerAndWait(
2973
+ claudeSdkFrame({
2974
+ type: "system",
2975
+ subtype: "compact_boundary",
2976
+ compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 },
2977
+ uuid: "00000000-0000-4000-8000-000000000813",
2978
+ session_id: WAKE_NATIVE_SESSION,
2979
+ }),
2980
+ );
2981
+ if (outcome === "cancel-after") {
2982
+ yield* Fiber.interrupt(pending);
2983
+ assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(pending)));
2984
+ } else if (outcome === "release-after") {
2985
+ yield* Deferred.succeed(release, undefined);
2986
+ yield* Fiber.join(pending);
2987
+ }
2988
+ // Flush the budget update through the event stream before trying again.
2989
+ yield* harness.offerAndWait(
2990
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000814", result: "Read." }),
2991
+ );
2992
+ yield* Queue.take(harness.terminalReceipts);
2993
+ const updates = harness.events.flatMap((event) =>
2994
+ event.type === "provider_thread.updated" ? [event.providerThread] : [],
2995
+ );
2996
+ for (const thread of updates) {
2997
+ yield* decodeProviderThreadJson(yield* encodeProviderThreadJson(thread));
2998
+ }
2999
+ const persisted = yield* decodeProviderThreadJson(
3000
+ yield* encodeProviderThreadJson(updates.at(-1)!),
3001
+ );
3002
+ const usage = persisted.nativeMetadata?.claudeAttachmentBudget;
3003
+ const undelivered = outcome === "cancel-after" || outcome === "resume-pending";
3004
+ assert.equal(usage?.pagesUsed, undelivered ? 0 : 60);
3005
+ if (undelivered) assert.equal(usage?.bytesUsed, 0);
3006
+ else assert.isAbove(usage?.bytesUsed ?? 0, 25 * 1024 * 1024);
3007
+ const next = outcome === "resume-pending" ? yield* makeWakeHarness : harness;
3008
+ const providerThread =
3009
+ outcome === "resume-pending"
3010
+ ? yield* next.runtime.resumeThread({ providerThread: persisted })
3011
+ : persisted;
3012
+ if (outcome === "resume-pending") {
3013
+ assert.lengthOf(harness.offeredMessages, 1);
3014
+ yield* fileSystem.copyFile(
3015
+ path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
3016
+ path.join(next.attachmentsDir, attachmentRelativePath(document)!),
3017
+ );
3018
+ }
3019
+ yield* next.runtime.startTurn(
3020
+ makeClaudeTestTurnInput({
3021
+ threadId: next.threadId,
3022
+ providerThread,
3023
+ now: yield* DateTime.now,
3024
+ attemptId: RunAttemptId.make("after-compacting-reservation"),
3025
+ text: "Read this PDF again.",
3026
+ attachments: [document],
3027
+ providerTurnOrdinal: 2,
3028
+ nativeThreadHasTurns: true,
3029
+ }),
3030
+ );
3031
+ if (outcome === "resume-pending") {
3032
+ assert.equal(next.getOpenedOptions()?.resume, WAKE_NATIVE_SESSION);
3033
+ }
3034
+ const delivered = next.offeredMessages.slice(outcome === "resume-pending" ? 0 : 1);
3035
+ const documents = delivered.flatMap((message) =>
3036
+ Array.isArray(message.message.content)
3037
+ ? message.message.content.filter((block) => block.type === "document")
3038
+ : [],
3039
+ );
3040
+ assert.lengthOf(documents, 1);
3041
+ assert.isBelow(
3042
+ Buffer.byteLength(encodeJsonString(delivered.map((message) => message.message.content))),
3043
+ 32_000_000,
3044
+ );
3045
+ }).pipe(
3046
+ Effect.provide(
3047
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3048
+ ),
3049
+ ),
3050
+ );
3051
+
3052
+ const attachmentBudgetOutcomes = [
3053
+ "resume",
3054
+ "legacy",
3055
+ "compacted",
3056
+ "preserved-segment",
3057
+ "preserved-messages",
3058
+ "failed",
3059
+ "stopped",
3060
+ "fork-bytes",
3061
+ "fork-pages",
3062
+ ] as const;
3063
+ it.effect.each(attachmentBudgetOutcomes)(
3064
+ "restores retained attachment counters after %s",
3065
+ (outcome) =>
3066
+ Effect.gen(function* () {
3067
+ const fileSystem = yield* FileSystem.FileSystem;
3068
+ const path = yield* Path.Path;
3069
+ const document = ChatFileAttachment.make({
3070
+ type: "file",
3071
+ id: ChatAttachmentId.make("budget-document"),
3072
+ name: "budget.pdf",
3073
+ mimeType: "application/pdf",
3074
+ sizeBytes: 19 * 1024 * 1024,
3075
+ });
3076
+ const image = ChatImageAttachment.make({
3077
+ type: "image",
3078
+ id: ChatAttachmentId.make("budget-image"),
3079
+ name: "budget.png",
3080
+ mimeType: "image/png",
3081
+ sizeBytes: 4 * 1024 * 1024,
3082
+ });
3083
+ const pages = Buffer.from(
3084
+ `%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`,
3085
+ );
3086
+ const persisted = yield* Effect.scoped(
3087
+ Effect.gen(function* () {
3088
+ const harness = yield* makeWakeHarness;
3089
+ yield* fileSystem.writeFile(
3090
+ path.join(harness.attachmentsDir, attachmentRelativePath(document)!),
3091
+ Buffer.concat([
3092
+ pages,
3093
+ Buffer.alloc(document.sizeBytes - pages.length - 5, 32),
3094
+ Buffer.from("%%EOF"),
3095
+ ]),
3096
+ );
3097
+ yield* harness.runtime.startTurn(
3098
+ makeClaudeTestTurnInput({
3099
+ threadId: harness.threadId,
3100
+ providerThread: harness.providerThread,
3101
+ now: yield* DateTime.now,
3102
+ attemptId: RunAttemptId.make("spend-attachment-budget"),
3103
+ text: "Read this PDF.",
3104
+ attachments: [document],
3105
+ }),
3106
+ );
3107
+ const first = harness.offeredMessages[0]?.message.content;
3108
+ assert.isArray(first);
3109
+ if (Array.isArray(first)) assert.equal(first[0]?.type, "document");
3110
+ if (
3111
+ [
3112
+ "compacted",
3113
+ "preserved-segment",
3114
+ "preserved-messages",
3115
+ "failed",
3116
+ "stopped",
3117
+ ].includes(outcome)
3118
+ ) {
3119
+ yield* harness.offerAndWait(
3120
+ claudeSdkFrame({
3121
+ type: "system",
3122
+ subtype: "status",
3123
+ status: "compacting",
3124
+ uuid: "00000000-0000-4000-8000-000000000801",
3125
+ session_id: WAKE_NATIVE_SESSION,
3126
+ }),
3127
+ );
3128
+ yield* harness.offerAndWait(
3129
+ claudeSdkFrame(
3130
+ outcome === "compacted" ||
3131
+ outcome === "preserved-segment" ||
3132
+ outcome === "preserved-messages"
3133
+ ? {
3134
+ type: "system",
3135
+ subtype: "compact_boundary",
3136
+ compact_metadata: {
3137
+ trigger: "auto",
3138
+ pre_tokens: 1500,
3139
+ post_tokens: 400,
3140
+ ...(outcome === "preserved-segment"
3141
+ ? {
3142
+ preserved_segment: {
3143
+ head_uuid: harness.promptUuid(0),
3144
+ tail_uuid: harness.promptUuid(0),
3145
+ anchor_uuid: "00000000-0000-4000-8000-000000000802",
3146
+ },
3147
+ }
3148
+ : outcome === "preserved-messages"
3149
+ ? {
3150
+ preserved_messages: {
3151
+ anchor_uuid: "00000000-0000-4000-8000-000000000802",
3152
+ uuids: [harness.promptUuid(0)],
3153
+ },
3154
+ }
3155
+ : {}),
3156
+ },
3157
+ uuid: "00000000-0000-4000-8000-000000000802",
3158
+ session_id: WAKE_NATIVE_SESSION,
3159
+ }
3160
+ : {
3161
+ type: "system",
3162
+ subtype: "status",
3163
+ status: null,
3164
+ ...(outcome === "failed"
3165
+ ? { compact_result: "failed", compact_error: "Could not compact." }
3166
+ : {}),
3167
+ uuid: "00000000-0000-4000-8000-000000000802",
3168
+ session_id: WAKE_NATIVE_SESSION,
3169
+ },
3170
+ ),
3171
+ );
3172
+ }
3173
+ yield* harness.offerAndWait(
3174
+ makeResultFrame({
3175
+ uuid: "00000000-0000-4000-8000-000000000803",
3176
+ result: "Read.",
3177
+ }),
3178
+ );
3179
+ yield* Queue.take(harness.terminalReceipts);
3180
+ const event = harness.events.findLast(
3181
+ (entry) => entry.type === "provider_thread.updated",
3182
+ );
3183
+ assert.equal(event?.type, "provider_thread.updated");
3184
+ if (event?.type !== "provider_thread.updated")
3185
+ return yield* Effect.die("Missing persisted thread");
3186
+ const budget = event.providerThread.nativeMetadata?.claudeAttachmentBudget;
3187
+ assert.isDefined(budget);
3188
+ if (outcome === "compacted") assert.deepEqual(budget, { bytesUsed: 0, pagesUsed: 0 });
3189
+ else {
3190
+ assert.equal(budget?.pagesUsed, 100);
3191
+ assert.isAbove(budget?.bytesUsed ?? 0, 25 * 1024 * 1024);
3192
+ }
3193
+ // Exercise the same schema boundary as the persisted provider thread.
3194
+ return yield* decodeProviderThreadJson(
3195
+ yield* encodeProviderThreadJson({
3196
+ ...event.providerThread,
3197
+ ...(outcome === "legacy" ? { nativeMetadata: null } : {}),
3198
+ }),
3199
+ );
3200
+ }),
3201
+ );
3202
+ const fork = outcome === "fork-bytes" || outcome === "fork-pages";
3203
+ const inherited = fork
3204
+ ? yield* Effect.scoped(
3205
+ Effect.gen(function* () {
3206
+ const harness = yield* makeWakeHarnessWithOptions({
3207
+ forkSession: () =>
3208
+ Effect.succeed({
3209
+ sessionId: "forked-native-session",
3210
+ ...(outcome === "fork-bytes"
3211
+ ? { headMessageId: "forked-assistant-head" }
3212
+ : {}),
3213
+ }),
3214
+ });
3215
+ const forked = yield* harness.runtime.forkThread({
3216
+ sourceProviderThread: persisted,
3217
+ targetThreadId: harness.threadId,
3218
+ });
3219
+ return yield* decodeProviderThreadJson(yield* encodeProviderThreadJson(forked));
3220
+ }),
3221
+ )
3222
+ : persisted;
3223
+ const resumed = yield* makeWakeHarness;
3224
+ const providerThread = yield* resumed.runtime.resumeThread({ providerThread: inherited });
3225
+ yield* fileSystem.writeFileString(
3226
+ path.join(resumed.attachmentsDir, attachmentRelativePath(document)!),
3227
+ "%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",
3228
+ );
3229
+ yield* fileSystem.writeFile(
3230
+ path.join(resumed.attachmentsDir, attachmentRelativePath(image)!),
3231
+ Buffer.alloc(image.sizeBytes, 1),
3232
+ );
3233
+ yield* resumed.runtime.startTurn({
3234
+ ...makeClaudeTestTurnInput({
3235
+ threadId: resumed.threadId,
3236
+ providerThread,
3237
+ now: yield* DateTime.now,
3238
+ attemptId: RunAttemptId.make("resume-attachment-budget"),
3239
+ text: "Read the PDF and both images.",
3240
+ attachments:
3241
+ outcome === "fork-bytes"
3242
+ ? [image, image]
3243
+ : outcome === "fork-pages"
3244
+ ? [document]
3245
+ : [document, image, image],
3246
+ }),
3247
+ nativeThreadHasTurns: true,
3248
+ });
3249
+ assert.equal(
3250
+ resumed.getOpenedOptions()?.resume,
3251
+ fork ? "forked-native-session" : WAKE_NATIVE_SESSION,
3252
+ );
3253
+ const content = resumed.offeredMessages[0]?.message.content;
3254
+ assert.isArray(content);
3255
+ if (!Array.isArray(content)) return;
3256
+ const native = outcome === "legacy" || outcome === "compacted";
3257
+ assert.equal(content.filter((block) => block.type === "document").length, native ? 1 : 0);
3258
+ assert.equal(content.filter((block) => block.type === "image").length, native ? 2 : 0);
3259
+ assert.isBelow(Buffer.byteLength(encodeJsonString(content)), 32_000_000);
3260
+ if (fork) {
3261
+ assert.deepEqual(
3262
+ inherited.nativeMetadata?.claudeAttachmentBudget,
3263
+ persisted.nativeMetadata?.claudeAttachmentBudget,
3264
+ );
3265
+ assert.equal(
3266
+ inherited.nativeMetadata?.forkHeadMessageId,
3267
+ outcome === "fork-bytes" ? "forked-assistant-head" : undefined,
3268
+ );
3269
+ assert.isBelow(
3270
+ (persisted.nativeMetadata?.claudeAttachmentBudget?.bytesUsed ?? 0) +
3271
+ Buffer.byteLength(encodeJsonString(content)),
3272
+ 32_000_000,
3273
+ );
3274
+ assert.include(encodeJsonString(content), "budget.");
3275
+ }
3276
+ }).pipe(
3277
+ Effect.provide(
3278
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
3279
+ ),
3280
+ ),
3281
+ );
3282
+
3283
describe("Claude settings restrictions", () => {
3284
it.effect("resolves cached managed policy from the configured home through the real SDK", () =>
3285
Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+395
-34
@@ -64,6 +64,7 @@ import {
64
} from "@t3tools/shared/claudeCompaction";
65
import {
66
type ChatAttachment,
67
+ PROVIDER_SEND_TURN_MAX_FILE_BYTES,
68
ClaudeSettings,
69
TrimmedNonEmptyString,
70
defaultInstanceIdForDriver,
@@ -499,7 +500,10 @@ export interface ClaudeAgentSdkQueryOpenInput {
500
501
export interface ClaudeAgentSdkQuerySession {
502
readonly messages: Stream.Stream<SDKMessage, ClaudeAgentSdkQueryRunnerError>;
502
- readonly offer: (message: SDKUserMessage) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
503
+ readonly offer: (
504
+ message: SDKUserMessage,
505
+ onQueued?: () => void,
506
+ ) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
507
readonly setModel: (model: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
508
readonly applyFlagSettings: (
509
settings: ClaudeFlagSettings,
@@ -815,7 +819,7 @@ function makeClaudeAgentSdkProtocolLogger(input: {
819
};
820
}
821
818
-const encodeClaudeHistoryOptions = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
822
+const encodeClaudeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
823
const decodeClaudeHistoryFork = Schema.decodeUnknownEffect(
824
Schema.fromJsonString(
825
Schema.Struct({ sessionId: Schema.String, headMessageId: Schema.optionalKey(Schema.String) }),
@@ -830,9 +834,12 @@ const claudeConfigDirOf = (
834
835
// The SDK reads CLAUDE_CONFIG_DIR from process.env. Isolate custom homes in a
836
// worker so concurrent providers keep the server's environment.
833
-const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
834
- input: ClaudeAgentSdkSessionForkInput,
835
-) {
837
+const runClaudeWorker = Effect.fn("runClaudeWorker")(function* (input: {
838
+ readonly method: "forkSession";
839
+ readonly sessionId: string;
840
+ readonly options?: ForkSessionOptions;
841
+ readonly environment: NodeJS.ProcessEnv;
842
+}) {
843
const path = yield* Path.Path;
844
const fromSource = import.meta.url.endsWith(".ts");
845
// A single executable hosts the worker itself; it has no sibling script.
@@ -852,22 +859,30 @@ const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(functio
859
executablePath,
860
ChildProcess.make(
861
executablePath,
855
- [
856
- ...workerArguments,
857
- "forkSession",
858
- input.sessionId,
859
- encodeClaudeHistoryOptions(input.options),
860
- ],
861
- { env: { ...input.environment, ELECTRON_RUN_AS_NODE: "1" } },
862
+ [...workerArguments, input.method, input.sessionId, encodeClaudeJson(input.options ?? {})],
863
+ {
864
+ env: {
865
+ ...input.environment,
866
+ ELECTRON_RUN_AS_NODE: "1",
867
+ },
868
+ },
869
),
870
).pipe(Effect.timeout("30 seconds"));
871
if (result.code !== 0) {
872
return yield* new ClaudeAgentSdkQueryRunnerError({
866
- method: "forkSession",
873
+ method: input.method,
874
cause: result.stderr.trim() || `Claude history worker exited with code ${result.code}.`,
875
});
876
}
870
- return yield* decodeClaudeHistoryFork(result.stdout);
877
+ return result.stdout;
878
+});
879
+
880
+const forkClaudeSessionInWorker = Effect.fn("forkClaudeSessionInWorker")(function* (
881
+ input: ClaudeAgentSdkSessionForkInput,
882
+) {
883
+ return yield* runClaudeWorker({ ...input, method: "forkSession" }).pipe(
884
+ Effect.flatMap(decodeClaudeHistoryFork),
885
+ );
886
});
887
888
export const layerQueryRunner: Layer.Layer<
@@ -1015,8 +1030,12 @@ export const layerQueryRunner: Layer.Layer<
1030
}),
1031
),
1032
),
1018
- offer: (message) =>
1019
- Queue.offer(promptQueue, message).pipe(
1033
+ offer: (message, onQueued) =>
1034
+ Effect.uninterruptibleMask((restore) =>
1035
+ restore(Queue.offer(promptQueue, message)).pipe(
1036
+ Effect.tap(() => Effect.sync(() => onQueued?.())),
1037
+ ),
1038
+ ).pipe(
1039
Effect.asVoid,
1040
Effect.tap(() =>
1041
logProtocolEvent({
@@ -1884,6 +1903,138 @@ export function makeClaudeUserMessage(input: {
1903
};
1904
}
1905
1906
+// Never decode streams just to enforce a provider limit. Only accept an explicit,
1907
+// uncompressed page tree whose /Count agrees with the visible page objects.
1908
+const estimateClaudePdfPages = (bytes: Buffer): number | null => {
1909
+ if (bytes.length > 20 * 1024 * 1024 || bytes.subarray(0, 5).toString() !== "%PDF-") return null;
1910
+ if (!bytes.subarray(-1024).includes("%%EOF")) return null;
1911
+ let pages = 0;
1912
+ let count = 0;
1913
+ let catalog = false;
1914
+ let pageTree = false;
1915
+ let previous = "";
1916
+ const delimiter = (byte: number) =>
1917
+ byte <= 32 || "()<>[]{}/%".includes(String.fromCharCode(byte));
1918
+ for (let i = 0; i < bytes.length;) {
1919
+ const byte = bytes[i]!;
1920
+ if (byte === 37) {
1921
+ while (i < bytes.length && bytes[i] !== 10 && bytes[i] !== 13) i++;
1922
+ continue;
1923
+ }
1924
+ if (byte <= 32) {
1925
+ i++;
1926
+ continue;
1927
+ }
1928
+ if (previous === "/Type" && byte !== 47) return null;
1929
+ if (previous === "/Kids") {
1930
+ if (byte !== 91) return null;
1931
+ previous = "";
1932
+ }
1933
+ if (byte === 40) {
1934
+ let depth = 1;
1935
+ for (i++; i < bytes.length && depth > 0; i++) {
1936
+ if (bytes[i] === 92) i++;
1937
+ else if (bytes[i] === 40) depth++;
1938
+ else if (bytes[i] === 41) depth--;
1939
+ }
1940
+ if (depth !== 0) return null;
1941
+ previous = "";
1942
+ continue;
1943
+ }
1944
+ if (byte === 60 && bytes[i + 1] !== 60) {
1945
+ i = bytes.indexOf(62, i + 1);
1946
+ if (i < 0) return null;
1947
+ i++;
1948
+ previous = "";
1949
+ continue;
1950
+ }
1951
+ if (byte === 60 && bytes[i + 1] === 60) {
1952
+ i += 2;
1953
+ previous = "";
1954
+ continue;
1955
+ }
1956
+ if (delimiter(byte) && byte !== 47) {
1957
+ i++;
1958
+ continue;
1959
+ }
1960
+ const start = i++;
1961
+ while (i < bytes.length && !delimiter(bytes[i]!)) i++;
1962
+ if (i - start > 64) return null;
1963
+ const token = bytes.toString("latin1", start, i);
1964
+ if (token.includes("#") || ["/ObjStm", "/XRef", "/Encrypt", "/Prev"].includes(token))
1965
+ return null;
1966
+ if (token === "stream") {
1967
+ i = bytes.indexOf("endstream", i);
1968
+ if (i < 0) return null;
1969
+ i += 9;
1970
+ previous = "";
1971
+ continue;
1972
+ }
1973
+ if (previous === "/Type") {
1974
+ if (token === "/Page") pages++;
1975
+ if (token === "/Catalog") catalog = true;
1976
+ if (token === "/Pages") pageTree = true;
1977
+ }
1978
+ if (previous === "/Count") {
1979
+ if (!/^[1-9]\d{0,8}$/.test(token)) return null;
1980
+ let next = i;
1981
+ while (next < bytes.length) {
1982
+ if (bytes[next]! <= 32) next++;
1983
+ else if (bytes[next] === 37) {
1984
+ while (next < bytes.length && bytes[next] !== 10 && bytes[next] !== 13) next++;
1985
+ } else break;
1986
+ }
1987
+ // A second scalar is an indirect reference, not a direct page count.
1988
+ if (next < bytes.length && !delimiter(bytes[next]!)) return null;
1989
+ count = Math.max(count, Number(token));
1990
+ }
1991
+ previous = token;
1992
+ }
1993
+ return catalog && pageTree && pages > 0 && count === pages ? pages : null;
1994
+};
1995
+
1996
+const CLAUDE_ATTACHMENT_MAX_BYTES = 28 * 1024 * 1024;
1997
+const CLAUDE_ATTACHMENT_MAX_PAGES = 100;
1998
+
1999
+const makeClaudeAttachmentBudget = (used?: { pagesUsed: number; bytesUsed: number }) => ({
2000
+ committed: { pages: used?.pagesUsed ?? 0, bytes: used?.bytesUsed ?? 0 },
2001
+ pending: { pages: 0, bytes: 0 },
2002
+ compacting: null as { pages: number; bytes: number } | null,
2003
+ get remainingPages() {
2004
+ return CLAUDE_ATTACHMENT_MAX_PAGES - this.committed.pages - this.pending.pages;
2005
+ },
2006
+ get remainingBytes() {
2007
+ return CLAUDE_ATTACHMENT_MAX_BYTES - this.committed.bytes - this.pending.bytes;
2008
+ },
2009
+});
2010
+
2011
+const reserveClaudePdfBudget = (
2012
+ budget: ReturnType<typeof makeClaudeAttachmentBudget>,
2013
+ persist: Effect.Effect<void>,
2014
+) =>
2015
+ Effect.acquireRelease(
2016
+ Effect.sync(() => ({
2017
+ budget,
2018
+ pages: 0,
2019
+ bytes: 0,
2020
+ delivered: false,
2021
+ commit() {
2022
+ if (this.delivered) return;
2023
+ this.delivered = true;
2024
+ budget.pending.pages -= this.pages;
2025
+ budget.pending.bytes -= this.bytes;
2026
+ budget.committed.pages += this.pages;
2027
+ budget.committed.bytes += this.bytes;
2028
+ },
2029
+ })),
2030
+ (reservation) =>
2031
+ Effect.sync(() => {
2032
+ if (reservation.delivered) return;
2033
+ budget.pending.pages -= reservation.pages;
2034
+ budget.pending.bytes -= reservation.bytes;
2035
+ }).pipe(Effect.andThen(persist)),
2036
+ );
2037
+
2038
const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input: {
2039
readonly text: string;
2040
readonly attachments: ReadonlyArray<ChatAttachment>;
@@ -1891,15 +2042,20 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
2042
readonly uuid?: SDKUserMessage["uuid"];
2043
readonly attachmentsDir: string;
2044
readonly fileSystem: FileSystem.FileSystem;
2045
+ readonly pdfReservation: Effect.Success<ReturnType<typeof reserveClaudePdfBudget>>;
2046
readonly skills?: ReadonlyMap<string, ClaudeSkillTarget>;
2047
}) {
2048
if (input.attachments.length === 0) {
1897
- return makeClaudeUserMessage({
2049
+ const message = makeClaudeUserMessage({
2050
text: input.text,
2051
...(input.skills === undefined ? {} : { skills: input.skills }),
2052
...(input.priority === undefined ? {} : { priority: input.priority }),
2053
...(input.uuid === undefined ? {} : { uuid: input.uuid }),
2054
});
2055
+ const bytes = Buffer.byteLength(encodeClaudeJson(message.message.content));
2056
+ input.pdfReservation.budget.pending.bytes += bytes;
2057
+ input.pdfReservation.bytes += bytes;
2058
+ return message;
2059
}
2060
2061
const textWithAttachmentPaths = providerMessageTextWithAttachmentPaths({
@@ -1914,21 +2070,39 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
2070
? undefined
2071
: planClaudeSkillDispatch(textWithAttachmentPaths, input.skills);
2072
const content: Array<ClaudeUserContentBlock> = [];
2073
+ // Base64 adds a third to the payload. Leave room below Anthropic's 32 MB
2074
+ // request limit for text, instructions, and SDK framing. The SDK does not
2075
+ // expose document/context-window capabilities, so use the 100-page limit
2076
+ // that also applies to models with less than a 1M-token context window.
2077
if (dispatch?.leadingText !== undefined) {
2078
content.push({ type: "text", text: dispatch.leadingText });
2079
}
2080
1921
- for (const attachment of input.attachments) {
1922
- if (attachment.type === "file") {
1923
- continue;
1924
- }
2081
+ // Reserve all text and actual image bytes before considering any document,
2082
+ // including images that follow it in attachment order.
2083
+ const images = new Map<number, ClaudeUserContentBlock>();
2084
+ const textBytes = Buffer.byteLength(
2085
+ encodeClaudeJson(
2086
+ dispatch
2087
+ ? [
2088
+ ...(dispatch.leadingText === undefined
2089
+ ? []
2090
+ : [{ type: "text", text: dispatch.leadingText }]),
2091
+ { type: "text", text: dispatch.commandText },
2092
+ ]
2093
+ : [{ type: "text", text: textWithAttachmentPaths }],
2094
+ ),
2095
+ );
2096
+ input.pdfReservation.budget.pending.bytes += textBytes;
2097
+ input.pdfReservation.bytes += textBytes;
2098
+ for (const [index, attachment] of input.attachments.entries()) {
2099
+ if (attachment.type !== "image") continue;
2100
if (!isSupportedClaudeImageMimeType(attachment.mimeType)) {
2101
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
2102
driver: CLAUDE_PROVIDER,
2103
detail: `Unsupported Claude image attachment type '${attachment.mimeType}'`,
2104
});
2105
}
1931
-
2106
const attachmentPath = resolveAttachmentPath({
2107
attachmentsDir: input.attachmentsDir,
2108
attachment,
@@ -1939,7 +2113,6 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
2113
detail: `Invalid attachment id '${attachment.id}'`,
2114
});
2115
}
1942
-
2116
const bytes = yield* input.fileSystem.readFile(attachmentPath).pipe(
2117
Effect.mapError(
2118
(cause) =>
@@ -1951,14 +2124,76 @@ const makeClaudeUserMessageWithAttachments = Effect.fnUntraced(function* (input:
2124
}),
2125
),
2126
);
1954
- content.push({
2127
+ const retainedBytes = 4 * Math.ceil(bytes.length / 3) + 128;
2128
+ if (retainedBytes > input.pdfReservation.budget.remainingBytes) continue;
2129
+ input.pdfReservation.budget.pending.bytes += retainedBytes;
2130
+ input.pdfReservation.bytes += retainedBytes;
2131
+ const block: ClaudeUserContentBlock = {
2132
type: "image",
2133
source: {
2134
type: "base64",
2135
media_type: attachment.mimeType,
2136
data: Buffer.from(bytes).toString("base64"),
2137
},
1961
- });
2138
+ };
2139
+ images.set(index, block);
2140
+ }
2141
+ for (const [index, attachment] of input.attachments.entries()) {
2142
+ if (attachment.type === "file") {
2143
+ if (
2144
+ input.pdfReservation.budget.remainingPages <= 0 ||
2145
+ attachment.mimeType.toLowerCase().split(";", 1)[0]?.trim() !== "application/pdf" ||
2146
+ ("source" in attachment && attachment.source?._tag === "pasted-text")
2147
+ )
2148
+ continue;
2149
+ const attachmentPath = resolveAttachmentPath({
2150
+ attachmentsDir: input.attachmentsDir,
2151
+ attachment,
2152
+ });
2153
+ if (attachmentPath === null) continue;
2154
+ const remainingBytes = Math.min(
2155
+ PROVIDER_SEND_TURN_MAX_FILE_BYTES,
2156
+ 20 * 1024 * 1024,
2157
+ Math.floor(((input.pdfReservation.budget.remainingBytes - 1024) * 3) / 4),
2158
+ );
2159
+ const info = yield* input.fileSystem
2160
+ .stat(attachmentPath)
2161
+ .pipe(Effect.orElseSucceed(() => null));
2162
+ if (info?.type !== "File" || Number(info.size) > remainingBytes || remainingBytes <= 0)
2163
+ continue;
2164
+ const bytes = yield* input.fileSystem
2165
+ .stream(attachmentPath, { bytesToRead: remainingBytes + 1 })
2166
+ .pipe(
2167
+ Stream.runCollect,
2168
+ Effect.map((chunks) => Buffer.concat(chunks)),
2169
+ Effect.orElseSucceed(() => null),
2170
+ );
2171
+ if (bytes === null || bytes.length > remainingBytes) continue;
2172
+ const pageCount = estimateClaudePdfPages(bytes);
2173
+ if (pageCount === null) {
2174
+ yield* Effect.logDebug("Claude PDF page count is unknown; keeping attachment path-only.");
2175
+ continue;
2176
+ }
2177
+ const retainedBytes = 4 * Math.ceil(bytes.length / 3) + 128;
2178
+ if (
2179
+ pageCount <= 0 ||
2180
+ pageCount > input.pdfReservation.budget.remainingPages ||
2181
+ retainedBytes > input.pdfReservation.budget.remainingBytes
2182
+ )
2183
+ continue;
2184
+ input.pdfReservation.budget.pending.pages += pageCount;
2185
+ input.pdfReservation.pages += pageCount;
2186
+ const block: ClaudeUserContentBlock = {
2187
+ type: "document",
2188
+ source: { type: "base64", media_type: "application/pdf", data: bytes.toString("base64") },
2189
+ };
2190
+ input.pdfReservation.budget.pending.bytes += retainedBytes;
2191
+ input.pdfReservation.bytes += retainedBytes;
2192
+ content.push(block);
2193
+ continue;
2194
+ }
2195
+ const image = images.get(index);
2196
+ if (image !== undefined) content.push(image);
2197
}
2198
2199
// Images must precede the command block for skill expansion.
@@ -3921,6 +4156,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4156
adapterOptions: ClaudeAdapterV2Options,
4157
) {
4158
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
4159
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
4160
const serverSettings = yield* Effect.serviceOption(ServerSettings.ServerSettingsService);
4161
const { attachmentsDir, fileSystem, path, crypto, idAllocator, queryRunner } = adapterOptions;
4162
const subagentModelCatalog = scopeClaudeModelCatalog(
@@ -4170,6 +4406,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4406
);
4407
});
4408
const openedNativeThreads = yield* Ref.make(new Set<string>());
4409
+ const pdfBudgets = new Map<string, ReturnType<typeof makeClaudeAttachmentBudget>>();
4410
const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>());
4411
// Claude 5 task tools edit one list per native session, across turns.
4412
const taskListsByNativeThread = yield* Ref.make(
@@ -4382,8 +4619,44 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
4619
const runtimeContext = yield* Effect.context<never>();
4620
const runPromise = Effect.runPromiseWith(runtimeContext);
4621
4385
- const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
4386
- Queue.offer(events, event).pipe(Effect.asVoid);
4622
+ const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => {
4623
+ if (event.type === "provider_thread.updated") {
4624
+ const budget = pdfBudgets.get(event.providerThread.nativeThreadRef?.nativeId ?? "");
4625
+ if (budget !== undefined) {
4626
+ event = {
4627
+ ...event,
4628
+ providerThread: {
4629
+ ...event.providerThread,
4630
+ nativeMetadata: {
4631
+ ...event.providerThread.nativeMetadata,
4632
+ claudeAttachmentBudget: {
4633
+ bytesUsed: budget.committed.bytes,
4634
+ pagesUsed: budget.committed.pages,
4635
+ },
4636
+ },
4637
+ },
4638
+ };
4639
+ }
4640
+ }
4641
+ return Queue.offer(events, event).pipe(Effect.asVoid);
4642
+ };
4643
+
4644
+ const persistAttachmentBudget = Effect.fnUntraced(function* (nativeThreadId: string) {
4645
+ const providerThread = (yield* Ref.get(lastProviderThreadByNativeThread)).get(
4646
+ nativeThreadId,
4647
+ );
4648
+ if (providerThread === undefined) return;
4649
+ const active = yield* Ref.get(activeTurn);
4650
+ yield* emitProviderEvent({
4651
+ type: "provider_thread.updated",
4652
+ driver: CLAUDE_PROVIDER,
4653
+ providerThread: {
4654
+ ...providerThread,
4655
+ status: active?.nativeThreadId === nativeThreadId ? "active" : providerThread.status,
4656
+ updatedAt: yield* DateTime.now,
4657
+ },
4658
+ });
4659
+ });
4660
4661
// Usage without input is a placeholder, not a context measurement.
4662
const emitContextUsage = Effect.fnUntraced(function* (
@@ -7819,7 +8092,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8092
driver: CLAUDE_PROVIDER,
8093
turnItem: context.compaction,
8094
});
7822
- if (message.compact_result !== "success") context.compaction = null;
8095
+ if (message.compact_result !== "success") {
8096
+ context.compaction = null;
8097
+ const budget = pdfBudgets.get(context.nativeThreadId);
8098
+ if (budget !== undefined) budget.compacting = null;
8099
+ }
8100
}
8101
}
8102
@@ -7859,6 +8136,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8136
updatedAt: now,
8137
} satisfies OrchestrationV2TurnItem);
8138
if (message.subtype === "status") {
8139
+ const budget = pdfBudgets.get(context.nativeThreadId);
8140
+ // Offers made while compaction runs are outside the history it
8141
+ // removes. Pending reservations must survive its boundary too.
8142
+ if (budget !== undefined) budget.compacting = { ...budget.committed };
8143
context.compaction = compaction;
8144
yield* emitProviderEvent({
8145
type: "turn_item.updated",
@@ -7867,6 +8148,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
8148
});
8149
return;
8150
}
8151
+ const budget = pdfBudgets.get(context.nativeThreadId);
8152
+ if (budget !== undefined) {
8153
+ // Aggregate persisted usage cannot identify attachments in a
8154
+ // preserved segment. Retain it conservatively on partial compacts.
8155
+ if (
8156
+ message.compact_metadata.preserved_segment === undefined &&
8157
+ message.compact_metadata.preserved_messages === undefined
8158
+ ) {
8159
+ const compacted = budget.compacting ?? { ...budget.committed };
8160
+ budget.committed.pages -= compacted.pages;
8161
+ budget.committed.bytes -= compacted.bytes;
8162
+ }
8163
+ budget.compacting = null;
8164
+ yield* persistAttachmentBudget(context.nativeThreadId);
8165
+ }
8166
if (context.streamUsage !== null) context.streamUsage.usage = null;
8167
const postTokens = message.compact_metadata.post_tokens;
8168
const afterTokenCount =
@@ -9520,6 +9816,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9816
if (!goalsByNativeThread.has(nativeThreadId)) {
9817
goalsByNativeThread.set(nativeThreadId, turnInput.providerThread.goal ?? null);
9818
}
9819
+ if (!pdfBudgets.has(nativeThreadId)) {
9820
+ // Older sessions did not record retained attachments. Keep their
9821
+ // existing native-image allowance rather than disabling images.
9822
+ const used = turnInput.providerThread.nativeMetadata?.claudeAttachmentBudget;
9823
+ pdfBudgets.set(nativeThreadId, makeClaudeAttachmentBudget(used));
9824
+ }
9825
+ const pdfReservation = yield* reserveClaudePdfBudget(
9826
+ pdfBudgets.get(nativeThreadId)!,
9827
+ persistAttachmentBudget(nativeThreadId),
9828
+ );
9829
const userMessage =
9830
promptUuid === null
9831
? null
@@ -9531,9 +9837,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9837
attachments: turnInput.message.attachments,
9838
attachmentsDir,
9839
fileSystem,
9840
+ pdfReservation,
9841
skills: yield* userInvocableSkills(turnInput.runtimePolicy.cwd),
9842
uuid: promptUuid,
9536
- });
9843
+ }).pipe(
9844
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
9845
+ Effect.provideService(Path.Path, path),
9846
+ );
9847
const querySession = yield* openQuery(turnInput, nativeThreadId);
9848
const context: ActiveClaudeTurnContext = {
9849
input: turnInput,
@@ -9642,7 +9952,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9952
if (userMessage !== null) {
9953
yield* attachTurn;
9954
yield* startUserTurnForWakeReports(nativeThreadId);
9645
- yield* querySession.query.offer(userMessage);
9955
+ yield* Effect.uninterruptibleMask((restore) =>
9956
+ restore(
9957
+ querySession.query.offer(userMessage, () => {
9958
+ pdfReservation.commit();
9959
+ }),
9960
+ ).pipe(
9961
+ Effect.tap(() =>
9962
+ Effect.sync(() => {
9963
+ pdfReservation.commit();
9964
+ }),
9965
+ ),
9966
+ ),
9967
+ );
9968
return;
9969
}
9970
// 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* (
10090
},
10091
(effect, turnInput) =>
10092
effect.pipe(
10093
+ Effect.scoped,
10094
Effect.mapError(
10095
(cause) =>
10096
new ProviderAdapter.ProviderAdapterTurnStartError({
@@ -9951,6 +10274,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10274
detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`,
10275
});
10276
}
10277
+ const pdfReservation = yield* reserveClaudePdfBudget(
10278
+ pdfBudgets.get(existing.nativeThreadId) ??
10279
+ makeClaudeAttachmentBudget({
10280
+ pagesUsed: CLAUDE_ATTACHMENT_MAX_PAGES,
10281
+ bytesUsed: CLAUDE_ATTACHMENT_MAX_BYTES,
10282
+ }),
10283
+ persistAttachmentBudget(existing.nativeThreadId),
10284
+ );
10285
const userMessage = yield* makeClaudeUserMessageWithAttachments({
10286
text: applyClaudePromptEffortPrefix(
10287
turnInput.message.text,
@@ -9960,8 +10291,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10291
priority: "now",
10292
attachmentsDir,
10293
fileSystem,
10294
+ pdfReservation,
10295
skills: yield* userInvocableSkills(currentTurn.input.runtimePolicy.cwd),
9964
- });
10296
+ }).pipe(
10297
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
10298
+ Effect.provideService(Path.Path, path),
10299
+ );
10300
yield* backgroundForegroundSubagents(existing, backgroundDeadline);
10301
// The turn can end while the moves are answered. A steer offered
10302
// then would start a new turn the orchestrator never asked for, so
@@ -9980,10 +10315,23 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10315
next.add(turnInput.providerTurnId);
10316
return next;
10317
});
9983
- yield* existing.query.offer(userMessage);
10318
+ yield* Effect.uninterruptibleMask((restore) =>
10319
+ restore(
10320
+ existing.query.offer(userMessage, () => {
10321
+ pdfReservation.commit();
10322
+ }),
10323
+ ).pipe(
10324
+ Effect.tap(() =>
10325
+ Effect.sync(() => {
10326
+ pdfReservation.commit();
10327
+ }),
10328
+ ),
10329
+ ),
10330
+ );
10331
},
10332
(effect, turnInput) =>
10333
effect.pipe(
10334
+ Effect.scoped,
10335
Effect.mapError(
10336
(cause) =>
10337
new ProviderAdapter.ProviderAdapterSteerRunError({
@@ -10489,6 +10837,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10837
return updated;
10838
});
10839
const now = yield* DateTime.now;
10840
+ // Native forks retain document/image history. Inherit full current
10841
+ // usage even at an earlier fork point; this is conservative.
10842
+ const claudeAttachmentBudget =
10843
+ forkInput.sourceProviderThread.nativeMetadata?.claudeAttachmentBudget;
10844
return makeProviderThread({
10845
idAllocator,
10846
providerInstanceId: adapterOptions.instanceId,
@@ -10502,9 +10854,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10854
? {}
10855
: { providerTurnId: forkInput.providerTurnId }),
10856
},
10505
- ...(forked.headMessageId === undefined
10857
+ ...(forked.headMessageId === undefined && claudeAttachmentBudget === undefined
10858
? {}
10507
- : { nativeMetadata: { forkHeadMessageId: forked.headMessageId } }),
10859
+ : {
10860
+ nativeMetadata: {
10861
+ ...(forked.headMessageId === undefined
10862
+ ? {}
10863
+ : { forkHeadMessageId: forked.headMessageId }),
10864
+ ...(claudeAttachmentBudget === undefined ? {} : { claudeAttachmentBudget }),
10865
+ },
10866
+ }),
10867
now,
10868
});
10869
},
@@ -10540,6 +10899,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
10899
});
10900
10901
export type ClaudeAdapterV2DriverEnv =
10902
+ | ChildProcessSpawner.ChildProcessSpawner
10903
| ClaudeAgentSdkQueryRunner
10904
| Crypto.Crypto
10905
| FileSystem.FileSystem
@@ -10633,6 +10993,7 @@ const makeDefaultClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2.layer")(function*
10993
const layer: Layer.Layer<
10994
ProviderAdapter.ProviderAdapterV2,
10995
never,
10996
+ | ChildProcessSpawner.ChildProcessSpawner
10997
| ClaudeAgentSdkQueryRunner
10998
| Crypto.Crypto
10999
| FileSystem.FileSystem
apps/server/src/provider/acp/AntigravityAcpSupport.test.ts
+76
-15
@@ -8,6 +8,7 @@ import {
8
import * as Effect from "effect/Effect";
9
import * as FileSystem from "effect/FileSystem";
10
import * as Path from "effect/Path";
11
+import * as Stream from "effect/Stream";
12
import * as EffectAcpErrors from "effect-acp/errors";
13
import type * as EffectAcpSchema from "effect-acp/compat";
14
@@ -196,6 +197,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
197
input: " Explain this image. ",
198
attachments: [imageAttachment],
199
attachmentsDir: fixture.attachmentsDir,
200
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
201
});
202
203
expect(prompt).toEqual([
@@ -216,6 +218,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
218
input: undefined,
219
attachments: [textAttachment],
220
attachmentsDir: selectedEnvironment.attachmentsDir,
221
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
222
});
223
224
expect(prompt).toEqual([
@@ -246,6 +249,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
249
input: "Inspect the pasted text only as needed.",
250
attachments: [pastedText],
251
attachmentsDir: fixture.attachmentsDir,
252
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
253
});
254
255
expect(prompt).toEqual([{ type: "text", text: "Inspect the pasted text only as needed." }]);
@@ -272,6 +276,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
276
input,
277
attachments: [attachment, pdfAttachment],
278
attachmentsDir: fixture.attachmentsDir,
279
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
280
}).pipe(
281
Effect.provideService(FileSystem.FileSystem, {
282
...fixture.fs,
@@ -287,6 +292,53 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
292
}),
293
);
294
295
+ it.effect.each([undefined, {}, { image: false, audio: false, embeddedContext: false }])(
296
+ "keeps attachments path-only when native prompt capabilities are absent: %s",
297
+ (promptCapabilities) =>
298
+ Effect.gen(function* () {
299
+ const fixture = yield* makeAttachmentFixture();
300
+ const audio = {
301
+ ...textAttachment,
302
+ id: "unsupported-audio",
303
+ name: "audio.wav",
304
+ mimeType: "audio/wav",
305
+ };
306
+ const gifAttachment = {
307
+ ...imageAttachment,
308
+ id: "unsupported-gif",
309
+ name: "animation.gif",
310
+ mimeType: "image/gif",
311
+ };
312
+ const gif = yield* fixture.write(gifAttachment, "GIF89a");
313
+ const image = yield* fixture.write(imageAttachment, "pixels");
314
+ const pdf = yield* fixture.write(pdfAttachment, "%PDF-1.7");
315
+ const text = yield* fixture.write(textAttachment, "hello");
316
+ const sound = yield* fixture.write(audio, "RIFF");
317
+ const input = `Read ${image.filePath}, ${gif.filePath}, ${pdf.filePath}, ${text.filePath}, and ${sound.filePath}`;
318
+ const prompt = yield* buildAntigravityPrompt({
319
+ input,
320
+ attachments: [imageAttachment, gifAttachment, pdfAttachment, textAttachment, audio],
321
+ attachmentsDir: fixture.attachmentsDir,
322
+ promptCapabilities,
323
+ }).pipe(
324
+ Effect.provideService(FileSystem.FileSystem, {
325
+ ...fixture.fs,
326
+ stream: () =>
327
+ Effect.die("Unnegotiated attachments must not be read").pipe(Stream.fromEffect),
328
+ }),
329
+ );
330
+ expect(prompt).toEqual([{ type: "text", text: input }]);
331
+ expect(
332
+ yield* buildAntigravityPrompt({
333
+ input: "Continue",
334
+ attachments: [],
335
+ attachmentsDir: fixture.attachmentsDir,
336
+ promptCapabilities,
337
+ }),
338
+ ).toEqual([{ type: "text", text: "Continue" }]);
339
+ }),
340
+ );
341
+
342
it.effect("sends supported audio files as native audio content", () =>
343
Effect.gen(function* () {
344
const fixture = yield* makeAttachmentFixture();
@@ -302,6 +354,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
354
input: "Transcribe this.",
355
attachments: [audioAttachment],
356
attachmentsDir: fixture.attachmentsDir,
357
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
358
});
359
360
expect(prompt).toEqual([
@@ -311,25 +364,27 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
364
}),
365
);
366
314
- it.effect.each([
315
- { ...imageAttachment, name: "animation.gif", mimeType: "image/gif" },
316
- ] satisfies ReadonlyArray<ChatAttachment>)(
317
- "rejects $name instead of silently dropping it from a valid prompt",
318
- (attachment) =>
367
+ it.effect.each([undefined, {}, { image: false }, { image: true }])(
368
+ "keeps unsupported image formats path-only with capabilities %s",
369
+ (promptCapabilities) =>
370
Effect.gen(function* () {
371
const fixture = yield* makeAttachmentFixture();
321
- yield* fixture.write(imageAttachment, new Uint8Array([1, 2, 3]));
322
- const error = yield* buildAntigravityPrompt({
323
- input: "Analyze every attachment.",
324
- attachments: [imageAttachment, attachment],
372
+ const attachment = { ...imageAttachment, name: "animation.gif", mimeType: "image/gif" };
373
+ const upload = yield* fixture.write(attachment, "GIF89a");
374
+ const input = `Analyze the image at ${upload.filePath}`;
375
+ const prompt = yield* buildAntigravityPrompt({
376
+ input,
377
+ attachments: [attachment],
378
attachmentsDir: fixture.attachmentsDir,
326
- }).pipe(Effect.flip);
379
+ promptCapabilities,
380
+ }).pipe(
381
+ Effect.provideService(FileSystem.FileSystem, {
382
+ ...fixture.fs,
383
+ stream: () => Effect.die("Unsupported images must not be read").pipe(Stream.fromEffect),
384
+ }),
385
+ );
386
328
- expect(error).toMatchObject({
329
- _tag: "AcpRequestError",
330
- code: -32602,
331
- errorMessage: expect.stringContaining(`does not support '${attachment.name}'`),
332
- });
387
+ expect(prompt).toEqual([{ type: "text", text: input }]);
388
}),
389
);
390
@@ -342,6 +397,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
397
input: "Read this attachment.",
398
attachments: [imageAttachment],
399
attachmentsDir: fixture.attachmentsDir,
400
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
401
}).pipe(Effect.flip);
402
expect(error).toMatchObject({
403
_tag: "AcpRequestError",
@@ -367,6 +423,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
423
input: `Read ${first.filePath} and ${second.filePath}`,
424
attachments: [pdfAttachment, secondAttachment],
425
attachmentsDir: fixture.attachmentsDir,
426
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
427
};
428
const prompt = yield* buildAntigravityPrompt(input);
429
expect(prompt).toEqual([
@@ -408,6 +465,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
465
input: "Inspect both attachments.",
466
attachments: [pdfAttachment, imageAttachment],
467
attachmentsDir: fixture.attachmentsDir,
468
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
469
}).pipe(Effect.flip);
470
expect(error).toMatchObject({
471
_tag: "AcpRequestError",
@@ -426,6 +484,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
484
input: undefined,
485
attachments: [pdfAttachment, textAttachment],
486
attachmentsDir: fixture.attachmentsDir,
487
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
488
}).pipe(
489
Effect.provideService(FileSystem.FileSystem, {
490
...fixture.fs,
@@ -459,6 +518,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
518
input: undefined,
519
attachments: [textAttachment],
520
attachmentsDir: fixture.attachmentsDir,
521
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
522
}).pipe(Effect.flip);
523
524
expect(error).toMatchObject({
@@ -476,6 +536,7 @@ it.layer(NodeServices.layer)("buildAntigravityPrompt", (it) => {
536
input: "Read this image.",
537
attachments: [imageAttachment],
538
attachmentsDir: fixture.attachmentsDir,
539
+ promptCapabilities: { image: true, audio: true, embeddedContext: true },
540
}).pipe(Effect.flip);
541
542
expect(error).toMatchObject({
apps/server/src/provider/acp/AntigravityAcpSupport.ts
+9
-6
@@ -231,6 +231,7 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
231
readonly input: ProviderSendTurnInput["input"];
232
readonly attachments: ProviderSendTurnInput["attachments"];
233
readonly attachmentsDir: string;
234
+ readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
235
}): Effect.fn.Return<
236
ReadonlyArray<EffectAcpSchema.ContentBlock>,
237
EffectAcpErrors.AcpError,
@@ -259,12 +260,14 @@ export const buildAntigravityPrompt = Effect.fn("buildAntigravityPrompt")(functi
260
TEXT_MIME_TYPES.has(mimeType) ||
261
TEXT_FILE_EXTENSIONS.has(path.extname(attachment.name).toLowerCase()));
262
const isPathOnly =
262
- attachment.type === "file" && (isPastedText || (!audio && !pdf && !textFile));
263
- if (attachment.type === "image" && !image) {
264
- return yield* EffectAcpErrors.AcpRequestError.invalidParams(
265
- `Antigravity does not support '${attachment.name}' (${attachment.mimeType}). Attach a BMP, JPEG, PNG, WebP, PDF, audio, or text file.`,
266
- );
267
- }
263
+ (attachment.type === "image" && (!image || input.promptCapabilities?.image !== true)) ||
264
+ (attachment.type === "file" &&
265
+ (isPastedText ||
266
+ (audio
267
+ ? input.promptCapabilities?.audio !== true
268
+ : pdf || textFile
269
+ ? input.promptCapabilities?.embeddedContext !== true
270
+ : true)));
271
const attachmentPath = resolveAttachmentPath({
272
attachmentsDir: input.attachmentsDir,
273
attachment,
packages/contracts/src/orchestrationV2.ts
+3
@@ -918,6 +918,9 @@ export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({
918
updatedAt: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
919
itemIdentityVersion: Schema.optional(Schema.Literal(2)),
920
forkHeadMessageId: Schema.optional(TrimmedNonEmptyString),
921
+ claudeAttachmentBudget: Schema.optional(
922
+ Schema.Struct({ bytesUsed: NonNegativeInt, pagesUsed: NonNegativeInt }),
923
+ ),
924
});
925
export type OrchestrationV2ProviderThreadNativeMetadata =
926
typeof OrchestrationV2ProviderThreadNativeMetadata.Type;
packages/provider-acp/src/server/adapter.ts
+26
-1
@@ -217,6 +217,11 @@ class AcpModelSelectionError extends Schema.TaggedError<AcpModelSelectionError>(
217
}
218
219
export interface AcpAdapterV2Flavor {
220
+ readonly buildPrompt?: (input: {
221
+ readonly text: string;
222
+ readonly attachments: ReadonlyArray<ChatAttachment>;
223
+ readonly promptCapabilities: EffectAcpSchema.AgentCapabilities["promptCapabilities"];
224
+ }) => Effect.Effect<ReadonlyArray<EffectAcpSchema.ContentBlock>, EffectAcpErrors.AcpError>;
225
readonly promptFailure?: (cause: unknown) => OrchestrationV2ProviderFailure;
226
/**
227
* Runs before attachment paths, T3 instructions and native slash-command detection,
@@ -7130,7 +7135,27 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7135
detail: "ACP driver did not negotiate image prompt support",
7136
});
7137
}
7133
- for (const attachment of imageAttachments) {
7138
+ if (flavor.buildPrompt) {
7139
+ const setup = yield* Ref.get(activeSessionSetup);
7140
+ const blocks = yield* flavor
7141
+ .buildPrompt({
7142
+ text,
7143
+ attachments: turnInput.message.attachments,
7144
+ promptCapabilities: setup?.initializeResult.agentCapabilities?.promptCapabilities,
7145
+ })
7146
+ .pipe(
7147
+ Effect.mapError(
7148
+ (cause) =>
7149
+ new ProviderAdapter.ProviderAdapterProtocolError({
7150
+ driver,
7151
+ detail: "Failed to build ACP attachment prompt",
7152
+ payload: cause,
7153
+ }),
7154
+ ),
7155
+ );
7156
+ prompt.splice(0, prompt.length, ...blocks);
7157
+ }
7158
+ for (const attachment of flavor.buildPrompt ? [] : imageAttachments) {
7159
const path = host.resolveAttachmentPath(attachment as ChatAttachment);
7160
if (path === null) {
7161
return yield* new ProviderAdapter.ProviderAdapterProtocolError({