@magpie-community/opencode-agy-tui-auth 0.1.17 → 0.1.19
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 +113 -44
- package/package.json +2 -1
- 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
|
|
@@ -793,8 +793,8 @@ export function mcpConfig(mcp, tools) {
|
|
|
793
793
|
// own tools stay off. With a conversation (an id agy kept, carried), agy
|
|
794
794
|
// starts with it and the prompt carries it on; `messages` is the request's
|
|
795
795
|
// whole chat, which the conversation is kept under when the turn answers.
|
|
796
|
-
export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE, conversation = null, messages = null }) {
|
|
797
|
-
const opts = { agy, home, model, tools, helper, conversation }
|
|
796
|
+
export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE, conversation = null, messages = null, place = null }) {
|
|
797
|
+
const opts = { agy, home, model, tools, helper, conversation, place }
|
|
798
798
|
const key = spareKey(opts)
|
|
799
799
|
let turn = null
|
|
800
800
|
const spare = await takeSpare(key)
|
|
@@ -810,7 +810,7 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
810
810
|
if (!turn) turn = await (await launch(opts)).begin({ prompt, media, signal, messages })
|
|
811
811
|
// agy has the message: the next request's agy starts now (a chat carried
|
|
812
812
|
// on has its own, left as its turn ends)
|
|
813
|
-
if (!conversation) leaveSpare(key, { ...opts, conversation: null })
|
|
813
|
+
if (!conversation) leaveSpare(key, { ...opts, conversation: null, place: null })
|
|
814
814
|
return turn
|
|
815
815
|
}
|
|
816
816
|
|
|
@@ -872,15 +872,37 @@ export async function closeSpares() {
|
|
|
872
872
|
}))
|
|
873
873
|
}
|
|
874
874
|
|
|
875
|
+
// folderAt is a new, empty folder for a turn: at `want`, the path the
|
|
876
|
+
// conversation it carries on ran in before, when that is one of ours (in
|
|
877
|
+
// the temp folder, named as ours are) and nothing has it now; else one of
|
|
878
|
+
// its own. agy writes the folder's path into the model's instructions
|
|
879
|
+
// (the workspace's AGENTS.md rule, its active workspaces, the command
|
|
880
|
+
// folder, with tools the HOME's app data folder), and a conversation
|
|
881
|
+
// started again in another adds it beside the last ones: the instructions
|
|
882
|
+
// would change every turn, and every token after them miss the model's
|
|
883
|
+
// cache (plugins#1963).
|
|
884
|
+
function folderAt(want, prefix) {
|
|
885
|
+
const tmp = fs.realpathSync(os.tmpdir())
|
|
886
|
+
if (typeof want === "string" && path.dirname(want) === tmp && new RegExp(`^${prefix}[A-Za-z0-9]{6}$`).test(path.basename(want))) {
|
|
887
|
+
try {
|
|
888
|
+
fs.mkdirSync(want, { mode: 0o700 })
|
|
889
|
+
return fs.realpathSync(want)
|
|
890
|
+
} catch {}
|
|
891
|
+
}
|
|
892
|
+
return fs.realpathSync(fs.mkdtempSync(path.join(tmp, prefix)))
|
|
893
|
+
}
|
|
894
|
+
|
|
875
895
|
// launch starts agy for a turn, in a folder of its own (with the
|
|
876
|
-
// conversation it carries on, if any
|
|
877
|
-
// prompt, media, signal, messages
|
|
878
|
-
// types the request in and resolves
|
|
879
|
-
|
|
896
|
+
// conversation it carries on, if any, in the folders it ran in before,
|
|
897
|
+
// `place`), and resolves at once: begin({ prompt, media, signal, messages
|
|
898
|
+
// }) waits until it is at its prompt, types the request in and resolves
|
|
899
|
+
// with the turn
|
|
900
|
+
async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null, place = null }) {
|
|
880
901
|
if (!helper) throw new Failure(501, oldMagpie(TUI_HELPER_MAGPIE, "has a terminal for agy"))
|
|
881
902
|
settleHome(home)
|
|
882
903
|
const withTools = tools.length > 0
|
|
883
|
-
const
|
|
904
|
+
const clients = clientNames(tools)
|
|
905
|
+
const ws = folderAt(place?.ws, "agy-tui-")
|
|
884
906
|
// agy's default agent, never --agent: the instructions in AGENTS.md, agy's
|
|
885
907
|
// bundled skills left out, and a PreToolUse hook that denies every call of
|
|
886
908
|
// agy's own tools (what the old agent's `tools: []` did); with tools, the
|
|
@@ -894,7 +916,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
894
916
|
geminiDir: path.join(home, ".gemini"),
|
|
895
917
|
})
|
|
896
918
|
if (withTools) {
|
|
897
|
-
ownHome =
|
|
919
|
+
ownHome = folderAt(place?.ownHome, "agy-tui-home-")
|
|
898
920
|
sessionHome(home, ownHome)
|
|
899
921
|
}
|
|
900
922
|
} catch (error) {
|
|
@@ -1002,7 +1024,8 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1002
1024
|
pending.add(o.call.id)
|
|
1003
1025
|
if (!found?.id) look()
|
|
1004
1026
|
if (found?.id) publish(liveReply(home, found.id, stepBase))
|
|
1005
|
-
|
|
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 }
|
|
1006
1029
|
spent().then((usage) => stop({ call, usage }))
|
|
1007
1030
|
}
|
|
1008
1031
|
if (o.dropped) pending.delete(o.dropped)
|
|
@@ -1062,7 +1085,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1062
1085
|
try {
|
|
1063
1086
|
if (withTools) {
|
|
1064
1087
|
// the tool server first: agy reads its config as it starts
|
|
1065
|
-
send({ tools })
|
|
1088
|
+
send({ tools: offered(tools) })
|
|
1066
1089
|
try {
|
|
1067
1090
|
await waitFor("tool server", () => mcp, START_MS)
|
|
1068
1091
|
} catch (error) {
|
|
@@ -1225,7 +1248,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
|
|
|
1225
1248
|
const id = found?.id
|
|
1226
1249
|
const answered = Boolean(resumable && last.text && id && turn.messages)
|
|
1227
1250
|
const out = cleanup()
|
|
1228
|
-
if (answered) keep(home, turn.messages, id, [found.answer, since(turn, live.text)], { agy, home, model, tools, helper }, out)
|
|
1251
|
+
if (answered) keep(home, turn.messages, id, [found.answer, since(turn, live.text)], { agy, home, model, tools, helper, place: { ws, ownHome } }, out)
|
|
1229
1252
|
await leaving(out.then(() => {
|
|
1230
1253
|
if (!answered) forget(brain, id)
|
|
1231
1254
|
}))
|
|
@@ -1280,9 +1303,46 @@ export function toolContent(content) {
|
|
|
1280
1303
|
else if (part?.type === "image_url" || part?.type === "input_image") {
|
|
1281
1304
|
const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url
|
|
1282
1305
|
const m = /^data:([^;,]+);base64,(.*)$/s.exec(String(url ?? ""))
|
|
1283
|
-
if (!m) throw
|
|
1306
|
+
if (!m) throw unfit("a tool result's image goes to agy as data, not a link")
|
|
1284
1307
|
blocks.push({ type: "image", data: m[2], mimeType: m[1] })
|
|
1285
|
-
} else if (part?.type) throw
|
|
1308
|
+
} else if (part?.type) throw unfit(`a tool result's ${part.type} part can't go to agy`)
|
|
1309
|
+
}
|
|
1310
|
+
return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// NOTE_ROLES are the messages a client sends after a tool's result that
|
|
1314
|
+
// aren't the user's next turn: Claude Code's reminders beside a
|
|
1315
|
+
// tool_result, a system note Claude Desktop puts after every one, and the
|
|
1316
|
+
// images a tool returned, which magpie gives in a user message after the
|
|
1317
|
+
// tool message (a tool message holds text only)
|
|
1318
|
+
const NOTE_ROLES = new Set(["user", "system", "developer"])
|
|
1319
|
+
|
|
1320
|
+
// resultOf is the tool message a request ends with that answers a call,
|
|
1321
|
+
// and the notes the client sent after it ({ tool, notes }), or null: what
|
|
1322
|
+
// came after the request's last assistant message is tool messages, then
|
|
1323
|
+
// notes alone.
|
|
1324
|
+
export function resultOf(messages) {
|
|
1325
|
+
if (!Array.isArray(messages)) return null
|
|
1326
|
+
const tail = messages.slice(messages.findLastIndex((m) => m?.role === "assistant") + 1)
|
|
1327
|
+
const k = tail.findLastIndex((m) => m?.role === "tool")
|
|
1328
|
+
if (k < 0 || !tail.slice(0, k).every((m) => m?.role === "tool")) return null
|
|
1329
|
+
const notes = tail.slice(k + 1)
|
|
1330
|
+
if (!notes.every((m) => NOTE_ROLES.has(m?.role))) return null
|
|
1331
|
+
return { tool: tail[k], notes }
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
// resultContent is what agy gets as a call's result: the tool's content,
|
|
1335
|
+
// and the notes' text and images after it, so a parked turn goes on with
|
|
1336
|
+
// them (a note it didn't get would make the chat look new, typed in whole
|
|
1337
|
+
// into a new agy: a whole new prompt for the model's cache, every call,
|
|
1338
|
+
// plugins#1963). A note's part a result can't carry throws.
|
|
1339
|
+
export function resultContent(tool, notes = []) {
|
|
1340
|
+
const own = toolContent(tool.content)
|
|
1341
|
+
if (!notes.length) return own
|
|
1342
|
+
const blocks = typeof own === "string" ? (own ? [{ type: "text", text: own }] : []) : [...own]
|
|
1343
|
+
for (const n of notes) {
|
|
1344
|
+
const c = toolContent(n.content)
|
|
1345
|
+
if (typeof c === "string") { if (c.trim()) blocks.push({ type: "text", text: c }) } else blocks.push(...c)
|
|
1286
1346
|
}
|
|
1287
1347
|
return blocks.length === 1 && blocks[0].type === "text" ? blocks[0].text : blocks
|
|
1288
1348
|
}
|
|
@@ -1312,10 +1372,12 @@ function forget(brain, id) {
|
|
|
1312
1372
|
// (a new chat, one the client compacted or edited, an answer the client
|
|
1313
1373
|
// changed) starts a conversation of its own, the chat typed in as before.
|
|
1314
1374
|
// One carried on is taken off the list while its turn runs, so two
|
|
1315
|
-
// requests never share it; a fork of the chat starts its own.
|
|
1375
|
+
// requests never share it; a fork of the chat starts its own. Its agy
|
|
1376
|
+
// runs in the folders the turn before ran in (folderAt), so the model's
|
|
1377
|
+
// instructions are the same each turn and its cache holds. Each is kept
|
|
1316
1378
|
// KEEP_MS from its last answer, MAX_KEPT an account (the oldest go first),
|
|
1317
|
-
// and the list, hashes and
|
|
1318
|
-
// restart finds them.
|
|
1379
|
+
// and the list, hashes, ids and folder paths alone, is in the account's
|
|
1380
|
+
// home, so a restart finds them.
|
|
1319
1381
|
const KEEP_MS = 24 * 3600_000
|
|
1320
1382
|
const MAX_KEPT = 32
|
|
1321
1383
|
const KEPT_FILE = "agy-tui-conversations.json"
|
|
@@ -1362,7 +1424,7 @@ function saveKept(home, list) {
|
|
|
1362
1424
|
const file = path.join(home, KEPT_FILE)
|
|
1363
1425
|
const tmp = `${file}.${process.pid}.tmp`
|
|
1364
1426
|
try {
|
|
1365
|
-
fs.writeFileSync(tmp, JSON.stringify({ kept: [...list].map(([key, e]) => ({ key, id: e.id, replies: e.replies, at: e.at })) }), { mode: 0o600 })
|
|
1427
|
+
fs.writeFileSync(tmp, JSON.stringify({ kept: [...list].map(([key, e]) => ({ key, id: e.id, replies: e.replies, at: e.at, place: e.place })) }), { mode: 0o600 })
|
|
1366
1428
|
fs.renameSync(tmp, file)
|
|
1367
1429
|
} catch {
|
|
1368
1430
|
try { fs.rmSync(tmp, { force: true }) } catch {}
|
|
@@ -1389,7 +1451,8 @@ function keptOf(home) {
|
|
|
1389
1451
|
try { saved = JSON.parse(fs.readFileSync(path.join(home, KEPT_FILE), "utf8")) } catch {}
|
|
1390
1452
|
for (const e of Array.isArray(saved?.kept) ? saved.kept : []) {
|
|
1391
1453
|
if (typeof e?.key !== "string" || !CONVERSATION_ID.test(String(e?.id ?? "")) || !Array.isArray(e.replies) || !Number.isFinite(e.at)) continue
|
|
1392
|
-
|
|
1454
|
+
const place = { ws: typeof e.place?.ws === "string" ? e.place.ws : null, ownHome: typeof e.place?.ownHome === "string" ? e.place.ownHome : null }
|
|
1455
|
+
list.set(e.key, { id: e.id, replies: e.replies.filter((r) => typeof r === "string"), at: e.at, place })
|
|
1393
1456
|
// never another turn's answer
|
|
1394
1457
|
claimed.add(e.id)
|
|
1395
1458
|
}
|
|
@@ -1437,7 +1500,7 @@ function keep(home, messages, id, replies, opts, gone) {
|
|
|
1437
1500
|
list.delete(key)
|
|
1438
1501
|
if (old.id !== id) dropKept(home, old)
|
|
1439
1502
|
}
|
|
1440
|
-
const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), ready: Promise.resolve(gone).catch(() => {}) }
|
|
1503
|
+
const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), place: opts.place ?? null, ready: Promise.resolve(gone).catch(() => {}) }
|
|
1441
1504
|
list.set(key, e)
|
|
1442
1505
|
prune(home, list)
|
|
1443
1506
|
saveKept(home, list)
|
|
@@ -1484,7 +1547,7 @@ export async function carriedOn(home, messages, { agy, model, tools }) {
|
|
|
1484
1547
|
forget(brainOf(home), e.id)
|
|
1485
1548
|
return null
|
|
1486
1549
|
}
|
|
1487
|
-
return { id: e.id, prompt, media }
|
|
1550
|
+
return { id: e.id, prompt, media, place: e.place ?? null }
|
|
1488
1551
|
}
|
|
1489
1552
|
|
|
1490
1553
|
// ---- OpenAI chat completions
|
|
@@ -1637,20 +1700,26 @@ export async function handle(home, input, init = {}) {
|
|
|
1637
1700
|
// agent asked (efforts.mjs); a level's own id is run as it is
|
|
1638
1701
|
const said = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined) ?? {}).get("x-magpie-effort") ?? ""
|
|
1639
1702
|
const agyModel = home ? agyModelOf(model, (modelLists.get(home) ?? readModelList(home))?.list, body, said) : model
|
|
1640
|
-
// the result of a call a turn waits on goes on with that turn
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1703
|
+
// the result of a call a turn waits on goes on with that turn, with the
|
|
1704
|
+
// notes the client sent after it
|
|
1705
|
+
const result = resultOf(body.messages)
|
|
1706
|
+
if (result) {
|
|
1707
|
+
const { tool, notes } = result
|
|
1708
|
+
const waiting = unpark(tool.tool_call_id)
|
|
1644
1709
|
if (waiting && !waiting.ended) {
|
|
1645
|
-
waiting.messages = body.messages
|
|
1646
1710
|
let content
|
|
1647
|
-
try { content = toolContent(
|
|
1711
|
+
try { content = toolContent(tool.content) } catch (error) {
|
|
1648
1712
|
waiting.close()
|
|
1649
|
-
return jsonError(error.status ?? 400, error.message)
|
|
1713
|
+
return jsonError(error.status ?? 400, error.message, error.headers)
|
|
1650
1714
|
}
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1715
|
+
// a note a result can't carry: the chat typed in, as before
|
|
1716
|
+
try { content = resultContent(tool, notes) } catch { content = null }
|
|
1717
|
+
if (content !== null) {
|
|
1718
|
+
waiting.messages = body.messages
|
|
1719
|
+
if (waiting.reply(tool.tool_call_id, content)) {
|
|
1720
|
+
waiting.watch(signal)
|
|
1721
|
+
return respond(id, model, waiting, body.stream)
|
|
1722
|
+
}
|
|
1654
1723
|
}
|
|
1655
1724
|
}
|
|
1656
1725
|
// agy no longer waits on it: a turn of its own, the conversation
|
|
@@ -1686,8 +1755,8 @@ export async function handle(home, input, init = {}) {
|
|
|
1686
1755
|
const start = async (c) => {
|
|
1687
1756
|
const { prompt, media } = c ?? paste
|
|
1688
1757
|
// agy attaches a video for any model, but only Gemini's see one
|
|
1689
|
-
if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw
|
|
1690
|
-
return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, messages: body.messages })
|
|
1758
|
+
if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw unfit(`${model || "this model"} takes no video; a Gemini model does`)
|
|
1759
|
+
return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, place: c?.place ?? null, messages: body.messages })
|
|
1691
1760
|
}
|
|
1692
1761
|
try {
|
|
1693
1762
|
turn = await start(carried)
|
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.19",
|
|
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/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
|
}
|