Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion FORK.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

和上游相比多五处改动,都在 `index.mjs` 里(“容量不足报错改为 503”上游 0.1.95 已经自带,分叉里那份已删除):

1. **视频输入(OpenAI 写法和链接)**:上游 0.1.155 起自带视频/音频输入,但只收 `video`/`audio` 块里的 base64,链接一律 400。补丁把 `image_url` 里的视频(`data:video/…` 或 http(s) 链接)和链接形式的 `video` 块转成上游的 base64 `video` 块,之后全走上游。代码里搜 `Video (local patch)`。
1. **视频和图片链接(OpenAI 写法)**:上游 0.1.155 起自带视频/音频输入,但只收 `video`/`audio` 块里的 base64;图片也只收 base64,链接一律 400(agy 本身不收图片链接)。补丁把 `image_url` 里的视频(`data:video/…` 或 http(s) 链接)、图片链接,以及 Magpie 从部分 `/v1/responses` 写法原样留下的 `image_url` / `input_image` 块,下载或解码后转成上游的 base64 `image`/`video` 块,之后全走上游。链接下载禁止内网地址,最大 100 MB,缓存一小时。代码里搜 `Video (local patch)`。
2. **重发的请求接上原来那一轮**:客户端等不到首字就断开,把同一份请求再发一遍,而原请求还在跑;或者原请求的回复(一次工具调用)在路上丢了。上游插件对这种重发返回错误(0.1.106 之前一律是 409 `no active MCP call matches these tool results`,0.1.106 起原请求还在出流时是 503),要等原来那一轮结束才变,而原请求照常跑完并计费,产出没人收。现在重发的请求会等原请求出结果,拿到同一份回复,用量记 0,不重复计费。原请求失败或被取消时,重发的请求收到 503,客户端再发一次就会重新跑。已经正常结束、没有待答工具调用的回复不走这条路,再发一遍仍然重新生成。带工具结果的请求、原请求已经结束时,交给上游 0.1.131 的 `replay_tool_step`(比对整份请求的摘要,回放同一个消息 id);本补丁只接原请求还在跑的重发,以及不带工具结果的请求丢了回复的重发。代码里搜 `Retry attach (local patch)`。
3. **工具被拒后不再回空**:带视频的会话开放 agy 的读文件工具以后,模型有时会拿它去读客户端机器上的路径,比如 ZCode 用户 Mac 上的 `~/.zcode/...`。这个工具在服务器上跑,读会话目录以外的路径要先申请权限,插件会拒绝;agy 被拒后就直接结束这一轮。上游插件把这样的结束原样交给客户端,结果是空正文、没有工具调用,客户端看上去就是卡住不动。现在改成两处:
- (上游 0.1.161 起自带)会话说明写明 agy 自带工具都关着,带媒体时只开 `read_file` 读附带的文件。
Expand Down
33 changes: 33 additions & 0 deletions fork/patch-e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,39 @@ test("a video sent as an image block, inline or by link, goes to agy as a file f
}
})

// Video (local patch): an image by link, as an image block's url source or
// the raw image_url / input_image part, reaches agy inline (agy takes no links).
test("an image by link or as a raw image_url part goes to agy as inline base64", async () => {
const png = Buffer.concat([Buffer.from("89504e470d0a1a0a", "hex"), Buffer.alloc(24)])
const server = http.createServer((req, res) => { res.writeHead(200, { "content-type": "application/octet-stream" }); res.end(png) })
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve))
const url = `http://127.0.0.1:${server.address().port}/pic`
try {
await withKit(async (kit) => {
kit.defaultPrompt = async (agent) => {
await agent.text("seen")
return { stopReason: "end_turn" }
}
const ask = (block, user) => kit.request(baseBody({ model: "gemini-3.8-flash-high", metadata: { user_id: user }, messages: [{ role: "user", content: [
{ type: "text", text: "what is in it?" }, block] }] }))
for (const [user, block] of [["src-url", { type: "image", source: { type: "url", url } }],
["raw-obj", { type: "image_url", image_url: { url } }], ["raw-str", { type: "input_image", image_url: url }],
["raw-data", { type: "image_url", image_url: { url: `data:image/png;base64,${png.toString("base64")}` } }]]) {
const parsed = await readSse(await ask(block, user))
assert.equal(parsed.error, null, user)
}
const images = kit.acpLog.filter((e) => e.method === "session/prompt").flatMap((e) => e.params.prompt).filter((p) => p.type === "image")
assert.equal(images.length, 4)
for (const image of images) {
assert.equal(image.mimeType, "image/png")
assert.deepEqual(Buffer.from(image.data, "base64"), png)
}
}, { promptImages: true, env: { AGY_BRIDGE_VIDEO_PRIVATE: "1" } })
} finally {
server.close()
}
})

// agy asks the client to allow its own read_file on a path outside the media
// folder (a client path), as agy 1.5.10 does; returns the bridge's answer.
async function askReadFile(kit, agent, file) {
Expand Down
54 changes: 36 additions & 18 deletions index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -259,13 +259,15 @@ const systemAppend = () => /^(?:1|true|on|yes)$/i.test(process.env.AGY_BRIDGE_SY
const FORWARD_THINKING = process.env.AGY_BRIDGE_THINKING !== "0"

// Video (local patch). Upstream (0.1.155) stages a video or audio block with
// base64 data for agy's view_file and refuses one by URL. OpenAI clients send
// a video as image_url (a data:video/… URL or an http(s) link), which magpie
// passes on as an image block. videoizeBody turns those, and a video block by
// URL, into upstream's base64 video block. AGY_BRIDGE_VIDEO=0 turns it off.
// base64 data for agy's view_file, and refuses an image or video by URL (agy
// takes images only inline). OpenAI clients send a video as image_url (a
// data:video/… URL or an http(s) link), and images by link; magpie passes them
// on as an image block, or, from some /v1/responses shapes, as the raw
// image_url / input_image part. videoizeBody downloads links and turns all of
// these into upstream's base64 image or video block. AGY_BRIDGE_VIDEO=0 turns it off.
const videoOn = () => !/^(?:0|false|off|no)$/i.test(process.env.AGY_BRIDGE_VIDEO || "")
const VIDEO_MAX_BYTES = 100 * 1024 * 1024 // agy's file reading refuses larger files
const videoUrlTypes = new Map() // url -> video mime, or "" when it isn't a video
const videoUrlTypes = new Map() // url -> image or video mime, or "" when it is neither

// Downloaded videos, kept so a history that sends the same link every turn
// fetches it once.
Expand Down Expand Up @@ -303,20 +305,20 @@ async function fetchVideo(url) {
let target = url
for (let hop = 0; hop < 4; hop++) {
const u = new URL(target)
if (u.protocol !== "http:" && u.protocol !== "https:") throw new UnsupportedContent("a video URL other than http(s)")
if (u.protocol !== "http:" && u.protocol !== "https:") throw new UnsupportedContent("an image or video URL other than http(s)")
const host = u.hostname.replace(/^\[|\]$/g, "")
const addresses = net.isIP(host) ? [host] : (await dns.promises.lookup(host, { all: true })).map((a) => a.address)
// ponytail: checks the resolved addresses, then fetches by name: DNS rebinding in between is not covered; pin the address if untrusted keys reach this gateway
if (process.env.AGY_BRIDGE_VIDEO_PRIVATE !== "1" && addresses.some(privateAddress)) {
throw new UnsupportedContent("a video URL on a private or local address")
throw new UnsupportedContent("an image or video URL on a private or local address")
}
const res = await fetch(target, { redirect: "manual", signal: AbortSignal.timeout(120_000) })
const location = res.headers.get("location")
if (res.status >= 300 && res.status < 400 && location) {
target = new URL(location, target).href
continue
}
if (!res.ok) throw new UnsupportedContent(`a video URL that answered HTTP ${res.status}`)
if (!res.ok) throw new UnsupportedContent(`an image or video URL that answered HTTP ${res.status}`)
if (Number(res.headers.get("content-length")) > VIDEO_MAX_BYTES) throw new UnsupportedContent("a video over 100 MB")
const chunks = []
let size = 0
Expand All @@ -327,12 +329,12 @@ async function fetchVideo(url) {
}
const bytes = Buffer.concat(chunks)
const header = (res.headers.get("content-type") || "").split(";")[0].trim().toLowerCase()
return { bytes, type: sniffVideo(bytes) || (header.startsWith("video/") ? header : "") }
return { bytes, type: sniffVideo(bytes) || imageTypeOf(bytes) || (header.startsWith("video/") ? header : "") }
}
throw new UnsupportedContent("a video URL with more than 3 redirects")
throw new UnsupportedContent("an image or video URL with more than 3 redirects")
}

// The video at a link, from mediaDir() when fetched before; null when it isn't one.
// The image or video at a link, from mediaDir() when fetched before; null when it is neither.
async function urlVideo(url) {
const file = path.join(mediaDir(), digest(url))
const known = videoUrlTypes.get(url)
Expand Down Expand Up @@ -360,18 +362,34 @@ async function urlVideo(url) {
return got
}

// An image block that is a video, or a video block by link, as upstream's
// base64 video block; null for anything else.
// as upstream's base64 block: a video, or one of the four images agy takes
const asBlock = (type, data) => ({ type: type.startsWith("video/") ? "video" : "image", source: { type: "base64", media_type: type, data } })

// The link a block carries: an image or video block's url source, or the raw
// OpenAI image_url / input_image part (url as a string or { url }).
function blockUrl(block) {
if ((block?.type === "image" || block?.type === "video") && block.source?.type === "url") return block.source.url
if (block?.type === "image_url" || block?.type === "input_image") {
const v = block.image_url
return typeof v === "string" ? v : v?.url
}
return null
}

// A block with a video, a data: URL or an http(s) link, as upstream's base64
// image or video block; null for anything else (left for upstream to judge).
async function videoBlock(block) {
const source = block?.source
if (block?.type === "image" && source?.type === "base64" && typeof source.data === "string" && /^video\//i.test(source.media_type || "")) {
return { type: "video", source }
}
if ((block?.type === "image" || block?.type === "video") && source?.type === "url" && /^https?:/i.test(source.url || "")) {
const got = await urlVideo(source.url)
return got && { type: "video", source: { type: "base64", media_type: got.type, data: got.bytes.toString("base64") } }
}
return null
const url = blockUrl(block)
if (typeof url !== "string") return null
const data = /^data:([\w.+-]+\/[\w.+-]+)(?:;[^,]*)?;base64,(.*)$/is.exec(url)
if (data) return asBlock(data[1].toLowerCase(), data[2])
if (!/^https?:/i.test(url)) return null
const got = await urlVideo(url)
return got && asBlock(got.type, got.bytes.toString("base64"))
}

async function videoizeBody(body) {
Expand Down
Loading