@magpie-community/opencode-agy-tui-auth 0.1.7 → 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,9 +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.
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
+ - 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 a request that pastes it whole would be cut.
26
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).
27
- - 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.
28
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.
29
31
 
30
32
  ## Options (environment)
@@ -34,4 +36,5 @@ A request's tools (`tools`, function tools) are given to the model through magpi
34
36
  - `AGY_TUI_PARK_TIMEOUT_MS`: how long a turn waits for a tool call's result, 10 minutes by default.
35
37
  - `AGY_TUI_ATTACH_TIMEOUT_MS`: how long agy may take to attach a turn's images and videos, 15 seconds by default.
36
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.
37
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,9 +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
+ - agy 一条消息最多收 192,000 字节,超出部分会被它替换成 `<truncated N bytes>`,模型就看不到最新的消息了。所以粘贴的内容控制在 180,000 字节以内:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。系统指令本身放不下时截短。最后一条消息单独就超过时会被拒绝(400)。
27
+ - 模型宣告的上下文是 64K token(大约是 agy 一条消息能放下的量,加上 agy 自己约 10K 的指令),每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考),这样 agent 会在整段粘贴的请求被截断之前压缩对话。
26
28
  - 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。模型的思考(agy 向 Gemini 要了思考内容)同样边生成边作为 `reasoning_content` 返回,在回答之前;非流式时放在消息的 `reasoning_content` 里。回答写完就结束响应,不等 agy 退出(它退出前会先发完自己的遥测)。
27
- - agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
29
+ - agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。保留了会话的一轮,还会为这段对话的下一个请求预先启动一个带着这个会话的 agy。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
28
30
  - 需要 magpie 0.1.5217 或更新(带 `tui-helper` 及其工具服务器);magpie 太旧时,带工具的请求会提示更新 magpie。Windows 尚未测试。
29
31
 
30
32
  ## 选项(环境变量)
@@ -34,4 +36,5 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
34
36
  - `AGY_TUI_PARK_TIMEOUT_MS`:一轮等待工具调用结果的最长时间,默认 10 分钟。
35
37
  - `AGY_TUI_ATTACH_TIMEOUT_MS`:agy 附加本轮图片和视频的最长等待时间,默认 15 秒。
36
38
  - `AGY_TUI_SPARES=0`:不为下一个请求预先启动 agy。
39
+ - `AGY_TUI_CARRY=0`:每个请求都开新的 agy 会话、整段粘贴对话,不保留会话。
37
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 } 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
@@ -85,6 +85,9 @@ const MCP_CALL_SECONDS = 3600
85
85
  const LISTED_MS = 20_000
86
86
  // how many turns may wait on a call's result at once
87
87
  const MAX_PARKED = 8
88
+ // how long a response's end waits for agy to write its calls' token counts
89
+ const USAGE_POLL_MS = 100
90
+ const USAGE_TRIES = 15
88
91
 
89
92
  // how long a turn waits for the request with a call's result
90
93
  function parkTimeout() {
@@ -365,48 +368,97 @@ function partsOf(content, media) {
365
368
  return out.join("\n")
366
369
  }
367
370
 
371
+ // agy keeps the first 192,000 bytes of a message and puts
372
+ // "<truncated N bytes>" for the rest, so the model would see the head of a
373
+ // long paste and never its end, the newest message. What turnOf pastes is
374
+ // held under INPUT_BUDGET, the margin for what agy adds around it.
375
+ export const INPUT_BUDGET = 180_000
376
+ // the context the models say they have: what fits in INPUT_BUDGET, with
377
+ // agy's own instructions (about 10k tokens) on top, so an agent compacts
378
+ // its conversation before agy would cut it. Gemini's own window is larger,
379
+ // but agy takes no more than this in a message.
380
+ export const CONTEXT = 64_000
381
+ const bytes = (s) => Buffer.byteLength(s)
382
+
368
383
  // turnOf is what goes into agy's prompt: the images and videos, attached in
369
384
  // the order they came, and the text pasted after them, the last user
370
385
  // message alone, or with the instructions and the conversation before it.
371
386
  // The conversation's tool calls and results are written in, as what was
372
387
  // done: a turn that carries on after a call is typed in whole when no agy
373
388
  // waits on that call any more (parked).
389
+ // Held to budget bytes: the last message whole, then the instructions,
390
+ // then the conversation from its newest turn back, as much as fits; the
391
+ // oldest turns that don't are left out, with a line in their place that
392
+ // says so, and their images with them. A last message over budget alone
393
+ // is refused.
374
394
  // A file magpie could only name in words (ATTACHMENT_NOTE) in the last
375
395
  // user message is refused: the model would be told of a file it can't
376
396
  // see. One in an earlier turn stays, as what was said then.
377
- export function turnOf(messages) {
397
+ export function turnOf(messages, budget = INPUT_BUDGET) {
378
398
  if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
379
- const system = []
380
- const turns = []
381
- const media = []
382
- for (const m of messages) {
383
- if (m?.role === "system" || m?.role === "developer") {
384
- const text = partsOf(m?.content, media).trim()
385
- if (text) system.push(text)
386
- } else if (m?.role === "user" || m?.role === "assistant") {
387
- const said = [partsOf(m?.content, media).trim()]
388
- if (m.role === "assistant" && Array.isArray(m.tool_calls)) {
389
- for (const c of m.tool_calls) said.push(`[called ${c?.function?.name ?? "a tool"} ${c?.function?.arguments || "{}"} as ${c?.id ?? "a call"}]`)
399
+ // read once to weigh the turns, then again with only the kept ones, so
400
+ // the images are numbered as they are attached
401
+ const read = (list, media) => {
402
+ const system = []
403
+ const turns = []
404
+ for (const m of list) {
405
+ if (m?.role === "system" || m?.role === "developer") {
406
+ const text = partsOf(m?.content, media).trim()
407
+ if (text) system.push(text)
408
+ } else if (m?.role === "user" || m?.role === "assistant") {
409
+ const said = [partsOf(m?.content, media).trim()]
410
+ if (m.role === "assistant" && Array.isArray(m.tool_calls)) {
411
+ for (const c of m.tool_calls) said.push(`[called ${c?.function?.name ?? "a tool"} ${c?.function?.arguments || "{}"} as ${c?.id ?? "a call"}]`)
412
+ }
413
+ const text = said.filter(Boolean).join("\n")
414
+ if (text) turns.push({ role: m.role, text, m })
415
+ } else if (m?.role === "tool") {
416
+ turns.push({ role: "tool", text: `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}`, m })
390
417
  }
391
- const text = said.filter(Boolean).join("\n")
392
- if (text) turns.push({ role: m.role, text })
393
- } else if (m?.role === "tool") {
394
- turns.push({ role: "tool", text: `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}` })
395
418
  }
419
+ return { system, turns }
396
420
  }
421
+ let { system, turns } = read(messages, [])
397
422
  if (!turns.length || turns.at(-1).role === "assistant") throw refuse("the last message is not the user's or a tool's result")
398
423
  const note = ATTACHMENT_NOTE.exec(turns.at(-1).text)
399
424
  if (note) throw refuse(`${TAKES}; the message has ${named(note[1])}`)
400
- if (!system.length && turns.length === 1 && turns[0].role === "user") return { prompt: turns[0].text, media }
401
- const parts = []
402
425
  const said = (t) => `${{ user: "User", assistant: "Assistant", tool: "Tool" }[t.role]}: ${t.text}`
403
- if (system.length) parts.push(system.join("\n\n"))
404
- if (turns.length > 1 || turns[0].role !== "user") {
405
- parts.push(turns.slice(0, -1).map(said).join("\n\n"))
406
- parts.push(said(turns.at(-1)))
407
- } else {
408
- parts.push(turns[0].text)
426
+ // a user's message with nothing before it goes as it was written
427
+ const bare = turns.length === 1 && turns[0].role === "user"
428
+ const lastText = bare ? turns[0].text : said(turns.at(-1))
429
+ if (bytes(lastText) > budget) {
430
+ throw refuse(`the last message is ${bytes(lastText)} bytes, more than agy takes in one message (${budget}): send less of it at once`)
409
431
  }
432
+ // what is left once the last message and the parts' blank lines are in
433
+ const earlier = turns.slice(0, -1)
434
+ const LEFT_OUT = 120
435
+ let room = budget - bytes(lastText) - 8
436
+ let instructions = system.join("\n\n")
437
+ const cutInstructions = bytes(instructions) > room - (earlier.length ? LEFT_OUT : 0)
438
+ if (cutInstructions) {
439
+ const cut = `\n\n[the rest of the instructions, ${bytes(instructions)} bytes in all, is left out: the conversation is longer than one message takes]`
440
+ const keep = Math.max(0, room - (earlier.length ? LEFT_OUT : 0) - bytes(cut))
441
+ instructions = Buffer.from(instructions).subarray(0, keep).toString().replace(/\uFFFD+$/, "") + cut
442
+ }
443
+ room -= bytes(instructions)
444
+ // the earlier turns, newest first, while they fit with the line that
445
+ // says what was left out
446
+ let from = earlier.length
447
+ for (let used = 0; from > 0; from--) {
448
+ const n = bytes(said(earlier[from - 1])) + 2
449
+ if (used + n > room - (from > 1 ? LEFT_OUT : 0)) break
450
+ used += n
451
+ }
452
+ const kept = new Set([...earlier.slice(from), turns.at(-1)].map((t) => t.m))
453
+ const media = []
454
+ ;({ system, turns } = read(messages.filter((m) => m?.role === "system" || m?.role === "developer" || kept.has(m)), media))
455
+ if (bare && !system.length) return { prompt: turns[0].text, media }
456
+ const parts = []
457
+ if (system.length) parts.push(cutInstructions ? instructions : system.join("\n\n"))
458
+ const before = turns.slice(0, -1).map(said)
459
+ if (from > 0) before.unshift(`[${from} earlier message${from === 1 ? " is" : "s are"} left out here: the conversation is longer than one message takes]`)
460
+ if (before.length) parts.push(before.join("\n\n"))
461
+ parts.push(bare ? turns[0].text : said(turns.at(-1)))
410
462
  return { prompt: parts.join("\n\n"), media }
411
463
  }
412
464
 
@@ -452,22 +504,26 @@ const claimed = new Set()
452
504
  // answerOf is the turn's answer in agy's transcript: a conversation agy
453
505
  // started since `before`, whose user input is the prompt, and its last
454
506
  // PLANNER_RESPONSE. The screen is not read for it: agy draws a refused
455
- // call there too.
456
- 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) {
457
511
  // its own words, not an image's or a video's mark, which other turns have too
458
512
  const lines = prompt.split("\n").map((l) => l.trim())
459
513
  const snip = (lines.find((l) => l.replace(MEDIA_MARK, "").trim()) ?? lines.find(Boolean))?.slice(0, 60) ?? ""
460
514
  let ids = []
461
- try { ids = fs.readdirSync(brain) } catch {}
515
+ if (from) ids = [from.id]
516
+ else try { ids = fs.readdirSync(brain) } catch {}
462
517
  for (const id of ids) {
463
518
  // another turn's, of the same words, running beside this one
464
- if (before.has(id) || (claimed.has(id) && id !== own)) continue
465
- const file = path.join(brain, id, ".system_generated", "logs", "transcript_full.jsonl")
466
- let text
467
- 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)
468
524
  let mine = false
469
525
  let answer = ""
470
- for (const line of text.split("\n")) {
526
+ for (const line of rows) {
471
527
  let row
472
528
  try { row = JSON.parse(line) } catch { continue }
473
529
  const type = row.type ?? row.Type
@@ -483,6 +539,13 @@ export function answerOf(brain, before, prompt, own = null) {
483
539
  return null
484
540
  }
485
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
+
486
549
  // screenTail is what agy drew last, for an error: its warning when it
487
550
  // shows one ("⚠ …" up to the next rule), else the last lines.
488
551
  export function screenTail(screen, n = 8) {
@@ -563,24 +626,27 @@ export function mcpConfig(mcp, tools) {
563
626
  // `reply(id, content)`, and the turn goes on to its next stop. With tools
564
627
  // (MCP tools: name, description, inputSchema), agy is given them through
565
628
  // magpie's tool server, in a HOME of the turn's own (sessionHome), and its
566
- // own tools stay off.
567
- export async function startTurn({ agy, home, model, prompt, media = [], tools = [], signal, helper = process.env.MAGPIE_EXE }) {
568
- 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 }
569
634
  const key = spareKey(opts)
570
635
  let turn = null
571
636
  const spare = await takeSpare(key)
572
637
  if (spare) {
573
638
  try {
574
- turn = await spare.begin({ prompt, media, signal })
639
+ turn = await spare.begin({ prompt, media, signal, messages })
575
640
  } catch (error) {
576
641
  // a spare that died while it waited is started again; the
577
642
  // request's own failures are its own
578
643
  if (!error.boot || signal?.aborted) throw error
579
644
  }
580
645
  }
581
- if (!turn) turn = await (await launch(opts)).begin({ prompt, media, signal })
582
- // agy has the message: the next request's agy starts now
583
- 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 })
584
650
  return turn
585
651
  }
586
652
 
@@ -596,8 +662,8 @@ const SPARE_IDLE_MS = 10 * 60_000
596
662
  const MAX_SPARES = 3
597
663
  const spares = new Map()
598
664
 
599
- function spareKey({ agy, home, model, tools, helper }) {
600
- 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")
601
667
  }
602
668
 
603
669
  async function takeSpare(key) {
@@ -611,12 +677,14 @@ async function takeSpare(key) {
611
677
  return null
612
678
  }
613
679
 
680
+ // dropSpare ends the spare of key, if one waits; it resolves once its agy
681
+ // has gone
614
682
  function dropSpare(key) {
615
683
  const s = spares.get(key)
616
- if (!s) return
684
+ if (!s) return Promise.resolve()
617
685
  spares.delete(key)
618
686
  clearTimeout(s.timer)
619
- s.started.then((a) => a.close(), () => {})
687
+ return s.started.then((a) => a.close(), () => {})
620
688
  }
621
689
 
622
690
  function leaveSpare(key, opts) {
@@ -640,10 +708,11 @@ export async function closeSpares() {
640
708
  }))
641
709
  }
642
710
 
643
- // launch starts agy for a turn, in a folder of its own, and resolves at
644
- // 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,
645
714
  // types the request in and resolves with the turn
646
- 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 }) {
647
716
  if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
648
717
  settleHome(home)
649
718
  const withTools = tools.length > 0
@@ -682,8 +751,12 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
682
751
  const args = ["--settings", JSON.stringify(settings)]
683
752
  // agy's own default customizations stay out, as the old agent's
684
753
  // inheritCustomizations: false kept them
685
- 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")
686
758
  if (model) args.push("--model", model)
759
+ if (conversation) args.push("--conversation", conversation)
687
760
  const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
688
761
  let screen = ""
689
762
  let ended = null
@@ -707,8 +780,12 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
707
780
  // answered
708
781
  const pending = new Set()
709
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
710
787
  const look = () => {
711
- found = answerOf(brain, before, prompt, found?.id)
788
+ found = answerOf(brain, before, prompt, found?.id, from) ?? (from ? { id: from.id, answer: "" } : null)
712
789
  if (found?.id) claimed.add(found.id)
713
790
  }
714
791
  // what the model has said so far, its text and its thinking, from agy's
@@ -722,6 +799,24 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
722
799
  }
723
800
  if (grew) for (const fn of live.listeners) fn()
724
801
  }
802
+ // the tokens the model calls since the last response took, as an OpenAI
803
+ // usage, read from agy's store as each response ends (null when it has
804
+ // none): agy writes a call's counts as the call ends, so a moment is
805
+ // given for them
806
+ let usageAt = null
807
+ const spent = async () => {
808
+ for (let i = 0; i < USAGE_TRIES; i++) {
809
+ if (!found?.id) look()
810
+ const got = found?.id ? callsAfter(home, found.id, usageAt) : null
811
+ if (!got) return null
812
+ if (got.calls.length) {
813
+ usageAt = got.cursor
814
+ return usageOf(got.calls)
815
+ }
816
+ await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
817
+ }
818
+ return null
819
+ }
725
820
 
726
821
  let buf = ""
727
822
  child.stdout.setEncoding("utf8").on("data", (d) => {
@@ -741,8 +836,9 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
741
836
  // what the model wrote before the call goes first
742
837
  pending.add(o.call.id)
743
838
  if (!found?.id) look()
744
- if (found?.id) publish(liveReply(home, found.id))
745
- stop({ call: o.call })
839
+ if (found?.id) publish(liveReply(home, found.id, stepBase))
840
+ const call = o.call
841
+ spent().then((usage) => stop({ call, usage }))
746
842
  }
747
843
  if (o.dropped) pending.delete(o.dropped)
748
844
  }
@@ -834,6 +930,14 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
834
930
  error.boot = true
835
931
  throw error
836
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
+ }
837
941
  try {
838
942
  let files
839
943
  try {
@@ -861,7 +965,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
861
965
  send({ write: "\r" })
862
966
  // agy has the message once it is in a turn, or its transcript has it
863
967
  // (a turn that failed at once may never draw "esc to cancel")
864
- 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)
865
969
  } catch (error) {
866
970
  await cleanup()
867
971
  throw error
@@ -869,6 +973,9 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
869
973
 
870
974
  const turn = {
871
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,
872
979
  // the reply's text and thinking the client has had, in the responses
873
980
  // before this one
874
981
  sent: "",
@@ -909,7 +1016,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
909
1016
  if (Date.now() - polled >= LIVE_POLL_MS) {
910
1017
  polled = Date.now()
911
1018
  if (!found?.id) look()
912
- if (found?.id) publish(liveReply(home, found.id))
1019
+ if (found?.id) publish(liveReply(home, found.id, stepBase))
913
1020
  }
914
1021
  return false
915
1022
  }
@@ -920,8 +1027,8 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
920
1027
  }, () => until)
921
1028
  if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
922
1029
  // the whole of it, read before the conversation goes
923
- publish(liveReply(home, found.id))
924
- last = { text: found.answer }
1030
+ publish(liveReply(home, found.id, stepBase))
1031
+ last = { text: found.answer, usage: await spent() }
925
1032
  } catch (error) {
926
1033
  last = { error }
927
1034
  } finally {
@@ -931,7 +1038,16 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
931
1038
  turn.ended = true
932
1039
  watch(null)
933
1040
  stop(last)
934
- 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
+ }))
935
1051
  }
936
1052
  })()
937
1053
  return turn
@@ -991,18 +1107,205 @@ export function toolContent(content) {
991
1107
  }
992
1108
 
993
1109
  // forget removes the conversation agy kept for a turn from the account's
994
- // home: each request is a conversation of its own.
1110
+ // home.
995
1111
  function forget(brain, id) {
996
- if (!id) return
1112
+ if (!CONVERSATION_ID.test(String(id ?? ""))) return
997
1113
  claimed.delete(id)
998
1114
  if (process.env.AGY_TUI_KEEP) return
999
1115
  fs.rmSync(path.join(brain, id), { recursive: true, force: true })
1000
1116
  const conv = path.join(path.dirname(brain), "conversations")
1001
1117
  try {
1002
- 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 })
1003
1119
  } catch {}
1004
1120
  }
1005
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
+
1006
1309
  // ---- OpenAI chat completions
1007
1310
 
1008
1311
  function jsonError(status, message, headers = {}) {
@@ -1029,13 +1332,14 @@ function stopped(turn, call) {
1029
1332
  park(call.id, turn)
1030
1333
  }
1031
1334
 
1032
- function completion(id, model, message, finish) {
1335
+ function completion(id, model, message, finish, usage = null) {
1033
1336
  return {
1034
1337
  id,
1035
1338
  object: "chat.completion",
1036
1339
  created: Math.floor(Date.now() / 1000),
1037
1340
  model,
1038
1341
  choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }],
1342
+ ...(usage ? { usage } : {}),
1039
1343
  }
1040
1344
  }
1041
1345
 
@@ -1048,9 +1352,9 @@ async function answered(id, model, turn) {
1048
1352
  if (s.call) {
1049
1353
  const text = since(turn, turn.live.text)
1050
1354
  stopped(turn, s.call)
1051
- return completion(id, model, { content: text || null, ...reasoning, tool_calls: [toolCallOf(s.call)] }, "tool_calls")
1355
+ return completion(id, model, { content: text || null, ...reasoning, tool_calls: [toolCallOf(s.call)] }, "tool_calls", s.usage)
1052
1356
  }
1053
- return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop")
1357
+ return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop", s.usage)
1054
1358
  }
1055
1359
 
1056
1360
  // streamOf sends the turn's reply up to its next stop as agy's model
@@ -1061,7 +1365,7 @@ export function streamOf(id, model, turn) {
1061
1365
  const { live } = turn
1062
1366
  const enc = new TextEncoder()
1063
1367
  const created = Math.floor(Date.now() / 1000)
1064
- const chunk = (delta, finish = null) => `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`
1368
+ const chunk = (delta, finish = null, usage = null) => `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish }], ...(usage ? { usage } : {}) })}\n\n`
1065
1369
  let keep
1066
1370
  let listen
1067
1371
  let quiet = 0
@@ -1110,10 +1414,10 @@ export function streamOf(id, model, turn) {
1110
1414
  if (s.call) {
1111
1415
  stopped(turn, s.call)
1112
1416
  c.enqueue(enc.encode(chunk({ tool_calls: [toolCallOf(s.call, 0)] })))
1113
- c.enqueue(enc.encode(chunk({}, "tool_calls")))
1417
+ c.enqueue(enc.encode(chunk({}, "tool_calls", s.usage)))
1114
1418
  } else {
1115
1419
  if (!sent && s.text) c.enqueue(enc.encode(chunk({ content: s.text })))
1116
- c.enqueue(enc.encode(chunk({}, "stop")))
1420
+ c.enqueue(enc.encode(chunk({}, "stop", s.usage)))
1117
1421
  }
1118
1422
  } catch (error) {
1119
1423
  c.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: error.message, type: "agy_tui_error" } })}\n\n`))
@@ -1153,6 +1457,7 @@ export async function handle(home, input, init = {}) {
1153
1457
  if (last?.role === "tool") {
1154
1458
  const waiting = unpark(last.tool_call_id)
1155
1459
  if (waiting && !waiting.ended) {
1460
+ waiting.messages = body.messages
1156
1461
  let content
1157
1462
  try { content = toolContent(last.content) } catch (error) {
1158
1463
  waiting.close()
@@ -1174,13 +1479,20 @@ export async function handle(home, input, init = {}) {
1174
1479
  const refusal = await agyRefusal(agy)
1175
1480
  if (refusal) return jsonError(503, refusal)
1176
1481
  let turn
1482
+ let carried = null
1177
1483
  try {
1178
1484
  const tools = mcpToolsOf(body)
1179
- 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)
1180
1489
  // agy attaches a video for any model, but only Gemini's see one
1181
1490
  if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
1182
- 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 })
1183
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)
1184
1496
  return jsonError(error.status ?? 502, error.message, error.headers)
1185
1497
  }
1186
1498
  return respond(id, model, turn, body.stream)
@@ -1194,7 +1506,7 @@ export function modelEntry(m) {
1194
1506
  name: m.name,
1195
1507
  npm: NPM,
1196
1508
  api: { id: m.id, url: "agy-tui://local", npm: NPM },
1197
- limit: { context: 1_000_000, output: 65_536 },
1509
+ limit: { context: CONTEXT, output: 65_536 },
1198
1510
  // Gemini's and Claude's see the images agy attaches, as agy-cli says,
1199
1511
  // and Gemini's the videos too
1200
1512
  ...(/^(?:gemini-|claude-)/.test(m.id) ? { capabilities: { attachment: true, input: { text: true, image: true, video: m.id.startsWith("gemini-"), audio: false, pdf: false }, output: { text: true } } } : {}),
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,7 +160,139 @@ 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
164
185
  }
186
+
187
+ // ---- what each model call cost
188
+ //
189
+ // agy writes a model call's token counts to the same store: a row of
190
+ // gen_metadata when the call ends (the usage message at field 1.4 of
191
+ // `data`), and, in older stores, field 9 of a finished (status 3)
192
+ // PLANNER_RESPONSE step's `metadata`. Either message has 2 the uncached
193
+ // input, 3 the output (thinking included), 4 the cache write, 5 the cache
194
+ // read, 9 the thinking. One table is read for a conversation, never both:
195
+ // they hold the same calls. (Layout as agy-cli's step-usage.mjs reads it.)
196
+
197
+ const STEP_DONE = 3
198
+ const count = (n) => Number.isSafeInteger(n) && n > 0 ? n : 0
199
+
200
+ function counts(buf) {
201
+ const u = { input: 0, output: 0, write: 0, read: 0, thinking: 0 }
202
+ const ok = fields(buf, (f, w, n) => {
203
+ if (w !== 0) return
204
+ if (f === 2) u.input = count(n)
205
+ else if (f === 3) u.output = count(n)
206
+ else if (f === 4) u.write = count(n)
207
+ else if (f === 5) u.read = count(n)
208
+ else if (f === 9) u.thinking = count(n)
209
+ })
210
+ return ok ? u : null
211
+ }
212
+
213
+ // generationUsage is a gen_metadata row's counts, null with none.
214
+ export function generationUsage(data) {
215
+ const buf = bytesOf(data)
216
+ if (!buf) return null
217
+ let u = null
218
+ if (!fields(buf, (f, w, chat) => {
219
+ if (f !== 1 || w !== 2) return
220
+ fields(chat, (g, gw, v) => { if (g === 4 && gw === 2) u = counts(v) })
221
+ })) return null
222
+ return u && u.input + u.output + u.write + u.read + u.thinking ? u : null
223
+ }
224
+
225
+ // stepUsage is a finished step's counts from its metadata, null with none.
226
+ export function stepUsage(metadata) {
227
+ const buf = bytesOf(metadata)
228
+ if (!buf) return null
229
+ let u = null
230
+ if (!fields(buf, (f, w, v) => { if (f === 9 && w === 2) u = counts(v) })) return null
231
+ return u && u.input + u.output + u.write + u.read + u.thinking ? u : null
232
+ }
233
+
234
+ const rowsOf = (db, sql) => {
235
+ try { return db.all(sql) } catch (e) {
236
+ if (/no such table|no such column/i.test(String(e?.message ?? ""))) return null
237
+ throw e
238
+ }
239
+ }
240
+
241
+ // callsAfter is the model calls the conversation id has made since
242
+ // cursor ({ source, idx }; null for none read yet), oldest first, and the
243
+ // cursor past them: { calls: [{ input, output, write, read, thinking }],
244
+ // cursor }. null when the store can't be read.
245
+ export function callsAfter(home, id, cursor = null) {
246
+ const file = conversationDb(home, id)
247
+ if (!file || !fs.existsSync(file)) return null
248
+ const open = loadOpener()
249
+ if (!open) return null
250
+ let db
251
+ try {
252
+ db = open(file)
253
+ const read = (source) => {
254
+ const after = cursor?.source === source ? cursor.idx : -1
255
+ const rows = source === "gen_metadata"
256
+ ? rowsOf(db, `SELECT idx, data AS v FROM gen_metadata WHERE idx > ${Number(after)} ORDER BY idx`)
257
+ : rowsOf(db, `SELECT idx, metadata AS v FROM steps WHERE step_type = ${MODEL_STEP} AND status = ${STEP_DONE} AND idx > ${Number(after)} ORDER BY idx`)
258
+ if (!rows) return null
259
+ const calls = []
260
+ let idx = after
261
+ for (const row of rows) {
262
+ const u = source === "gen_metadata" ? generationUsage(row.v) : stepUsage(row.v)
263
+ if (!u) continue
264
+ calls.push(u)
265
+ idx = Math.max(idx, Number(row.idx))
266
+ }
267
+ return { calls, cursor: { source, idx } }
268
+ }
269
+ if (cursor?.source) return read(cursor.source)
270
+ const gen = read("gen_metadata")
271
+ if (gen?.calls.length) return gen
272
+ const steps = read("steps")
273
+ if (steps?.calls.length) return steps
274
+ return { calls: [], cursor: null }
275
+ } catch {
276
+ return null
277
+ } finally {
278
+ try { db?.close() } catch {}
279
+ }
280
+ }
281
+
282
+ // usageOf is calls as an OpenAI usage: the prompt the last call sent
283
+ // (uncached, cache read and cache write), every call's output; null for
284
+ // no calls.
285
+ export function usageOf(calls) {
286
+ if (!calls?.length) return null
287
+ const last = calls.at(-1)
288
+ const prompt = last.input + last.read + last.write
289
+ const completion = calls.reduce((n, c) => n + c.output, 0)
290
+ const thinking = calls.reduce((n, c) => n + c.thinking, 0)
291
+ return {
292
+ prompt_tokens: prompt,
293
+ completion_tokens: completion,
294
+ total_tokens: prompt + completion,
295
+ prompt_tokens_details: { cached_tokens: last.read },
296
+ completion_tokens_details: { reasoning_tokens: thinking },
297
+ }
298
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.7",
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",