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

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
@@ -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
@@ -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
@@ -504,22 +504,26 @@ const claimed = new Set()
504
504
  // answerOf is the turn's answer in agy's transcript: a conversation agy
505
505
  // started since `before`, whose user input is the prompt, and its last
506
506
  // 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) {
507
+ // call there too. A turn that carries a conversation on (`from`: its id
508
+ // and the transcript's length in lines before the turn) looks in that
509
+ // one alone, past those lines.
510
+ export function answerOf(brain, before, prompt, own = null, from = null) {
509
511
  // its own words, not an image's or a video's mark, which other turns have too
510
512
  const lines = prompt.split("\n").map((l) => l.trim())
511
513
  const snip = (lines.find((l) => l.replace(MEDIA_MARK, "").trim()) ?? lines.find(Boolean))?.slice(0, 60) ?? ""
512
514
  let ids = []
513
- try { ids = fs.readdirSync(brain) } catch {}
515
+ if (from) ids = [from.id]
516
+ else try { ids = fs.readdirSync(brain) } catch {}
514
517
  for (const id of ids) {
515
518
  // 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 }
519
+ if (!from && (before.has(id) || (claimed.has(id) && id !== own))) continue
520
+ let rows
521
+ try { rows = fs.readFileSync(transcriptOf(brain, id), "utf8").split("\n") } catch { continue }
522
+ // a transcript agy wrote again shorter (compacted) is read whole
523
+ if (from && rows.length > from.line) rows = rows.slice(from.line)
520
524
  let mine = false
521
525
  let answer = ""
522
- for (const line of text.split("\n")) {
526
+ for (const line of rows) {
523
527
  let row
524
528
  try { row = JSON.parse(line) } catch { continue }
525
529
  const type = row.type ?? row.Type
@@ -535,6 +539,13 @@ export function answerOf(brain, before, prompt, own = null) {
535
539
  return null
536
540
  }
537
541
 
542
+ const transcriptOf = (brain, id) => path.join(brain, id, ".system_generated", "logs", "transcript_full.jsonl")
543
+
544
+ // transcriptLines is how many lines the conversation's transcript has
545
+ function transcriptLines(brain, id) {
546
+ try { return fs.readFileSync(transcriptOf(brain, id), "utf8").split("\n").length - 1 } catch { return 0 }
547
+ }
548
+
538
549
  // screenTail is what agy drew last, for an error: its warning when it
539
550
  // shows one ("⚠ …" up to the next rule), else the last lines.
540
551
  export function screenTail(screen, n = 8) {
@@ -615,24 +626,27 @@ export function mcpConfig(mcp, tools) {
615
626
  // `reply(id, content)`, and the turn goes on to its next stop. With tools
616
627
  // (MCP tools: name, description, inputSchema), agy is given them through
617
628
  // 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 }
629
+ // own tools stay off. With a conversation (an id agy kept, carried), agy
630
+ // starts with it and the prompt carries it on; `messages` is the request's
631
+ // whole chat, which the conversation is kept under when the turn answers.
632
+ export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE, conversation = null, messages = null }) {
633
+ const opts = { agy, home, model, tools, helper, conversation }
621
634
  const key = spareKey(opts)
622
635
  let turn = null
623
636
  const spare = await takeSpare(key)
624
637
  if (spare) {
625
638
  try {
626
- turn = await spare.begin({ prompt, media, signal })
639
+ turn = await spare.begin({ prompt, media, signal, messages })
627
640
  } catch (error) {
628
641
  // a spare that died while it waited is started again; the
629
642
  // request's own failures are its own
630
643
  if (!error.boot || signal?.aborted) throw error
631
644
  }
632
645
  }
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)
646
+ if (!turn) turn = await (await launch(opts)).begin({ prompt, media, signal, messages })
647
+ // agy has the message: the next request's agy starts now (a chat carried
648
+ // on has its own, left as its turn ends)
649
+ if (!conversation) leaveSpare(key, { ...opts, conversation: null })
636
650
  return turn
637
651
  }
638
652
 
@@ -648,8 +662,8 @@ const SPARE_IDLE_MS = 10 * 60_000
648
662
  const MAX_SPARES = 3
649
663
  const spares = new Map()
650
664
 
651
- function spareKey({ agy, home, model, tools, helper }) {
652
- return createHash("sha256").update(JSON.stringify([agy, home, model ?? "", tools, helper ?? ""])).digest("hex")
665
+ function spareKey({ agy, home, model, tools, helper, conversation }) {
666
+ return createHash("sha256").update(JSON.stringify([agy, home, model ?? "", tools, helper ?? "", conversation ?? ""])).digest("hex")
653
667
  }
654
668
 
655
669
  async function takeSpare(key) {
@@ -663,12 +677,14 @@ async function takeSpare(key) {
663
677
  return null
664
678
  }
665
679
 
680
+ // dropSpare ends the spare of key, if one waits; it resolves once its agy
681
+ // has gone
666
682
  function dropSpare(key) {
667
683
  const s = spares.get(key)
668
- if (!s) return
684
+ if (!s) return Promise.resolve()
669
685
  spares.delete(key)
670
686
  clearTimeout(s.timer)
671
- s.started.then((a) => a.close(), () => {})
687
+ return s.started.then((a) => a.close(), () => {})
672
688
  }
673
689
 
674
690
  function leaveSpare(key, opts) {
@@ -692,10 +708,11 @@ export async function closeSpares() {
692
708
  }))
693
709
  }
694
710
 
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,
711
+ // launch starts agy for a turn, in a folder of its own (with the
712
+ // conversation it carries on, if any), and resolves at once: begin({
713
+ // prompt, media, signal, messages }) waits until it is at its prompt,
697
714
  // types the request in and resolves with the turn
698
- async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE }) {
715
+ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE, conversation = null }) {
699
716
  if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
700
717
  settleHome(home)
701
718
  const withTools = tools.length > 0
@@ -734,8 +751,12 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
734
751
  const args = ["--settings", JSON.stringify(settings)]
735
752
  // agy's own default customizations stay out, as the old agent's
736
753
  // inheritCustomizations: false kept them
737
- if ((await agyHelp(agy)).includes("--include-default-customizations")) args.push("--include-default-customizations=false")
754
+ const help = await agyHelp(agy)
755
+ if (help.includes("--include-default-customizations")) args.push("--include-default-customizations=false")
756
+ // an agy that can start with a conversation keeps the turn's
757
+ const resumable = help.includes("--conversation")
738
758
  if (model) args.push("--model", model)
759
+ if (conversation) args.push("--conversation", conversation)
739
760
  const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
740
761
  let screen = ""
741
762
  let ended = null
@@ -759,8 +780,12 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
759
780
  // answered
760
781
  const pending = new Set()
761
782
  let found = null
783
+ // a conversation carried on: where this turn's part of it starts, in its
784
+ // transcript (from) and its store (stepBase)
785
+ let from = null
786
+ let stepBase = -1
762
787
  const look = () => {
763
- found = answerOf(brain, before, prompt, found?.id)
788
+ found = answerOf(brain, before, prompt, found?.id, from) ?? (from ? { id: from.id, answer: "" } : null)
764
789
  if (found?.id) claimed.add(found.id)
765
790
  }
766
791
  // what the model has said so far, its text and its thinking, from agy's
@@ -811,7 +836,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
811
836
  // what the model wrote before the call goes first
812
837
  pending.add(o.call.id)
813
838
  if (!found?.id) look()
814
- if (found?.id) publish(liveReply(home, found.id))
839
+ if (found?.id) publish(liveReply(home, found.id, stepBase))
815
840
  const call = o.call
816
841
  spent().then((usage) => stop({ call, usage }))
817
842
  }
@@ -905,6 +930,14 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
905
930
  error.boot = true
906
931
  throw error
907
932
  }
933
+ if (conversation) {
934
+ // what the conversation has already, before this turn's message
935
+ from = { id: conversation, line: transcriptLines(brain, conversation) }
936
+ stepBase = lastStep(home, conversation) ?? -1
937
+ usageAt = callsAfter(home, conversation)?.cursor ?? null
938
+ found = { id: conversation, answer: "" }
939
+ claimed.add(conversation)
940
+ }
908
941
  try {
909
942
  let files
910
943
  try {
@@ -932,7 +965,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
932
965
  send({ write: "\r" })
933
966
  // agy has the message once it is in a turn, or its transcript has it
934
967
  // (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)
968
+ await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt, null, from)), SUBMIT_MS)
936
969
  } catch (error) {
937
970
  await cleanup()
938
971
  throw error
@@ -940,6 +973,9 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
940
973
 
941
974
  const turn = {
942
975
  live,
976
+ // the request's chat, which the conversation is kept under once the
977
+ // turn answers (handle gives each request's that goes on with it)
978
+ messages: req.messages ?? null,
943
979
  // the reply's text and thinking the client has had, in the responses
944
980
  // before this one
945
981
  sent: "",
@@ -980,7 +1016,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
980
1016
  if (Date.now() - polled >= LIVE_POLL_MS) {
981
1017
  polled = Date.now()
982
1018
  if (!found?.id) look()
983
- if (found?.id) publish(liveReply(home, found.id))
1019
+ if (found?.id) publish(liveReply(home, found.id, stepBase))
984
1020
  }
985
1021
  return false
986
1022
  }
@@ -991,7 +1027,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
991
1027
  }, () => until)
992
1028
  if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
993
1029
  // the whole of it, read before the conversation goes
994
- publish(liveReply(home, found.id))
1030
+ publish(liveReply(home, found.id, stepBase))
995
1031
  last = { text: found.answer, usage: await spent() }
996
1032
  } catch (error) {
997
1033
  last = { error }
@@ -1002,7 +1038,16 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1002
1038
  turn.ended = true
1003
1039
  watch(null)
1004
1040
  stop(last)
1005
- await leaving(cleanup().then(() => forget(brain, found?.id)))
1041
+ // an answered turn's conversation is kept for the chat's next
1042
+ // request, from now (that request can come before agy has gone,
1043
+ // and waits for it); any other goes
1044
+ const id = found?.id
1045
+ const answered = Boolean(resumable && last.text && id && turn.messages)
1046
+ const out = cleanup()
1047
+ if (answered) keep(home, turn.messages, id, [found.answer, since(turn, live.text)], { agy, home, model, tools, helper }, out)
1048
+ await leaving(out.then(() => {
1049
+ if (!answered) forget(brain, id)
1050
+ }))
1006
1051
  }
1007
1052
  })()
1008
1053
  return turn
@@ -1062,18 +1107,205 @@ export function toolContent(content) {
1062
1107
  }
1063
1108
 
1064
1109
  // forget removes the conversation agy kept for a turn from the account's
1065
- // home: each request is a conversation of its own.
1110
+ // home.
1066
1111
  function forget(brain, id) {
1067
- if (!id) return
1112
+ if (!CONVERSATION_ID.test(String(id ?? ""))) return
1068
1113
  claimed.delete(id)
1069
1114
  if (process.env.AGY_TUI_KEEP) return
1070
1115
  fs.rmSync(path.join(brain, id), { recursive: true, force: true })
1071
1116
  const conv = path.join(path.dirname(brain), "conversations")
1072
1117
  try {
1073
- for (const name of fs.readdirSync(conv)) if (name.startsWith(id)) fs.rmSync(path.join(conv, name), { recursive: true, force: true })
1118
+ for (const name of fs.readdirSync(conv)) if (name.startsWith(`${id}.`)) fs.rmSync(path.join(conv, name), { recursive: true, force: true })
1074
1119
  } catch {}
1075
1120
  }
1076
1121
 
1122
+ // ---- conversations carried on
1123
+ //
1124
+ // agy keeps each conversation, and starts with one again given its id
1125
+ // (--conversation). A turn that answered keeps its conversation, under the
1126
+ // request's chat: the chat's next request (the same messages, the answer,
1127
+ // and the user's new ones) carries it on, typing in only the new
1128
+ // messages, never the whole chat again, however long it is and however
1129
+ // long it waited. The conversation is agy's own, so Gemini gets the turns
1130
+ // as turns, and agy compacts it when it grows too long. Any other request
1131
+ // (a new chat, one the client compacted or edited, an answer the client
1132
+ // changed) starts a conversation of its own, the chat typed in as before.
1133
+ // One carried on is taken off the list while its turn runs, so two
1134
+ // requests never share it; a fork of the chat starts its own. Each is kept
1135
+ // KEEP_MS from its last answer, MAX_KEPT an account (the oldest go first),
1136
+ // and the list, hashes and ids alone, is in the account's home, so a
1137
+ // restart finds them.
1138
+ const KEEP_MS = 24 * 3600_000
1139
+ const MAX_KEPT = 32
1140
+ const KEPT_FILE = "agy-tui-conversations.json"
1141
+ const CONVERSATION_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
1142
+ const keptByHome = new Map()
1143
+ const sha = (s) => createHash("sha256").update(s).digest("hex")
1144
+ const brainOf = (home) => path.join(home, ".gemini", "antigravity-cli", "brain")
1145
+
1146
+ // what of a message's content says what was said: its words, and each
1147
+ // file by its bytes' hash
1148
+ function contentKey(c) {
1149
+ if (typeof c === "string") return c.trim()
1150
+ if (!Array.isArray(c)) return c == null ? "" : JSON.stringify(c)
1151
+ const text = (p) => p?.type === "text" || p?.type === "input_text"
1152
+ if (c.every(text)) return c.map((p) => String(p.text ?? "")).join("\n").trim()
1153
+ return c.map((p) => {
1154
+ if (text(p)) return String(p.text ?? "").trim()
1155
+ const { cache_control, ...rest } = p ?? {}
1156
+ return { [String(p?.type)]: sha(JSON.stringify(rest)) }
1157
+ })
1158
+ }
1159
+
1160
+ const argsKey = (a) => { try { return JSON.stringify(JSON.parse(a)) } catch { return String(a ?? "") } }
1161
+
1162
+ // chatKey is what a chat is kept under: each message's role, content,
1163
+ // calls and the call it answers, nothing a client adds beside them
1164
+ // (reasoning, cache marks)
1165
+ export function chatKey(messages) {
1166
+ return sha(JSON.stringify(messages.map((m) => [
1167
+ m?.role === "developer" ? "system" : m?.role,
1168
+ contentKey(m?.content),
1169
+ (Array.isArray(m?.tool_calls) ? m.tool_calls : []).map((c) => [c?.id ?? "", c?.function?.name ?? "", argsKey(c?.function?.arguments)]),
1170
+ m?.tool_call_id ?? "",
1171
+ ])))
1172
+ }
1173
+
1174
+ // replyKey is an answer as it is matched: its words, whitespace aside
1175
+ const replyKey = (c) => {
1176
+ const k = contentKey(c)
1177
+ return sha((typeof k === "string" ? k : JSON.stringify(k)).replace(/\s+/g, " ").trim())
1178
+ }
1179
+
1180
+ function saveKept(home, list) {
1181
+ const file = path.join(home, KEPT_FILE)
1182
+ const tmp = `${file}.${process.pid}.tmp`
1183
+ try {
1184
+ fs.writeFileSync(tmp, JSON.stringify({ kept: [...list].map(([key, e]) => ({ key, id: e.id, replies: e.replies, at: e.at })) }), { mode: 0o600 })
1185
+ fs.renameSync(tmp, file)
1186
+ } catch {
1187
+ try { fs.rmSync(tmp, { force: true }) } catch {}
1188
+ }
1189
+ }
1190
+
1191
+ // dropKept ends a kept conversation: once its turn's agy has gone, its
1192
+ // spare, then its files
1193
+ function dropKept(home, e) {
1194
+ leaving(Promise.resolve(e.ready).then(() => (e.spare ? dropSpare(e.spare) : null)).then(() => forget(brainOf(home), e.id)))
1195
+ }
1196
+
1197
+ // keptOf is the account's list of kept conversations, by chatKey, oldest
1198
+ // first, with those past KEEP_MS gone. Read from its file the first time,
1199
+ // when a conversation left in the account's home by none on the list
1200
+ // (from a run that ended before it could forget it) goes too, once it is
1201
+ // older than KEEP_MS.
1202
+ function keptOf(home) {
1203
+ let list = keptByHome.get(home)
1204
+ if (!list) {
1205
+ list = new Map()
1206
+ keptByHome.set(home, list)
1207
+ let saved = null
1208
+ try { saved = JSON.parse(fs.readFileSync(path.join(home, KEPT_FILE), "utf8")) } catch {}
1209
+ for (const e of Array.isArray(saved?.kept) ? saved.kept : []) {
1210
+ if (typeof e?.key !== "string" || !CONVERSATION_ID.test(String(e?.id ?? "")) || !Array.isArray(e.replies) || !Number.isFinite(e.at)) continue
1211
+ list.set(e.key, { id: e.id, replies: e.replies.filter((r) => typeof r === "string"), at: e.at })
1212
+ // never another turn's answer
1213
+ claimed.add(e.id)
1214
+ }
1215
+ const ids = new Set([...list.values()].map((e) => e.id))
1216
+ const ac = path.dirname(brainOf(home))
1217
+ for (const [dir, idOf] of [["brain", (n) => n], ["conversations", (n) => n.replace(/\.db(-wal|-shm)?$/, "")]]) {
1218
+ let names = []
1219
+ try { names = fs.readdirSync(path.join(ac, dir)) } catch {}
1220
+ for (const name of names) {
1221
+ const id = idOf(name)
1222
+ if (ids.has(id) || claimed.has(id) || !CONVERSATION_ID.test(id)) continue
1223
+ try {
1224
+ if (Date.now() - fs.statSync(path.join(ac, dir, name)).mtimeMs > KEEP_MS) forget(brainOf(home), id)
1225
+ } catch {}
1226
+ }
1227
+ }
1228
+ }
1229
+ if (prune(home, list)) saveKept(home, list)
1230
+ return list
1231
+ }
1232
+
1233
+ // prune ends the conversations past KEEP_MS, and the oldest past MAX_KEPT;
1234
+ // whether it ended any
1235
+ function prune(home, list) {
1236
+ let changed = false
1237
+ for (const [key, e] of list) {
1238
+ if (Date.now() - e.at <= KEEP_MS && list.size <= MAX_KEPT) continue
1239
+ list.delete(key)
1240
+ dropKept(home, e)
1241
+ changed = true
1242
+ }
1243
+ return changed
1244
+ }
1245
+
1246
+ // keep puts an answered turn's conversation on the account's list, under
1247
+ // the request's chat, with the words of the answer (as the client may have
1248
+ // had it, `replies`), and, once the turn's agy has gone (`gone`), starts an
1249
+ // agy with it for the chat's next request (`opts`: the turn's own)
1250
+ function keep(home, messages, id, replies, opts, gone) {
1251
+ if (!CONVERSATION_ID.test(String(id ?? "")) || !carrying()) return forget(brainOf(home), id)
1252
+ const list = keptOf(home)
1253
+ const key = chatKey(messages)
1254
+ const old = list.get(key)
1255
+ if (old) {
1256
+ list.delete(key)
1257
+ if (old.id !== id) dropKept(home, old)
1258
+ }
1259
+ const e = { id, replies: [...new Set(replies.filter(Boolean).map(replyKey))], at: Date.now(), ready: Promise.resolve(gone).catch(() => {}) }
1260
+ list.set(key, e)
1261
+ prune(home, list)
1262
+ saveKept(home, list)
1263
+ if (process.env.AGY_TUI_SPARES === "0") return
1264
+ e.ready.then(() => {
1265
+ // not when the chat went on, or the conversation went, first
1266
+ if (list.get(key) !== e) return
1267
+ const next = { ...opts, conversation: id }
1268
+ e.spare = spareKey(next)
1269
+ leaveSpare(e.spare, next)
1270
+ })
1271
+ }
1272
+
1273
+ function carrying() {
1274
+ return process.env.AGY_TUI_CARRY !== "0"
1275
+ }
1276
+
1277
+ // carriedOn is the kept conversation a request's chat carries on, taken
1278
+ // off the list, and the prompt of its new messages ({ id, prompt, media }),
1279
+ // or null: the chat, up to its last answer, is one a turn answered, the
1280
+ // answer is the one that turn gave, and what comes after it is the user's
1281
+ // alone and fits in one message.
1282
+ export async function carriedOn(home, messages, { agy, model, tools }) {
1283
+ if (!carrying() || !Array.isArray(messages)) return null
1284
+ const j = messages.findLastIndex((m) => m?.role === "assistant")
1285
+ if (j < 0) return null
1286
+ const answer = messages[j]
1287
+ const tail = messages.slice(j + 1)
1288
+ if (!tail.length || !tail.every((m) => m?.role === "user")) return null
1289
+ if (Array.isArray(answer.tool_calls) && answer.tool_calls.length) return null
1290
+ const list = keptOf(home)
1291
+ const key = chatKey(messages.slice(0, j))
1292
+ const e = list.get(key)
1293
+ if (!e || !e.replies.includes(replyKey(answer.content))) return null
1294
+ const { prompt, media } = turnOf(tail, Infinity)
1295
+ if (bytes(prompt) > INPUT_BUDGET) return null
1296
+ list.delete(key)
1297
+ saveKept(home, list)
1298
+ // the agy of the turn that kept it gone, and its spare, when it isn't
1299
+ // one this request takes, before another agy opens the conversation
1300
+ await e.ready
1301
+ if (e.spare && e.spare !== spareKey({ agy, home, model, tools, helper: process.env.MAGPIE_EXE, conversation: e.id })) await dropSpare(e.spare)
1302
+ if (!fs.existsSync(path.join(brainOf(home), e.id))) {
1303
+ forget(brainOf(home), e.id)
1304
+ return null
1305
+ }
1306
+ return { id: e.id, prompt, media }
1307
+ }
1308
+
1077
1309
  // ---- OpenAI chat completions
1078
1310
 
1079
1311
  function jsonError(status, message, headers = {}) {
@@ -1225,6 +1457,7 @@ export async function handle(home, input, init = {}) {
1225
1457
  if (last?.role === "tool") {
1226
1458
  const waiting = unpark(last.tool_call_id)
1227
1459
  if (waiting && !waiting.ended) {
1460
+ waiting.messages = body.messages
1228
1461
  let content
1229
1462
  try { content = toolContent(last.content) } catch (error) {
1230
1463
  waiting.close()
@@ -1246,13 +1479,20 @@ export async function handle(home, input, init = {}) {
1246
1479
  const refusal = await agyRefusal(agy)
1247
1480
  if (refusal) return jsonError(503, refusal)
1248
1481
  let turn
1482
+ let carried = null
1249
1483
  try {
1250
1484
  const tools = mcpToolsOf(body)
1251
- const { prompt, media } = turnOf(body.messages)
1485
+ // the chat's conversation, kept from its last answer, goes on with the
1486
+ // new messages alone; any other is typed in whole
1487
+ carried = (await agyHelp(agy)).includes("--conversation") ? await carriedOn(home, body.messages, { agy, model, tools }) : null
1488
+ const { prompt, media } = carried ?? turnOf(body.messages)
1252
1489
  // agy attaches a video for any model, but only Gemini's see one
1253
1490
  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 })
1491
+ turn = await startTurn({ agy, home, model, prompt, media, tools, signal, conversation: carried?.id ?? null, messages: body.messages })
1255
1492
  } catch (error) {
1493
+ // a conversation taken for a turn that never began is in a state
1494
+ // nothing knows
1495
+ if (carried) forget(brainOf(home), carried.id)
1256
1496
  return jsonError(error.status ?? 502, error.message, error.headers)
1257
1497
  }
1258
1498
  return respond(id, model, turn, body.stream)
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.9",
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",