@magpie-community/opencode-agy-tui-auth 0.1.8 → 0.1.10

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
@@ -8,7 +8,7 @@ Antigravity's models through agy's own interactive mode (its TUI). Each request
8
8
 
9
9
  1. Install the [Antigravity CLI](https://antigravity.google/docs/cli) (`agy`), version 1.5.19 or newer. An older agy is refused with "Update agy".
10
10
  2. Install this plugin from magpie's Plugins page, add **Antigravity (agy TUI)** under Providers and pick "Sign in with Google": magpie opens agy's sign-in link, and you paste back the code the page shows.
11
- 3. The models are the ones `agy models` lists.
11
+ 3. The models are the ones `agy models` lists: asked at sign-in and kept in the account's folder, and asked again only when you refresh the list.
12
12
 
13
13
  Each account has a home of its own (`~/.local/state/magpie-agy-tui/accounts/<id>`), where agy keeps its sign-in as a file. Your own `~/.gemini`, skills and MCP servers are neither used nor changed.
14
14
 
@@ -22,11 +22,11 @@ A request's tools (`tools`, function tools) are given to the model through magpi
22
22
 
23
23
  - 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.
24
24
  - 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.
25
- - Each request is a new agy conversation, but for a tool call's result, which goes on in the agy that made the call; the conversation before it is pasted with it as text. So a conversation taken up again after a long while is pasted whole again.
25
+ - 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.
26
26
  - 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).
27
- - The models say a context of 64K tokens (about what fits in agy's message, with agy's own ~10K of instructions), and each response has the usage agy recorded (`usage`: the call's input, cache read and write, and every call's output and thinking), so an agent compacts its conversation before agy would cut it.
27
+ - The models say a context of 64K tokens (about what fits in agy's message, with agy's own ~10K of instructions), and each response has the usage agy recorded (`usage`: the call's input, cache read and write, and every call's output and thinking), so an agent compacts its conversation before a request that pastes it whole would be cut.
28
28
  - 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).
29
- - 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. 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.
29
+ - 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.
30
30
  - It needs magpie 0.1.5217 or newer (with `tui-helper` and its tool server); an older magpie is told to update when a request has tools. Not yet tried on Windows.
31
31
 
32
32
  ## Options (environment)
@@ -36,4 +36,5 @@ A request's tools (`tools`, function tools) are given to the model through magpi
36
36
  - `AGY_TUI_PARK_TIMEOUT_MS`: how long a turn waits for a tool call's result, 10 minutes by default.
37
37
  - `AGY_TUI_ATTACH_TIMEOUT_MS`: how long agy may take to attach a turn's images and videos, 15 seconds by default.
38
38
  - `AGY_TUI_SPARES=0`: no agy started ahead for the next request.
39
+ - `AGY_TUI_CARRY=0`: every request in a new agy conversation, the chat pasted in whole, and no conversation kept.
39
40
  - `AGY_TUI_KEEP=1`: keep each turn's folder (its images and videos too) and agy's conversation, to look into a problem.
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  1. 安装 [Antigravity CLI](https://antigravity.google/docs/cli)(`agy`),需要 1.5.19 或更新;更旧的 agy 会被拒绝,并提示「Update agy」。
10
10
  2. 在 magpie 的插件页安装本插件,然后在 Providers 里添加 **Antigravity (agy TUI)**,选「使用 Google 登录」:magpie 打开 agy 的登录链接,把页面上显示的代码粘贴回来即可。
11
- 3. 模型列表来自 `agy models`。
11
+ 3. 模型列表来自 `agy models`:登录时问一次,存在账号目录里,之后只在你刷新列表时再问。
12
12
 
13
13
  每个账号都有自己的 home(`~/.local/state/magpie-agy-tui/accounts/<id>`),agy 的登录信息以文件形式存在那里。你自己的 `~/.gemini`、skills 和 MCP 服务器都不会被用到,也不会被改动。
14
14
 
@@ -22,11 +22,11 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
22
22
 
23
23
  - 图片(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 模型。每个文件写进本轮的临时目录,随目录一起删除。
24
24
  - 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。
25
- - 每个请求都是一次新的 agy 会话(工具调用的结果除外,它会回到发起调用的那个 agy 里继续),之前的对话会整理成文字一起粘贴进去。所以长时间不用后再继续的对话,下一个请求会重新粘贴整段对话。
25
+ - 一段对话在 agy 自己的会话里接着进行。一轮得到回答后,会保留它的 agy 会话;这段对话的下一个请求(同样的消息、这条回答,再加上用户的新消息)用 `--conversation` 接着这个会话,只输入新的消息。不管对话已经多长,模型拿到的都是完整的、按轮次组织的之前的对话,会话太长时由 agy 自己压缩。其他请求会开一个新的 agy 会话,把最后一条消息之前的对话整理成文字粘贴进去:新的对话、客户端压缩过、改过或分叉的对话、客户端改过的回答、回答之后出现的系统消息,以及工具调用的结果(它会回到发起调用的那个 agy 里继续)。会话在最后一次回答后保留 24 小时,每个账号最多 32 个(先删最早的);会话列表放在账号目录里(`agy-tui-conversations.json`),只有哈希和 agy 的会话 id,没有对话内容。每次请求系统指令都会变的对话,总是整段粘贴。
26
26
  - agy 一条消息最多收 192,000 字节,超出部分会被它替换成 `<truncated N bytes>`,模型就看不到最新的消息了。所以粘贴的内容控制在 180,000 字节以内:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。系统指令本身放不下时截短。最后一条消息单独就超过时会被拒绝(400)。
27
- - 模型宣告的上下文是 64K token(大约是 agy 一条消息能放下的量,加上 agy 自己约 10K 的指令),每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考),这样 agent 会在 agy 截断之前压缩对话。
27
+ - 模型宣告的上下文是 64K token(大约是 agy 一条消息能放下的量,加上 agy 自己约 10K 的指令),每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考),这样 agent 会在整段粘贴的请求被截断之前压缩对话。
28
28
  - 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。模型的思考(agy 向 Gemini 要了思考内容)同样边生成边作为 `reasoning_content` 返回,在回答之前;非流式时放在消息的 `reasoning_content` 里。回答写完就结束响应,不等 agy 退出(它退出前会先发完自己的遥测)。
29
- - agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
29
+ - agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。保留了会话的一轮,还会为这段对话的下一个请求预先启动一个带着这个会话的 agy。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
30
30
  - 需要 magpie 0.1.5217 或更新(带 `tui-helper` 及其工具服务器);magpie 太旧时,带工具的请求会提示更新 magpie。Windows 尚未测试。
31
31
 
32
32
  ## 选项(环境变量)
@@ -36,4 +36,5 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
36
36
  - `AGY_TUI_PARK_TIMEOUT_MS`:一轮等待工具调用结果的最长时间,默认 10 分钟。
37
37
  - `AGY_TUI_ATTACH_TIMEOUT_MS`:agy 附加本轮图片和视频的最长等待时间,默认 15 秒。
38
38
  - `AGY_TUI_SPARES=0`:不为下一个请求预先启动 agy。
39
+ - `AGY_TUI_CARRY=0`:每个请求都开新的 agy 会话、整段粘贴对话,不保留会话。
39
40
  - `AGY_TUI_KEEP=1`:保留每轮的临时目录(包括图片和视频)和 agy 的对话记录,方便排查。
package/index.mjs CHANGED
@@ -6,7 +6,7 @@ import path from "node:path"
6
6
  import { startLogin } from "./login.mjs"
7
7
  import { writeDefaultAgentFiles } from "./default-agent.mjs"
8
8
  import { agyTooOld, MIN_AGY_VERSION } from "./agy-version.mjs"
9
- import { liveReply, callsAfter, usageOf } from "./live.mjs"
9
+ import { liveReply, callsAfter, usageOf, lastStep } from "./live.mjs"
10
10
  import { mcpToolsOf } from "./tools.mjs"
11
11
 
12
12
  // agy-tui: Antigravity's models through agy's own interactive mode. Each
@@ -261,6 +261,58 @@ async function listModels(agy, home) {
261
261
  return models
262
262
  }
263
263
 
264
+ // The account's list, as `agy models` gave it last (Discord, 12-03: an
265
+ // Antigravity account was banned with no agent using it). An idle account
266
+ // sends Google nothing of its own, so the list is asked at the sign-in, on
267
+ // the user's refresh (ctx.refresh), or when there is none, and kept in the
268
+ // account's home across restarts (magpie-models.json, written to a temp
269
+ // file renamed over it). A file that can't be read keeps the last good read.
270
+ const MODELS_FILE = "magpie-models.json"
271
+ const modelLists = new Map()
272
+
273
+ function readModelList(home) {
274
+ try {
275
+ const saved = JSON.parse(fs.readFileSync(path.join(home, MODELS_FILE), "utf8"))
276
+ const list = Array.isArray(saved?.list)
277
+ ? saved.list.filter((m) => typeof m?.id === "string" && m.id && typeof m.name === "string").map(({ id, name }) => ({ id, name }))
278
+ : []
279
+ if (!list.length) return modelLists.get(home) ?? null
280
+ const read = { list, fetchedAt: Number.isFinite(saved.fetchedAt) ? saved.fetchedAt : 0 }
281
+ modelLists.set(home, read)
282
+ return read
283
+ } catch {
284
+ return modelLists.get(home) ?? null
285
+ }
286
+ }
287
+
288
+ function saveModelList(home, list) {
289
+ const kept = { list, fetchedAt: Date.now() }
290
+ modelLists.set(home, kept)
291
+ const file = path.join(home, MODELS_FILE)
292
+ const temp = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`
293
+ try {
294
+ fs.writeFileSync(temp, JSON.stringify({ version: 1, ...kept }) + "\n", { mode: 0o600 })
295
+ fs.renameSync(temp, file)
296
+ } catch {
297
+ fs.rmSync(temp, { force: true })
298
+ }
299
+ }
300
+
301
+ // cachedModels is the account's list: the one kept, unless refresh (or
302
+ // none is kept) asks agy. A refresh that fails gives the kept list.
303
+ export async function cachedModels(agy, home, { refresh = false } = {}) {
304
+ const kept = modelLists.get(home) ?? readModelList(home)
305
+ if (kept && !refresh) return kept.list
306
+ try {
307
+ const list = await listModels(agy, home)
308
+ saveModelList(home, list)
309
+ return list
310
+ } catch (error) {
311
+ if (kept) return kept.list
312
+ throw error
313
+ }
314
+ }
315
+
264
316
  function lastLine(text) {
265
317
  return String(text ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean).at(-1) ?? ""
266
318
  }
@@ -504,22 +556,26 @@ const claimed = new Set()
504
556
  // answerOf is the turn's answer in agy's transcript: a conversation agy
505
557
  // started since `before`, whose user input is the prompt, and its last
506
558
  // PLANNER_RESPONSE. The screen is not read for it: agy draws a refused
507
- // call there too.
508
- export function answerOf(brain, before, prompt, own = null) {
559
+ // call there too. A turn that carries a conversation on (`from`: its id
560
+ // and the transcript's length in lines before the turn) looks in that
561
+ // one alone, past those lines.
562
+ export function answerOf(brain, before, prompt, own = null, from = null) {
509
563
  // its own words, not an image's or a video's mark, which other turns have too
510
564
  const lines = prompt.split("\n").map((l) => l.trim())
511
565
  const snip = (lines.find((l) => l.replace(MEDIA_MARK, "").trim()) ?? lines.find(Boolean))?.slice(0, 60) ?? ""
512
566
  let ids = []
513
- try { ids = fs.readdirSync(brain) } catch {}
567
+ if (from) ids = [from.id]
568
+ else try { ids = fs.readdirSync(brain) } catch {}
514
569
  for (const id of ids) {
515
570
  // another turn's, of the same words, running beside this one
516
- if (before.has(id) || (claimed.has(id) && id !== own)) continue
517
- const file = path.join(brain, id, ".system_generated", "logs", "transcript_full.jsonl")
518
- let text
519
- try { text = fs.readFileSync(file, "utf8") } catch { continue }
571
+ if (!from && (before.has(id) || (claimed.has(id) && id !== own))) continue
572
+ let rows
573
+ try { rows = fs.readFileSync(transcriptOf(brain, id), "utf8").split("\n") } catch { continue }
574
+ // a transcript agy wrote again shorter (compacted) is read whole
575
+ if (from && rows.length > from.line) rows = rows.slice(from.line)
520
576
  let mine = false
521
577
  let answer = ""
522
- for (const line of text.split("\n")) {
578
+ for (const line of rows) {
523
579
  let row
524
580
  try { row = JSON.parse(line) } catch { continue }
525
581
  const type = row.type ?? row.Type
@@ -535,6 +591,13 @@ export function answerOf(brain, before, prompt, own = null) {
535
591
  return null
536
592
  }
537
593
 
594
+ const transcriptOf = (brain, id) => path.join(brain, id, ".system_generated", "logs", "transcript_full.jsonl")
595
+
596
+ // transcriptLines is how many lines the conversation's transcript has
597
+ function transcriptLines(brain, id) {
598
+ try { return fs.readFileSync(transcriptOf(brain, id), "utf8").split("\n").length - 1 } catch { return 0 }
599
+ }
600
+
538
601
  // screenTail is what agy drew last, for an error: its warning when it
539
602
  // shows one ("⚠ …" up to the next rule), else the last lines.
540
603
  export function screenTail(screen, n = 8) {
@@ -615,24 +678,27 @@ export function mcpConfig(mcp, tools) {
615
678
  // `reply(id, content)`, and the turn goes on to its next stop. With tools
616
679
  // (MCP tools: name, description, inputSchema), agy is given them through
617
680
  // magpie's tool server, in a HOME of the turn's own (sessionHome), and its
618
- // own tools stay off.
619
- export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE }) {
620
- const opts = { agy, home, model, tools, helper }
681
+ // own tools stay off. With a conversation (an id agy kept, carried), agy
682
+ // starts with it and the prompt carries it on; `messages` is the request's
683
+ // whole chat, which the conversation is kept under when the turn answers.
684
+ export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE, conversation = null, messages = null }) {
685
+ const opts = { agy, home, model, tools, helper, conversation }
621
686
  const key = spareKey(opts)
622
687
  let turn = null
623
688
  const spare = await takeSpare(key)
624
689
  if (spare) {
625
690
  try {
626
- turn = await spare.begin({ prompt, media, signal })
691
+ turn = await spare.begin({ prompt, media, signal, messages })
627
692
  } catch (error) {
628
693
  // a spare that died while it waited is started again; the
629
694
  // request's own failures are its own
630
695
  if (!error.boot || signal?.aborted) throw error
631
696
  }
632
697
  }
633
- if (!turn) turn = await (await launch(opts)).begin({ prompt, media, signal })
634
- // agy has the message: the next request's agy starts now
635
- leaveSpare(key, opts)
698
+ if (!turn) turn = await (await launch(opts)).begin({ prompt, media, signal, messages })
699
+ // agy has the message: the next request's agy starts now (a chat carried
700
+ // on has its own, left as its turn ends)
701
+ if (!conversation) leaveSpare(key, { ...opts, conversation: null })
636
702
  return turn
637
703
  }
638
704
 
@@ -648,8 +714,8 @@ const SPARE_IDLE_MS = 10 * 60_000
648
714
  const MAX_SPARES = 3
649
715
  const spares = new Map()
650
716
 
651
- function spareKey({ agy, home, model, tools, helper }) {
652
- return createHash("sha256").update(JSON.stringify([agy, home, model ?? "", tools, helper ?? ""])).digest("hex")
717
+ function spareKey({ agy, home, model, tools, helper, conversation }) {
718
+ return createHash("sha256").update(JSON.stringify([agy, home, model ?? "", tools, helper ?? "", conversation ?? ""])).digest("hex")
653
719
  }
654
720
 
655
721
  async function takeSpare(key) {
@@ -663,12 +729,14 @@ async function takeSpare(key) {
663
729
  return null
664
730
  }
665
731
 
732
+ // dropSpare ends the spare of key, if one waits; it resolves once its agy
733
+ // has gone
666
734
  function dropSpare(key) {
667
735
  const s = spares.get(key)
668
- if (!s) return
736
+ if (!s) return Promise.resolve()
669
737
  spares.delete(key)
670
738
  clearTimeout(s.timer)
671
- s.started.then((a) => a.close(), () => {})
739
+ return s.started.then((a) => a.close(), () => {})
672
740
  }
673
741
 
674
742
  function leaveSpare(key, opts) {
@@ -692,10 +760,11 @@ export async function closeSpares() {
692
760
  }))
693
761
  }
694
762
 
695
- // launch starts agy for a turn, in a folder of its own, and resolves at
696
- // once: begin({ prompt, media, signal }) waits until it is at its prompt,
763
+ // launch starts agy for a turn, in a folder of its own (with the
764
+ // conversation it carries on, if any), and resolves at once: begin({
765
+ // prompt, media, signal, messages }) waits until it is at its prompt,
697
766
  // types the request in and resolves with the turn
698
- async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE }) {
767
+ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null }) {
699
768
  if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
700
769
  settleHome(home)
701
770
  const withTools = tools.length > 0
@@ -734,8 +803,12 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
734
803
  const args = ["--settings", JSON.stringify(settings)]
735
804
  // agy's own default customizations stay out, as the old agent's
736
805
  // inheritCustomizations: false kept them
737
- if ((await agyHelp(agy)).includes("--include-default-customizations")) args.push("--include-default-customizations=false")
806
+ const help = await agyHelp(agy)
807
+ if (help.includes("--include-default-customizations")) args.push("--include-default-customizations=false")
808
+ // an agy that can start with a conversation keeps the turn's
809
+ const resumable = help.includes("--conversation")
738
810
  if (model) args.push("--model", model)
811
+ if (conversation) args.push("--conversation", conversation)
739
812
  const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
740
813
  let screen = ""
741
814
  let ended = null
@@ -759,8 +832,12 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
759
832
  // answered
760
833
  const pending = new Set()
761
834
  let found = null
835
+ // a conversation carried on: where this turn's part of it starts, in its
836
+ // transcript (from) and its store (stepBase)
837
+ let from = null
838
+ let stepBase = -1
762
839
  const look = () => {
763
- found = answerOf(brain, before, prompt, found?.id)
840
+ found = answerOf(brain, before, prompt, found?.id, from) ?? (from ? { id: from.id, answer: "" } : null)
764
841
  if (found?.id) claimed.add(found.id)
765
842
  }
766
843
  // what the model has said so far, its text and its thinking, from agy's
@@ -811,7 +888,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
811
888
  // what the model wrote before the call goes first
812
889
  pending.add(o.call.id)
813
890
  if (!found?.id) look()
814
- if (found?.id) publish(liveReply(home, found.id))
891
+ if (found?.id) publish(liveReply(home, found.id, stepBase))
815
892
  const call = o.call
816
893
  spent().then((usage) => stop({ call, usage }))
817
894
  }
@@ -905,6 +982,14 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
905
982
  error.boot = true
906
983
  throw error
907
984
  }
985
+ if (conversation) {
986
+ // what the conversation has already, before this turn's message
987
+ from = { id: conversation, line: transcriptLines(brain, conversation) }
988
+ stepBase = lastStep(home, conversation) ?? -1
989
+ usageAt = callsAfter(home, conversation)?.cursor ?? null
990
+ found = { id: conversation, answer: "" }
991
+ claimed.add(conversation)
992
+ }
908
993
  try {
909
994
  let files
910
995
  try {
@@ -932,7 +1017,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
932
1017
  send({ write: "\r" })
933
1018
  // agy has the message once it is in a turn, or its transcript has it
934
1019
  // (a turn that failed at once may never draw "esc to cancel")
935
- await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt)), SUBMIT_MS)
1020
+ await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt, null, from)), SUBMIT_MS)
936
1021
  } catch (error) {
937
1022
  await cleanup()
938
1023
  throw error
@@ -940,6 +1025,9 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
940
1025
 
941
1026
  const turn = {
942
1027
  live,
1028
+ // the request's chat, which the conversation is kept under once the
1029
+ // turn answers (handle gives each request's that goes on with it)
1030
+ messages: req.messages ?? null,
943
1031
  // the reply's text and thinking the client has had, in the responses
944
1032
  // before this one
945
1033
  sent: "",
@@ -980,7 +1068,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
980
1068
  if (Date.now() - polled >= LIVE_POLL_MS) {
981
1069
  polled = Date.now()
982
1070
  if (!found?.id) look()
983
- if (found?.id) publish(liveReply(home, found.id))
1071
+ if (found?.id) publish(liveReply(home, found.id, stepBase))
984
1072
  }
985
1073
  return false
986
1074
  }
@@ -991,7 +1079,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
991
1079
  }, () => until)
992
1080
  if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
993
1081
  // the whole of it, read before the conversation goes
994
- publish(liveReply(home, found.id))
1082
+ publish(liveReply(home, found.id, stepBase))
995
1083
  last = { text: found.answer, usage: await spent() }
996
1084
  } catch (error) {
997
1085
  last = { error }
@@ -1002,7 +1090,16 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1002
1090
  turn.ended = true
1003
1091
  watch(null)
1004
1092
  stop(last)
1005
- await leaving(cleanup().then(() => forget(brain, found?.id)))
1093
+ // an answered turn's conversation is kept for the chat's next
1094
+ // request, from now (that request can come before agy has gone,
1095
+ // and waits for it); any other goes
1096
+ const id = found?.id
1097
+ const answered = Boolean(resumable && last.text && id && turn.messages)
1098
+ const out = cleanup()
1099
+ if (answered) keep(home, turn.messages, id, [found.answer, since(turn, live.text)], { agy, home, model, tools, helper }, out)
1100
+ await leaving(out.then(() => {
1101
+ if (!answered) forget(brain, id)
1102
+ }))
1006
1103
  }
1007
1104
  })()
1008
1105
  return turn
@@ -1062,18 +1159,205 @@ export function toolContent(content) {
1062
1159
  }
1063
1160
 
1064
1161
  // forget removes the conversation agy kept for a turn from the account's
1065
- // home: each request is a conversation of its own.
1162
+ // home.
1066
1163
  function forget(brain, id) {
1067
- if (!id) return
1164
+ if (!CONVERSATION_ID.test(String(id ?? ""))) return
1068
1165
  claimed.delete(id)
1069
1166
  if (process.env.AGY_TUI_KEEP) return
1070
1167
  fs.rmSync(path.join(brain, id), { recursive: true, force: true })
1071
1168
  const conv = path.join(path.dirname(brain), "conversations")
1072
1169
  try {
1073
- for (const name of fs.readdirSync(conv)) if (name.startsWith(id)) fs.rmSync(path.join(conv, name), { recursive: true, force: true })
1170
+ for (const name of fs.readdirSync(conv)) if (name.startsWith(`${id}.`)) fs.rmSync(path.join(conv, name), { recursive: true, force: true })
1074
1171
  } catch {}
1075
1172
  }
1076
1173
 
1174
+ // ---- conversations carried on
1175
+ //
1176
+ // agy keeps each conversation, and starts with one again given its id
1177
+ // (--conversation). A turn that answered keeps its conversation, under the
1178
+ // request's chat: the chat's next request (the same messages, the answer,
1179
+ // and the user's new ones) carries it on, typing in only the new
1180
+ // messages, never the whole chat again, however long it is and however
1181
+ // long it waited. The conversation is agy's own, so Gemini gets the turns
1182
+ // as turns, and agy compacts it when it grows too long. Any other request
1183
+ // (a new chat, one the client compacted or edited, an answer the client
1184
+ // changed) starts a conversation of its own, the chat typed in as before.
1185
+ // One carried on is taken off the list while its turn runs, so two
1186
+ // requests never share it; a fork of the chat starts its own. Each is kept
1187
+ // KEEP_MS from its last answer, MAX_KEPT an account (the oldest go first),
1188
+ // and the list, hashes and ids alone, is in the account's home, so a
1189
+ // restart finds them.
1190
+ const KEEP_MS = 24 * 3600_000
1191
+ const MAX_KEPT = 32
1192
+ const KEPT_FILE = "agy-tui-conversations.json"
1193
+ const CONVERSATION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
1194
+ const keptByHome = new Map()
1195
+ const sha = (s) => createHash("sha256").update(s).digest("hex")
1196
+ const brainOf = (home) => path.join(home, ".gemini", "antigravity-cli", "brain")
1197
+
1198
+ // what of a message's content says what was said: its words, and each
1199
+ // file by its bytes' hash
1200
+ function contentKey(c) {
1201
+ if (typeof c === "string") return c.trim()
1202
+ if (!Array.isArray(c)) return c == null ? "" : JSON.stringify(c)
1203
+ const text = (p) => p?.type === "text" || p?.type === "input_text"
1204
+ if (c.every(text)) return c.map((p) => String(p.text ?? "")).join("\n").trim()
1205
+ return c.map((p) => {
1206
+ if (text(p)) return String(p.text ?? "").trim()
1207
+ const { cache_control, ...rest } = p ?? {}
1208
+ return { [String(p?.type)]: sha(JSON.stringify(rest)) }
1209
+ })
1210
+ }
1211
+
1212
+ const argsKey = (a) => { try { return JSON.stringify(JSON.parse(a)) } catch { return String(a ?? "") } }
1213
+
1214
+ // chatKey is what a chat is kept under: each message's role, content,
1215
+ // calls and the call it answers, nothing a client adds beside them
1216
+ // (reasoning, cache marks)
1217
+ export function chatKey(messages) {
1218
+ return sha(JSON.stringify(messages.map((m) => [
1219
+ m?.role === "developer" ? "system" : m?.role,
1220
+ contentKey(m?.content),
1221
+ (Array.isArray(m?.tool_calls) ? m.tool_calls : []).map((c) => [c?.id ?? "", c?.function?.name ?? "", argsKey(c?.function?.arguments)]),
1222
+ m?.tool_call_id ?? "",
1223
+ ])))
1224
+ }
1225
+
1226
+ // replyKey is an answer as it is matched: its words, whitespace aside
1227
+ const replyKey = (c) => {
1228
+ const k = contentKey(c)
1229
+ return sha((typeof k === "string" ? k : JSON.stringify(k)).replace(/\s+/g, " ").trim())
1230
+ }
1231
+
1232
+ function saveKept(home, list) {
1233
+ const file = path.join(home, KEPT_FILE)
1234
+ const tmp = `${file}.${process.pid}.tmp`
1235
+ try {
1236
+ fs.writeFileSync(tmp, JSON.stringify({ kept: [...list].map(([key, e]) => ({ key, id: e.id, replies: e.replies, at: e.at })) }), { mode: 0o600 })
1237
+ fs.renameSync(tmp, file)
1238
+ } catch {
1239
+ try { fs.rmSync(tmp, { force: true }) } catch {}
1240
+ }
1241
+ }
1242
+
1243
+ // dropKept ends a kept conversation: once its turn's agy has gone, its
1244
+ // spare, then its files
1245
+ function dropKept(home, e) {
1246
+ leaving(Promise.resolve(e.ready).then(() => (e.spare ? dropSpare(e.spare) : null)).then(() => forget(brainOf(home), e.id)))
1247
+ }
1248
+
1249
+ // keptOf is the account's list of kept conversations, by chatKey, oldest
1250
+ // first, with those past KEEP_MS gone. Read from its file the first time,
1251
+ // when a conversation left in the account's home by none on the list
1252
+ // (from a run that ended before it could forget it) goes too, once it is
1253
+ // older than KEEP_MS.
1254
+ function keptOf(home) {
1255
+ let list = keptByHome.get(home)
1256
+ if (!list) {
1257
+ list = new Map()
1258
+ keptByHome.set(home, list)
1259
+ let saved = null
1260
+ try { saved = JSON.parse(fs.readFileSync(path.join(home, KEPT_FILE), "utf8")) } catch {}
1261
+ for (const e of Array.isArray(saved?.kept) ? saved.kept : []) {
1262
+ if (typeof e?.key !== "string" || !CONVERSATION_ID.test(String(e?.id ?? "")) || !Array.isArray(e.replies) || !Number.isFinite(e.at)) continue
1263
+ list.set(e.key, { id: e.id, replies: e.replies.filter((r) => typeof r === "string"), at: e.at })
1264
+ // never another turn's answer
1265
+ claimed.add(e.id)
1266
+ }
1267
+ const ids = new Set([...list.values()].map((e) => e.id))
1268
+ const ac = path.dirname(brainOf(home))
1269
+ for (const [dir, idOf] of [["brain", (n) => n], ["conversations", (n) => n.replace(/\.db(-wal|-shm)?$/, "")]]) {
1270
+ let names = []
1271
+ try { names = fs.readdirSync(path.join(ac, dir)) } catch {}
1272
+ for (const name of names) {
1273
+ const id = idOf(name)
1274
+ if (ids.has(id) || claimed.has(id) || !CONVERSATION_ID.test(id)) continue
1275
+ try {
1276
+ if (Date.now() - fs.statSync(path.join(ac, dir, name)).mtimeMs > KEEP_MS) forget(brainOf(home), id)
1277
+ } catch {}
1278
+ }
1279
+ }
1280
+ }
1281
+ if (prune(home, list)) saveKept(home, list)
1282
+ return list
1283
+ }
1284
+
1285
+ // prune ends the conversations past KEEP_MS, and the oldest past MAX_KEPT;
1286
+ // whether it ended any
1287
+ function prune(home, list) {
1288
+ let changed = false
1289
+ for (const [key, e] of list) {
1290
+ if (Date.now() - e.at <= KEEP_MS && list.size <= MAX_KEPT) continue
1291
+ list.delete(key)
1292
+ dropKept(home, e)
1293
+ changed = true
1294
+ }
1295
+ return changed
1296
+ }
1297
+
1298
+ // keep puts an answered turn's conversation on the account's list, under
1299
+ // the request's chat, with the words of the answer (as the client may have
1300
+ // had it, `replies`), and, once the turn's agy has gone (`gone`), starts an
1301
+ // agy with it for the chat's next request (`opts`: the turn's own)
1302
+ function keep(home, messages, id, replies, opts, gone) {
1303
+ if (!CONVERSATION_ID.test(String(id ?? "")) || !carrying()) return forget(brainOf(home), id)
1304
+ const list = keptOf(home)
1305
+ const key = chatKey(messages)
1306
+ const old = list.get(key)
1307
+ if (old) {
1308
+ list.delete(key)
1309
+ if (old.id !== id) dropKept(home, old)
1310
+ }
1311
+ const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), ready: Promise.resolve(gone).catch(() => {}) }
1312
+ list.set(key, e)
1313
+ prune(home, list)
1314
+ saveKept(home, list)
1315
+ if (process.env.AGY_TUI_SPARES === "0") return
1316
+ e.ready.then(() => {
1317
+ // not when the chat went on, or the conversation went, first
1318
+ if (list.get(key) !== e) return
1319
+ const next = { ...opts, conversation: id }
1320
+ e.spare = spareKey(next)
1321
+ leaveSpare(e.spare, next)
1322
+ })
1323
+ }
1324
+
1325
+ function carrying() {
1326
+ return process.env.AGY_TUI_CARRY !== "0"
1327
+ }
1328
+
1329
+ // carriedOn is the kept conversation a request's chat carries on, taken
1330
+ // off the list, and the prompt of its new messages ({ id, prompt, media }),
1331
+ // or null: the chat, up to its last answer, is one a turn answered, the
1332
+ // answer is the one that turn gave, and what comes after it is the user's
1333
+ // alone and fits in one message.
1334
+ export async function carriedOn(home, messages, { agy, model, tools }) {
1335
+ if (!carrying() || !Array.isArray(messages)) return null
1336
+ const j = messages.findLastIndex((m) => m?.role === "assistant")
1337
+ if (j < 0) return null
1338
+ const answer = messages[j]
1339
+ const tail = messages.slice(j + 1)
1340
+ if (!tail.length || !tail.every((m) => m?.role === "user")) return null
1341
+ if (Array.isArray(answer.tool_calls) && answer.tool_calls.length) return null
1342
+ const list = keptOf(home)
1343
+ const key = chatKey(messages.slice(0, j))
1344
+ const e = list.get(key)
1345
+ if (!e || !e.replies.includes(replyKey(answer.content))) return null
1346
+ const { prompt, media } = turnOf(tail, Infinity)
1347
+ if (bytes(prompt) > INPUT_BUDGET) return null
1348
+ list.delete(key)
1349
+ saveKept(home, list)
1350
+ // the agy of the turn that kept it gone, and its spare, when it isn't
1351
+ // one this request takes, before another agy opens the conversation
1352
+ await e.ready
1353
+ if (e.spare && e.spare !== spareKey({ agy, home, model, tools, helper: process.env.MAGPIE_EXE, conversation: e.id })) await dropSpare(e.spare)
1354
+ if (!fs.existsSync(path.join(brainOf(home), e.id))) {
1355
+ forget(brainOf(home), e.id)
1356
+ return null
1357
+ }
1358
+ return { id: e.id, prompt, media }
1359
+ }
1360
+
1077
1361
  // ---- OpenAI chat completions
1078
1362
 
1079
1363
  function jsonError(status, message, headers = {}) {
@@ -1225,6 +1509,7 @@ export async function handle(home, input, init = {}) {
1225
1509
  if (last?.role === "tool") {
1226
1510
  const waiting = unpark(last.tool_call_id)
1227
1511
  if (waiting && !waiting.ended) {
1512
+ waiting.messages = body.messages
1228
1513
  let content
1229
1514
  try { content = toolContent(last.content) } catch (error) {
1230
1515
  waiting.close()
@@ -1246,13 +1531,20 @@ export async function handle(home, input, init = {}) {
1246
1531
  const refusal = await agyRefusal(agy)
1247
1532
  if (refusal) return jsonError(503, refusal)
1248
1533
  let turn
1534
+ let carried = null
1249
1535
  try {
1250
1536
  const tools = mcpToolsOf(body)
1251
- const { prompt, media } = turnOf(body.messages)
1537
+ // the chat's conversation, kept from its last answer, goes on with the
1538
+ // new messages alone; any other is typed in whole
1539
+ carried = (await agyHelp(agy)).includes("--conversation") ? await carriedOn(home, body.messages, { agy, model, tools }) : null
1540
+ const { prompt, media } = carried ?? turnOf(body.messages)
1252
1541
  // agy attaches a video for any model, but only Gemini's see one
1253
1542
  if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
1254
- turn = await startTurn({ agy, home, model, prompt, media, tools, signal })
1543
+ turn = await startTurn({ agy, home, model, prompt, media, tools, signal, conversation: carried?.id ?? null, messages: body.messages })
1255
1544
  } catch (error) {
1545
+ // a conversation taken for a turn that never began is in a state
1546
+ // nothing knows
1547
+ if (carried) forget(brainOf(home), carried.id)
1256
1548
  return jsonError(error.status ?? 502, error.message, error.headers)
1257
1549
  }
1258
1550
  return respond(id, model, turn, body.stream)
@@ -1294,7 +1586,7 @@ function signIn(agy) {
1294
1586
  const done = await login.finish(code, { signal: opts.signal })
1295
1587
  if (done.error) return fail(done.error)
1296
1588
  try {
1297
- await listModels(agy, account.home)
1589
+ saveModelList(account.home, await listModels(agy, account.home))
1298
1590
  } catch (error) {
1299
1591
  return fail(`agy signed in, but ${error.message}`)
1300
1592
  }
@@ -1344,7 +1636,7 @@ export const AgyTuiPlugin = async () => ({
1344
1636
  const agy = findAgy()
1345
1637
  if (!home || !agy) return {}
1346
1638
  const out = {}
1347
- for (const m of await listModels(agy, home)) out[m.id] = modelEntry(m)
1639
+ for (const m of await cachedModels(agy, home, { refresh: ctx?.refresh === true })) out[m.id] = modelEntry(m)
1348
1640
  return out
1349
1641
  },
1350
1642
  },
package/live.mjs CHANGED
@@ -132,9 +132,11 @@ export function replyOf(payload) {
132
132
  }
133
133
 
134
134
  // liveReply is what agy's model has said so far in the conversation id of
135
- // the account at home: { text, thinking }, each the replies' own, in
136
- // order, a blank line between two; null when the store can't be read.
137
- export function liveReply(home, id) {
135
+ // the account at home, past the step `after` (a conversation carried on
136
+ // from an earlier request has that one's replies before it): { text,
137
+ // thinking }, each the replies' own, in order, a blank line between two;
138
+ // null when the store can't be read.
139
+ export function liveReply(home, id, after = -1) {
138
140
  const file = conversationDb(home, id)
139
141
  if (!file || !fs.existsSync(file)) return null
140
142
  const open = loadOpener()
@@ -142,7 +144,7 @@ export function liveReply(home, id) {
142
144
  let db
143
145
  try {
144
146
  db = open(file)
145
- const rows = db.all(`SELECT idx, step_payload FROM steps WHERE step_type = ${MODEL_STEP} ORDER BY idx`)
147
+ const rows = db.all(`SELECT idx, step_payload FROM steps WHERE step_type = ${MODEL_STEP} AND idx > ${Number.isFinite(Number(after)) ? Number(after) : -1} ORDER BY idx`)
146
148
  const texts = []
147
149
  const thoughts = []
148
150
  for (const row of rows) {
@@ -158,6 +160,25 @@ export function liveReply(home, id) {
158
160
  }
159
161
  }
160
162
 
163
+ // lastStep is the conversation's last step (-1 for none), what a turn
164
+ // that carries it on reads past; null when the store can't be read.
165
+ export function lastStep(home, id) {
166
+ const file = conversationDb(home, id)
167
+ if (!file || !fs.existsSync(file)) return null
168
+ const open = loadOpener()
169
+ if (!open) return null
170
+ let db
171
+ try {
172
+ db = open(file)
173
+ const n = db.all("SELECT max(idx) AS n FROM steps")[0]?.n
174
+ return n == null ? -1 : Number(n)
175
+ } catch {
176
+ return null
177
+ } finally {
178
+ try { db?.close() } catch {}
179
+ }
180
+ }
181
+
161
182
  // liveText is liveReply's text alone.
162
183
  export function liveText(home, id) {
163
184
  return liveReply(home, id)?.text ?? null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
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",