diff --git a/src/main/acp/acp-dialects/acp-dialect.ts b/src/main/acp/acp-dialects/acp-dialect.ts index 25412f7547c..e283e6a7188 100644 --- a/src/main/acp/acp-dialects/acp-dialect.ts +++ b/src/main/acp/acp-dialects/acp-dialect.ts @@ -185,6 +185,8 @@ export type AcpDialect = { text(value: string): string reply(text: string): AcpModelCommandReply } + /** The agent reads a mentioned file only from a resource link, not from `@path` text. */ + linksFileMentions?: true /** Hide these commands and reject command-only prompts before dispatch. */ withheldCommands?: readonly string[] /** Which sign-in a not-signed-in chat needs; absent is the agent's usual one. */ diff --git a/src/main/acp/acp-dialects/opencode-dialect.ts b/src/main/acp/acp-dialects/opencode-dialect.ts index 4b0ad20e23d..d177f690405 100644 --- a/src/main/acp/acp-dialects/opencode-dialect.ts +++ b/src/main/acp/acp-dialects/opencode-dialect.ts @@ -111,6 +111,7 @@ export const OPENCODE_ACP_DIALECT: AcpDialect = { supported: (initialized) => initialized.agentCapabilities?.sessionCapabilities?.close != null }, effortChangesModel: true, + linksFileMentions: true, normalizeToolUpdate, notification: openCodeChildUpdate, promptFailure diff --git a/src/main/acp/session/acp-structured-acquire.ts b/src/main/acp/session/acp-structured-acquire.ts index 4fecd8a131d..c69ac58a884 100644 --- a/src/main/acp/session/acp-structured-acquire.ts +++ b/src/main/acp/session/acp-structured-acquire.ts @@ -256,6 +256,7 @@ export async function acquireAcpStructuredSession(input: { fence: acquire.fence, acquisitionGeneration: generation, spec, + cwd: launch.cwd, permissionModes, connection, lane: null, diff --git a/src/main/acp/session/acp-structured-session-contract.ts b/src/main/acp/session/acp-structured-session-contract.ts index 5af81feb4e2..cad258b796d 100644 --- a/src/main/acp/session/acp-structured-session-contract.ts +++ b/src/main/acp/session/acp-structured-session-contract.ts @@ -15,6 +15,8 @@ export type AcpStructuredSession = { fence: number acquisitionGeneration: string spec: AcpLaunchSpec + /** The session's folder on the agent's host. */ + cwd: string /** Session modes this launch reports as Orca's permission modes. */ permissionModes: Readonly>> | undefined childStops?: AcpChildStops diff --git a/src/main/acp/session/children/acp-structured-child.ts b/src/main/acp/session/children/acp-structured-child.ts index 0f26e9ba4b2..7f340c68c97 100644 --- a/src/main/acp/session/children/acp-structured-child.ts +++ b/src/main/acp/session/children/acp-structured-child.ts @@ -12,6 +12,7 @@ export type AcpStructuredChild = Pick< | 'fence' | 'acquisitionGeneration' | 'spec' + | 'cwd' | 'permissionModes' | 'connection' | 'closeRequested' diff --git a/src/main/acp/turns/acp-file-mention-links.ts b/src/main/acp/turns/acp-file-mention-links.ts new file mode 100644 index 00000000000..eaad4abf79f --- /dev/null +++ b/src/main/acp/turns/acp-file-mention-links.ts @@ -0,0 +1,66 @@ +import { realpath, stat } from 'node:fs/promises' +import { isAbsolute, relative, resolve, sep } from 'node:path' +import { pathToFileURL } from 'node:url' +import { nativeChatTextAttachmentParts } from '../../../shared/native-chat-text-attachment-references' +import type { ContentBlock } from '../generated/acp-protocol.generated' + +const TRAILING_PUNCTUATION = /[.,;:!?)\]}`"'*]+$/ + +/** The real path of a file inside `realRoot`; symlinks and `..` cannot leave it. */ +async function fileInside( + realRoot: string, + path: string, + maxBytes: number +): Promise { + const target = await realpath(resolve(realRoot, path)).catch(() => null) + // Byte-exact: Unicode or case folding would admit a sibling folder on Linux. + const inside = target ? relative(realRoot, target) : '' + if ( + !target || + !inside || + inside === '..' || + inside.startsWith(`..${sep}`) || + isAbsolute(inside) + ) { + return null + } + return (await stat(target).then( + (info) => info.isFile() && info.size <= maxBytes, + () => false + )) + ? target + : null +} + +/** One link per `@path` naming a file inside `root`; larger files stay text for the agent's own tools. */ +export async function acpFileMentionLinks( + texts: readonly string[], + root: string, + maxBytes: number +): Promise { + const paths = new Set( + texts.flatMap((text) => + nativeChatTextAttachmentParts(text, true, () => true).flatMap((part) => + part.path ? [part.path] : [] + ) + ) + ) + const realRoot = paths.size > 0 ? await realpath(root).catch(() => null) : null + if (!realRoot) { + return [] + } + const links = new Map() + for (const path of paths) { + // Punctuation after a mention belongs to the sentence unless the name itself exists. + const trimmed = path.replace(TRAILING_PUNCTUATION, '') + const literal = await fileInside(realRoot, path, maxBytes) + const name = literal ? path : trimmed + const target = + literal ?? + (trimmed && trimmed !== path ? await fileInside(realRoot, trimmed, maxBytes) : null) + if (target && !links.has(target)) { + links.set(target, { type: 'resource_link', uri: pathToFileURL(target).href, name }) + } + } + return [...links.values()] +} diff --git a/src/main/acp/turns/acp-prompt-content.test.ts b/src/main/acp/turns/acp-prompt-content.test.ts index 1d48824649f..b948f0de45f 100644 --- a/src/main/acp/turns/acp-prompt-content.test.ts +++ b/src/main/acp/turns/acp-prompt-content.test.ts @@ -1,6 +1,7 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { pathToFileURL } from 'node:url' import { afterAll, describe, expect, it } from 'vitest' import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types' @@ -64,4 +65,35 @@ describe('ACP prompt content', () => { attachment: { reason: 'totalTooLarge' } }) }) + + it('links mentioned files inside the session folder and keeps the text as typed', async () => { + const root = join(dir, 'project') + mkdirSync(join(root, 'my dir'), { recursive: true }) + writeFileSync(join(root, 'a.txt'), 'a') + writeFileSync(join(root, 'my dir', 'b.txt'), 'b') + writeFileSync(join(root, "it's.txt"), 'c') + writeFileSync(join(root, 'report!'), 'd') + writeFileSync(join(root, 'report'), 'e') + // OpenCode 2 fails the whole turn for a linked file over 20 MiB. + writeFileSync(join(root, 'big.log'), Buffer.alloc(20 * 1024 * 1024 + 1)) + mkdirSync(join(dir, 'outside')) + writeFileSync(join(dir, 'outside', 'c.txt'), 'secret') + // A junction needs no privilege on Windows. + symlinkSync(join(dir, 'outside'), join(root, 'escape'), 'junction') + const text = + 'Read @a.txt. and @"my dir/b.txt" @it\'s.txt, see:@report! not @../outside/c.txt @escape/c.txt @missing.txt @big.log' + const real = realpathSync(root) + + expect(await acpPromptBlocks(message({ type: 'text', text }), true, root)).toEqual([ + { type: 'text', text }, + { type: 'resource_link', uri: pathToFileURL(join(real, 'a.txt')).href, name: 'a.txt' }, + { + type: 'resource_link', + uri: pathToFileURL(join(real, 'my dir', 'b.txt')).href, + name: 'my dir/b.txt' + }, + { type: 'resource_link', uri: pathToFileURL(join(real, "it's.txt")).href, name: "it's.txt" }, + { type: 'resource_link', uri: pathToFileURL(join(real, 'report!')).href, name: 'report!' } + ]) + }) }) diff --git a/src/main/acp/turns/acp-prompt-content.ts b/src/main/acp/turns/acp-prompt-content.ts index 81a2db01b67..069a223f48d 100644 --- a/src/main/acp/turns/acp-prompt-content.ts +++ b/src/main/acp/turns/acp-prompt-content.ts @@ -26,13 +26,14 @@ import { acpAgentName } from '../session/acp-structured-agent-definitions' import type { AcpStructuredConnection } from '../process/acp-structured-connection' import { acpSessionAcceptsImages } from '../protocol/acp-image-capability' import type { ContentBlock } from '../generated/acp-protocol.generated' +import { acpFileMentionLinks } from './acp-file-mention-links' // Reserve space for the JSON-RPC envelope around the prompt blocks. const ACP_PROMPT_LINE_BUDGET = ACP_MAX_LINE_BYTES - 64 * 1024 // Budget raw images for base64's 4:3 expansion and leave room for text. const ACP_PROMPT_TOTAL_IMAGE_MAX_BYTES = Math.floor((ACP_PROMPT_LINE_BUDGET * 3) / 4) - 1024 * 1024 -// OpenCode 2 fails the turn for any attachment over 20 MiB. -const ACP_PROMPT_PER_IMAGE_MAX_BYTES = 20 * 1024 * 1024 +// OpenCode 2 fails the turn for any image or linked file over 20 MiB. +const ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024 const MAX_IMAGE_COUNT = 20 const READ_TIMEOUT_MS = 15_000 @@ -74,8 +75,8 @@ async function imageBlock( if (bytes === 0) { throw attachmentProblem({ reason: 'empty' }) } - if (bytes > ACP_PROMPT_PER_IMAGE_MAX_BYTES) { - throw attachmentProblem({ reason: 'tooLarge', limit: ACP_PROMPT_PER_IMAGE_MAX_BYTES }) + if (bytes > ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES) { + throw attachmentProblem({ reason: 'tooLarge', limit: ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES }) } if (bytes > remainingBytes) { throw attachmentProblem({ reason: 'totalTooLarge', limit: ACP_PROMPT_TOTAL_IMAGE_MAX_BYTES }) @@ -91,7 +92,7 @@ async function imageBlock( block: { type: 'text' as const, text: formatNativeChatFileReference(path) }, bytes: 0 } - const maxBytes = Math.min(remainingBytes, ACP_PROMPT_PER_IMAGE_MAX_BYTES) + const maxBytes = Math.min(remainingBytes, ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES) if (!mimeType || maxBytes <= 0) { return fallback } @@ -119,9 +120,11 @@ async function imageBlock( return { block: { type: 'image', mimeType, data: data.toString('base64') }, bytes: data.length } } +/** `mentionRoot` links each `@path` there, for agents that read only linked files. */ export async function acpPromptBlocks( body: AgentJournalMessageItem, - acceptsImages: boolean + acceptsImages: boolean, + mentionRoot?: string ): Promise { // Reserve later text and file references before allocating image capacity. const blocks: ContentBlock[] = body.blocks.map((block) => { @@ -131,6 +134,12 @@ export async function acpPromptBlocks( const path = block.type === 'image-ref' ? hostImagePath(block) : null return { type: 'text', text: path ? formatNativeChatFileReference(path) : '' } }) + if (mentionRoot !== undefined) { + const texts = body.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : [])) + blocks.push( + ...(await acpFileMentionLinks(texts, mentionRoot, ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES)) + ) + } const blockBytes = (block: ContentBlock): number => Buffer.byteLength(JSON.stringify(block)) let encodedBytes = 2 + Math.max(0, blocks.length - 1) + blocks.reduce((n, b) => n + blockBytes(b), 0) @@ -194,6 +203,7 @@ export async function acpDispatchPrompt( session: { spec: Pick connection: Pick + cwd: string } ): Promise { if (isWithheldCommand(body, session.spec.dialect.withheldCommands ?? [])) { @@ -203,7 +213,11 @@ export async function acpDispatchPrompt( }) } try { - return await acpPromptBlocks(body, await acpSessionAcceptsImages(session)) + return await acpPromptBlocks( + body, + await acpSessionAcceptsImages(session), + session.spec.dialect.linksFileMentions ? session.cwd : undefined + ) } catch (error) { if (error instanceof AcpPromptContentError) { return agentSessionFailureWords(error.failure, {