@magpie-community/opencode-agy-tui-auth 0.1.6 → 0.1.8
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 +5 -1
- package/README.md +5 -1
- package/index.mjs +323 -139
- package/live.mjs +113 -0
- package/package.json +1 -1
package/README.en.md
CHANGED
|
@@ -22,8 +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
|
+
- 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.
|
|
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.
|
|
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).
|
|
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.
|
|
27
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.
|
|
28
31
|
|
|
29
32
|
## Options (environment)
|
|
@@ -32,4 +35,5 @@ A request's tools (`tools`, function tools) are given to the model through magpi
|
|
|
32
35
|
- `AGY_TUI_TURN_TIMEOUT_MS`: the longest a turn may take, 15 minutes by default.
|
|
33
36
|
- `AGY_TUI_PARK_TIMEOUT_MS`: how long a turn waits for a tool call's result, 10 minutes by default.
|
|
34
37
|
- `AGY_TUI_ATTACH_TIMEOUT_MS`: how long agy may take to attach a turn's images and videos, 15 seconds by default.
|
|
38
|
+
- `AGY_TUI_SPARES=0`: no agy started ahead for the next request.
|
|
35
39
|
- `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,8 +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 里继续),之前的对话会整理成文字一起粘贴进去。所以长时间不用后再继续的对话,下一个请求会重新粘贴整段对话。
|
|
26
|
+
- agy 一条消息最多收 192,000 字节,超出部分会被它替换成 `<truncated N bytes>`,模型就看不到最新的消息了。所以粘贴的内容控制在 180,000 字节以内:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。系统指令本身放不下时截短。最后一条消息单独就超过时会被拒绝(400)。
|
|
27
|
+
- 模型宣告的上下文是 64K token(大约是 agy 一条消息能放下的量,加上 agy 自己约 10K 的指令),每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考),这样 agent 会在 agy 截断之前压缩对话。
|
|
26
28
|
- 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。模型的思考(agy 向 Gemini 要了思考内容)同样边生成边作为 `reasoning_content` 返回,在回答之前;非流式时放在消息的 `reasoning_content` 里。回答写完就结束响应,不等 agy 退出(它退出前会先发完自己的遥测)。
|
|
29
|
+
- agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
|
|
27
30
|
- 需要 magpie 0.1.5217 或更新(带 `tui-helper` 及其工具服务器);magpie 太旧时,带工具的请求会提示更新 magpie。Windows 尚未测试。
|
|
28
31
|
|
|
29
32
|
## 选项(环境变量)
|
|
@@ -32,4 +35,5 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
|
|
|
32
35
|
- `AGY_TUI_TURN_TIMEOUT_MS`:一轮的最长时间,默认 15 分钟。
|
|
33
36
|
- `AGY_TUI_PARK_TIMEOUT_MS`:一轮等待工具调用结果的最长时间,默认 10 分钟。
|
|
34
37
|
- `AGY_TUI_ATTACH_TIMEOUT_MS`:agy 附加本轮图片和视频的最长等待时间,默认 15 秒。
|
|
38
|
+
- `AGY_TUI_SPARES=0`:不为下一个请求预先启动 agy。
|
|
35
39
|
- `AGY_TUI_KEEP=1`:保留每轮的临时目录(包括图片和视频)和 agy 的对话记录,方便排查。
|
package/index.mjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { spawn } from "node:child_process"
|
|
2
|
-
import { randomBytes } from "node:crypto"
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto"
|
|
3
3
|
import fs from "node:fs"
|
|
4
4
|
import os from "node:os"
|
|
5
5
|
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 } 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
|
|
@@ -53,8 +53,10 @@ const leaving = (p) => {
|
|
|
53
53
|
return p.finally(() => going.delete(p))
|
|
54
54
|
}
|
|
55
55
|
|
|
56
|
-
// settled is when every turn's agy has gone and its files with it
|
|
56
|
+
// settled is when every turn's agy has gone and its files with it, the
|
|
57
|
+
// spares' too
|
|
57
58
|
export async function settled() {
|
|
59
|
+
await closeSpares()
|
|
58
60
|
while (going.size) await Promise.allSettled([...going])
|
|
59
61
|
}
|
|
60
62
|
|
|
@@ -83,6 +85,9 @@ const MCP_CALL_SECONDS = 3600
|
|
|
83
85
|
const LISTED_MS = 20_000
|
|
84
86
|
// how many turns may wait on a call's result at once
|
|
85
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
|
|
86
91
|
|
|
87
92
|
// how long a turn waits for the request with a call's result
|
|
88
93
|
function parkTimeout() {
|
|
@@ -363,48 +368,97 @@ function partsOf(content, media) {
|
|
|
363
368
|
return out.join("\n")
|
|
364
369
|
}
|
|
365
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
|
+
|
|
366
383
|
// turnOf is what goes into agy's prompt: the images and videos, attached in
|
|
367
384
|
// the order they came, and the text pasted after them, the last user
|
|
368
385
|
// message alone, or with the instructions and the conversation before it.
|
|
369
386
|
// The conversation's tool calls and results are written in, as what was
|
|
370
387
|
// done: a turn that carries on after a call is typed in whole when no agy
|
|
371
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.
|
|
372
394
|
// A file magpie could only name in words (ATTACHMENT_NOTE) in the last
|
|
373
395
|
// user message is refused: the model would be told of a file it can't
|
|
374
396
|
// see. One in an earlier turn stays, as what was said then.
|
|
375
|
-
export function turnOf(messages) {
|
|
397
|
+
export function turnOf(messages, budget = INPUT_BUDGET) {
|
|
376
398
|
if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
if (
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
if (m
|
|
387
|
-
|
|
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 })
|
|
388
417
|
}
|
|
389
|
-
const text = said.filter(Boolean).join("\n")
|
|
390
|
-
if (text) turns.push({ role: m.role, text })
|
|
391
|
-
} else if (m?.role === "tool") {
|
|
392
|
-
turns.push({ role: "tool", text: `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}` })
|
|
393
418
|
}
|
|
419
|
+
return { system, turns }
|
|
394
420
|
}
|
|
421
|
+
let { system, turns } = read(messages, [])
|
|
395
422
|
if (!turns.length || turns.at(-1).role === "assistant") throw refuse("the last message is not the user's or a tool's result")
|
|
396
423
|
const note = ATTACHMENT_NOTE.exec(turns.at(-1).text)
|
|
397
424
|
if (note) throw refuse(`${TAKES}; the message has ${named(note[1])}`)
|
|
398
|
-
if (!system.length && turns.length === 1 && turns[0].role === "user") return { prompt: turns[0].text, media }
|
|
399
|
-
const parts = []
|
|
400
425
|
const said = (t) => `${{ user: "User", assistant: "Assistant", tool: "Tool" }[t.role]}: ${t.text}`
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
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`)
|
|
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
|
|
407
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)))
|
|
408
462
|
return { prompt: parts.join("\n\n"), media }
|
|
409
463
|
}
|
|
410
464
|
|
|
@@ -563,6 +617,85 @@ export function mcpConfig(mcp, tools) {
|
|
|
563
617
|
// magpie's tool server, in a HOME of the turn's own (sessionHome), and its
|
|
564
618
|
// own tools stay off.
|
|
565
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 }
|
|
621
|
+
const key = spareKey(opts)
|
|
622
|
+
let turn = null
|
|
623
|
+
const spare = await takeSpare(key)
|
|
624
|
+
if (spare) {
|
|
625
|
+
try {
|
|
626
|
+
turn = await spare.begin({ prompt, media, signal })
|
|
627
|
+
} catch (error) {
|
|
628
|
+
// a spare that died while it waited is started again; the
|
|
629
|
+
// request's own failures are its own
|
|
630
|
+
if (!error.boot || signal?.aborted) throw error
|
|
631
|
+
}
|
|
632
|
+
}
|
|
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)
|
|
636
|
+
return turn
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
// ---- spares
|
|
640
|
+
//
|
|
641
|
+
// agy takes seconds to start: signed in with Google, it asks Cloud Code for
|
|
642
|
+
// the account, its plan and its models before it takes a message (a median
|
|
643
|
+
// of 3.8s a start on a real account, 11s at worst). So each turn leaves an
|
|
644
|
+
// agy started for the next request with the same account, model and tools,
|
|
645
|
+
// which only types its message into it. One waits per kind, for
|
|
646
|
+
// SPARE_IDLE_MS at most.
|
|
647
|
+
const SPARE_IDLE_MS = 10 * 60_000
|
|
648
|
+
const MAX_SPARES = 3
|
|
649
|
+
const spares = new Map()
|
|
650
|
+
|
|
651
|
+
function spareKey({ agy, home, model, tools, helper }) {
|
|
652
|
+
return createHash("sha256").update(JSON.stringify([agy, home, model ?? "", tools, helper ?? ""])).digest("hex")
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
async function takeSpare(key) {
|
|
656
|
+
const s = spares.get(key)
|
|
657
|
+
if (!s) return null
|
|
658
|
+
spares.delete(key)
|
|
659
|
+
clearTimeout(s.timer)
|
|
660
|
+
const a = await s.started.catch(() => null)
|
|
661
|
+
if (a?.alive()) return a
|
|
662
|
+
a?.close()
|
|
663
|
+
return null
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
function dropSpare(key) {
|
|
667
|
+
const s = spares.get(key)
|
|
668
|
+
if (!s) return
|
|
669
|
+
spares.delete(key)
|
|
670
|
+
clearTimeout(s.timer)
|
|
671
|
+
s.started.then((a) => a.close(), () => {})
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function leaveSpare(key, opts) {
|
|
675
|
+
if (process.env.AGY_TUI_SPARES === "0" || spares.has(key)) return
|
|
676
|
+
while (spares.size >= MAX_SPARES) dropSpare(spares.keys().next().value)
|
|
677
|
+
const started = launch(opts)
|
|
678
|
+
started.catch(() => {})
|
|
679
|
+
const timer = setTimeout(() => dropSpare(key), SPARE_IDLE_MS)
|
|
680
|
+
timer.unref?.()
|
|
681
|
+
spares.set(key, { started, timer })
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
// closeSpares ends every agy that waits for a request
|
|
685
|
+
export async function closeSpares() {
|
|
686
|
+
const all = [...spares.values()]
|
|
687
|
+
spares.clear()
|
|
688
|
+
await Promise.all(all.map(async (s) => {
|
|
689
|
+
clearTimeout(s.timer)
|
|
690
|
+
const a = await s.started.catch(() => null)
|
|
691
|
+
await a?.close()
|
|
692
|
+
}))
|
|
693
|
+
}
|
|
694
|
+
|
|
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,
|
|
697
|
+
// types the request in and resolves with the turn
|
|
698
|
+
async function launch({ agy, home, model, tools = [], helper = process.env.MAGPIE_EXE }) {
|
|
566
699
|
if (!helper) throw new Failure(501, "this magpie has no tui-helper: update magpie")
|
|
567
700
|
settleHome(home)
|
|
568
701
|
const withTools = tools.length > 0
|
|
@@ -572,7 +705,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
572
705
|
// agy's own tools (what the old agent's `tools: []` did); with tools, the
|
|
573
706
|
// caller's are let through
|
|
574
707
|
let hookEnv
|
|
575
|
-
let files
|
|
576
708
|
let ownHome = null
|
|
577
709
|
try {
|
|
578
710
|
hookEnv = await writeDefaultAgentFiles(ws, {
|
|
@@ -580,10 +712,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
580
712
|
allowed: withTools ? [MCP_FUNCTIONS] : [],
|
|
581
713
|
geminiDir: path.join(home, ".gemini"),
|
|
582
714
|
})
|
|
583
|
-
// the images and videos, in the turn's folder: agy copies each one it
|
|
584
|
-
// attaches into the conversation's own (forget removes it), and the
|
|
585
|
-
// folder goes with the turn
|
|
586
|
-
files = writeMedia(path.join(ws, "attachments"), media)
|
|
587
715
|
if (withTools) {
|
|
588
716
|
ownHome = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "agy-tui-home-")))
|
|
589
717
|
sessionHome(home, ownHome)
|
|
@@ -594,6 +722,8 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
594
722
|
throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
|
|
595
723
|
}
|
|
596
724
|
const brain = path.join(home, ".gemini", "antigravity-cli", "brain")
|
|
725
|
+
// the message, once a request gives it (begin)
|
|
726
|
+
let prompt = ""
|
|
597
727
|
let before
|
|
598
728
|
try { before = new Set(fs.readdirSync(brain)) } catch { before = new Set() }
|
|
599
729
|
|
|
@@ -644,6 +774,24 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
644
774
|
}
|
|
645
775
|
if (grew) for (const fn of live.listeners) fn()
|
|
646
776
|
}
|
|
777
|
+
// the tokens the model calls since the last response took, as an OpenAI
|
|
778
|
+
// usage, read from agy's store as each response ends (null when it has
|
|
779
|
+
// none): agy writes a call's counts as the call ends, so a moment is
|
|
780
|
+
// given for them
|
|
781
|
+
let usageAt = null
|
|
782
|
+
const spent = async () => {
|
|
783
|
+
for (let i = 0; i < USAGE_TRIES; i++) {
|
|
784
|
+
if (!found?.id) look()
|
|
785
|
+
const got = found?.id ? callsAfter(home, found.id, usageAt) : null
|
|
786
|
+
if (!got) return null
|
|
787
|
+
if (got.calls.length) {
|
|
788
|
+
usageAt = got.cursor
|
|
789
|
+
return usageOf(got.calls)
|
|
790
|
+
}
|
|
791
|
+
await new Promise((r) => setTimeout(r, USAGE_POLL_MS))
|
|
792
|
+
}
|
|
793
|
+
return null
|
|
794
|
+
}
|
|
647
795
|
|
|
648
796
|
let buf = ""
|
|
649
797
|
child.stdout.setEncoding("utf8").on("data", (d) => {
|
|
@@ -664,7 +812,8 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
664
812
|
pending.add(o.call.id)
|
|
665
813
|
if (!found?.id) look()
|
|
666
814
|
if (found?.id) publish(liveReply(home, found.id))
|
|
667
|
-
|
|
815
|
+
const call = o.call
|
|
816
|
+
spent().then((usage) => stop({ call, usage }))
|
|
668
817
|
}
|
|
669
818
|
if (o.dropped) pending.delete(o.dropped)
|
|
670
819
|
}
|
|
@@ -698,7 +847,6 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
698
847
|
sig?.addEventListener?.("abort", onAbort, { once: true })
|
|
699
848
|
if (sig?.aborted) onAbort()
|
|
700
849
|
}
|
|
701
|
-
watch(signal)
|
|
702
850
|
|
|
703
851
|
// waitFor resolves once ok() holds; ms is how long it may take, or a
|
|
704
852
|
// function giving the time it must hold by
|
|
@@ -718,113 +866,148 @@ export async function startTurn({ agy, home, model, prompt, media = [], tools =
|
|
|
718
866
|
})
|
|
719
867
|
const ready = () => screen.includes(READY) && !screen.includes(BUSY)
|
|
720
868
|
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
869
|
+
// agy started, at its prompt, with the tools listed: what a request
|
|
870
|
+
// waits on before its message is typed (begin)
|
|
871
|
+
const booted = (async () => {
|
|
872
|
+
try {
|
|
873
|
+
if (withTools) {
|
|
874
|
+
// the tool server first: agy reads its config as it starts
|
|
875
|
+
send({ tools })
|
|
876
|
+
try {
|
|
877
|
+
await waitFor("tool server", () => mcp, START_MS)
|
|
878
|
+
} catch (error) {
|
|
879
|
+
if (error.status === 499) throw error
|
|
880
|
+
throw new Failure(501, `this magpie's terminal can't give agy tools (${errorLine || error.message}): update magpie`)
|
|
881
|
+
}
|
|
882
|
+
fs.writeFileSync(path.join(ownHome, ".gemini", "config", "mcp_config.json"), JSON.stringify(mcpConfig(mcp, tools)), { mode: 0o600 })
|
|
730
883
|
}
|
|
731
|
-
|
|
884
|
+
send({ start: { path: agy, args, dir: ws, replies: REPLIES } })
|
|
885
|
+
await waitFor("prompt", ready, START_MS)
|
|
886
|
+
// a message sent before agy listed the tools may find none of them
|
|
887
|
+
if (withTools) await waitFor("tools listed", () => listed, LISTED_MS)
|
|
888
|
+
} catch (error) {
|
|
889
|
+
await cleanup()
|
|
890
|
+
throw error
|
|
732
891
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
892
|
+
})()
|
|
893
|
+
// told to the request that begins, not before
|
|
894
|
+
booted.catch(() => {})
|
|
895
|
+
|
|
896
|
+
// begin types a request into this agy, its files and then its message,
|
|
897
|
+
// and resolves with the turn once agy has it
|
|
898
|
+
const begin = async (req) => {
|
|
899
|
+
prompt = req.prompt
|
|
900
|
+
const media = req.media ?? []
|
|
901
|
+
watch(req.signal)
|
|
902
|
+
try {
|
|
903
|
+
await booted
|
|
904
|
+
} catch (error) {
|
|
905
|
+
error.boot = true
|
|
906
|
+
throw error
|
|
907
|
+
}
|
|
908
|
+
try {
|
|
909
|
+
let files
|
|
742
910
|
try {
|
|
743
|
-
|
|
911
|
+
// the images and videos, in the turn's folder: agy copies each one
|
|
912
|
+
// it attaches into the conversation's own (forget removes it), and
|
|
913
|
+
// the folder goes with the turn
|
|
914
|
+
files = writeMedia(path.join(ws, "attachments"), media)
|
|
744
915
|
} catch (error) {
|
|
745
|
-
|
|
746
|
-
throw new Failure(502, `agy didn't attach the ${files.length === 1 ? kindOf(media[0].type) : `${files.length} files`} (it shows ${attached(screen)})${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
|
|
916
|
+
throw new Failure(500, `agy-tui couldn't ready the turn's folder: ${error.message}`)
|
|
747
917
|
}
|
|
918
|
+
if (files.length) {
|
|
919
|
+
// pasted alone, the paths are attached, as files dragged onto the
|
|
920
|
+
// terminal are; the turn waits until agy shows every one attached,
|
|
921
|
+
// so a path agy took for text is never sent as the message
|
|
922
|
+
send({ write: `\x1b[200~${pastedPaths(files)}\x1b[201~` })
|
|
923
|
+
try {
|
|
924
|
+
await waitFor("attachment", () => attached(screen) >= files.length, attachTimeout())
|
|
925
|
+
} catch (error) {
|
|
926
|
+
if (error.status !== 504) throw error
|
|
927
|
+
throw new Failure(502, `agy didn't attach the ${files.length === 1 ? kindOf(media[0].type) : `${files.length} files`} (it shows ${attached(screen)})${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
send({ write: `\x1b[200~${prompt}\x1b[201~` })
|
|
931
|
+
await new Promise((r) => setTimeout(r, PASTE_SETTLE_MS))
|
|
932
|
+
send({ write: "\r" })
|
|
933
|
+
// agy has the message once it is in a turn, or its transcript has it
|
|
934
|
+
// (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)
|
|
936
|
+
} catch (error) {
|
|
937
|
+
await cleanup()
|
|
938
|
+
throw error
|
|
748
939
|
}
|
|
749
|
-
send({ write: `\x1b[200~${prompt}\x1b[201~` })
|
|
750
|
-
await new Promise((r) => setTimeout(r, PASTE_SETTLE_MS))
|
|
751
|
-
send({ write: "\r" })
|
|
752
|
-
// agy has the message once it is in a turn, or its transcript has it
|
|
753
|
-
// (a turn that failed at once may never draw "esc to cancel")
|
|
754
|
-
await waitFor("turn", () => screen.includes(BUSY) || Boolean(answerOf(brain, before, prompt)), SUBMIT_MS)
|
|
755
|
-
} catch (error) {
|
|
756
|
-
await cleanup()
|
|
757
|
-
throw error
|
|
758
|
-
}
|
|
759
940
|
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
941
|
+
const turn = {
|
|
942
|
+
live,
|
|
943
|
+
// the reply's text and thinking the client has had, in the responses
|
|
944
|
+
// before this one
|
|
945
|
+
sent: "",
|
|
946
|
+
thought: "",
|
|
947
|
+
ended: false,
|
|
948
|
+
next: async () => {
|
|
949
|
+
while (!stops.length) await new Promise((r) => { wake = r })
|
|
950
|
+
return stops.shift()
|
|
951
|
+
},
|
|
952
|
+
// reply answers a call agy waits on; false when it waits no more
|
|
953
|
+
reply: (id, content, isError = false) => {
|
|
954
|
+
if (!pending.delete(id)) return false
|
|
955
|
+
send({ result: { id, content, isError } })
|
|
956
|
+
return true
|
|
957
|
+
},
|
|
958
|
+
watch,
|
|
959
|
+
close: () => cleanup(),
|
|
960
|
+
}
|
|
780
961
|
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
}
|
|
797
|
-
if (!ready()) {
|
|
798
|
-
idleSince = 0
|
|
799
|
-
if (Date.now() - polled >= LIVE_POLL_MS) {
|
|
800
|
-
polled = Date.now()
|
|
801
|
-
if (!found?.id) look()
|
|
802
|
-
if (found?.id) publish(liveReply(home, found.id))
|
|
962
|
+
;(async () => {
|
|
963
|
+
let last
|
|
964
|
+
let polled = 0
|
|
965
|
+
// a turn waiting on the client's tool has no clock: the time is the
|
|
966
|
+
// client's (a parked turn has its own, parkTimeout)
|
|
967
|
+
let until = Date.now() + turnTimeout()
|
|
968
|
+
try {
|
|
969
|
+
// back at its prompt with nothing in the transcript for a while:
|
|
970
|
+
// the turn failed, and what agy drew says why (a quota, a refusal)
|
|
971
|
+
let idleSince = 0
|
|
972
|
+
await waitFor("answer", () => {
|
|
973
|
+
if (pending.size) {
|
|
974
|
+
until = Date.now() + turnTimeout()
|
|
975
|
+
idleSince = 0
|
|
976
|
+
return false
|
|
803
977
|
}
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
978
|
+
if (!ready()) {
|
|
979
|
+
idleSince = 0
|
|
980
|
+
if (Date.now() - polled >= LIVE_POLL_MS) {
|
|
981
|
+
polled = Date.now()
|
|
982
|
+
if (!found?.id) look()
|
|
983
|
+
if (found?.id) publish(liveReply(home, found.id))
|
|
984
|
+
}
|
|
985
|
+
return false
|
|
986
|
+
}
|
|
987
|
+
look()
|
|
988
|
+
if (found?.answer) return true
|
|
989
|
+
idleSince ||= Date.now()
|
|
990
|
+
return Date.now() - idleSince > IDLE_MS
|
|
991
|
+
}, () => until)
|
|
992
|
+
if (!found?.answer) throw new Failure(502, `agy answered nothing${screenTail(screen) ? `:\n${screenTail(screen)}` : ""}`)
|
|
993
|
+
// the whole of it, read before the conversation goes
|
|
994
|
+
publish(liveReply(home, found.id))
|
|
995
|
+
last = { text: found.answer, usage: await spent() }
|
|
996
|
+
} catch (error) {
|
|
997
|
+
last = { error }
|
|
998
|
+
} finally {
|
|
999
|
+
// the end is told at once: agy's exit can wait on its own network
|
|
1000
|
+
// (a telemetry flush on the way out), and the client needn't. The
|
|
1001
|
+
// turn's files go after, once agy has.
|
|
1002
|
+
turn.ended = true
|
|
1003
|
+
watch(null)
|
|
1004
|
+
stop(last)
|
|
1005
|
+
await leaving(cleanup().then(() => forget(brain, found?.id)))
|
|
1006
|
+
}
|
|
1007
|
+
})()
|
|
1008
|
+
return turn
|
|
1009
|
+
}
|
|
1010
|
+
return { begin, alive: () => !ended && !cleaned, close: () => cleanup() }
|
|
828
1011
|
}
|
|
829
1012
|
|
|
830
1013
|
// ---- turns waiting on the client's tool
|
|
@@ -917,13 +1100,14 @@ function stopped(turn, call) {
|
|
|
917
1100
|
park(call.id, turn)
|
|
918
1101
|
}
|
|
919
1102
|
|
|
920
|
-
function completion(id, model, message, finish) {
|
|
1103
|
+
function completion(id, model, message, finish, usage = null) {
|
|
921
1104
|
return {
|
|
922
1105
|
id,
|
|
923
1106
|
object: "chat.completion",
|
|
924
1107
|
created: Math.floor(Date.now() / 1000),
|
|
925
1108
|
model,
|
|
926
1109
|
choices: [{ index: 0, message: { role: "assistant", ...message }, finish_reason: finish }],
|
|
1110
|
+
...(usage ? { usage } : {}),
|
|
927
1111
|
}
|
|
928
1112
|
}
|
|
929
1113
|
|
|
@@ -936,9 +1120,9 @@ async function answered(id, model, turn) {
|
|
|
936
1120
|
if (s.call) {
|
|
937
1121
|
const text = since(turn, turn.live.text)
|
|
938
1122
|
stopped(turn, s.call)
|
|
939
|
-
return completion(id, model, { content: text || null, ...reasoning, tool_calls: [toolCallOf(s.call)] }, "tool_calls")
|
|
1123
|
+
return completion(id, model, { content: text || null, ...reasoning, tool_calls: [toolCallOf(s.call)] }, "tool_calls", s.usage)
|
|
940
1124
|
}
|
|
941
|
-
return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop")
|
|
1125
|
+
return completion(id, model, { content: turn.sent ? since(turn, turn.live.text) || s.text : s.text, ...reasoning }, "stop", s.usage)
|
|
942
1126
|
}
|
|
943
1127
|
|
|
944
1128
|
// streamOf sends the turn's reply up to its next stop as agy's model
|
|
@@ -949,7 +1133,7 @@ export function streamOf(id, model, turn) {
|
|
|
949
1133
|
const { live } = turn
|
|
950
1134
|
const enc = new TextEncoder()
|
|
951
1135
|
const created = Math.floor(Date.now() / 1000)
|
|
952
|
-
const chunk = (delta, finish = null) => `data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`
|
|
1136
|
+
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`
|
|
953
1137
|
let keep
|
|
954
1138
|
let listen
|
|
955
1139
|
let quiet = 0
|
|
@@ -998,10 +1182,10 @@ export function streamOf(id, model, turn) {
|
|
|
998
1182
|
if (s.call) {
|
|
999
1183
|
stopped(turn, s.call)
|
|
1000
1184
|
c.enqueue(enc.encode(chunk({ tool_calls: [toolCallOf(s.call, 0)] })))
|
|
1001
|
-
c.enqueue(enc.encode(chunk({}, "tool_calls")))
|
|
1185
|
+
c.enqueue(enc.encode(chunk({}, "tool_calls", s.usage)))
|
|
1002
1186
|
} else {
|
|
1003
1187
|
if (!sent && s.text) c.enqueue(enc.encode(chunk({ content: s.text })))
|
|
1004
|
-
c.enqueue(enc.encode(chunk({}, "stop")))
|
|
1188
|
+
c.enqueue(enc.encode(chunk({}, "stop", s.usage)))
|
|
1005
1189
|
}
|
|
1006
1190
|
} catch (error) {
|
|
1007
1191
|
c.enqueue(enc.encode(`data: ${JSON.stringify({ error: { message: error.message, type: "agy_tui_error" } })}\n\n`))
|
|
@@ -1082,7 +1266,7 @@ export function modelEntry(m) {
|
|
|
1082
1266
|
name: m.name,
|
|
1083
1267
|
npm: NPM,
|
|
1084
1268
|
api: { id: m.id, url: "agy-tui://local", npm: NPM },
|
|
1085
|
-
limit: { context:
|
|
1269
|
+
limit: { context: CONTEXT, output: 65_536 },
|
|
1086
1270
|
// Gemini's and Claude's see the images agy attaches, as agy-cli says,
|
|
1087
1271
|
// and Gemini's the videos too
|
|
1088
1272
|
...(/^(?: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
|
@@ -162,3 +162,116 @@ export function liveReply(home, id) {
|
|
|
162
162
|
export function liveText(home, id) {
|
|
163
163
|
return liveReply(home, id)?.text ?? null
|
|
164
164
|
}
|
|
165
|
+
|
|
166
|
+
// ---- what each model call cost
|
|
167
|
+
//
|
|
168
|
+
// agy writes a model call's token counts to the same store: a row of
|
|
169
|
+
// gen_metadata when the call ends (the usage message at field 1.4 of
|
|
170
|
+
// `data`), and, in older stores, field 9 of a finished (status 3)
|
|
171
|
+
// PLANNER_RESPONSE step's `metadata`. Either message has 2 the uncached
|
|
172
|
+
// input, 3 the output (thinking included), 4 the cache write, 5 the cache
|
|
173
|
+
// read, 9 the thinking. One table is read for a conversation, never both:
|
|
174
|
+
// they hold the same calls. (Layout as agy-cli's step-usage.mjs reads it.)
|
|
175
|
+
|
|
176
|
+
const STEP_DONE = 3
|
|
177
|
+
const count = (n) => Number.isSafeInteger(n) && n > 0 ? n : 0
|
|
178
|
+
|
|
179
|
+
function counts(buf) {
|
|
180
|
+
const u = { input: 0, output: 0, write: 0, read: 0, thinking: 0 }
|
|
181
|
+
const ok = fields(buf, (f, w, n) => {
|
|
182
|
+
if (w !== 0) return
|
|
183
|
+
if (f === 2) u.input = count(n)
|
|
184
|
+
else if (f === 3) u.output = count(n)
|
|
185
|
+
else if (f === 4) u.write = count(n)
|
|
186
|
+
else if (f === 5) u.read = count(n)
|
|
187
|
+
else if (f === 9) u.thinking = count(n)
|
|
188
|
+
})
|
|
189
|
+
return ok ? u : null
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// generationUsage is a gen_metadata row's counts, null with none.
|
|
193
|
+
export function generationUsage(data) {
|
|
194
|
+
const buf = bytesOf(data)
|
|
195
|
+
if (!buf) return null
|
|
196
|
+
let u = null
|
|
197
|
+
if (!fields(buf, (f, w, chat) => {
|
|
198
|
+
if (f !== 1 || w !== 2) return
|
|
199
|
+
fields(chat, (g, gw, v) => { if (g === 4 && gw === 2) u = counts(v) })
|
|
200
|
+
})) return null
|
|
201
|
+
return u && u.input + u.output + u.write + u.read + u.thinking ? u : null
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// stepUsage is a finished step's counts from its metadata, null with none.
|
|
205
|
+
export function stepUsage(metadata) {
|
|
206
|
+
const buf = bytesOf(metadata)
|
|
207
|
+
if (!buf) return null
|
|
208
|
+
let u = null
|
|
209
|
+
if (!fields(buf, (f, w, v) => { if (f === 9 && w === 2) u = counts(v) })) return null
|
|
210
|
+
return u && u.input + u.output + u.write + u.read + u.thinking ? u : null
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const rowsOf = (db, sql) => {
|
|
214
|
+
try { return db.all(sql) } catch (e) {
|
|
215
|
+
if (/no such table|no such column/i.test(String(e?.message ?? ""))) return null
|
|
216
|
+
throw e
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// callsAfter is the model calls the conversation id has made since
|
|
221
|
+
// cursor ({ source, idx }; null for none read yet), oldest first, and the
|
|
222
|
+
// cursor past them: { calls: [{ input, output, write, read, thinking }],
|
|
223
|
+
// cursor }. null when the store can't be read.
|
|
224
|
+
export function callsAfter(home, id, cursor = null) {
|
|
225
|
+
const file = conversationDb(home, id)
|
|
226
|
+
if (!file || !fs.existsSync(file)) return null
|
|
227
|
+
const open = loadOpener()
|
|
228
|
+
if (!open) return null
|
|
229
|
+
let db
|
|
230
|
+
try {
|
|
231
|
+
db = open(file)
|
|
232
|
+
const read = (source) => {
|
|
233
|
+
const after = cursor?.source === source ? cursor.idx : -1
|
|
234
|
+
const rows = source === "gen_metadata"
|
|
235
|
+
? rowsOf(db, `SELECT idx, data AS v FROM gen_metadata WHERE idx > ${Number(after)} ORDER BY idx`)
|
|
236
|
+
: 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`)
|
|
237
|
+
if (!rows) return null
|
|
238
|
+
const calls = []
|
|
239
|
+
let idx = after
|
|
240
|
+
for (const row of rows) {
|
|
241
|
+
const u = source === "gen_metadata" ? generationUsage(row.v) : stepUsage(row.v)
|
|
242
|
+
if (!u) continue
|
|
243
|
+
calls.push(u)
|
|
244
|
+
idx = Math.max(idx, Number(row.idx))
|
|
245
|
+
}
|
|
246
|
+
return { calls, cursor: { source, idx } }
|
|
247
|
+
}
|
|
248
|
+
if (cursor?.source) return read(cursor.source)
|
|
249
|
+
const gen = read("gen_metadata")
|
|
250
|
+
if (gen?.calls.length) return gen
|
|
251
|
+
const steps = read("steps")
|
|
252
|
+
if (steps?.calls.length) return steps
|
|
253
|
+
return { calls: [], cursor: null }
|
|
254
|
+
} catch {
|
|
255
|
+
return null
|
|
256
|
+
} finally {
|
|
257
|
+
try { db?.close() } catch {}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// usageOf is calls as an OpenAI usage: the prompt the last call sent
|
|
262
|
+
// (uncached, cache read and cache write), every call's output; null for
|
|
263
|
+
// no calls.
|
|
264
|
+
export function usageOf(calls) {
|
|
265
|
+
if (!calls?.length) return null
|
|
266
|
+
const last = calls.at(-1)
|
|
267
|
+
const prompt = last.input + last.read + last.write
|
|
268
|
+
const completion = calls.reduce((n, c) => n + c.output, 0)
|
|
269
|
+
const thinking = calls.reduce((n, c) => n + c.thinking, 0)
|
|
270
|
+
return {
|
|
271
|
+
prompt_tokens: prompt,
|
|
272
|
+
completion_tokens: completion,
|
|
273
|
+
total_tokens: prompt + completion,
|
|
274
|
+
prompt_tokens_details: { cached_tokens: last.read },
|
|
275
|
+
completion_tokens_details: { reasoning_tokens: thinking },
|
|
276
|
+
}
|
|
277
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-agy-tui-auth",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
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",
|