@magpie-community/opencode-agy-tui-auth 0.1.18 → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/index.mjs +19 -17
- package/package.json +2 -1
- package/seed.mjs +18 -2
- package/tool-names.mjs +64 -0
- package/tools.mjs +15 -4
package/README.md
CHANGED
|
@@ -18,12 +18,12 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
|
|
|
18
18
|
|
|
19
19
|
## 工具
|
|
20
20
|
|
|
21
|
-
请求里的工具(`tools`,function 工具)通过 magpie 的工具服务器(`magpie mcp-helper`,由 `tui-helper` 启动)交给模型:agy 把它们列为 `mcp_magpie_<name>`,hook 只放行这些。模型调用其中一个时,响应就以这个工具调用结束(`finish_reason: "tool_calls"`,流式和非流式都一样),agy 保留这一轮,等待带着调用结果的请求(`role: "tool"`,按 `tool_call_id` 对应),然后在同一个 agy 里继续回答。如果结果来时这一轮已经不再等待(默认 10 分钟),就开一轮新的,把对话连同其中的调用和结果整理成文字输入进去。工具服务器的配置放在本轮自己的 HOME 里,其余部分链接到账号的 home,所以同一账号的多轮可以同时运行,账号的 `mcp_config.json` 也不会被改写。`tool_choice: "none"`
|
|
21
|
+
请求里的工具(`tools`,function 工具)通过 magpie 的工具服务器(`magpie mcp-helper`,由 `tui-helper` 启动)交给模型:agy 把它们列为 `mcp_magpie_<name>`,hook 只放行这些。模型调用其中一个时,响应就以这个工具调用结束(`finish_reason: "tool_calls"`,流式和非流式都一样),agy 保留这一轮,等待带着调用结果的请求(`role: "tool"`,按 `tool_call_id` 对应),然后在同一个 agy 里继续回答。如果结果来时这一轮已经不再等待(默认 10 分钟),就开一轮新的,把对话连同其中的调用和结果整理成文字输入进去。工具服务器的配置放在本轮自己的 HOME 里,其余部分链接到账号的 home,所以同一账号的多轮可以同时运行,账号的 `mcp_config.json` 也不会被改写。`tool_choice: "none"` 时不提供工具。agy 的函数名最长 64 个字符,加上 `mcp_magpie_` 之后放不下的工具名(比如 Claude Code 插件的 MCP 工具 `mcp__plugin_<插件>_<服务器>__<工具>`),会换成由原名开头、整个名字的哈希和原名结尾组成的短名交给 agy,描述开头写明原名;模型调用短名时,响应里的工具调用还是原名(0.1.19 起;之前整个请求返回 400)。工具结果里的文字原样交给模型,图片(data: URL)作为图片交给模型。
|
|
22
22
|
|
|
23
23
|
## 限制(v0.1)
|
|
24
24
|
|
|
25
25
|
- 图片(PNG、JPEG、GIF、WebP、BMP、TIFF、SVG,每张不超过 10 MB)和视频(MP4、MOV、WebM、AVI,每个不超过 50 MB)以 data: URL 内联发送,会像拖进 agy 输入框的文件一样作为附件交给 agy:正是 agy 1.5.19 输入框能附加的类型,大小限制也和 agy 自己的一样。图片适用于 Gemini 和 Claude 模型,视频只适用于 Gemini 模型。每个文件写进本轮的临时目录,随目录一起删除。
|
|
26
|
-
- 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude
|
|
26
|
+
- 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。这类拒绝带有 `X-Magpie-Shape-Refused: 1`:在 magpie 的路由组里,组会接着问下一个成员(比如 agy-cli),而不是停在这里,agy-tui 也不会因此被歇下。请求本身有错(没有消息、工具重名、工具名里有非法字符等)时不带这个头,组照旧在这里结束。
|
|
27
27
|
- 一段对话在 agy 自己的会话里接着进行。一轮得到回答后,会保留它的 agy 会话;这段对话的下一个请求(同样的消息、这条回答,再加上用户的新消息)用 `--conversation` 接着这个会话,只输入新的消息。不管对话已经多长,模型拿到的都是完整的、按轮次组织的之前的对话,会话太长时由 agy 自己压缩。其他请求会开一个新的 agy 会话,把最后一条消息之前的对话整理成文字粘贴进去:新的对话、客户端压缩过、改过或分叉的对话、客户端改过的回答、回答之后出现的系统消息,以及工具调用的结果(它会回到发起调用的那个 agy 里继续)。会话在最后一次回答后保留 24 小时,每个账号最多 32 个(先删最早的);会话列表放在账号目录里(`agy-tui-conversations.json`),只有哈希和 agy 的会话 id,没有对话内容。每次请求系统指令都会变的对话,总是整段粘贴。
|
|
28
28
|
- agy 一条消息最多收 192,000 字节,超出部分会被替换成 `<truncated N bytes>`。180,000 字节以内的对话作为一条消息粘贴。更长的对话,或者最新一条消息单独就超过的,会写进 agy 自己的会话存储,成为一个会话(之前的每一轮是一个步骤,很长的用户消息拆成连续几个步骤),再用 `--conversation` 启动 agy,只输入最新的消息。agy 会把这些步骤按原本的轮次发给模型,所以不管对话多长都不会丢内容。这需要支持 `--conversation` 的 agy(1.5.20 及以上),以及插件宿主里的 SQLite(Bun 或 Node 自带的)。没有这两样、设置了 `AGY_TUI_SEED=0`,或者 agy 没有接受这个会话(它的日志会写明)时,按原来的方式粘贴:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。此时最后一条消息单独超过 180,000 字节会被拒绝(400)。
|
|
29
29
|
- 每个模型宣告的是它在 agy 里自己的上下文窗口:Gemini 1,048,576 token,Claude Opus 和 Sonnet 5.5 1,000,000,Claude 4.6 250,000,GPT-OSS 120B 131,072(0.1.16 之前是一条消息能放下的 64K)。会话超出窗口时由 agy 自己压缩。每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考)。
|
package/index.mjs
CHANGED
|
@@ -8,7 +8,8 @@ import { writeDefaultAgentFiles } from "./default-agent.mjs"
|
|
|
8
8
|
import { agyHasUsageSubcommand, agyTooOld, MIN_AGY_VERSION, oldAgyError, USAGE_SUBCOMMAND_AGY_VERSION } from "./agy-version.mjs"
|
|
9
9
|
import { liveReply, callsAfter, usageOf, lastStep } from "./live.mjs"
|
|
10
10
|
import { canSeed, chunks, resumed, writeConversation } from "./seed.mjs"
|
|
11
|
-
import { mcpToolsOf } from "./tools.mjs"
|
|
11
|
+
import { mcpToolsOf, unfit } from "./tools.mjs"
|
|
12
|
+
import { clientNames, MCP_SERVER, offered } from "./tool-names.mjs"
|
|
12
13
|
import { agyModelOf, foldModels } from "./efforts.mjs"
|
|
13
14
|
import { readUsage } from "./usage.mjs"
|
|
14
15
|
|
|
@@ -44,7 +45,6 @@ const AGY_MANUAL = "https://antigravity.google/docs/cli"
|
|
|
44
45
|
// with the caller's tools: agy's own stay off, and the caller's come as
|
|
45
46
|
// functions agy names mcp_magpie_<name> (its MCP server's name and the
|
|
46
47
|
// tool's), each the tool the conversation calls <name>
|
|
47
|
-
const MCP_SERVER = "magpie"
|
|
48
48
|
const MCP_FUNCTIONS = `mcp_${MCP_SERVER}_*`
|
|
49
49
|
const TOOL_INSTRUCTIONS = `agy's own tools are turned off in this session. The user's tools are given to you as ${MCP_FUNCTIONS.slice(0, -1)}<name>: each is the tool the conversation calls <name>, run on the user's computer. Call them when the task needs one.`
|
|
50
50
|
|
|
@@ -364,10 +364,10 @@ function named(type) {
|
|
|
364
364
|
// file, so a link elsewhere would have to be fetched for it.
|
|
365
365
|
function mediaOf(url, mediaType) {
|
|
366
366
|
const m = /^data:([^;,]*)((?:;[^;,]*)*),(.*)$/s.exec(String(url ?? ""))
|
|
367
|
-
if (!m) throw
|
|
367
|
+
if (!m) throw unfit(`agy-tui takes images and videos sent inline (a data: URL), not a link to one`)
|
|
368
368
|
let type = (m[1].trim() || String(mediaType ?? "").trim()).toLowerCase()
|
|
369
369
|
type = SAME_TYPE[type] ?? type
|
|
370
|
-
if (!MEDIA_TYPES[type]) throw
|
|
370
|
+
if (!MEDIA_TYPES[type]) throw unfit(`${TAKES}; the message has ${named(type)}`)
|
|
371
371
|
const base64 = /;base64$/i.test(m[2])
|
|
372
372
|
let data
|
|
373
373
|
try {
|
|
@@ -376,7 +376,7 @@ function mediaOf(url, mediaType) {
|
|
|
376
376
|
throw refuse(`the message has ${kindOf(type) === "video" ? "a video" : "an image"} that can't be read`)
|
|
377
377
|
}
|
|
378
378
|
if (!data.length) throw refuse(`the message has an empty ${kindOf(type)}`)
|
|
379
|
-
if (data.length > maxBytes(type)) throw
|
|
379
|
+
if (data.length > maxBytes(type)) throw unfit(`${kindOf(type) === "video" ? "a video" : "an image"} is ${Math.ceil(data.length / MB)} MB; agy attaches up to ${maxBytes(type) / MB} MB of one`)
|
|
380
380
|
return { type, data }
|
|
381
381
|
}
|
|
382
382
|
|
|
@@ -394,11 +394,11 @@ function fileOf(part) {
|
|
|
394
394
|
const type = String(f.mediaType ?? f.media_type ?? f.mime_type ?? typeByName(f.filename) ?? "").toLowerCase()
|
|
395
395
|
const src = f.file_data ?? f.data ?? f.file_url ?? f.url
|
|
396
396
|
if (typeof src !== "string" || !src) {
|
|
397
|
-
throw
|
|
397
|
+
throw unfit(`${TAKES}; the message has ${f.file_id ? "a file by its id" : named(type)}`)
|
|
398
398
|
}
|
|
399
399
|
if (src.startsWith("data:")) return mediaOf(src, type)
|
|
400
400
|
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(src)) {
|
|
401
|
-
if (!MEDIA_TYPES[SAME_TYPE[type] ?? type]) throw
|
|
401
|
+
if (!MEDIA_TYPES[SAME_TYPE[type] ?? type]) throw unfit(`${TAKES}; the message has ${named(type)}`)
|
|
402
402
|
return mediaOf(src)
|
|
403
403
|
}
|
|
404
404
|
return mediaOf(`data:${type};base64,${src}`)
|
|
@@ -420,8 +420,8 @@ function partsOf(content, media) {
|
|
|
420
420
|
else if (type === "image_url" || type === "input_image") add(mediaOf(typeof part.image_url === "string" ? part.image_url : part.image_url?.url))
|
|
421
421
|
else if (type === "video_url" || type === "input_video") add(mediaOf(typeof part.video_url === "string" ? part.video_url : part.video_url?.url))
|
|
422
422
|
else if (type === "file" || type === "input_file") add(fileOf(part))
|
|
423
|
-
else if (type === "input_audio" || type === "audio") throw
|
|
424
|
-
else if (type) throw
|
|
423
|
+
else if (type === "input_audio" || type === "audio") throw unfit(`${TAKES}; the message has audio${part.input_audio?.format ? ` (${part.input_audio.format})` : ""}`)
|
|
424
|
+
else if (type) throw unfit(`${TAKES}; the message has a ${type} part`)
|
|
425
425
|
}
|
|
426
426
|
return out.join("\n")
|
|
427
427
|
}
|
|
@@ -487,13 +487,13 @@ export function turnOf(messages, budget = INPUT_BUDGET) {
|
|
|
487
487
|
let { system, turns } = read(messages, [])
|
|
488
488
|
if (!turns.length || turns.at(-1).role === "assistant") throw refuse("the last message is not the user's or a tool's result")
|
|
489
489
|
const note = ATTACHMENT_NOTE.exec(turns.at(-1).text)
|
|
490
|
-
if (note) throw
|
|
490
|
+
if (note) throw unfit(`${TAKES}; the message has ${named(note[1])}`)
|
|
491
491
|
const said = (t) => `${{ user: "User", assistant: "Assistant", tool: "Tool" }[t.role]}: ${t.text}`
|
|
492
492
|
// a user's message with nothing before it goes as it was written
|
|
493
493
|
const bare = turns.length === 1 && turns[0].role === "user"
|
|
494
494
|
const lastText = bare ? turns[0].text : said(turns.at(-1))
|
|
495
495
|
if (bytes(lastText) > budget) {
|
|
496
|
-
const error =
|
|
496
|
+
const error = unfit(`the last message is ${bytes(lastText)} bytes, more than agy takes in one message (${budget}): send less of it at once`)
|
|
497
497
|
// seedOf takes the chat as a conversation instead
|
|
498
498
|
error.long = true
|
|
499
499
|
throw error
|
|
@@ -901,6 +901,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
901
901
|
if (!helper) throw new Failure(501, oldMagpie(TUI_HELPER_MAGPIE, "has a terminal for agy"))
|
|
902
902
|
settleHome(home)
|
|
903
903
|
const withTools = tools.length > 0
|
|
904
|
+
const clients = clientNames(tools)
|
|
904
905
|
const ws = folderAt(place?.ws, "agy-tui-")
|
|
905
906
|
// agy's default agent, never --agent: the instructions in AGENTS.md, agy's
|
|
906
907
|
// bundled skills left out, and a PreToolUse hook that denies every call of
|
|
@@ -1023,7 +1024,8 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1023
1024
|
pending.add(o.call.id)
|
|
1024
1025
|
if (!found?.id) look()
|
|
1025
1026
|
if (found?.id) publish(liveReply(home, found.id, stepBase))
|
|
1026
|
-
|
|
1027
|
+
// a tool agy has under a short name goes back under the client's
|
|
1028
|
+
const call = { ...o.call, name: clients.get(o.call.name) ?? o.call.name }
|
|
1027
1029
|
spent().then((usage) => stop({ call, usage }))
|
|
1028
1030
|
}
|
|
1029
1031
|
if (o.dropped) pending.delete(o.dropped)
|
|
@@ -1083,7 +1085,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1083
1085
|
try {
|
|
1084
1086
|
if (withTools) {
|
|
1085
1087
|
// the tool server first: agy reads its config as it starts
|
|
1086
|
-
send({ tools })
|
|
1088
|
+
send({ tools: offered(tools) })
|
|
1087
1089
|
try {
|
|
1088
1090
|
await waitFor("tool server", () => mcp, START_MS)
|
|
1089
1091
|
} catch (error) {
|
|
@@ -1301,9 +1303,9 @@ export function toolContent(content) {
|
|
|
1301
1303
|
else if (part?.type === "image_url" || part?.type === "input_image") {
|
|
1302
1304
|
const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url
|
|
1303
1305
|
const m = /^data:([^;,]+);base64,(.*)$/s.exec(String(url ?? ""))
|
|
1304
|
-
if (!m) throw
|
|
1306
|
+
if (!m) throw unfit("a tool result's image goes to agy as data, not a link")
|
|
1305
1307
|
blocks.push({ type: "image", data: m[2], mimeType: m[1] })
|
|
1306
|
-
} else if (part?.type) throw
|
|
1308
|
+
} else if (part?.type) throw unfit(`a tool result's ${part.type} part can't go to agy`)
|
|
1307
1309
|
}
|
|
1308
1310
|
return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
|
|
1309
1311
|
}
|
|
@@ -1708,7 +1710,7 @@ export async function handle(home, input, init = {}) {
|
|
|
1708
1710
|
let content
|
|
1709
1711
|
try { content = toolContent(tool.content) } catch (error) {
|
|
1710
1712
|
waiting.close()
|
|
1711
|
-
return jsonError(error.status ?? 400, error.message)
|
|
1713
|
+
return jsonError(error.status ?? 400, error.message, error.headers)
|
|
1712
1714
|
}
|
|
1713
1715
|
// a note a result can't carry: the chat typed in, as before
|
|
1714
1716
|
try { content = resultContent(tool, notes) } catch { content = null }
|
|
@@ -1753,7 +1755,7 @@ export async function handle(home, input, init = {}) {
|
|
|
1753
1755
|
const start = async (c) => {
|
|
1754
1756
|
const { prompt, media } = c ?? paste
|
|
1755
1757
|
// agy attaches a video for any model, but only Gemini's see one
|
|
1756
|
-
if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw
|
|
1758
|
+
if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw unfit(`${model || "this model"} takes no video; a Gemini model does`)
|
|
1757
1759
|
return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages: body.messages })
|
|
1758
1760
|
}
|
|
1759
1761
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-agy-tui-auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.20",
|
|
4
4
|
"description": "Magpie/OpenCode model provider that runs Antigravity's models through agy's own interactive mode: each request is typed into the real agy TUI and its answer streamed from agy's own conversation store as the model writes it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./opencode.mjs",
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
"agy-version.mjs",
|
|
17
17
|
"tool-gate.mjs",
|
|
18
18
|
"tools.mjs",
|
|
19
|
+
"tool-names.mjs",
|
|
19
20
|
"tool-schema.mjs",
|
|
20
21
|
"re2-pattern.mjs",
|
|
21
22
|
"array-items.mjs",
|
package/seed.mjs
CHANGED
|
@@ -90,6 +90,22 @@ function loadOpener() {
|
|
|
90
90
|
return opener
|
|
91
91
|
}
|
|
92
92
|
|
|
93
|
+
// workspaceUri is a folder as the file URI agy keeps a conversation's
|
|
94
|
+
// workspace under. On Windows a path is C:\Users\…, and file:// before it
|
|
95
|
+
// as it is gave file://C:\Users\…, which agy reads as a host C with a port
|
|
96
|
+
// ":\Users\…" and turns the conversation away (lijiho96940561 on X, every
|
|
97
|
+
// seeded chat on Windows from 0.1.16): there the drive goes after
|
|
98
|
+
// file:/// with forward slashes, and a share (\\server\share) is the
|
|
99
|
+
// URI's host. The characters a URI reads as its own (%, # and ?) are
|
|
100
|
+
// escaped on every system.
|
|
101
|
+
export function workspaceUri(dir, win = process.platform === "win32") {
|
|
102
|
+
const esc = (p) => p.replace(/[%#?]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)
|
|
103
|
+
if (!win) return `file://${esc(dir)}`
|
|
104
|
+
const p = dir.replace(/^\\\\[?.]\\(?:UNC\\)?/i, (m) => (/UNC/i.test(m) ? "\\\\" : "")).replace(/\\/g, "/")
|
|
105
|
+
if (p.startsWith("//")) return `file:${esc(p)}`
|
|
106
|
+
return `file:///${esc(p.replace(/^\/+/, ""))}`
|
|
107
|
+
}
|
|
108
|
+
|
|
93
109
|
// canSeed is whether a store can be written here
|
|
94
110
|
export function canSeed() {
|
|
95
111
|
return Boolean(loadOpener())
|
|
@@ -109,7 +125,7 @@ CREATE TABLE battle_mode_infos (idx integer,data blob,PRIMARY KEY (idx));`
|
|
|
109
125
|
// order) as a conversation in the account's store (home), with its brain
|
|
110
126
|
// folder, and gives its id; null when no store can be written here. A
|
|
111
127
|
// conversation half written is taken away again.
|
|
112
|
-
export function writeConversation(home, steps, { ws = home, now = Date.now() } = {}) {
|
|
128
|
+
export function writeConversation(home, steps, { ws = home, now = Date.now(), win = process.platform === "win32" } = {}) {
|
|
113
129
|
const open = loadOpener()
|
|
114
130
|
if (!open) return null
|
|
115
131
|
const ac = path.join(home, ".gemini", "antigravity-cli")
|
|
@@ -126,7 +142,7 @@ export function writeConversation(home, steps, { ws = home, now = Date.now() } =
|
|
|
126
142
|
db.exec(SCHEMA)
|
|
127
143
|
db.exec("BEGIN")
|
|
128
144
|
db.run("INSERT INTO trajectory_meta VALUES (?,?,4,17)", traj, id)
|
|
129
|
-
const uri =
|
|
145
|
+
const uri = workspaceUri(ws, win)
|
|
130
146
|
db.run("INSERT INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)", encode([[1, [[1, uri], [3, ""]]], [2, stamp(now)], [3, randomUUID()], [6, id], [7, uri], [25, 1]]))
|
|
131
147
|
let turn = -1
|
|
132
148
|
steps.forEach((s, idx) => {
|
package/tool-names.mjs
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Names agy can offer the caller's tools under. agy gives the model each
|
|
2
|
+
// MCP tool as the function mcp_<server>_<name>, and a function's name is
|
|
3
|
+
// 64 characters at most, so a tool whose own name leaves no room for the
|
|
4
|
+
// prefix (Claude Code's plugin MCP tools, mcp__plugin_<plugin>_<server>__
|
|
5
|
+
// <tool>, run past it easily) is offered under a short name made from its
|
|
6
|
+
// own: its start, a hash of the whole name, and its end. The same tools
|
|
7
|
+
// always get the same short names (a turn's spare is keyed by its tools),
|
|
8
|
+
// two long names that share a start and an end still differ by the hash,
|
|
9
|
+
// and a call of the short name goes back to the client under its own.
|
|
10
|
+
import { createHash } from "node:crypto"
|
|
11
|
+
|
|
12
|
+
export const MCP_SERVER = "magpie"
|
|
13
|
+
// a function name's longest, and what of it is left for the tool's own
|
|
14
|
+
export const FUNCTION_NAME_MAX = 64
|
|
15
|
+
export const NAME_ROOM = FUNCTION_NAME_MAX - `mcp_${MCP_SERVER}_`.length
|
|
16
|
+
|
|
17
|
+
// shortName is name within room characters: name itself when it fits,
|
|
18
|
+
// else its start, a hash of it and its end, the hash grown until the short
|
|
19
|
+
// name is none of taken's.
|
|
20
|
+
export function shortName(name, room = NAME_ROOM, taken = new Set()) {
|
|
21
|
+
if (name.length <= room) return name
|
|
22
|
+
const hash = createHash("sha256").update(name).digest("hex")
|
|
23
|
+
for (let n = 8; n <= 32; n += 4) {
|
|
24
|
+
const left = room - n - 2
|
|
25
|
+
const head = Math.floor(left / 3)
|
|
26
|
+
const short = `${name.slice(0, head)}_${hash.slice(0, n)}_${name.slice(name.length - (left - head))}`
|
|
27
|
+
if (!taken.has(short)) return short
|
|
28
|
+
}
|
|
29
|
+
throw new Error(`no short name for the tool ${name}`)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// clientNote is what a renamed tool's description starts with: the name
|
|
33
|
+
// the conversation knows it by, which the history's calls name.
|
|
34
|
+
export const clientNote = (name) => `The conversation calls this tool ${name}.`
|
|
35
|
+
|
|
36
|
+
// shortenTools gives each tool whose name is over room a short one, with
|
|
37
|
+
// `client`, its own name, beside it; the rest are as they were. A short
|
|
38
|
+
// name never takes the name of another tool of the list.
|
|
39
|
+
export function shortenTools(tools, room = NAME_ROOM) {
|
|
40
|
+
const taken = new Set(tools.map((t) => t.name).filter((n) => n.length <= room))
|
|
41
|
+
return tools.map((t) => {
|
|
42
|
+
if (t.name.length <= room) return t
|
|
43
|
+
const name = shortName(t.name, room, taken)
|
|
44
|
+
taken.add(name)
|
|
45
|
+
return { ...t, name, client: t.name }
|
|
46
|
+
})
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// noted is a renamed tool with clientNote at the start of its description,
|
|
50
|
+
// once: a description trimmed to fit agy's budget keeps its start, and one
|
|
51
|
+
// dropped whole gets the note back.
|
|
52
|
+
export function noted(tool) {
|
|
53
|
+
if (!tool.client) return tool
|
|
54
|
+
const note = clientNote(tool.client)
|
|
55
|
+
const d = typeof tool.description === "string" ? tool.description : ""
|
|
56
|
+
return d.startsWith(note) ? tool : { ...tool, description: d ? `${note} ${d}` : note }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// offered is the tools as agy's tool server and its config take them,
|
|
60
|
+
// without the client's own names
|
|
61
|
+
export const offered = (tools) => tools.map(({ client, ...t }) => t)
|
|
62
|
+
|
|
63
|
+
// clientNames is each renamed tool's short name to its own
|
|
64
|
+
export const clientNames = (tools) => new Map(tools.filter((t) => t.client).map((t) => [t.name, t.client]))
|
package/tools.mjs
CHANGED
|
@@ -10,9 +10,18 @@ import { ensureGeminiArrayItems } from "./array-items.mjs"
|
|
|
10
10
|
import { sanitizePatternFields } from "./re2-pattern.mjs"
|
|
11
11
|
import { fitTools } from "./tool-budget.mjs"
|
|
12
12
|
import { expandToolSchema } from "./tool-schema.mjs"
|
|
13
|
+
import { noted, shortenTools } from "./tool-names.mjs"
|
|
13
14
|
|
|
14
15
|
const refuse = (message) => Object.assign(new Error(message), { status: 400 })
|
|
15
16
|
|
|
17
|
+
// unfit is a 400 over something agy alone can't be given, which another
|
|
18
|
+
// model's API may take as it is (a tool that isn't a function, a link to
|
|
19
|
+
// an image, audio): magpie's routing group asks its next member for it,
|
|
20
|
+
// where a request at fault (refuse) ends there. Older magpies read it as
|
|
21
|
+
// refuse.
|
|
22
|
+
export const SHAPE_REFUSED_HEADER = "X-Magpie-Shape-Refused"
|
|
23
|
+
export const unfit = (message) => Object.assign(refuse(message), { headers: { [SHAPE_REFUSED_HEADER]: "1" } })
|
|
24
|
+
|
|
16
25
|
function appendSchemaHint(node, hint) {
|
|
17
26
|
if (!hint) return
|
|
18
27
|
if (typeof node.description === "string" && node.description.trim()) {
|
|
@@ -173,7 +182,9 @@ function sanitizeInputSchema(schema) {
|
|
|
173
182
|
// mcpToolsOf is the body's tools as MCP tools; none when it declares none
|
|
174
183
|
// or turns them off (tool_choice "none"). A tool_choice naming one function
|
|
175
184
|
// offers only that one. A tool agy can't be given (no name, a name used
|
|
176
|
-
// twice, a schema that isn't an object) is refused, never dropped.
|
|
185
|
+
// twice, a schema that isn't an object) is refused, never dropped. A name
|
|
186
|
+
// too long for agy's functions goes under a short one (tool-names.mjs),
|
|
187
|
+
// with `client`, the name the conversation knows, beside it.
|
|
177
188
|
export function mcpToolsOf(body) {
|
|
178
189
|
const list = body?.tools
|
|
179
190
|
if (!Array.isArray(list) || !list.length) return []
|
|
@@ -183,10 +194,10 @@ export function mcpToolsOf(body) {
|
|
|
183
194
|
const seen = new Set()
|
|
184
195
|
const tools = []
|
|
185
196
|
for (const entry of list) {
|
|
186
|
-
if (entry?.type && entry.type !== "function") throw
|
|
197
|
+
if (entry?.type && entry.type !== "function") throw unfit(`agy-tui offers function tools only; the request has a ${entry.type} tool`)
|
|
187
198
|
const fn = entry?.function ?? entry
|
|
188
199
|
const name = fn?.name
|
|
189
|
-
if (typeof name !== "string" || !/^[A-Za-z0-9_.:-]
|
|
200
|
+
if (typeof name !== "string" || !/^[A-Za-z0-9_.:-]+$/.test(name)) throw refuse(`a tool without a valid name${typeof name === "string" ? ` (${JSON.stringify(name.slice(0, 80))})` : ""}`)
|
|
190
201
|
if (seen.has(name)) throw refuse(`the tool ${name} is declared twice`)
|
|
191
202
|
seen.add(name)
|
|
192
203
|
if (selected && name !== selected) continue
|
|
@@ -200,5 +211,5 @@ export function mcpToolsOf(body) {
|
|
|
200
211
|
tools.push({ name, description: typeof fn.description === "string" ? fn.description : "", inputSchema })
|
|
201
212
|
}
|
|
202
213
|
if (selected && !tools.length) throw refuse(`tool_choice names ${selected}, which the request doesn't declare`)
|
|
203
|
-
return fitTools(tools)
|
|
214
|
+
return fitTools(shortenTools(tools).map(noted)).map(noted)
|
|
204
215
|
}
|