mirror of
https://github.com/stablyai/orca.git
synced 2026-11-18 11:54:46 +00:00
fix(opencode): attach @-mentioned files to OpenCode chat prompts (#41932)
* fix(opencode): attach @-mentioned files to OpenCode chat prompts OpenCode's ACP agent reads a file only from a resource_link block and ignores @path text, so mentioned files never reached the model. Keep the text as typed and link each mentioned file inside the session folder. * fix(opencode): reuse the chat mention scanner and compare paths byte-exactly * fix(opencode): leave mentioned files over 20 MiB as text
This commit is contained in:
@@ -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. */
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -256,6 +256,7 @@ export async function acquireAcpStructuredSession(input: {
|
||||
fence: acquire.fence,
|
||||
acquisitionGeneration: generation,
|
||||
spec,
|
||||
cwd: launch.cwd,
|
||||
permissionModes,
|
||||
connection,
|
||||
lane: null,
|
||||
|
||||
@@ -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<Partial<Record<AgentChatPermissionMode, string>>> | undefined
|
||||
childStops?: AcpChildStops
|
||||
|
||||
@@ -12,6 +12,7 @@ export type AcpStructuredChild = Pick<
|
||||
| 'fence'
|
||||
| 'acquisitionGeneration'
|
||||
| 'spec'
|
||||
| 'cwd'
|
||||
| 'permissionModes'
|
||||
| 'connection'
|
||||
| 'closeRequested'
|
||||
|
||||
@@ -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<string | null> {
|
||||
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<ContentBlock[]> {
|
||||
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<string, ContentBlock>()
|
||||
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()]
|
||||
}
|
||||
@@ -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!' }
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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<ContentBlock[]> {
|
||||
// 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<AcpLaunchSpec, 'agent' | 'dialect'>
|
||||
connection: Pick<AcpStructuredConnection, 'initialize'>
|
||||
cwd: string
|
||||
}
|
||||
): Promise<ContentBlock[] | AgentJournalDispatchRejection> {
|
||||
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, {
|
||||
|
||||
Reference in New Issue
Block a user