@magpie-community/opencode-agy-tui-auth 0.1.15 → 0.1.16

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.en.md CHANGED
@@ -25,8 +25,8 @@ A request's tools (`tools`, function tools) are given to the model through magpi
25
25
  - Images (PNG, JPEG, GIF, WebP, BMP, TIFF, SVG; up to 10 MB each) and videos (MP4, MOV, WebM, AVI; up to 50 MB each), sent inline as a data: URL, go to agy as attachments, the way a file dragged into its prompt does: what agy 1.5.19's prompt attaches, at its own size limits. Images work with Gemini and Claude models, videos with Gemini models. Each file is written to the turn's folder and deleted with it.
26
26
  - Anything else agy's prompt doesn't attach, so it is refused (400) with what it was, never dropped: a PDF, audio, a text or code file, a HEIC, a link to a file instead of the file itself, and a video for a Claude model.
27
27
  - A chat goes on in agy's own conversation. A turn that answers keeps its agy conversation, and the chat's next request (the same messages, that answer, then the user's new ones) carries it on with `--conversation`, typing in only the new messages; the model gets the chat's earlier turns as turns, whole, however long the chat has grown, and agy compacts the conversation itself when it gets too long. Any other request starts a new agy conversation, with the chat before its last message pasted in as text: a new chat, one the client compacted, edited or forked, an answer the client changed, a system message after the answer, and a tool call's result, which goes on in the agy that made the call. A conversation is kept for 24 hours after its last answer, 32 for each account (the oldest go first); the list of them, in the account's folder (`agy-tui-conversations.json`), holds hashes and agy's ids, no words. A chat whose instructions change on each request is always pasted whole.
28
- - agy takes up to 192,000 bytes in a message and puts `<truncated N bytes>` for the rest, so the model wouldn't see the newest message. What is pasted is held to 180,000 bytes: the last message whole, then the instructions, then the conversation from its newest turn back; the oldest turns that don't fit are left out, with a line that says so, and instructions too long on their own are cut. A last message over it alone is refused (400).
29
- - The models say a context of 64K tokens. That is agy's limit on one message, not the model's: Gemini 4 Hydrogen has 1,048,576 in agy itself. 64K is about what fits in the 180,000 bytes pasted, with agy's own ~10K of instructions, so an agent compacts its conversation before a request that pastes it whole would be cut. A chat carried on in agy's own conversation isn't held to it (only the new messages are typed, and agy compacts its conversation by its own window), but which request will be carried on isn't known when the window is said, and any other pastes the chat whole, so the window stays what one message takes. Each response has the usage agy recorded (`usage`: the call's input, cache read and write, and every call's output and thinking).
28
+ - agy takes up to 192,000 bytes in a message and puts `<truncated N bytes>` for the rest. A chat that fits in 180,000 bytes is pasted as one message. A longer one, or one whose newest message alone is longer, is written into agy's own conversation store as a conversation (every earlier turn a step, a long user's message as several in a row), agy is started with it (`--conversation`), and only the newest message is typed. agy sends those steps to the model as the turns they are, so nothing is left out, whatever the chat's length. It needs an agy with `--conversation` (1.5.20 or later) and SQLite in the plugin host (Bun's or Node's). Without them, or with `AGY_TUI_SEED=0`, or if agy doesn't take the conversation (its log says so), the chat is pasted as before: the last message whole, then the instructions, then the conversation from its newest turn back; the oldest turns that don't fit are left out, with a line that says so. A last message over 180,000 bytes alone is then refused (400).
29
+ - Each model says its own window in agy: 1,048,576 tokens for Gemini, 1,000,000 for Claude Opus and Sonnet 5.5, 250,000 for Claude 4.6, 131,072 for GPT-OSS 120B (64K, one message's worth, until 0.1.16). agy compacts a conversation by that window itself. Each response has the usage agy recorded (`usage`: the call's input, cache read and write, and every call's output and thinking).
30
30
  - A streamed request gets the answer as the model writes it: agy commits each piece of the reply to its own conversation store (`conversations/<id>.db`), and the plugin reads what is new, read-only. When the store can't be read, the answer comes whole when the turn ends. The model's thinking (agy asks Gemini for it) comes the same way, as `reasoning_content`, before the answer; not streamed, it is the message's `reasoning_content`. The response ends when the answer is whole, without waiting for agy to exit (it sends its own telemetry on the way out).
31
31
  - agy takes seconds to start (signed in with Google, it asks Google for the account, its plan and its models before it takes a message), so each request leaves an agy started, at its prompt, for the next request with the same account, model and tools, which only types its message into it, and a turn that keeps its conversation leaves one with that conversation for the chat's next request. One waits for each such kind (three at most), for 10 minutes at most; `AGY_TUI_SPARES=0` starts each request's agy when it comes instead.
32
32
  - It needs magpie 0.1.5538 or newer (`tui-helper` and its tool server came in 0.1.5217; 0.1.5537 keeps the old per-level model ids working, 0.1.5538 reads the quota when you refresh it); an older magpie is told which version the magpie running the plugin needs when a request has tools (as a Remote magpie, the server's; a Docker image never updates itself, while its plugins update every hour). Not yet tried on Windows.
package/README.md CHANGED
@@ -25,8 +25,8 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
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
26
  - 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。
27
27
  - 一段对话在 agy 自己的会话里接着进行。一轮得到回答后,会保留它的 agy 会话;这段对话的下一个请求(同样的消息、这条回答,再加上用户的新消息)用 `--conversation` 接着这个会话,只输入新的消息。不管对话已经多长,模型拿到的都是完整的、按轮次组织的之前的对话,会话太长时由 agy 自己压缩。其他请求会开一个新的 agy 会话,把最后一条消息之前的对话整理成文字粘贴进去:新的对话、客户端压缩过、改过或分叉的对话、客户端改过的回答、回答之后出现的系统消息,以及工具调用的结果(它会回到发起调用的那个 agy 里继续)。会话在最后一次回答后保留 24 小时,每个账号最多 32 个(先删最早的);会话列表放在账号目录里(`agy-tui-conversations.json`),只有哈希和 agy 的会话 id,没有对话内容。每次请求系统指令都会变的对话,总是整段粘贴。
28
- - agy 一条消息最多收 192,000 字节,超出部分会被它替换成 `<truncated N bytes>`,模型就看不到最新的消息了。所以粘贴的内容控制在 180,000 字节以内:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。系统指令本身放不下时截短。最后一条消息单独就超过时会被拒绝(400)。
29
- - 模型宣告的上下文是 64K token。这是 agy 一条消息的上限,不是模型本身的:Gemini 4 Hydrogen 在 agy 里有 1,048,576。64K 大约是粘贴的 180,000 字节、加上 agy 自己约 10K 的指令能放下的量,这样 agent 会在整段粘贴的请求被截断之前压缩对话。在 agy 自己的会话里接着进行的对话不受它限制(只输入新消息,会话由 agy 按自己的窗口压缩),但宣告窗口时并不知道哪个请求能接着会话,其他请求都要整段粘贴,所以窗口仍按一条消息能放下的量。每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考)。
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
+ - 每个模型宣告的是它在 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`:本次调用的输入、缓存读写,以及所有调用的输出和思考)。
30
30
  - 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。模型的思考(agy 向 Gemini 要了思考内容)同样边生成边作为 `reasoning_content` 返回,在回答之前;非流式时放在消息的 `reasoning_content` 里。回答写完就结束响应,不等 agy 退出(它退出前会先发完自己的遥测)。
31
31
  - agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。保留了会话的一轮,还会为这段对话的下一个请求预先启动一个带着这个会话的 agy。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
32
32
  - 需要 magpie 0.1.5538 或更新(`tui-helper` 及其工具服务器从 0.1.5217 起有;0.1.5537 让按档位区分的旧模型 id 继续可用,0.1.5538 在你刷新时读额度);magpie 太旧时,带工具的请求会说明运行这个插件的 magpie 需要哪个版本(作为远程 magpie 使用时是服务器上的那个;Docker 镜像不会自己更新,插件却每小时更新)。Windows 尚未测试。
package/index.mjs CHANGED
@@ -7,6 +7,7 @@ import { startLogin } from "./login.mjs"
7
7
  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
+ import { canSeed, chunks, resumed, writeConversation } from "./seed.mjs"
10
11
  import { mcpToolsOf } from "./tools.mjs"
11
12
  import { agyModelOf, foldModels } from "./efforts.mjs"
12
13
  import { readUsage } from "./usage.mjs"
@@ -80,6 +81,9 @@ const PASTE_SETTLE_MS = 300
80
81
  const IDLE_MS = 5_000
81
82
  // how often a running turn's reply is read from agy's store (live.mjs)
82
83
  const LIVE_POLL_MS = 100
84
+ // how many LIVE_POLL_MS a turn that starts with a conversation waits for
85
+ // agy's log to say whether it took it
86
+ const RESUME_TRIES = 20
83
87
  // how long agy waits for a call of the caller's tool, which the client
84
88
  // runs: as long as a turn waits for its result (parkTimeout) and more
85
89
  const MCP_CALL_SECONDS = 3600
@@ -427,19 +431,19 @@ function partsOf(content, media) {
427
431
  // long paste and never its end, the newest message. What turnOf pastes is
428
432
  // held under INPUT_BUDGET, the margin for what agy adds around it.
429
433
  export const INPUT_BUDGET = 180_000
430
- // the context the models say they have: what fits in INPUT_BUDGET, with
431
- // agy's own instructions (about 10k tokens) on top, so an agent compacts
432
- // its conversation before agy would cut it. Gemini's own window is larger
433
- // (Gemini 4 Hydrogen's is 1,048,576 in agy), but agy takes no more than
434
- // this in a message. A chat carried on in agy's conversation (carriedOn)
435
- // types only its new messages, so it could go past this; but a model has
436
- // one window for every request, and whether a request is carried on is
437
- // known only when it comes (a compacted, edited or forked chat, a tool
438
- // result agy stopped waiting for, a conversation past KEEP_MS or MAX_KEPT,
439
- // AGY_TUI_CARRY=0 or an agy without --conversation all paste it whole), so
440
- // a larger window would let a pasted chat lose its oldest turns
441
- // (marovole on X asked for one).
442
- export const CONTEXT = 64_000
434
+ // the context a model says it has: its own window in agy (agy-cli's
435
+ // table, from Antigravity's own model list). A chat longer than one
436
+ // message takes goes to agy as a conversation of its own (seedOf), each
437
+ // turn whole, so the window is the model's, not one message's (64K until
438
+ // 0.1.16; baranwang on X).
439
+ export const CONTEXT = 1_048_576
440
+ export function contextOf(id) {
441
+ const family = String(id ?? "").replace(/-(?:minimal|low|medium|high|xhigh|max)$/i, "")
442
+ if (/^claude-(?:opus|sonnet)-4-6(?:-thinking)?$/i.test(family)) return 250_000
443
+ if (/^claude-/i.test(family)) return 1_000_000
444
+ if (/^gpt-oss-120b$/i.test(family)) return 131_072
445
+ return CONTEXT
446
+ }
443
447
  const bytes = (s) => Buffer.byteLength(s)
444
448
 
445
449
  // turnOf is what goes into agy's prompt: the images and videos, attached in
@@ -489,7 +493,10 @@ export function turnOf(messages, budget = INPUT_BUDGET) {
489
493
  const bare = turns.length === 1 && turns[0].role === "user"
490
494
  const lastText = bare ? turns[0].text : said(turns.at(-1))
491
495
  if (bytes(lastText) > budget) {
492
- throw refuse(`the last message is ${bytes(lastText)} bytes, more than agy takes in one message (${budget}): send less of it at once`)
496
+ const error = refuse(`the last message is ${bytes(lastText)} bytes, more than agy takes in one message (${budget}): send less of it at once`)
497
+ // seedOf takes the chat as a conversation instead
498
+ error.long = true
499
+ throw error
493
500
  }
494
501
  // what is left once the last message and the parts' blank lines are in
495
502
  const earlier = turns.slice(0, -1)
@@ -514,14 +521,16 @@ export function turnOf(messages, budget = INPUT_BUDGET) {
514
521
  const kept = new Set([...earlier.slice(from), turns.at(-1)].map((t) => t.m))
515
522
  const media = []
516
523
  ;({ system, turns } = read(messages.filter((m) => m?.role === "system" || m?.role === "developer" || kept.has(m)), media))
517
- if (bare && !system.length) return { prompt: turns[0].text, media }
524
+ // cut: something of the chat is left out
525
+ const cut = cutInstructions || from > 0
526
+ if (bare && !system.length) return { prompt: turns[0].text, media, cut }
518
527
  const parts = []
519
528
  if (system.length) parts.push(cutInstructions ? instructions : system.join("\n\n"))
520
529
  const before = turns.slice(0, -1).map(said)
521
530
  if (from > 0) before.unshift(`[${from} earlier message${from === 1 ? " is" : "s are"} left out here: the conversation is longer than one message takes]`)
522
531
  if (before.length) parts.push(before.join("\n\n"))
523
532
  parts.push(bare ? turns[0].text : said(turns.at(-1)))
524
- return { prompt: parts.join("\n\n"), media }
533
+ return { prompt: parts.join("\n\n"), media, cut }
525
534
  }
526
535
 
527
536
  // promptOf is the text turnOf pastes.
@@ -529,6 +538,77 @@ export function promptOf(messages) {
529
538
  return turnOf(messages).prompt
530
539
  }
531
540
 
541
+ // what ends a user's step a message too long for one goes on from
542
+ const GOES_ON = "\n\n[continued in the next message]"
543
+
544
+ // seedSteps is a chat as the steps of an agy conversation (seed.mjs) and
545
+ // the message typed into it: the instructions and the turns before the
546
+ // newest message as steps, the user's and the tool results in a row as
547
+ // one user's step, each assistant's words and calls (written in as turnOf
548
+ // writes them) as the model's; the newest message, the user's or the tool
549
+ // results after the last answer, typed. A user's step over budget goes as
550
+ // several in a row, each but the last saying the next goes on with it, a
551
+ // newest message over budget too, its last part typed. The images and
552
+ // videos are attached to the typed message, numbered in the order they
553
+ // came, as their marks in the steps say.
554
+ export function seedSteps(messages, budget = INPUT_BUDGET) {
555
+ if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
556
+ const media = []
557
+ const system = []
558
+ const groups = []
559
+ const add = (role, text) => {
560
+ const g = groups.at(-1)
561
+ if (g?.role === role) g.text += `\n\n${text}`
562
+ else groups.push({ role, text })
563
+ }
564
+ for (const m of messages) {
565
+ if (m?.role === "system" || m?.role === "developer") {
566
+ const text = partsOf(m?.content, media).trim()
567
+ if (text) system.push(text)
568
+ } else if (m?.role === "user") {
569
+ const text = partsOf(m?.content, media).trim()
570
+ if (text) add("user", text)
571
+ } else if (m?.role === "assistant") {
572
+ const said = [partsOf(m?.content, media).trim()]
573
+ if (Array.isArray(m.tool_calls)) {
574
+ for (const c of m.tool_calls) said.push(`[called ${c?.function?.name ?? "a tool"} ${c?.function?.arguments || "{}"} as ${c?.id ?? "a call"}]`)
575
+ }
576
+ const text = said.filter(Boolean).join("\n")
577
+ if (text) add("model", text)
578
+ } else if (m?.role === "tool") {
579
+ add("user", `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}`)
580
+ }
581
+ }
582
+ if (groups.at(-1)?.role !== "user") throw refuse("the last message is not the user's or a tool's result")
583
+ const instructions = system.join("\n\n")
584
+ if (instructions) {
585
+ if (groups[0].role === "user") groups[0].text = `${instructions}\n\n${groups[0].text}`
586
+ else groups.unshift({ role: "user", text: instructions })
587
+ }
588
+ const users = (text) => chunks(text, budget - bytes(GOES_ON)).map((c, i, all) => (i < all.length - 1 ? c + GOES_ON : c))
589
+ const steps = []
590
+ const newest = groups.pop()
591
+ for (const g of groups) {
592
+ if (g.role === "model") steps.push(g)
593
+ else for (const text of users(g.text)) steps.push({ role: "user", text })
594
+ }
595
+ const typed = users(newest.text)
596
+ const prompt = typed.pop()
597
+ for (const text of typed) steps.push({ role: "user", text })
598
+ return { steps, prompt, media }
599
+ }
600
+
601
+ // seedOf is a chat too long for one message (turnOf would leave some of it
602
+ // out, or its newest message is longer than one) written as a conversation
603
+ // of the account's agy, for a turn to start with: { id, prompt, media,
604
+ // seeded }, or null when no store can be written here.
605
+ export function seedOf(home, messages) {
606
+ if (!canSeed()) return null
607
+ const { steps, prompt, media } = seedSteps(messages)
608
+ const id = writeConversation(home, steps)
609
+ return id ? { id, prompt, media, seeded: true } : null
610
+ }
611
+
532
612
  // writeMedia writes a turn's images and videos into dir, named in order
533
613
  // (image-1.png, video-1.mp4), and gives their paths.
534
614
  export function writeMedia(dir, media) {
@@ -841,6 +921,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
841
921
  const resumable = help.includes("--conversation")
842
922
  if (model) args.push("--model", model)
843
923
  if (conversation) args.push("--conversation", conversation)
924
+ const startedAt = Date.now()
844
925
  const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
845
926
  let screen = ""
846
927
  let ended = null
@@ -1018,6 +1099,19 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1018
1099
  throw error
1019
1100
  }
1020
1101
  if (conversation) {
1102
+ // agy that ignored the conversation (its log says it found none) has
1103
+ // started one of its own, which the message would go to without the
1104
+ // chat: the request goes without it (handle). Its log says one or
1105
+ // the other as it starts; one that says neither is let go on.
1106
+ let took = resumed(home, conversation, startedAt)
1107
+ for (let i = 0; took === null && i < RESUME_TRIES; i++) {
1108
+ await new Promise((r) => setTimeout(r, LIVE_POLL_MS))
1109
+ took = resumed(home, conversation, startedAt)
1110
+ }
1111
+ if (took === false) {
1112
+ await cleanup()
1113
+ throw Object.assign(new Failure(502, `agy didn't start with conversation ${conversation}`), { ignored: true })
1114
+ }
1021
1115
  // what the conversation has already, before this turn's message
1022
1116
  from = { id: conversation, line: transcriptLines(brain, conversation) }
1023
1117
  stepBase = lastStep(home, conversation) ?? -1
@@ -1573,13 +1667,39 @@ export async function handle(home, input, init = {}) {
1573
1667
  let carried = null
1574
1668
  try {
1575
1669
  const tools = mcpToolsOf(body)
1670
+ const resumable = (await agyHelp(agy)).includes("--conversation")
1576
1671
  // the chat's conversation, kept from its last answer, goes on with the
1577
- // new messages alone; any other is typed in whole
1578
- carried = (await agyHelp(agy)).includes("--conversation") ? await carriedOn(home, body.messages, { agy, model: agyModel, tools }) : null
1579
- const { prompt, media } = carried ?? turnOf(body.messages)
1580
- // agy attaches a video for any model, but only Gemini's see one
1581
- if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
1582
- turn = await startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: carried?.id ?? null, messages: body.messages })
1672
+ // new messages alone; any other is typed in whole, and one too long
1673
+ // for one message is written into agy's store as a conversation
1674
+ // (seedOf) that the turn starts with, its newest message typed
1675
+ carried = resumable ? await carriedOn(home, body.messages, { agy, model: agyModel, tools }) : null
1676
+ let paste = null
1677
+ if (!carried) {
1678
+ try {
1679
+ paste = turnOf(body.messages)
1680
+ } catch (error) {
1681
+ if (!error.long || !resumable) throw error
1682
+ }
1683
+ if (resumable && (!paste || paste.cut) && process.env.AGY_TUI_SEED !== "0") carried = seedOf(home, body.messages)
1684
+ if (!carried && !paste) paste = turnOf(body.messages)
1685
+ }
1686
+ const start = async (c) => {
1687
+ const { prompt, media } = c ?? paste
1688
+ // 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 refuse(`${model || "this model"} takes no video; a Gemini model does`)
1690
+ return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, messages: body.messages })
1691
+ }
1692
+ try {
1693
+ turn = await start(carried)
1694
+ } catch (error) {
1695
+ if (!error.ignored) throw error
1696
+ // an agy that wouldn't start with the conversation: the chat typed
1697
+ // in, as much of it as one message takes
1698
+ forget(brainOf(home), carried.id)
1699
+ carried = null
1700
+ paste ??= turnOf(body.messages)
1701
+ turn = await start(null)
1702
+ }
1583
1703
  } catch (error) {
1584
1704
  // a conversation taken for a turn that never began is in a state
1585
1705
  // nothing knows
@@ -1602,7 +1722,7 @@ export function modelEntry(m) {
1602
1722
  name: m.name,
1603
1723
  npm: NPM,
1604
1724
  api: { id: m.id, url: "agy-tui://local", npm: NPM },
1605
- limit: { context: CONTEXT, output: 65_536 },
1725
+ limit: { context: contextOf(m.id), output: 65_536 },
1606
1726
  ...(m.variants?.length ? { reasoning: true, variants: Object.fromEntries(m.variants.map((e) => [e, { reasoningEffort: e }])), former: m.former ?? [] } : {}),
1607
1727
  // Gemini's and Claude's see the images agy attaches, as agy-cli says,
1608
1728
  // and Gemini's the videos too
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
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",
@@ -10,6 +10,7 @@
10
10
  "files": [
11
11
  "index.mjs",
12
12
  "live.mjs",
13
+ "seed.mjs",
13
14
  "login.mjs",
14
15
  "default-agent.mjs",
15
16
  "agy-version.mjs",
package/seed.mjs ADDED
@@ -0,0 +1,195 @@
1
+ // A conversation written into agy's store, for agy to start with
2
+ // (--conversation), so a chat longer than one of agy's messages goes to
3
+ // the model whole, as turns. agy takes no more than 192,000 bytes in a
4
+ // message it is typed, and rebuilds a conversation it starts with from the
5
+ // steps in its store: the user's steps (each held to the same 192,000
6
+ // bytes) and the model's (taken whole), sent to Gemini as the turns they
7
+ // are. So the chat's earlier turns are written there as steps, a user's
8
+ // long message as several in a row, and only its newest message is typed.
9
+ // (The layout is agy 1.5.20's, read from conversations it wrote, and 1.5.23's the same: the
10
+ // tables, the pragmas it checks, user_version 1 above all, without which
11
+ // it takes the store for one never set up and starts a conversation of
12
+ // its own, and each step's fields.)
13
+ import { createRequire } from "node:module"
14
+ import { randomUUID } from "node:crypto"
15
+ import fs from "node:fs"
16
+ import path from "node:path"
17
+
18
+ const require = createRequire(import.meta.url)
19
+ const USER_STEP = 14
20
+ const MODEL_STEP = 15
21
+ const DONE = 3
22
+
23
+ // ---- a minimal protobuf writer: a message is [[field, value], …]; a
24
+ // value is a number (varint), a string or bytes, or an array (a message
25
+ // in it); undefined is left out
26
+
27
+ function varint(n) {
28
+ const out = []
29
+ let v = BigInt(n)
30
+ do {
31
+ let b = Number(v & 0x7fn)
32
+ v >>= 7n
33
+ if (v) b |= 0x80
34
+ out.push(b)
35
+ } while (v)
36
+ return Buffer.from(out)
37
+ }
38
+
39
+ export function encode(msg) {
40
+ const out = []
41
+ for (const [field, v] of msg) {
42
+ if (v === undefined || v === null) continue
43
+ if (typeof v === "number" || typeof v === "bigint") {
44
+ out.push(varint((field << 3) | 0), varint(v))
45
+ continue
46
+ }
47
+ const b = Array.isArray(v) ? encode(v) : Buffer.isBuffer(v) ? v : Buffer.from(String(v))
48
+ out.push(varint((field << 3) | 2), varint(b.length), b)
49
+ }
50
+ return Buffer.concat(out)
51
+ }
52
+
53
+ const stamp = (ms) => [[1, Math.floor(ms / 1000)], [2, (ms % 1000) * 1e6]]
54
+ const hex = () => randomUUID().replace(/-/g, "")
55
+
56
+ // bun:sqlite under Bun (magpie's plugin host), node:sqlite on Node 22.5+;
57
+ // null when neither is there
58
+ let opener
59
+ function loadOpener() {
60
+ if (opener !== undefined) return opener
61
+ opener = null
62
+ try {
63
+ const { Database } = require("bun:sqlite")
64
+ if (typeof Database === "function") {
65
+ opener = (file) => {
66
+ const db = new Database(file, { create: true })
67
+ return {
68
+ exec: (sql) => db.exec(sql),
69
+ run: (sql, ...args) => db.prepare(sql).run(...args),
70
+ close: () => db.close(),
71
+ }
72
+ }
73
+ return opener
74
+ }
75
+ } catch {}
76
+ try {
77
+ const { DatabaseSync } = require("node:sqlite")
78
+ if (typeof DatabaseSync === "function") {
79
+ opener = (file) => {
80
+ const db = new DatabaseSync(file)
81
+ return {
82
+ exec: (sql) => db.exec(sql),
83
+ run: (sql, ...args) => db.prepare(sql).run(...args),
84
+ close: () => db.close(),
85
+ }
86
+ }
87
+ return opener
88
+ }
89
+ } catch {}
90
+ return opener
91
+ }
92
+
93
+ // canSeed is whether a store can be written here
94
+ export function canSeed() {
95
+ return Boolean(loadOpener())
96
+ }
97
+
98
+ const SCHEMA = `CREATE TABLE trajectory_meta (trajectory_id text,cascade_id text,trajectory_type integer,source integer,PRIMARY KEY (trajectory_id));
99
+ CREATE TABLE steps (idx integer,step_type integer NOT NULL DEFAULT 0,status integer NOT NULL DEFAULT 0,has_subtrajectory numeric NOT NULL DEFAULT false,metadata blob,error_details blob,permissions blob,task_details blob,render_info blob,step_payload blob,step_format integer NOT NULL DEFAULT 0,PRIMARY KEY (idx));
100
+ CREATE INDEX idx_steps_status ON steps(status);
101
+ CREATE INDEX idx_steps_step_type ON steps(step_type);
102
+ CREATE TABLE gen_metadata (idx integer,data blob,size integer NOT NULL DEFAULT 0,PRIMARY KEY (idx));
103
+ CREATE TABLE executor_metadata (idx integer,data blob,PRIMARY KEY (idx));
104
+ CREATE TABLE parent_references (idx integer,data blob,PRIMARY KEY (idx));
105
+ CREATE TABLE trajectory_metadata_blob (id text DEFAULT "main",data blob,PRIMARY KEY (id));
106
+ CREATE TABLE battle_mode_infos (idx integer,data blob,PRIMARY KEY (idx));`
107
+
108
+ // writeConversation writes steps ({role: "user" | "model", text}, in
109
+ // order) as a conversation in the account's store (home), with its brain
110
+ // folder, and gives its id; null when no store can be written here. A
111
+ // conversation half written is taken away again.
112
+ export function writeConversation(home, steps, { ws = home, now = Date.now() } = {}) {
113
+ const open = loadOpener()
114
+ if (!open) return null
115
+ const ac = path.join(home, ".gemini", "antigravity-cli")
116
+ const id = randomUUID()
117
+ const traj = randomUUID()
118
+ const dir = path.join(ac, "conversations")
119
+ const file = path.join(dir, `${id}.db`)
120
+ let db
121
+ try {
122
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
123
+ fs.mkdirSync(path.join(ac, "brain", id), { recursive: true, mode: 0o700 })
124
+ db = open(file)
125
+ db.exec("PRAGMA page_size=32768; PRAGMA journal_mode=WAL; PRAGMA user_version=1")
126
+ db.exec(SCHEMA)
127
+ db.exec("BEGIN")
128
+ db.run("INSERT INTO trajectory_meta VALUES (?,?,4,17)", traj, id)
129
+ const uri = `file://${ws}`
130
+ 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
+ let turn = -1
132
+ steps.forEach((s, idx) => {
133
+ const user = s.role === "user"
134
+ // a user's step after a model's starts the next turn
135
+ if (user && (idx === 0 || steps[idx - 1].role !== "user")) turn++
136
+ const at = now - (steps.length - idx) * 1000
137
+ const meta = [[1, stamp(at)], [3, user ? 4 : 2], [12, randomUUID()], [20, [[1, traj], [2, idx || undefined], [3, Math.max(turn, 0) || undefined], [4, id]]], [35, hex()]]
138
+ const body = user ? [19, [[2, s.text], [3, [[1, s.text]]], [4, ""]]] : [20, [[1, s.text], [8, s.text]]]
139
+ const type = user ? USER_STEP : MODEL_STEP
140
+ db.run("INSERT INTO steps (idx, step_type, status, metadata, step_payload) VALUES (?,?,?,?,?)", idx, type, DONE, encode(meta), encode([[1, type], [4, DONE], [5, meta], body]))
141
+ })
142
+ db.exec("COMMIT")
143
+ db.close()
144
+ db = null
145
+ return id
146
+ } catch (error) {
147
+ try { db?.close() } catch {}
148
+ fs.rmSync(path.join(ac, "brain", id), { recursive: true, force: true })
149
+ for (const end of ["", "-wal", "-shm", "-journal"]) fs.rmSync(file + end, { force: true })
150
+ throw error
151
+ }
152
+ }
153
+
154
+ // resumed is whether agy, started at `since` (ms) with the conversation
155
+ // id, says in its log that it took it: true when it is resuming it, false
156
+ // when it ignored it (and started one of its own), null while its log
157
+ // says neither.
158
+ export function resumed(home, id, since) {
159
+ const dir = path.join(home, ".gemini", "antigravity-cli", "log")
160
+ let names = []
161
+ try { names = fs.readdirSync(dir).filter((n) => n.endsWith(".log")) } catch { return null }
162
+ let took = null
163
+ for (const name of names) {
164
+ const file = path.join(dir, name)
165
+ let text
166
+ try {
167
+ if (fs.statSync(file).mtimeMs < since - 2000) continue
168
+ text = fs.readFileSync(file, "utf8")
169
+ } catch { continue }
170
+ if (!text.includes(id)) continue
171
+ if (text.includes(`Conversation ${id} not found`)) return false
172
+ if (text.includes(`Resuming conversation ${id}`)) took = true
173
+ }
174
+ return took
175
+ }
176
+
177
+ // chunks cuts text into pieces of at most max bytes, at a line's end where
178
+ // one is near, never inside a character
179
+ export function chunks(text, max) {
180
+ const buf = Buffer.from(text)
181
+ if (buf.length <= max) return [text]
182
+ const out = []
183
+ let at = 0
184
+ while (buf.length - at > max) {
185
+ let end = at + max
186
+ // a character's continuation bytes stay with it
187
+ while (end > at && (buf[end] & 0xc0) === 0x80) end--
188
+ const nl = buf.lastIndexOf(0x0a, end - 1)
189
+ if (nl >= at + max * 0.8) end = nl + 1
190
+ out.push(buf.subarray(at, end).toString())
191
+ at = end
192
+ }
193
+ out.push(buf.subarray(at).toString())
194
+ return out
195
+ }