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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -10,6 +10,7 @@ Antigravity's models through agy's own interactive mode (its TUI). Each request
10
10
  2. Install this plugin from magpie's Plugins page, add **Antigravity (agy TUI)** under Providers and pick "Sign in with Google": magpie opens agy's sign-in link, and you paste back the code the page shows.
11
11
  3. The models are the ones `agy models` lists: asked at sign-in and kept in the account's folder, and asked again only when you refresh the list.
12
12
  4. A model `agy models` lists at several thinking levels (`claude-opus-5-5-low`, `-medium`, `-high`) is listed once, as `claude-opus-5-5`, with its levels as variants. A request runs agy at the level the agent asks for (its reasoning effort or thinking level; the nearest the model has, the higher of two as near), and at `high` when it asks none, which is what Antigravity itself starts a model on (or the highest level, for a model without `high`). A level's own id, picked or set in an agent or routing group before, still works and runs that level. A model at one level, and Orchestrator, are listed as agy lists them. The list folds the next time it is asked (sign-in or refresh).
13
+ 5. Quota: when you refresh the account's quota card or row in magpie, the plugin reads it with agy's own `agy usage --output-format json` (agy 1.5.22 and later) in the account's home, as the agy-cli plugin reads it: each pool's (Gemini, Claude & GPT) 5-hour and 7-day windows, and the pool each model draws on. magpie never reads it on its own. An older agy is told to update (`agy update`), never read through print mode.
13
14
 
14
15
  Each account has a home of its own (`~/.local/state/magpie-agy-tui/accounts/<id>`), where agy keeps its sign-in as a file. Your own `~/.gemini`, skills and MCP servers are neither used nor changed.
15
16
 
@@ -24,11 +25,11 @@ A request's tools (`tools`, function tools) are given to the model through magpi
24
25
  - Images (PNG, JPEG, GIF, WebP, BMP, TIFF, SVG; up to 10 MB each) and videos (MP4, MOV, WebM, AVI; up to 50 MB each), sent inline as a data: URL, go to agy as attachments, the way a file dragged into its prompt does: what agy 1.5.19's prompt attaches, at its own size limits. Images work with Gemini and Claude models, videos with Gemini models. Each file is written to the turn's folder and deleted with it.
25
26
  - Anything else agy's prompt doesn't attach, so it is refused (400) with what it was, never dropped: a PDF, audio, a text or code file, a HEIC, a link to a file instead of the file itself, and a video for a Claude model.
26
27
  - A chat goes on in agy's own conversation. A turn that answers keeps its agy conversation, and the chat's next request (the same messages, that answer, then the user's new ones) carries it on with `--conversation`, typing in only the new messages; the model gets the chat's earlier turns as turns, whole, however long the chat has grown, and agy compacts the conversation itself when it gets too long. Any other request starts a new agy conversation, with the chat before its last message pasted in as text: a new chat, one the client compacted, edited or forked, an answer the client changed, a system message after the answer, and a tool call's result, which goes on in the agy that made the call. A conversation is kept for 24 hours after its last answer, 32 for each account (the oldest go first); the list of them, in the account's folder (`agy-tui-conversations.json`), holds hashes and agy's ids, no words. A chat whose instructions change on each request is always pasted whole.
27
- - 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).
28
- - The models say a context of 64K tokens (about what fits in agy's message, with agy's own ~10K of instructions), and each response has the usage agy recorded (`usage`: the call's input, cache read and write, and every call's output and thinking), so an agent compacts its conversation before a request that pastes it whole would be cut.
28
+ - agy takes up to 192,000 bytes in a message and puts `<truncated N bytes>` for the rest. A chat that fits in 180,000 bytes is pasted as one message. A longer one, or one whose newest message alone is longer, is written into agy's own conversation store as a conversation (every earlier turn a step, a long user's message as several in a row), agy is started with it (`--conversation`), and only the newest message is typed. agy sends those steps to the model as the turns they are, so nothing is left out, whatever the chat's length. It needs an agy with `--conversation` (1.5.20 or later) and SQLite in the plugin host (Bun's or Node's). Without them, or with `AGY_TUI_SEED=0`, or if agy doesn't take the conversation (its log says so), the chat is pasted as before: the last message whole, then the instructions, then the conversation from its newest turn back; the oldest turns that don't fit are left out, with a line that says so. A last message over 180,000 bytes alone is then refused (400).
29
+ - Each model says its own window in agy: 1,048,576 tokens for Gemini, 1,000,000 for Claude Opus and Sonnet 5.5, 250,000 for Claude 4.6, 131,072 for GPT-OSS 120B (64K, one message's worth, until 0.1.16). agy compacts a conversation by that window itself. Each response has the usage agy recorded (`usage`: the call's input, cache read and write, and every call's output and thinking).
29
30
  - A streamed request gets the answer as the model writes it: agy commits each piece of the reply to its own conversation store (`conversations/<id>.db`), and the plugin reads what is new, read-only. When the store can't be read, the answer comes whole when the turn ends. The model's thinking (agy asks Gemini for it) comes the same way, as `reasoning_content`, before the answer; not streamed, it is the message's `reasoning_content`. The response ends when the answer is whole, without waiting for agy to exit (it sends its own telemetry on the way out).
30
31
  - agy takes seconds to start (signed in with Google, it asks Google for the account, its plan and its models before it takes a message), so each request leaves an agy started, at its prompt, for the next request with the same account, model and tools, which only types its message into it, and a turn that keeps its conversation leaves one with that conversation for the chat's next request. One waits for each such kind (three at most), for 10 minutes at most; `AGY_TUI_SPARES=0` starts each request's agy when it comes instead.
31
- - It needs magpie 0.1.5537 or newer (`tui-helper` and its tool server came in 0.1.5217; 0.1.5537 keeps the old per-level model ids working); an older magpie is told which version the magpie running the plugin needs when a request has tools (as a Remote magpie, the server's; a Docker image never updates itself, while its plugins update every hour). Not yet tried on Windows.
32
+ - It needs magpie 0.1.5538 or newer (`tui-helper` and its tool server came in 0.1.5217; 0.1.5537 keeps the old per-level model ids working, 0.1.5538 reads the quota when you refresh it); an older magpie is told which version the magpie running the plugin needs when a request has tools (as a Remote magpie, the server's; a Docker image never updates itself, while its plugins update every hour). Not yet tried on Windows.
32
33
 
33
34
  ## Options (environment)
34
35
 
package/README.md CHANGED
@@ -10,6 +10,7 @@
10
10
  2. 在 magpie 的插件页安装本插件,然后在 Providers 里添加 **Antigravity (agy TUI)**,选「使用 Google 登录」:magpie 打开 agy 的登录链接,把页面上显示的代码粘贴回来即可。
11
11
  3. 模型列表来自 `agy models`:登录时问一次,存在账号目录里,之后只在你刷新列表时再问。
12
12
  4. `agy models` 里按思考档位分成几个的模型(`claude-opus-5-5-low`、`-medium`、`-high`)只列一次,即 `claude-opus-5-5`,档位作为它的 variants。请求按 agent 要的档位(reasoning effort 或 thinking level;模型没有这一档时取最接近的,一样近取高的)运行 agy;没说档位时用 `high`,这是 Antigravity 自己默认的档位(没有 `high` 的模型用最高档)。以前选过、或在 agent、路由组里写的带档位 id 依然可用,跑的还是那一档。只有一个档位的模型和 Orchestrator 照 agy 列出的样子列。下次登录或刷新列表时才会合并。
13
+ 5. 额度:在 magpie 里刷新这个账号的额度卡片或行时,插件用 agy 自己的 `agy usage --output-format json`(agy 1.5.22 起有)在账号的 home 里读出额度,和 agy-cli 插件读法相同:每个池子(Gemini、Claude & GPT)的 5 小时和 7 天窗口,以及各模型对应的池子。magpie 不会自己去读。更旧的 agy 会提示更新(`agy update`),不会改用打印模式。
13
14
 
14
15
  每个账号都有自己的 home(`~/.local/state/magpie-agy-tui/accounts/<id>`),agy 的登录信息以文件形式存在那里。你自己的 `~/.gemini`、skills 和 MCP 服务器都不会被用到,也不会被改动。
15
16
 
@@ -24,11 +25,11 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
24
25
  - 图片(PNG、JPEG、GIF、WebP、BMP、TIFF、SVG,每张不超过 10 MB)和视频(MP4、MOV、WebM、AVI,每个不超过 50 MB)以 data: URL 内联发送,会像拖进 agy 输入框的文件一样作为附件交给 agy:正是 agy 1.5.19 输入框能附加的类型,大小限制也和 agy 自己的一样。图片适用于 Gemini 和 Claude 模型,视频只适用于 Gemini 模型。每个文件写进本轮的临时目录,随目录一起删除。
25
26
  - 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。
26
27
  - 一段对话在 agy 自己的会话里接着进行。一轮得到回答后,会保留它的 agy 会话;这段对话的下一个请求(同样的消息、这条回答,再加上用户的新消息)用 `--conversation` 接着这个会话,只输入新的消息。不管对话已经多长,模型拿到的都是完整的、按轮次组织的之前的对话,会话太长时由 agy 自己压缩。其他请求会开一个新的 agy 会话,把最后一条消息之前的对话整理成文字粘贴进去:新的对话、客户端压缩过、改过或分叉的对话、客户端改过的回答、回答之后出现的系统消息,以及工具调用的结果(它会回到发起调用的那个 agy 里继续)。会话在最后一次回答后保留 24 小时,每个账号最多 32 个(先删最早的);会话列表放在账号目录里(`agy-tui-conversations.json`),只有哈希和 agy 的会话 id,没有对话内容。每次请求系统指令都会变的对话,总是整段粘贴。
27
- - agy 一条消息最多收 192,000 字节,超出部分会被它替换成 `<truncated N bytes>`,模型就看不到最新的消息了。所以粘贴的内容控制在 180,000 字节以内:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。系统指令本身放不下时截短。最后一条消息单独就超过时会被拒绝(400)。
28
- - 模型宣告的上下文是 64K token(大约是 agy 一条消息能放下的量,加上 agy 自己约 10K 的指令),每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考),这样 agent 会在整段粘贴的请求被截断之前压缩对话。
28
+ - agy 一条消息最多收 192,000 字节,超出部分会被替换成 `<truncated N bytes>`。180,000 字节以内的对话作为一条消息粘贴。更长的对话,或者最新一条消息单独就超过的,会写进 agy 自己的会话存储,成为一个会话(之前的每一轮是一个步骤,很长的用户消息拆成连续几个步骤),再用 `--conversation` 启动 agy,只输入最新的消息。agy 会把这些步骤按原本的轮次发给模型,所以不管对话多长都不会丢内容。这需要支持 `--conversation` 的 agy(1.5.20 及以上),以及插件宿主里的 SQLite(Bun 或 Node 自带的)。没有这两样、设置了 `AGY_TUI_SEED=0`,或者 agy 没有接受这个会话(它的日志会写明)时,按原来的方式粘贴:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。此时最后一条消息单独超过 180,000 字节会被拒绝(400)。
29
+ - 每个模型宣告的是它在 agy 里自己的上下文窗口:Gemini 1,048,576 token,Claude Opus 和 Sonnet 5.5 1,000,000,Claude 4.6 250,000,GPT-OSS 120B 131,072(0.1.16 之前是一条消息能放下的 64K)。会话超出窗口时由 agy 自己压缩。每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考)。
29
30
  - 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。模型的思考(agy 向 Gemini 要了思考内容)同样边生成边作为 `reasoning_content` 返回,在回答之前;非流式时放在消息的 `reasoning_content` 里。回答写完就结束响应,不等 agy 退出(它退出前会先发完自己的遥测)。
30
31
  - agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。保留了会话的一轮,还会为这段对话的下一个请求预先启动一个带着这个会话的 agy。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
31
- - 需要 magpie 0.1.5537 或更新(`tui-helper` 及其工具服务器从 0.1.5217 起有;0.1.5537 让按档位区分的旧模型 id 继续可用);magpie 太旧时,带工具的请求会说明运行这个插件的 magpie 需要哪个版本(作为远程 magpie 使用时是服务器上的那个;Docker 镜像不会自己更新,插件却每小时更新)。Windows 尚未测试。
32
+ - 需要 magpie 0.1.5538 或更新(`tui-helper` 及其工具服务器从 0.1.5217 起有;0.1.5537 让按档位区分的旧模型 id 继续可用,0.1.5538 在你刷新时读额度);magpie 太旧时,带工具的请求会说明运行这个插件的 magpie 需要哪个版本(作为远程 magpie 使用时是服务器上的那个;Docker 镜像不会自己更新,插件却每小时更新)。Windows 尚未测试。
32
33
 
33
34
  ## 选项(环境变量)
34
35
 
package/account.mjs ADDED
@@ -0,0 +1,21 @@
1
+ // The account whose usage report is being read (usage.mjs). model-ids.mjs,
2
+ // a copy of agy-cli's, keeps the catalog it names a report's windows by
3
+ // under currentHome(), which in agy-cli is the account agy is on; here it
4
+ // is the account home being read, set only around the parse (inAccount),
5
+ // which runs to its end without waiting, so two accounts read at once never
6
+ // see each other's catalog.
7
+ let reading = null
8
+
9
+ export function currentHome() {
10
+ return reading
11
+ }
12
+
13
+ export function inAccount(home, fn) {
14
+ const was = reading
15
+ reading = home
16
+ try {
17
+ return fn()
18
+ } finally {
19
+ reading = was
20
+ }
21
+ }
package/agy-version.mjs CHANGED
@@ -2,12 +2,28 @@
2
2
  // Default-agent instructions and hooks were verified on agy 1.5.19.
3
3
  export const MIN_AGY_VERSION = "1.5.19"
4
4
 
5
+ // agy 1.5.22 added `agy usage`, which reads the account quota without print
6
+ // mode. Older agy still needs `agy -p /usage`.
7
+ export const USAGE_SUBCOMMAND_AGY_VERSION = "1.5.22"
8
+
9
+ const parseVersion = value => /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value ?? "").trim())?.slice(1).map(Number)
10
+
11
+ export function agyHasUsageSubcommand(version) {
12
+ const have = parseVersion(version)
13
+ if (!have) return false
14
+ const need = parseVersion(USAGE_SUBCOMMAND_AGY_VERSION)
15
+ for (let i = 0; i < 3; i++) {
16
+ if (have[i] > need[i]) return true
17
+ if (have[i] < need[i]) return false
18
+ }
19
+ return true
20
+ }
21
+
5
22
  export function agyTooOld(version) {
6
- const parse = value => /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(value ?? "").trim())?.slice(1).map(Number)
7
- const have = parse(version)
23
+ const have = parseVersion(version)
8
24
  // An ACP peer can omit its version. Keep the existing handshake behavior.
9
25
  if (!have) return null
10
- const need = parse(MIN_AGY_VERSION)
26
+ const need = parseVersion(MIN_AGY_VERSION)
11
27
  for (let i = 0; i < 3; i++) {
12
28
  if (have[i] > need[i]) return null
13
29
  if (have[i] < need[i]) return `agy ${version} is older than ${MIN_AGY_VERSION}, the oldest version this plugin was checked on. Update agy.`
package/index.mjs CHANGED
@@ -5,10 +5,12 @@ 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
- import { agyTooOld, MIN_AGY_VERSION, oldAgyError } from "./agy-version.mjs"
8
+ import { agyHasUsageSubcommand, agyTooOld, MIN_AGY_VERSION, oldAgyError, USAGE_SUBCOMMAND_AGY_VERSION } from "./agy-version.mjs"
9
9
  import { liveReply, callsAfter, usageOf, lastStep } from "./live.mjs"
10
+ import { canSeed, chunks, resumed, writeConversation } from "./seed.mjs"
10
11
  import { mcpToolsOf } from "./tools.mjs"
11
12
  import { agyModelOf, foldModels } from "./efforts.mjs"
13
+ import { readUsage } from "./usage.mjs"
12
14
 
13
15
  // agy-tui: Antigravity's models through agy's own interactive mode. Each
14
16
  // request starts the real `agy` TUI in a terminal magpie gives it (`magpie
@@ -79,6 +81,9 @@ const PASTE_SETTLE_MS = 300
79
81
  const IDLE_MS = 5_000
80
82
  // how often a running turn's reply is read from agy's store (live.mjs)
81
83
  const LIVE_POLL_MS = 100
84
+ // how many LIVE_POLL_MS a turn that starts with a conversation waits for
85
+ // agy's log to say whether it took it
86
+ const RESUME_TRIES = 20
82
87
  // how long agy waits for a call of the caller's tool, which the client
83
88
  // runs: as long as a turn waits for its result (parkTimeout) and more
84
89
  const MCP_CALL_SECONDS = 3600
@@ -426,11 +431,19 @@ function partsOf(content, media) {
426
431
  // long paste and never its end, the newest message. What turnOf pastes is
427
432
  // held under INPUT_BUDGET, the margin for what agy adds around it.
428
433
  export const INPUT_BUDGET = 180_000
429
- // the context the models say they have: what fits in INPUT_BUDGET, with
430
- // agy's own instructions (about 10k tokens) on top, so an agent compacts
431
- // its conversation before agy would cut it. Gemini's own window is larger,
432
- // but agy takes no more than this in a message.
433
- export const CONTEXT = 64_000
434
+ // the context a model says it has: its own window in agy (agy-cli's
435
+ // table, from Antigravity's own model list). A chat longer than one
436
+ // message takes goes to agy as a conversation of its own (seedOf), each
437
+ // turn whole, so the window is the model's, not one message's (64K until
438
+ // 0.1.16; baranwang on X).
439
+ export const CONTEXT = 1_048_576
440
+ export function contextOf(id) {
441
+ const family = String(id ?? "").replace(/-(?:minimal|low|medium|high|xhigh|max)$/i, "")
442
+ if (/^claude-(?:opus|sonnet)-4-6(?:-thinking)?$/i.test(family)) return 250_000
443
+ if (/^claude-/i.test(family)) return 1_000_000
444
+ if (/^gpt-oss-120b$/i.test(family)) return 131_072
445
+ return CONTEXT
446
+ }
434
447
  const bytes = (s) => Buffer.byteLength(s)
435
448
 
436
449
  // turnOf is what goes into agy's prompt: the images and videos, attached in
@@ -480,7 +493,10 @@ export function turnOf(messages, budget = INPUT_BUDGET) {
480
493
  const bare = turns.length === 1 && turns[0].role === "user"
481
494
  const lastText = bare ? turns[0].text : said(turns.at(-1))
482
495
  if (bytes(lastText) > budget) {
483
- throw refuse(`the last message is ${bytes(lastText)} bytes, more than agy takes in one message (${budget}): send less of it at once`)
496
+ const error = refuse(`the last message is ${bytes(lastText)} bytes, more than agy takes in one message (${budget}): send less of it at once`)
497
+ // seedOf takes the chat as a conversation instead
498
+ error.long = true
499
+ throw error
484
500
  }
485
501
  // what is left once the last message and the parts' blank lines are in
486
502
  const earlier = turns.slice(0, -1)
@@ -505,14 +521,16 @@ export function turnOf(messages, budget = INPUT_BUDGET) {
505
521
  const kept = new Set([...earlier.slice(from), turns.at(-1)].map((t) => t.m))
506
522
  const media = []
507
523
  ;({ system, turns } = read(messages.filter((m) => m?.role === "system" || m?.role === "developer" || kept.has(m)), media))
508
- if (bare && !system.length) return { prompt: turns[0].text, media }
524
+ // cut: something of the chat is left out
525
+ const cut = cutInstructions || from > 0
526
+ if (bare && !system.length) return { prompt: turns[0].text, media, cut }
509
527
  const parts = []
510
528
  if (system.length) parts.push(cutInstructions ? instructions : system.join("\n\n"))
511
529
  const before = turns.slice(0, -1).map(said)
512
530
  if (from > 0) before.unshift(`[${from} earlier message${from === 1 ? " is" : "s are"} left out here: the conversation is longer than one message takes]`)
513
531
  if (before.length) parts.push(before.join("\n\n"))
514
532
  parts.push(bare ? turns[0].text : said(turns.at(-1)))
515
- return { prompt: parts.join("\n\n"), media }
533
+ return { prompt: parts.join("\n\n"), media, cut }
516
534
  }
517
535
 
518
536
  // promptOf is the text turnOf pastes.
@@ -520,6 +538,77 @@ export function promptOf(messages) {
520
538
  return turnOf(messages).prompt
521
539
  }
522
540
 
541
+ // what ends a user's step a message too long for one goes on from
542
+ const GOES_ON = "\n\n[continued in the next message]"
543
+
544
+ // seedSteps is a chat as the steps of an agy conversation (seed.mjs) and
545
+ // the message typed into it: the instructions and the turns before the
546
+ // newest message as steps, the user's and the tool results in a row as
547
+ // one user's step, each assistant's words and calls (written in as turnOf
548
+ // writes them) as the model's; the newest message, the user's or the tool
549
+ // results after the last answer, typed. A user's step over budget goes as
550
+ // several in a row, each but the last saying the next goes on with it, a
551
+ // newest message over budget too, its last part typed. The images and
552
+ // videos are attached to the typed message, numbered in the order they
553
+ // came, as their marks in the steps say.
554
+ export function seedSteps(messages, budget = INPUT_BUDGET) {
555
+ if (!Array.isArray(messages) || !messages.length) throw refuse("no messages")
556
+ const media = []
557
+ const system = []
558
+ const groups = []
559
+ const add = (role, text) => {
560
+ const g = groups.at(-1)
561
+ if (g?.role === role) g.text += `\n\n${text}`
562
+ else groups.push({ role, text })
563
+ }
564
+ for (const m of messages) {
565
+ if (m?.role === "system" || m?.role === "developer") {
566
+ const text = partsOf(m?.content, media).trim()
567
+ if (text) system.push(text)
568
+ } else if (m?.role === "user") {
569
+ const text = partsOf(m?.content, media).trim()
570
+ if (text) add("user", text)
571
+ } else if (m?.role === "assistant") {
572
+ const said = [partsOf(m?.content, media).trim()]
573
+ if (Array.isArray(m.tool_calls)) {
574
+ for (const c of m.tool_calls) said.push(`[called ${c?.function?.name ?? "a tool"} ${c?.function?.arguments || "{}"} as ${c?.id ?? "a call"}]`)
575
+ }
576
+ const text = said.filter(Boolean).join("\n")
577
+ if (text) add("model", text)
578
+ } else if (m?.role === "tool") {
579
+ add("user", `[result of ${m.tool_call_id ?? "a call"}]\n${partsOf(m?.content, media).trim()}`)
580
+ }
581
+ }
582
+ if (groups.at(-1)?.role !== "user") throw refuse("the last message is not the user's or a tool's result")
583
+ const instructions = system.join("\n\n")
584
+ if (instructions) {
585
+ if (groups[0].role === "user") groups[0].text = `${instructions}\n\n${groups[0].text}`
586
+ else groups.unshift({ role: "user", text: instructions })
587
+ }
588
+ const users = (text) => chunks(text, budget - bytes(GOES_ON)).map((c, i, all) => (i < all.length - 1 ? c + GOES_ON : c))
589
+ const steps = []
590
+ const newest = groups.pop()
591
+ for (const g of groups) {
592
+ if (g.role === "model") steps.push(g)
593
+ else for (const text of users(g.text)) steps.push({ role: "user", text })
594
+ }
595
+ const typed = users(newest.text)
596
+ const prompt = typed.pop()
597
+ for (const text of typed) steps.push({ role: "user", text })
598
+ return { steps, prompt, media }
599
+ }
600
+
601
+ // seedOf is a chat too long for one message (turnOf would leave some of it
602
+ // out, or its newest message is longer than one) written as a conversation
603
+ // of the account's agy, for a turn to start with: { id, prompt, media,
604
+ // seeded }, or null when no store can be written here.
605
+ export function seedOf(home, messages) {
606
+ if (!canSeed()) return null
607
+ const { steps, prompt, media } = seedSteps(messages)
608
+ const id = writeConversation(home, steps)
609
+ return id ? { id, prompt, media, seeded: true } : null
610
+ }
611
+
523
612
  // writeMedia writes a turn's images and videos into dir, named in order
524
613
  // (image-1.png, video-1.mp4), and gives their paths.
525
614
  export function writeMedia(dir, media) {
@@ -832,6 +921,7 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
832
921
  const resumable = help.includes("--conversation")
833
922
  if (model) args.push("--model", model)
834
923
  if (conversation) args.push("--conversation", conversation)
924
+ const startedAt = Date.now()
835
925
  const child = spawn(helper, ["tui-helper"], { env: { ...agyEnv(ownHome ?? home), ...hookEnv }, cwd: ws, stdio: ["pipe", "pipe", "pipe"], windowsHide: true })
836
926
  let screen = ""
837
927
  let ended = null
@@ -1009,6 +1099,19 @@ async function launch({ agy, home, model, tools = [], helper = process.env.MAGPI
1009
1099
  throw error
1010
1100
  }
1011
1101
  if (conversation) {
1102
+ // agy that ignored the conversation (its log says it found none) has
1103
+ // started one of its own, which the message would go to without the
1104
+ // chat: the request goes without it (handle). Its log says one or
1105
+ // the other as it starts; one that says neither is let go on.
1106
+ let took = resumed(home, conversation, startedAt)
1107
+ for (let i = 0; took === null && i < RESUME_TRIES; i++) {
1108
+ await new Promise((r) => setTimeout(r, LIVE_POLL_MS))
1109
+ took = resumed(home, conversation, startedAt)
1110
+ }
1111
+ if (took === false) {
1112
+ await cleanup()
1113
+ throw Object.assign(new Failure(502, `agy didn't start with conversation ${conversation}`), { ignored: true })
1114
+ }
1012
1115
  // what the conversation has already, before this turn's message
1013
1116
  from = { id: conversation, line: transcriptLines(brain, conversation) }
1014
1117
  stepBase = lastStep(home, conversation) ?? -1
@@ -1564,13 +1667,39 @@ export async function handle(home, input, init = {}) {
1564
1667
  let carried = null
1565
1668
  try {
1566
1669
  const tools = mcpToolsOf(body)
1670
+ const resumable = (await agyHelp(agy)).includes("--conversation")
1567
1671
  // the chat's conversation, kept from its last answer, goes on with the
1568
- // new messages alone; any other is typed in whole
1569
- carried = (await agyHelp(agy)).includes("--conversation") ? await carriedOn(home, body.messages, { agy, model: agyModel, tools }) : null
1570
- const { prompt, media } = carried ?? turnOf(body.messages)
1571
- // agy attaches a video for any model, but only Gemini's see one
1572
- if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
1573
- turn = await startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: carried?.id ?? null, messages: body.messages })
1672
+ // new messages alone; any other is typed in whole, and one too long
1673
+ // for one message is written into agy's store as a conversation
1674
+ // (seedOf) that the turn starts with, its newest message typed
1675
+ carried = resumable ? await carriedOn(home, body.messages, { agy, model: agyModel, tools }) : null
1676
+ let paste = null
1677
+ if (!carried) {
1678
+ try {
1679
+ paste = turnOf(body.messages)
1680
+ } catch (error) {
1681
+ if (!error.long || !resumable) throw error
1682
+ }
1683
+ if (resumable && (!paste || paste.cut) && process.env.AGY_TUI_SEED !== "0") carried = seedOf(home, body.messages)
1684
+ if (!carried && !paste) paste = turnOf(body.messages)
1685
+ }
1686
+ const start = async (c) => {
1687
+ const { prompt, media } = c ?? paste
1688
+ // agy attaches a video for any model, but only Gemini's see one
1689
+ if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
1690
+ return startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: c?.id ?? null, messages: body.messages })
1691
+ }
1692
+ try {
1693
+ turn = await start(carried)
1694
+ } catch (error) {
1695
+ if (!error.ignored) throw error
1696
+ // an agy that wouldn't start with the conversation: the chat typed
1697
+ // in, as much of it as one message takes
1698
+ forget(brainOf(home), carried.id)
1699
+ carried = null
1700
+ paste ??= turnOf(body.messages)
1701
+ turn = await start(null)
1702
+ }
1574
1703
  } catch (error) {
1575
1704
  // a conversation taken for a turn that never began is in a state
1576
1705
  // nothing knows
@@ -1593,7 +1722,7 @@ export function modelEntry(m) {
1593
1722
  name: m.name,
1594
1723
  npm: NPM,
1595
1724
  api: { id: m.id, url: "agy-tui://local", npm: NPM },
1596
- limit: { context: CONTEXT, output: 65_536 },
1725
+ limit: { context: contextOf(m.id), output: 65_536 },
1597
1726
  ...(m.variants?.length ? { reasoning: true, variants: Object.fromEntries(m.variants.map((e) => [e, { reasoningEffort: e }])), former: m.former ?? [] } : {}),
1598
1727
  // Gemini's and Claude's see the images agy attaches, as agy-cli says,
1599
1728
  // and Gemini's the videos too
@@ -1654,6 +1783,21 @@ export const AgyTuiPlugin = async () => ({
1654
1783
  },
1655
1784
  },
1656
1785
  ],
1786
+ // magpie's usage hook (OpenCode ignores it): the account's quota as
1787
+ // `agy usage` tells it, the agy-cli plugin's read (usage.mjs). magpie
1788
+ // asks it only when the user refreshes the account's card or row.
1789
+ usage: async (getAuth, _provider, { signal } = {}) => {
1790
+ const auth = typeof getAuth === "function" ? await getAuth() : getAuth
1791
+ const home = homeOfAuth(auth)
1792
+ if (!home || !fs.existsSync(tokenFile(home))) return { windows: [], error: "agy-tui: the account's agy is signed out; sign in again", signIn: "expired" }
1793
+ const agy = findAgy()
1794
+ if (!agy) return { windows: [], error: `agy CLI not found on this machine: ${AGY_MANUAL}`, signIn: "kept" }
1795
+ const version = await agyVersion(agy)
1796
+ if (!agyHasUsageSubcommand(version)) {
1797
+ return { windows: [], error: `${version ? `agy ${version}` : "this agy"} has no \`agy usage\`, which came in agy ${USAGE_SUBCOMMAND_AGY_VERSION} and is how the quota is read: update agy (agy update)`, signIn: "kept" }
1798
+ }
1799
+ return readUsage(agy, home, { env: agyEnv(home), list: (modelLists.get(home) ?? readModelList(home))?.list ?? [], signal })
1800
+ },
1657
1801
  loader: async (getAuth) => {
1658
1802
  const auth = typeof getAuth === "function" ? await getAuth() : getAuth
1659
1803
  const home = homeOfAuth(auth)
package/model-ids.mjs ADDED
@@ -0,0 +1,126 @@
1
+ // A copy of packages/agy-cli/model-ids.mjs (each package is published alone):
2
+ // a change to one goes to the other. Here currentHome is the account whose
3
+ // usage is being read (account.mjs).
4
+ import { currentHome } from "./account.mjs"
5
+
6
+ // The runtime catalog `agy models` listed for each account (keyed by
7
+ // currentHome() ?? ""), so usage windows name the ids that account serves
8
+ // without one account's refresh overwriting another's (usage.mjs stays
9
+ // import-free of index.mjs).
10
+ //
11
+ // rows(): [{ id, name, effort? }] — the shape `agy models` parses into
12
+ // (parseAgyModels), the saved catalog, and FALLBACK_MODELS.
13
+ //
14
+ // nameIndex(): display name ("Claude Opus 5.5", case- and space-insensitive)
15
+ // → the family id ("claude-opus-5-5") and every effort variant id agy listed
16
+ // in it, plus the bare family id itself even when agy lists no variant of
17
+ // that name (the catalog serves it as its default).
18
+
19
+ const states = new Map()
20
+
21
+ // Orchestrator is a planner the bridge doesn't serve (index.mjs's
22
+ // orchestratorRefusal): agy lists it, and its usage group names it beside
23
+ // the Gemini models, but no window is made for it. A window of a model the
24
+ // provider never lists is one magpie can't tell the account's picks from
25
+ // (#1891: with the pools' models unpicked, Orchestrator (Argon) was the one
26
+ // window left of the card, and the menu bar showed it alone).
27
+ export function isOrchestrator(model) {
28
+ const id = typeof model === "string" ? model : model?.id ?? ""
29
+ const name = typeof model === "string" ? "" : model?.name ?? ""
30
+ return /^gemini-[a-z0-9.]*-?orchestrator/i.test(id) || /^Orchestrator\b/i.test(name)
31
+ }
32
+
33
+ export function storeCatalogRows(list) {
34
+ const key = currentHome() ?? ""
35
+ const rows = Array.isArray(list) ? list.filter(model => model && typeof model.id === "string" && model.id && !isOrchestrator(model)) : null
36
+ if (!rows) {
37
+ states.delete(key)
38
+ return
39
+ }
40
+ states.set(key, { rows, index: null })
41
+ }
42
+
43
+ export function catalogRows() {
44
+ const rows = states.get(currentHome() ?? "")?.rows
45
+ return rows ? [...rows] : null
46
+ }
47
+
48
+ const normalizeName = (value) => String(value ?? "").trim().toLowerCase().replace(/\s+/g, " ").replace(/[.,;]$/, "")
49
+
50
+ // `agy models` names its variants "Gemini 4 Hydrogen (High)" while usage
51
+ // groups say "Gemini 4 Hydrogen": match on the name without the effort
52
+ // suffix, too, so every variant of a family answers its display name.
53
+ const stripEffortSuffix = (name) => name.replace(/\s+\((?:high|medium|low|minimal|xhigh|max)\)$/i, "")
54
+
55
+ // In "Models within this group: A, B and C", the separator before "and" can
56
+ // be a comma (as agy prints today) or nothing at all.
57
+ function listedNames(description) {
58
+ const listed = /Models within this group:\s*(.+)/i.exec(String(description ?? ""))
59
+ if (!listed) return null
60
+ return listed[1]
61
+ .split(/,|\s+and\s+/i)
62
+ .map(normalizeName)
63
+ .filter(Boolean)
64
+ }
65
+
66
+ export function nameIndex() {
67
+ const state = states.get(currentHome() ?? "")
68
+ if (!state?.rows) return new Map()
69
+ if (state.index) return state.index
70
+ const index = new Map()
71
+ const families = new Map()
72
+ const shown = new Map() // family -> its display name
73
+ const claims = new Map() // display name -> the families that use it
74
+ for (const model of state.rows) {
75
+ const effort = /-(high|medium|low|minimal|xhigh|max)$/i.exec(model.id)?.[1]?.toLowerCase() || ""
76
+ const family = effort ? model.id.slice(0, -(effort.length + 1)) : model.id
77
+ if (!families.has(family)) families.set(family, new Set())
78
+ families.get(family).add(model.id)
79
+ const name = normalizeName(model.name)
80
+ if (!name) continue
81
+ // the family's name as agy shows it, its effort word left off
82
+ if (!shown.has(family)) shown.set(family, stripEffortSuffix(String(model.name).trim().replace(/\s+/g, " ")))
83
+ for (const alias of [name, stripEffortSuffix(name)]) {
84
+ if (!claims.has(alias)) claims.set(alias, new Set())
85
+ claims.get(alias).add(family)
86
+ }
87
+ }
88
+ for (const [family, ids] of families) {
89
+ // the bare id the catalog serves even when agy lists no variant of it
90
+ ids.add(family)
91
+ }
92
+ for (const [name, owners] of claims) {
93
+ // one name, two families: no match, rather than whichever came first
94
+ if (owners.size !== 1) continue
95
+ const [family] = owners
96
+ index.set(name, { family, ids: families.get(family), name: shown.get(family) || family })
97
+ }
98
+ state.index = index
99
+ return index
100
+ }
101
+
102
+ // familiesInGroup answers the model families a usage group covers, each
103
+ // { id, name, ids }: the family id, its display name without the effort
104
+ // word ("Claude Opus 5.5"), and every id of it the catalog serves. Group
105
+ // names are matched against the catalog's display names; a name that
106
+ // matches nothing is left out, as is a group whose description names no
107
+ // model and whose own name isn't a catalog name either.
108
+ export function familiesInGroup(group) {
109
+ const index = nameIndex()
110
+ if (!index.size) return []
111
+ const found = new Map()
112
+ const add = entry => { if (entry && !found.has(entry.family)) found.set(entry.family, entry) }
113
+ for (const name of listedNames(group?.description) || []) add(index.get(name))
114
+ if (!found.size) {
115
+ add(index.get(normalizeName((group?.displayName || group?.display_name || group?.name || "").replace(/\s+models$/i, ""))))
116
+ }
117
+ return [...found.values()].map(e => ({ id: e.family, name: e.name, ids: [...e.ids].sort() }))
118
+ }
119
+
120
+ // modelsInGroup answers the ids to put on a usage window: every id of
121
+ // every family the group covers (familiesInGroup).
122
+ export function modelsInGroup(group) {
123
+ const ids = new Set()
124
+ for (const family of familiesInGroup(group)) for (const id of family.ids) ids.add(id)
125
+ return [...ids].sort()
126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-agy-tui-auth",
3
- "version": "0.1.13",
3
+ "version": "0.1.16",
4
4
  "description": "Magpie/OpenCode model provider that runs Antigravity's models through agy's own interactive mode: each request is typed into the real agy TUI and its answer streamed from agy's own conversation store as the model writes it",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",
@@ -10,6 +10,7 @@
10
10
  "files": [
11
11
  "index.mjs",
12
12
  "live.mjs",
13
+ "seed.mjs",
13
14
  "login.mjs",
14
15
  "default-agent.mjs",
15
16
  "agy-version.mjs",
@@ -20,6 +21,10 @@
20
21
  "array-items.mjs",
21
22
  "tool-budget.mjs",
22
23
  "efforts.mjs",
24
+ "usage.mjs",
25
+ "usage-report.mjs",
26
+ "model-ids.mjs",
27
+ "account.mjs",
23
28
  "opencode.mjs",
24
29
  "opencode2.mjs",
25
30
  "README.md",
@@ -45,7 +50,7 @@
45
50
  "test": "bun test"
46
51
  },
47
52
  "engines": {
48
- "magpie": ">=0.1.5537"
53
+ "magpie": ">=0.1.5538"
49
54
  },
50
55
  "magpie": {
51
56
  "maxConcurrency": 4
package/seed.mjs ADDED
@@ -0,0 +1,195 @@
1
+ // A conversation written into agy's store, for agy to start with
2
+ // (--conversation), so a chat longer than one of agy's messages goes to
3
+ // the model whole, as turns. agy takes no more than 192,000 bytes in a
4
+ // message it is typed, and rebuilds a conversation it starts with from the
5
+ // steps in its store: the user's steps (each held to the same 192,000
6
+ // bytes) and the model's (taken whole), sent to Gemini as the turns they
7
+ // are. So the chat's earlier turns are written there as steps, a user's
8
+ // long message as several in a row, and only its newest message is typed.
9
+ // (The layout is agy 1.5.20's, read from conversations it wrote, and 1.5.23's the same: the
10
+ // tables, the pragmas it checks, user_version 1 above all, without which
11
+ // it takes the store for one never set up and starts a conversation of
12
+ // its own, and each step's fields.)
13
+ import { createRequire } from "node:module"
14
+ import { randomUUID } from "node:crypto"
15
+ import fs from "node:fs"
16
+ import path from "node:path"
17
+
18
+ const require = createRequire(import.meta.url)
19
+ const USER_STEP = 14
20
+ const MODEL_STEP = 15
21
+ const DONE = 3
22
+
23
+ // ---- a minimal protobuf writer: a message is [[field, value], …]; a
24
+ // value is a number (varint), a string or bytes, or an array (a message
25
+ // in it); undefined is left out
26
+
27
+ function varint(n) {
28
+ const out = []
29
+ let v = BigInt(n)
30
+ do {
31
+ let b = Number(v & 0x7fn)
32
+ v >>= 7n
33
+ if (v) b |= 0x80
34
+ out.push(b)
35
+ } while (v)
36
+ return Buffer.from(out)
37
+ }
38
+
39
+ export function encode(msg) {
40
+ const out = []
41
+ for (const [field, v] of msg) {
42
+ if (v === undefined || v === null) continue
43
+ if (typeof v === "number" || typeof v === "bigint") {
44
+ out.push(varint((field << 3) | 0), varint(v))
45
+ continue
46
+ }
47
+ const b = Array.isArray(v) ? encode(v) : Buffer.isBuffer(v) ? v : Buffer.from(String(v))
48
+ out.push(varint((field << 3) | 2), varint(b.length), b)
49
+ }
50
+ return Buffer.concat(out)
51
+ }
52
+
53
+ const stamp = (ms) => [[1, Math.floor(ms / 1000)], [2, (ms % 1000) * 1e6]]
54
+ const hex = () => randomUUID().replace(/-/g, "")
55
+
56
+ // bun:sqlite under Bun (magpie's plugin host), node:sqlite on Node 22.5+;
57
+ // null when neither is there
58
+ let opener
59
+ function loadOpener() {
60
+ if (opener !== undefined) return opener
61
+ opener = null
62
+ try {
63
+ const { Database } = require("bun:sqlite")
64
+ if (typeof Database === "function") {
65
+ opener = (file) => {
66
+ const db = new Database(file, { create: true })
67
+ return {
68
+ exec: (sql) => db.exec(sql),
69
+ run: (sql, ...args) => db.prepare(sql).run(...args),
70
+ close: () => db.close(),
71
+ }
72
+ }
73
+ return opener
74
+ }
75
+ } catch {}
76
+ try {
77
+ const { DatabaseSync } = require("node:sqlite")
78
+ if (typeof DatabaseSync === "function") {
79
+ opener = (file) => {
80
+ const db = new DatabaseSync(file)
81
+ return {
82
+ exec: (sql) => db.exec(sql),
83
+ run: (sql, ...args) => db.prepare(sql).run(...args),
84
+ close: () => db.close(),
85
+ }
86
+ }
87
+ return opener
88
+ }
89
+ } catch {}
90
+ return opener
91
+ }
92
+
93
+ // canSeed is whether a store can be written here
94
+ export function canSeed() {
95
+ return Boolean(loadOpener())
96
+ }
97
+
98
+ const SCHEMA = `CREATE TABLE trajectory_meta (trajectory_id text,cascade_id text,trajectory_type integer,source integer,PRIMARY KEY (trajectory_id));
99
+ CREATE TABLE steps (idx integer,step_type integer NOT NULL DEFAULT 0,status integer NOT NULL DEFAULT 0,has_subtrajectory numeric NOT NULL DEFAULT false,metadata blob,error_details blob,permissions blob,task_details blob,render_info blob,step_payload blob,step_format integer NOT NULL DEFAULT 0,PRIMARY KEY (idx));
100
+ CREATE INDEX idx_steps_status ON steps(status);
101
+ CREATE INDEX idx_steps_step_type ON steps(step_type);
102
+ CREATE TABLE gen_metadata (idx integer,data blob,size integer NOT NULL DEFAULT 0,PRIMARY KEY (idx));
103
+ CREATE TABLE executor_metadata (idx integer,data blob,PRIMARY KEY (idx));
104
+ CREATE TABLE parent_references (idx integer,data blob,PRIMARY KEY (idx));
105
+ CREATE TABLE trajectory_metadata_blob (id text DEFAULT "main",data blob,PRIMARY KEY (id));
106
+ CREATE TABLE battle_mode_infos (idx integer,data blob,PRIMARY KEY (idx));`
107
+
108
+ // writeConversation writes steps ({role: "user" | "model", text}, in
109
+ // order) as a conversation in the account's store (home), with its brain
110
+ // folder, and gives its id; null when no store can be written here. A
111
+ // conversation half written is taken away again.
112
+ export function writeConversation(home, steps, { ws = home, now = Date.now() } = {}) {
113
+ const open = loadOpener()
114
+ if (!open) return null
115
+ const ac = path.join(home, ".gemini", "antigravity-cli")
116
+ const id = randomUUID()
117
+ const traj = randomUUID()
118
+ const dir = path.join(ac, "conversations")
119
+ const file = path.join(dir, `${id}.db`)
120
+ let db
121
+ try {
122
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
123
+ fs.mkdirSync(path.join(ac, "brain", id), { recursive: true, mode: 0o700 })
124
+ db = open(file)
125
+ db.exec("PRAGMA page_size=32768; PRAGMA journal_mode=WAL; PRAGMA user_version=1")
126
+ db.exec(SCHEMA)
127
+ db.exec("BEGIN")
128
+ db.run("INSERT INTO trajectory_meta VALUES (?,?,4,17)", traj, id)
129
+ const uri = `file://${ws}`
130
+ db.run("INSERT INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)", encode([[1, [[1, uri], [3, ""]]], [2, stamp(now)], [3, randomUUID()], [6, id], [7, uri], [25, 1]]))
131
+ let turn = -1
132
+ steps.forEach((s, idx) => {
133
+ const user = s.role === "user"
134
+ // a user's step after a model's starts the next turn
135
+ if (user && (idx === 0 || steps[idx - 1].role !== "user")) turn++
136
+ const at = now - (steps.length - idx) * 1000
137
+ const meta = [[1, stamp(at)], [3, user ? 4 : 2], [12, randomUUID()], [20, [[1, traj], [2, idx || undefined], [3, Math.max(turn, 0) || undefined], [4, id]]], [35, hex()]]
138
+ const body = user ? [19, [[2, s.text], [3, [[1, s.text]]], [4, ""]]] : [20, [[1, s.text], [8, s.text]]]
139
+ const type = user ? USER_STEP : MODEL_STEP
140
+ db.run("INSERT INTO steps (idx, step_type, status, metadata, step_payload) VALUES (?,?,?,?,?)", idx, type, DONE, encode(meta), encode([[1, type], [4, DONE], [5, meta], body]))
141
+ })
142
+ db.exec("COMMIT")
143
+ db.close()
144
+ db = null
145
+ return id
146
+ } catch (error) {
147
+ try { db?.close() } catch {}
148
+ fs.rmSync(path.join(ac, "brain", id), { recursive: true, force: true })
149
+ for (const end of ["", "-wal", "-shm", "-journal"]) fs.rmSync(file + end, { force: true })
150
+ throw error
151
+ }
152
+ }
153
+
154
+ // resumed is whether agy, started at `since` (ms) with the conversation
155
+ // id, says in its log that it took it: true when it is resuming it, false
156
+ // when it ignored it (and started one of its own), null while its log
157
+ // says neither.
158
+ export function resumed(home, id, since) {
159
+ const dir = path.join(home, ".gemini", "antigravity-cli", "log")
160
+ let names = []
161
+ try { names = fs.readdirSync(dir).filter((n) => n.endsWith(".log")) } catch { return null }
162
+ let took = null
163
+ for (const name of names) {
164
+ const file = path.join(dir, name)
165
+ let text
166
+ try {
167
+ if (fs.statSync(file).mtimeMs < since - 2000) continue
168
+ text = fs.readFileSync(file, "utf8")
169
+ } catch { continue }
170
+ if (!text.includes(id)) continue
171
+ if (text.includes(`Conversation ${id} not found`)) return false
172
+ if (text.includes(`Resuming conversation ${id}`)) took = true
173
+ }
174
+ return took
175
+ }
176
+
177
+ // chunks cuts text into pieces of at most max bytes, at a line's end where
178
+ // one is near, never inside a character
179
+ export function chunks(text, max) {
180
+ const buf = Buffer.from(text)
181
+ if (buf.length <= max) return [text]
182
+ const out = []
183
+ let at = 0
184
+ while (buf.length - at > max) {
185
+ let end = at + max
186
+ // a character's continuation bytes stay with it
187
+ while (end > at && (buf[end] & 0xc0) === 0x80) end--
188
+ const nl = buf.lastIndexOf(0x0a, end - 1)
189
+ if (nl >= at + max * 0.8) end = nl + 1
190
+ out.push(buf.subarray(at, end).toString())
191
+ at = end
192
+ }
193
+ out.push(buf.subarray(at).toString())
194
+ return out
195
+ }
@@ -0,0 +1,306 @@
1
+ // A copy of packages/agy-cli/usage.mjs from UsageError to parseUsageReport
2
+ // (each package is published alone): a change to one goes to the other.
3
+ // What agy's own `agy usage` report says, read as agy-cli reads it; the
4
+ // export line at the end is this copy's own.
5
+ import { familiesInGroup } from "./model-ids.mjs"
6
+
7
+ // kind: "auth" (agy says it needs a sign-in), "timeout" (output: what agy
8
+ // had printed by then, never shown), "cancel", or none. slow: ran out of
9
+ // time where no sign-in is waited on (agy --version), asked again as soon
10
+ // as a timeout is.
11
+ class UsageError extends Error {
12
+ constructor(message, { kind = "", output = "", slow = false } = {}) {
13
+ super(message)
14
+ this.kind = kind
15
+ this.output = output
16
+ this.slow = slow
17
+ }
18
+ }
19
+
20
+ const SIGN_IN_TALK = /accounts\.google\.com|oauth|sign[ -]?in|log[ -]?in|authenticat|browser/i
21
+
22
+ const text = value => typeof value === "string" ? value.trim() : ""
23
+ const field = (value, camel, snake) => value?.[camel] ?? value?.[snake]
24
+
25
+ // agy logs unauthenticated cache lookups before loading its keyring.
26
+ function withoutDiagnostics(output) {
27
+ return output.split(/\r?\n/)
28
+ .filter(line => !/^\s*[IWEF]\d{4}\s+\d{2}:\d{2}:\d{2}\.\d+\s+\d+\s+[^\]]+\]/.test(line))
29
+ .join("\n")
30
+ }
31
+
32
+ const ELIGIBILITY = /eligibility check failed|not eligible|unsupported (?:country|region)|does not support google tos/i
33
+ const NETWORK = /\b(?:eof|timeout|timed out|deadline exceeded|no such host|connection (?:refused|reset)|network|proxy|tls|ssl|certificate)\b/i
34
+
35
+ // Google's 403 #3501 at agy's eligibility check: Google turns the account
36
+ // itself away, and agy refuses every command with it, `agy models`, print
37
+ // mode and a turn alike (agy 1.5.9 against a Code Assist answering it):
38
+ // Eligibility check failed: PERMISSION_DENIED (code 403): You do not have
39
+ // a valid license of this product. ... (#3501). Please log out (/logout)
40
+ // and log back in (/login).
41
+ // Three people on X (11-16) got only a list of fallback models, "model …
42
+ // is unavailable to this agy account" or "not eligible" from the plugin.
43
+ const LICENSE_REFUSAL = /valid license of this product|\(#3501\)/i
44
+
45
+ export const LICENSE_REFUSED = "Google refuses this Google account for Antigravity " +
46
+ "(403 #3501: \"You do not have a valid license of this product\"). agy itself gets the same " +
47
+ "answer, so this account can't be used until Google accepts it. Update agy, then sign in to " +
48
+ "the account again (in magpie, or run `agy` in a terminal and /logout, then /login); sign in " +
49
+ "with a personal Google account (@gmail.com) rather than a Workspace one; unset AGY_ADC_AUTH " +
50
+ "if it is set; and turn off a VPN or proxy that puts you in a region Antigravity isn't offered in."
51
+
52
+ const ACCOUNT_DISABLED_REFUSAL = /PERMISSION_DENIED \(code 403\):\s*This\s+service\s+has\s+been\s+disabled\s+in\s+this\s+account\s+for\s+violation\s+of\s+Terms\s+of\s+Service\.\s*Please\s+submit\s+an\s+appeal\s+to\s+continue\s+using\s+this\s+product\./
53
+ export const ACCOUNT_DISABLED_REFUSED = "Google has disabled this account's access to Antigravity " +
54
+ "for violating the Terms of Service (HTTP 403: \"This service has been disabled in this account " +
55
+ "for violation of Terms of Service\"). Submit an appeal with Google before using this account again."
56
+
57
+ // Google asks for the account to be verified (Cloud Code's 403
58
+ // VALIDATION_REQUIRED). agy 1.5.9 words it three ways: a turn's model call
59
+ // ends the reply with "⚠ Verification Required" alone (kidgpt on X, 11-16:
60
+ // that bare line was the whole answer in Claude Code), and its eligibility
61
+ // check says "…\n\nPlease verify your account in your browser to
62
+ // continue:\n<link>", or "Verification required. Please complete
63
+ // verification in your browser to continue." when Google gave no link.
64
+ const VERIFY_REFUSAL = /please verify your account in your browser to continue|verification required\. please complete verification|verify your account to continue/i
65
+
66
+ // The words magpie's gateway reads as Google's verification refusal
67
+ // (provider.verifyAdvice), and its link in them (provider.verifyLink): it
68
+ // rests the account as "verify" and shows Verify with the link, as it does
69
+ // for the Antigravity and Gemini CLI routes.
70
+ export const VERIFY_ADVICE = "this Google account needs to be verified"
71
+
72
+ // The validation link of Google's google.rpc.Help detail, as Gemini CLI's
73
+ // classifyValidationRequiredError takes it (and magpie's
74
+ // provider.Verification): the first of its links that isn't the "Learn
75
+ // more" one, which is on support.google.com. Only in a VALIDATION_REQUIRED
76
+ // body: another error's Help links (an API to enable) are not a way to
77
+ // verify.
78
+ function helpLinkIn(said) {
79
+ if (!/VALIDATION_REQUIRED/.test(said)) return ""
80
+ for (const [object] of said.matchAll(/\{[^{}]*"url"\s*:\s*"https:\/\/[^"]+"[^{}]*\}/g)) {
81
+ const url = /"url"\s*:\s*"(https:\/\/[^"\s\\<>]+)"/.exec(object)?.[1] || ""
82
+ const description = /"description"\s*:\s*"([^"]*)"/.exec(object)?.[1] || ""
83
+ if (!url || /^\s*learn more\s*$/i.test(description)) continue
84
+ try {
85
+ if (new URL(url).hostname === "support.google.com") continue
86
+ } catch {
87
+ continue
88
+ }
89
+ return url
90
+ }
91
+ return ""
92
+ }
93
+
94
+ // verifyLinkIn is the https link agy's output or log gives to verify the
95
+ // account at, "" when it gives none: the validation_link before the
96
+ // validation_url, else the Help detail's link (helpLinkIn), else the link
97
+ // agy prints after "continue:", else an accounts.google.com one.
98
+ export function verifyLinkIn(output) {
99
+ const said = String(output ?? "").replace(/\\u0026/g, "&").replace(/&amp;/g, "&")
100
+ const named = (key) => new RegExp(`"?${key}"?\\s*[:=]\\s*"?(https://[^\\s"'\\\\<>]+)`, "i").exec(said)?.[1]
101
+ const link = named("validation_?link") || named("validation_?url") || helpLinkIn(said) ||
102
+ /in your browser to continue:\s*(https:\/\/[^\s"'\\<>]+)/i.exec(said)?.[1] ||
103
+ /(https:\/\/accounts\.google\.com\/[^\s"'\\<>]+)/i.exec(said)?.[1] || ""
104
+ const trimmed = link.replace(/[).,;\]}]+$/, "")
105
+ try {
106
+ const u = new URL(trimmed)
107
+ return u.protocol === "https:" && u.host ? trimmed : ""
108
+ } catch {
109
+ return ""
110
+ }
111
+ }
112
+
113
+ // agy's eligibility check, which runs when agy starts and at sign-in, asks
114
+ // in these words and prints the link; a model call's refusal is the bare
115
+ // "Verification Required"
116
+ const VERIFY_AT_SIGN_IN = /please verify your account in your browser to continue|verification required\. please complete verification|eligibility check failed:[^\n]*verify your account/i
117
+
118
+ export function verifyAskedAtSignIn(text) {
119
+ return VERIFY_AT_SIGN_IN.test(String(text ?? ""))
120
+ }
121
+
122
+ // verifyRefused is what the agent is told when Google wants the account
123
+ // verified: with the link to do it at when agy gave one, else where to go.
124
+ //
125
+ // Asked on a model call (request), Google's 403 VALIDATION_REQUIRED
126
+ // reaches agy 1.5.21 as "Verification Required" alone: its
127
+ // CustomUserErrorMessageFromHTTPError keeps only the reason, and its log
128
+ // line only Google's message, so neither carries the link. agy's own
129
+ // sign-in check doesn't ask then, and `agy` in a terminal can answer on
130
+ // the same account (0xiaoge0 on X, 12-03: Codex's requests to
131
+ // gemini-4-neon at high refused, agy in a terminal at Medium answering).
132
+ // So "run agy in a terminal" verifies nothing there. `google` is
133
+ // Google's own words from agy's log, when it logged them.
134
+ export function verifyRefused(link, { request = false, google = "" } = {}) {
135
+ // Google's message, without a body agy logged after it
136
+ const words = String(google ?? "").split(/:?\s*\{/)[0].replace(/\s+/g, " ").trim().slice(0, 300)
137
+ const said = "Google wants this account verified before Antigravity serves it again (agy: \"Verification Required\"" +
138
+ (words ? `; Google: "${words}"` : "") + ")"
139
+ if (link) return `${said} — ${VERIFY_ADVICE}: open ${link} in a browser signed in to it, verify it, then try again`
140
+ if (!request) {
141
+ return `${said} — ${VERIFY_ADVICE}: open the Antigravity app, or run \`agy\` in a terminal, signed in to it and do what it asks, then try again`
142
+ }
143
+ return `${said} — ${VERIFY_ADVICE}, and agy passed on no link to do it at. Google asked on this model request, ` +
144
+ "not at sign-in, so signing in again won't show it, and `agy` in a terminal can still answer on the same account. " +
145
+ "Verify where Google shows the link when it asks: the Antigravity app or Gemini CLI, signed in to this account. " +
146
+ "If `agy` in a terminal answers this model, Google may be turning away this request rather than the account: " +
147
+ "try a lower reasoning level or a new conversation."
148
+ }
149
+
150
+ // agyRefusal is what to tell the user when agy's output says Google turned
151
+ // the account away at its eligibility check, or "" when it doesn't: the
152
+ // license refusal (#3501), or any other refusal of the check that isn't a
153
+ // network failure ("Eligibility check failed: EOF"), in agy's own words.
154
+ // agy's diagnostic log lines are not read: a background poll it logs can
155
+ // fail on its own.
156
+ // agy's eligibility check refused (agyRefusal), not a license, a disabled
157
+ // account or a verification: agy's print mode and `agy models` refuse an
158
+ // account whose loadCodeAssist names any ineligible tier, which agy acp
159
+ // may still serve (plugins#1602)
160
+ const ELIGIBILITY_REFUSED = "Google refuses this account for Antigravity: "
161
+
162
+ export function isEligibilityRefusal(why) {
163
+ return String(why ?? "").startsWith(ELIGIBILITY_REFUSED)
164
+ }
165
+
166
+ export function agyRefusal(output) {
167
+ const said = withoutDiagnostics(String(output ?? ""))
168
+ if (LICENSE_REFUSAL.test(said)) return LICENSE_REFUSED
169
+ if (ACCOUNT_DISABLED_REFUSAL.test(said)) return ACCOUNT_DISABLED_REFUSED
170
+ if (VERIFY_REFUSAL.test(said)) return verifyRefused(verifyLinkIn(said))
171
+ if (!ELIGIBILITY.test(said) || NETWORK.test(said)) return ""
172
+ const line = said.split(/\r?\n/).map(l => l.trim().replace(/^error:\s*/i, "")).find(l => ELIGIBILITY.test(l)) || ""
173
+ return `${ELIGIBILITY_REFUSED}${line.slice(0, 400)}. agy itself gets the same answer. ` +
174
+ "Antigravity isn't offered in every region: turn off a VPN or proxy that puts you in another one, or use an account Google serves there."
175
+ }
176
+
177
+ function commandFailure(output) {
178
+ if (/not (?:logged|signed) in(?:to)?\b|unauthenticated|authentication required|login required|please (?:log|sign) in|sign in again|\binvalid_grant\b/i.test(withoutDiagnostics(output))) {
179
+ return new UsageError("agy usage needs authentication. Run `agy` in a terminal to sign in again.", { kind: "auth" })
180
+ }
181
+ if (LICENSE_REFUSAL.test(withoutDiagnostics(output))) return new UsageError(LICENSE_REFUSED)
182
+ const eligibility = ELIGIBILITY.test(output)
183
+ const network = NETWORK.test(output)
184
+ if (network) return new UsageError(`agy usage ${eligibility ? "eligibility check " : ""}failed on a network request. Check network or proxy settings.`)
185
+ if (eligibility) return Object.assign(new UsageError("agy reports that this account is not eligible for Antigravity."), { ineligible: true })
186
+ return new UsageError("agy could not read usage. Run `agy` in a terminal to check its status.")
187
+ }
188
+
189
+ function resetTime(value) {
190
+ if (value == null || value === "" || typeof value === "boolean") return undefined
191
+ const raw = String(value)
192
+ let ms
193
+ if (/^\d+(?:\.\d+)?$/.test(raw)) ms = Number(raw) * (Number(raw) < 1e11 ? 1000 : 1)
194
+ else if (/^\d{4}-\d{2}-\d{2}T/.test(raw)) ms = Date.parse(raw)
195
+ if (!Number.isFinite(ms) || ms <= 0 || ms > 253402300799999) return undefined
196
+ return new Date(ms).toISOString()
197
+ }
198
+
199
+ function cadence(bucket, id, name) {
200
+ // An explicit, unfamiliar window must not be overridden by an older ID/label.
201
+ const value = text(bucket.window) || `${id} ${name}`
202
+ if (/^(?:5h|five[_ -]?hours?|five_hour|session)$/i.test(value) || !text(bucket.window) && /(?:5h|five[ _-]hour|session)/i.test(value)) {
203
+ return { name: "5 hours", span: 5 * 60 * 60 }
204
+ }
205
+ if (/^(?:weekly|week|7d|seven[_ -]?days?)$/i.test(value) || !text(bucket.window) && /(?:weekly|week|7d)/i.test(value)) {
206
+ return { name: "7 days", span: 7 * 24 * 60 * 60 }
207
+ }
208
+ return { name: name || id }
209
+ }
210
+
211
+ // vendorOf is a model's family as magpie's cards group them (Gemini,
212
+ // Claude, GPT-OSS), as the retired antigravity plugin named them.
213
+ function vendorOf(id, name) {
214
+ const l = id.toLowerCase()
215
+ if (l.startsWith("gemini")) return "Gemini"
216
+ if (l.startsWith("claude")) return "Claude"
217
+ if (l.startsWith("gpt-oss")) return "GPT-OSS"
218
+ return String(name ?? "").trim().split(" ")[0] || id.split("-")[0]
219
+ }
220
+
221
+ // agy's command report is not its token-usage object or a model-availability list.
222
+ // Unknown quota is not evidence of exhaustion or a full allowance.
223
+ //
224
+ // Each group is a pool its models share: its windows go as the pool's
225
+ // ({ pool: "Gemini", name: "5 hours" }), and each model family the group
226
+ // names gets a window of its own in that pool, reading the pool's most
227
+ // used bucket, the one that stops it. That is what Google's own per-model
228
+ // reading said: the retired antigravity plugin's fetchAvailableModels
229
+ // read of 2026-11-11 gave every model of a pool the pool's figure, to the
230
+ // digit (each Gemini model 1.58104% with Gemini's 7 days). So magpie's
231
+ // card shows the pools, and "Every model" lists the models, as it did for
232
+ // the antigravity plugin.
233
+ //
234
+ // A model's own window is not set aside: it is what routing weighs the
235
+ // account by for that model, as the antigravity plugin's were, so a
236
+ // routing group of Opus 5.5 reads the account's Claude & GPT share, not
237
+ // "not known yet" behind every account known (will930128 on X). The
238
+ // pool's own windows stay aside and hold their models at a cap the user
239
+ // sets on the pool (magpie's PoolWindow), as the antigravity plugin's did.
240
+ export function parseUsageReport(value) {
241
+ let report
242
+ try { report = typeof value === "string" ? JSON.parse(value) : value } catch {
243
+ throw new UsageError("agy returned an invalid usage report.")
244
+ }
245
+ if (report?.status !== "SUCCESS" || report?.command?.name !== "usage") {
246
+ throw commandFailure(text(report?.error) || text(report?.response))
247
+ }
248
+ const groups = report.command.data?.groups
249
+ const windows = []
250
+ const models = new Map() // family id -> its window
251
+ for (const group of Array.isArray(groups) ? groups : []) {
252
+ const pool = (text(field(group, "displayName", "display_name")) || text(group?.name) || "Quota")
253
+ .replace(/\s+models$/i, "").replace(/\s+and\s+/gi, " & ")
254
+ const families = familiesInGroup(group)
255
+ const ids = [...new Set(families.flatMap(f => f.ids))].sort()
256
+ let tightest
257
+ for (const bucket of Array.isArray(group?.buckets) ? group.buckets : []) {
258
+ const id = text(field(bucket, "bucketId", "bucket_id")) || text(bucket?.id)
259
+ if (!id || bucket?.disabled === true) continue
260
+ const label = text(field(bucket, "displayName", "display_name")) || text(bucket?.name)
261
+ const period = cadence(bucket, id, label)
262
+ const remaining = bucket.remaining
263
+ const fraction = field(bucket, "remainingFraction", "remaining_fraction")
264
+ ?? field(remaining, "remainingFraction", "remaining_fraction")
265
+ ?? (remaining?.case === "remainingFraction" ? remaining.value : undefined)
266
+ const known = typeof fraction === "number" && Number.isFinite(fraction) && fraction >= 0 && fraction <= 1
267
+ const resetsAt = resetTime(field(bucket, "resetTime", "reset_time"))
268
+ const w = {
269
+ name: period.name,
270
+ pool,
271
+ // the pool's own: its models' windows stop them (below)
272
+ aside: true,
273
+ ...(ids.length ? { models: ids } : {}),
274
+ ...(known ? { used: Math.round((1 - fraction) * 1e8) / 1e6 } : { display: "Limits not available" }),
275
+ ...(period.span ? { span: period.span } : {}),
276
+ ...(resetsAt ? { resetsAt } : {}),
277
+ }
278
+ windows.push(w)
279
+ if (known && (!tightest || w.used > tightest.used)) tightest = w
280
+ }
281
+ if (!tightest) continue
282
+ for (const f of families) {
283
+ const had = models.get(f.id)
284
+ // a model two groups name reads the one that stops it first
285
+ if (had && had.used >= tightest.used) continue
286
+ models.set(f.id, {
287
+ name: f.name,
288
+ model: f.id,
289
+ family: vendorOf(f.id, f.name),
290
+ pool,
291
+ models: f.ids,
292
+ used: tightest.used,
293
+ ...(tightest.span ? { span: tightest.span } : {}),
294
+ ...(tightest.resetsAt ? { resetsAt: tightest.resetsAt } : {}),
295
+ })
296
+ }
297
+ }
298
+ if (!windows.some(w => w.used !== undefined)) {
299
+ throw new UsageError("Limits not available: agy returned no enabled, measured quota buckets.")
300
+ }
301
+ // /usage has no verified account or plan identity: none is made up from
302
+ // it.
303
+ return { windows: [...[...models.values()].sort((a, b) => a.name.localeCompare(b.name)), ...windows] }
304
+ }
305
+
306
+ export { UsageError, commandFailure }
package/usage.mjs ADDED
@@ -0,0 +1,111 @@
1
+ import { spawn } from "node:child_process"
2
+ import fs from "node:fs"
3
+ import os from "node:os"
4
+ import path from "node:path"
5
+ import { inAccount } from "./account.mjs"
6
+ import { storeCatalogRows } from "./model-ids.mjs"
7
+ import { commandFailure, parseUsageReport, UsageError } from "./usage-report.mjs"
8
+
9
+ // An account's quota, as agy says it: `agy usage --output-format json`
10
+ // (agy 1.5.22 and later), run in the account's home, the same command the
11
+ // agy-cli plugin reads it with (packages/agy-cli/usage.mjs's fetchUsage),
12
+ // and its report read by the same code (usage-report.mjs, a copy of
13
+ // agy-cli's). Only agy asks Google for it. agy before 1.5.22 is not read:
14
+ // agy-cli falls back to `agy -p /usage` there, print mode, which this
15
+ // plugin never runs.
16
+ //
17
+ // magpie reads it only when the user refreshes the account's card or row
18
+ // (it reads none of Antigravity's usage on its own), so nothing is kept
19
+ // here: magpie keeps the reading. Two reads of one account at once share
20
+ // one agy.
21
+
22
+ const TIMEOUT_MS = 45_000
23
+ const MAX_OUTPUT_BYTES = 1024 * 1024
24
+
25
+ const pending = new Map()
26
+
27
+ // readUsage is the account at home's usage, as magpie's usage hook answers
28
+ // it. env is what agy runs with (index.mjs's agyEnv); list, the models agy
29
+ // listed for the account, names the windows' models.
30
+ export function readUsage(agy, home, { env, list = [], signal, timeoutMs = TIMEOUT_MS } = {}) {
31
+ let read = pending.get(home)
32
+ if (!read) {
33
+ read = fetchUsage(agy, home, { env, list, signal, timeoutMs }).finally(() => pending.delete(home))
34
+ pending.set(home, read)
35
+ }
36
+ return read.then((r) => structuredClone(r))
37
+ }
38
+
39
+ async function fetchUsage(agy, home, { env, list, signal, timeoutMs }) {
40
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "magpie-agy-tui-usage-"))
41
+ try {
42
+ // agy is run where nothing opens a browser, as agy-cli runs it: a
43
+ // sign-in it asks for is the account's to do again in magpie
44
+ for (const name of process.platform === "win32" ? ["open.cmd"] : ["open", "xdg-open"]) {
45
+ fs.writeFileSync(path.join(directory, name), process.platform === "win32" ? "@exit /b 1\r\n" : "#!/bin/sh\nexit 1\n", { mode: 0o700 })
46
+ }
47
+ const childEnv = { ...env, PATH: directory + path.delimiter + (env?.PATH ?? env?.Path ?? ""), BROWSER: path.join(directory, process.platform === "win32" ? "open.cmd" : "open") }
48
+ const result = await run(agy, ["usage", "--output-format", "json"], { cwd: directory, env: childEnv, signal, timeoutMs })
49
+ if (result.timedOut) {
50
+ return { windows: [], error: `agy's own usage read didn't finish in ${Math.round(timeoutMs / 1000)}s. agy asks Google about twelve times before it has the quota, which takes longer behind a slow network or proxy.`, signIn: "kept" }
51
+ }
52
+ if (result.canceled) return { windows: [], error: "the usage read was stopped", signIn: "kept" }
53
+ let report
54
+ try { report = JSON.parse(result.stdout) } catch {}
55
+ const parsed = (value) => inAccount(home, () => {
56
+ storeCatalogRows(list)
57
+ return parseUsageReport(value)
58
+ })
59
+ try {
60
+ // as agy-cli's fetchUsage: a report agy says it made, or output
61
+ // that isn't one, read as a report; an empty stdout (agy 1.5.22
62
+ // prints a failed request to stderr alone) is what stderr says
63
+ if (result.code === 0 && report?.status === "SUCCESS") return { ...parsed(report), signIn: "kept" }
64
+ if (result.code === 0 && !report?.status && result.stdout.trim()) return { ...parsed(result.stdout), signIn: "kept" }
65
+ const said = report?.status && report.status !== "SUCCESS"
66
+ ? String(report.error || report.response || "").trim()
67
+ : result.stderr + "\n" + result.stdout
68
+ throw commandFailure(said)
69
+ } catch (error) {
70
+ const message = error instanceof UsageError ? error.message : "agy's usage report couldn't be read."
71
+ if (error?.kind === "auth") return { windows: [], error: "agy's sign-in for this account no longer works: sign in to it again", signIn: "expired" }
72
+ return { windows: [], error: message, signIn: "kept" }
73
+ }
74
+ } finally {
75
+ fs.rmSync(directory, { recursive: true, force: true })
76
+ }
77
+ }
78
+
79
+ function run(file, args, { cwd, env, signal, timeoutMs }) {
80
+ return new Promise((resolve) => {
81
+ if (signal?.aborted) return resolve({ code: -1, stdout: "", stderr: "", canceled: true })
82
+ let child
83
+ try {
84
+ child = spawn(file, args, { cwd, env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true })
85
+ } catch (error) {
86
+ resolve({ code: -1, stdout: "", stderr: error.message })
87
+ return
88
+ }
89
+ let stdout = ""
90
+ let stderr = ""
91
+ let timedOut = false
92
+ let canceled = false
93
+ const stop = () => { try { child.kill() } catch {} }
94
+ const timer = setTimeout(() => { timedOut = true; stop() }, timeoutMs)
95
+ const onAbort = () => { canceled = true; stop() }
96
+ signal?.addEventListener("abort", onAbort, { once: true })
97
+ const take = (add) => (d) => {
98
+ add(d)
99
+ if (stdout.length + stderr.length > MAX_OUTPUT_BYTES) stop()
100
+ }
101
+ child.stdout.setEncoding("utf8").on("data", take((d) => (stdout += d)))
102
+ child.stderr.setEncoding("utf8").on("data", take((d) => (stderr += d)))
103
+ const done = (code, more = "") => {
104
+ clearTimeout(timer)
105
+ signal?.removeEventListener("abort", onAbort)
106
+ resolve({ code, stdout, stderr: stderr + more, timedOut, canceled })
107
+ }
108
+ child.on("error", (error) => done(-1, error.message))
109
+ child.on("close", (code) => done(code))
110
+ })
111
+ }