@magpie-community/opencode-agy-tui-auth 0.1.12 → 0.1.15
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 +4 -2
- package/README.md +4 -2
- package/account.mjs +21 -0
- package/agy-version.mjs +19 -3
- package/efforts.mjs +119 -0
- package/index.mjs +41 -6
- package/model-ids.mjs +126 -0
- package/package.json +7 -2
- package/usage-report.mjs +306 -0
- package/usage.mjs +111 -0
package/README.en.md
CHANGED
|
@@ -9,6 +9,8 @@ Antigravity's models through agy's own interactive mode (its TUI). Each request
|
|
|
9
9
|
1. Install the [Antigravity CLI](https://antigravity.google/docs/cli) (`agy`), version 1.5.19 or newer. An older agy is refused with "Update agy", and its sign-in says to run `agy update` (one before 1.5.0 has no `agy acp --login`).
|
|
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
|
+
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.
|
|
12
14
|
|
|
13
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.
|
|
14
16
|
|
|
@@ -24,10 +26,10 @@ A request's tools (`tools`, function tools) are given to the model through magpi
|
|
|
24
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.
|
|
25
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.
|
|
26
28
|
- 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
|
|
29
|
+
- The models say a context of 64K tokens. That is agy's limit on one message, not the model's: Gemini 4 Hydrogen has 1,048,576 in agy itself. 64K is about what fits in the 180,000 bytes pasted, with agy's own ~10K of instructions, so an agent compacts its conversation before a request that pastes it whole would be cut. A chat carried on in agy's own conversation isn't held to it (only the new messages are typed, and agy compacts its conversation by its own window), but which request will be carried on isn't known when the window is said, and any other pastes the chat whole, so the window stays what one message takes. Each response has the usage agy recorded (`usage`: the call's input, cache read and write, and every call's output and thinking).
|
|
28
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).
|
|
29
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.
|
|
30
|
-
- It needs magpie 0.1.
|
|
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.
|
|
31
33
|
|
|
32
34
|
## Options (environment)
|
|
33
35
|
|
package/README.md
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
1. 安装 [Antigravity CLI](https://antigravity.google/docs/cli)(`agy`),需要 1.5.19 或更新;更旧的 agy 会被拒绝,并提示「Update agy」,登录时会提示运行 `agy update`(1.5.0 之前的 agy 没有 `agy acp --login`)。
|
|
10
10
|
2. 在 magpie 的插件页安装本插件,然后在 Providers 里添加 **Antigravity (agy TUI)**,选「使用 Google 登录」:magpie 打开 agy 的登录链接,把页面上显示的代码粘贴回来即可。
|
|
11
11
|
3. 模型列表来自 `agy models`:登录时问一次,存在账号目录里,之后只在你刷新列表时再问。
|
|
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`),不会改用打印模式。
|
|
12
14
|
|
|
13
15
|
每个账号都有自己的 home(`~/.local/state/magpie-agy-tui/accounts/<id>`),agy 的登录信息以文件形式存在那里。你自己的 `~/.gemini`、skills 和 MCP 服务器都不会被用到,也不会被改动。
|
|
14
16
|
|
|
@@ -24,10 +26,10 @@ agy 运行的是它的默认 agent,不用自定义 agent(`--agent`):agy
|
|
|
24
26
|
- 其它 agy 输入框不能附加的内容会被拒绝(400)并说明是什么,不会被悄悄丢掉:PDF、音频、文本或代码文件、HEIC、文件链接(而不是文件本身),以及发给 Claude 模型的视频。
|
|
25
27
|
- 一段对话在 agy 自己的会话里接着进行。一轮得到回答后,会保留它的 agy 会话;这段对话的下一个请求(同样的消息、这条回答,再加上用户的新消息)用 `--conversation` 接着这个会话,只输入新的消息。不管对话已经多长,模型拿到的都是完整的、按轮次组织的之前的对话,会话太长时由 agy 自己压缩。其他请求会开一个新的 agy 会话,把最后一条消息之前的对话整理成文字粘贴进去:新的对话、客户端压缩过、改过或分叉的对话、客户端改过的回答、回答之后出现的系统消息,以及工具调用的结果(它会回到发起调用的那个 agy 里继续)。会话在最后一次回答后保留 24 小时,每个账号最多 32 个(先删最早的);会话列表放在账号目录里(`agy-tui-conversations.json`),只有哈希和 agy 的会话 id,没有对话内容。每次请求系统指令都会变的对话,总是整段粘贴。
|
|
26
28
|
- agy 一条消息最多收 192,000 字节,超出部分会被它替换成 `<truncated N bytes>`,模型就看不到最新的消息了。所以粘贴的内容控制在 180,000 字节以内:最后一条消息完整保留,然后是系统指令,再从最新往前放入之前的对话,放不下的最早几轮会被省略,并留一行说明。系统指令本身放不下时截短。最后一条消息单独就超过时会被拒绝(400)。
|
|
27
|
-
- 模型宣告的上下文是 64K token
|
|
29
|
+
- 模型宣告的上下文是 64K token。这是 agy 一条消息的上限,不是模型本身的:Gemini 4 Hydrogen 在 agy 里有 1,048,576。64K 大约是粘贴的 180,000 字节、加上 agy 自己约 10K 的指令能放下的量,这样 agent 会在整段粘贴的请求被截断之前压缩对话。在 agy 自己的会话里接着进行的对话不受它限制(只输入新消息,会话由 agy 按自己的窗口压缩),但宣告窗口时并不知道哪个请求能接着会话,其他请求都要整段粘贴,所以窗口仍按一条消息能放下的量。每次响应都会带上 agy 记录的用量(`usage`:本次调用的输入、缓存读写,以及所有调用的输出和思考)。
|
|
28
30
|
- 流式请求边生成边返回:agy 每收到模型的一段回答就写进它自己的对话库(`conversations/<id>.db`),插件只读地读出新增的部分发出去;读不到时在一轮结束后返回完整回答。模型的思考(agy 向 Gemini 要了思考内容)同样边生成边作为 `reasoning_content` 返回,在回答之前;非流式时放在消息的 `reasoning_content` 里。回答写完就结束响应,不等 agy 退出(它退出前会先发完自己的遥测)。
|
|
29
31
|
- agy 启动要好几秒(用 Google 账号登录时,它先向 Google 查询账号、套餐和模型,然后才接收消息),所以每个请求都会为下一个账号、模型和工具相同的请求预先启动一个 agy,停在输入框;下一个请求来了只需输入消息。保留了会话的一轮,还会为这段对话的下一个请求预先启动一个带着这个会话的 agy。每种组合最多留一个(总共最多三个),最多等 10 分钟;设置 `AGY_TUI_SPARES=0` 就改回请求来了才启动 agy。
|
|
30
|
-
- 需要 magpie 0.1.
|
|
32
|
+
- 需要 magpie 0.1.5538 或更新(`tui-helper` 及其工具服务器从 0.1.5217 起有;0.1.5537 让按档位区分的旧模型 id 继续可用,0.1.5538 在你刷新时读额度);magpie 太旧时,带工具的请求会说明运行这个插件的 magpie 需要哪个版本(作为远程 magpie 使用时是服务器上的那个;Docker 镜像不会自己更新,插件却每小时更新)。Windows 尚未测试。
|
|
31
33
|
|
|
32
34
|
## 选项(环境变量)
|
|
33
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
|
|
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 =
|
|
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/efforts.mjs
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// One model for each of Antigravity's models, its efforts as variants.
|
|
2
|
+
//
|
|
3
|
+
// `agy models` lists a model once for each thinking level it runs at:
|
|
4
|
+
// claude-opus-5-5-low "Claude Opus 5.5 (Low)" and claude-opus-5-5-high
|
|
5
|
+
// "Claude Opus 5.5 (High)". Listed as they are, a picker showed each model
|
|
6
|
+
// three times over (baranwang on X). So a model agy lists at two levels or
|
|
7
|
+
// more is listed once, by the id without the level (claude-opus-5-5), with
|
|
8
|
+
// the levels as its variants, and a request for it runs agy at the level the
|
|
9
|
+
// agent asks for (foldModels, agyModelOf). The levels' own ids stay the
|
|
10
|
+
// model's (former): a pick, a routing group or an agent left on
|
|
11
|
+
// claude-opus-5-5-low is still served, by agy at that level.
|
|
12
|
+
//
|
|
13
|
+
// A model agy lists at one level (gpt-oss-120b-medium) is listed as it is,
|
|
14
|
+
// and so is one whose id without the level agy lists too, and Orchestrator,
|
|
15
|
+
// whose Carbon and Argon are planners, not levels.
|
|
16
|
+
|
|
17
|
+
export const EFFORT_ORDER = ["minimal", "low", "medium", "high", "xhigh", "max"]
|
|
18
|
+
const LEVEL = /-(minimal|low|medium|high|xhigh|max)$/i
|
|
19
|
+
const LEVEL_NAME = /\s*\((minimal|low|medium|high|xhigh|max)\)\s*$/i
|
|
20
|
+
|
|
21
|
+
function isOrchestrator(m) {
|
|
22
|
+
return /orchestrator/i.test(m.id) || /^Orchestrator\b/i.test(m.name ?? "")
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// foldModels is list (`agy models`, parseModels) with each model agy lists
|
|
26
|
+
// at two levels or more as one: { id, name, variants, former } where
|
|
27
|
+
// variants are its levels, least first, and former the ids it was listed
|
|
28
|
+
// by. routes says, for each such model, the id of each level and the one
|
|
29
|
+
// run when the request names none (defaultEffort).
|
|
30
|
+
//
|
|
31
|
+
// The default is high, or the highest level there is without it: what
|
|
32
|
+
// Antigravity itself starts on (its model config's defaultAgentModelId is
|
|
33
|
+
// gemini-3.8-flash-high, and its Recommended list leads each model with
|
|
34
|
+
// its -high), and what agy-cli and magpie's own Antigravity ran a model
|
|
35
|
+
// named without its level at.
|
|
36
|
+
export function foldModels(list) {
|
|
37
|
+
const rows = Array.isArray(list) ? list.filter((m) => m && typeof m.id === "string" && m.id) : []
|
|
38
|
+
const ids = new Set(rows.map((m) => m.id))
|
|
39
|
+
const families = new Map()
|
|
40
|
+
for (const m of rows) {
|
|
41
|
+
const level = LEVEL.exec(m.id)
|
|
42
|
+
if (!level || isOrchestrator(m)) continue
|
|
43
|
+
const id = m.id.slice(0, level.index)
|
|
44
|
+
if (!families.has(id)) families.set(id, [])
|
|
45
|
+
families.get(id).push({ ...m, effort: level[1].toLowerCase() })
|
|
46
|
+
}
|
|
47
|
+
// A name that says another level than its id isn't taken for either:
|
|
48
|
+
// Antigravity's own config has gemini-3.5-flash-low named "Gemini 3.5
|
|
49
|
+
// Flash (Medium)" and gemini-3.5-flash-extra-low "(Low)" (magpie's
|
|
50
|
+
// testdata/antigravity-models-2026-10-20.json), so such a model is
|
|
51
|
+
// listed as agy lists it.
|
|
52
|
+
const saysOther = (l) => { const n = LEVEL_NAME.exec(l.name ?? ""); return n && n[1].toLowerCase() !== l.effort }
|
|
53
|
+
for (const [id, levels] of families) {
|
|
54
|
+
if (levels.length < 2 || new Set(levels.map((l) => l.effort)).size !== levels.length || ids.has(id) || levels.some(saysOther)) families.delete(id)
|
|
55
|
+
}
|
|
56
|
+
const models = []
|
|
57
|
+
const routes = new Map()
|
|
58
|
+
const familyOf = new Map()
|
|
59
|
+
for (const [id, levels] of families) for (const l of levels) familyOf.set(l.id, id)
|
|
60
|
+
for (const m of rows) {
|
|
61
|
+
const id = familyOf.get(m.id)
|
|
62
|
+
if (!id) {
|
|
63
|
+
models.push({ id: m.id, name: m.name })
|
|
64
|
+
continue
|
|
65
|
+
}
|
|
66
|
+
if (routes.has(id)) continue
|
|
67
|
+
const levels = [...families.get(id)].sort((a, b) => EFFORT_ORDER.indexOf(a.effort) - EFFORT_ORDER.indexOf(b.effort))
|
|
68
|
+
const efforts = levels.map((l) => l.effort)
|
|
69
|
+
const defaultEffort = efforts.includes("high") ? "high" : efforts.at(-1)
|
|
70
|
+
const named = levels.find((l) => l.effort === defaultEffort)
|
|
71
|
+
const name = String(named.name ?? "").replace(LEVEL_NAME, "").trim()
|
|
72
|
+
models.push({ id, name: name && name !== named.id ? name : id, variants: efforts, former: levels.map((l) => l.id) })
|
|
73
|
+
routes.set(id, { byEffort: new Map(levels.map((l) => [l.effort, l.id])), efforts, defaultEffort })
|
|
74
|
+
}
|
|
75
|
+
return { models, routes }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// effortOf is the level a request asks for, "" for none: what magpie says
|
|
79
|
+
// the agent asked for (X-Magpie-Effort, said) first, then the body's own.
|
|
80
|
+
// Thinking turned off ("none", "off", thinking disabled) asks for the
|
|
81
|
+
// least there is.
|
|
82
|
+
export function effortOf(body, said = "") {
|
|
83
|
+
const words = [said, body?.reasoning_effort, body?.reasoningEffort, body?.reasoning?.effort]
|
|
84
|
+
for (const w of words) {
|
|
85
|
+
const e = String(w ?? "").trim().toLowerCase()
|
|
86
|
+
if (!e) continue
|
|
87
|
+
if (e === "none" || e === "off") return "minimal"
|
|
88
|
+
if (e === "ultra") return "max"
|
|
89
|
+
if (EFFORT_ORDER.includes(e)) return e
|
|
90
|
+
}
|
|
91
|
+
if (body?.thinking?.type === "disabled") return "minimal"
|
|
92
|
+
return ""
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// closestEffort is the level of efforts nearest effort, the higher of two
|
|
96
|
+
// as near.
|
|
97
|
+
export function closestEffort(effort, efforts) {
|
|
98
|
+
const at = EFFORT_ORDER.indexOf(effort)
|
|
99
|
+
let best = efforts[0]
|
|
100
|
+
for (const e of efforts.slice(1)) {
|
|
101
|
+
const d = Math.abs(EFFORT_ORDER.indexOf(e) - at)
|
|
102
|
+
const bd = Math.abs(EFFORT_ORDER.indexOf(best) - at)
|
|
103
|
+
if (d < bd || (d === bd && EFFORT_ORDER.indexOf(e) > EFFORT_ORDER.indexOf(best))) best = e
|
|
104
|
+
}
|
|
105
|
+
return best
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// agyModelOf is the id agy is run with for a request for model: a level's
|
|
109
|
+
// own id as it is (a pick or setting from before the levels were one
|
|
110
|
+
// model), and a model listed with its levels as variants at the level the
|
|
111
|
+
// request asks for, or its default. list is the account's `agy models` as
|
|
112
|
+
// kept; with none kept, model is run as it is.
|
|
113
|
+
export function agyModelOf(model, list, body, said = "") {
|
|
114
|
+
if (!model || !Array.isArray(list) || list.some((m) => m?.id === model)) return model
|
|
115
|
+
const route = foldModels(list).routes.get(model)
|
|
116
|
+
if (!route) return model
|
|
117
|
+
const asked = effortOf(body, said)
|
|
118
|
+
return route.byEffort.get(asked ? closestEffort(asked, route.efforts) : route.defaultEffort)
|
|
119
|
+
}
|
package/index.mjs
CHANGED
|
@@ -5,9 +5,11 @@ 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
10
|
import { mcpToolsOf } from "./tools.mjs"
|
|
11
|
+
import { agyModelOf, foldModels } from "./efforts.mjs"
|
|
12
|
+
import { readUsage } from "./usage.mjs"
|
|
11
13
|
|
|
12
14
|
// agy-tui: Antigravity's models through agy's own interactive mode. Each
|
|
13
15
|
// request starts the real `agy` TUI in a terminal magpie gives it (`magpie
|
|
@@ -427,8 +429,16 @@ function partsOf(content, media) {
|
|
|
427
429
|
export const INPUT_BUDGET = 180_000
|
|
428
430
|
// the context the models say they have: what fits in INPUT_BUDGET, with
|
|
429
431
|
// agy's own instructions (about 10k tokens) on top, so an agent compacts
|
|
430
|
-
// its conversation before agy would cut it. Gemini's own window is larger
|
|
431
|
-
// but agy takes no more than
|
|
432
|
+
// its conversation before agy would cut it. Gemini's own window is larger
|
|
433
|
+
// (Gemini 4 Hydrogen's is 1,048,576 in agy), but agy takes no more than
|
|
434
|
+
// this in a message. A chat carried on in agy's conversation (carriedOn)
|
|
435
|
+
// types only its new messages, so it could go past this; but a model has
|
|
436
|
+
// one window for every request, and whether a request is carried on is
|
|
437
|
+
// known only when it comes (a compacted, edited or forked chat, a tool
|
|
438
|
+
// result agy stopped waiting for, a conversation past KEEP_MS or MAX_KEPT,
|
|
439
|
+
// AGY_TUI_CARRY=0 or an agy without --conversation all paste it whole), so
|
|
440
|
+
// a larger window would let a pasted chat lose its oldest turns
|
|
441
|
+
// (marovole on X asked for one).
|
|
432
442
|
export const CONTEXT = 64_000
|
|
433
443
|
const bytes = (s) => Buffer.byteLength(s)
|
|
434
444
|
|
|
@@ -1529,6 +1539,10 @@ export async function handle(home, input, init = {}) {
|
|
|
1529
1539
|
const signal = init.signal ?? input?.signal
|
|
1530
1540
|
const id = `chatcmpl-${randomBytes(12).toString("hex")}`
|
|
1531
1541
|
const model = String(body.model ?? "")
|
|
1542
|
+
// the level of a model listed with its levels as variants, as the
|
|
1543
|
+
// agent asked (efforts.mjs); a level's own id is run as it is
|
|
1544
|
+
const said = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined) ?? {}).get("x-magpie-effort") ?? ""
|
|
1545
|
+
const agyModel = home ? agyModelOf(model, (modelLists.get(home) ?? readModelList(home))?.list, body, said) : model
|
|
1532
1546
|
// the result of a call a turn waits on goes on with that turn
|
|
1533
1547
|
const last = Array.isArray(body.messages) ? body.messages.at(-1) : null
|
|
1534
1548
|
if (last?.role === "tool") {
|
|
@@ -1561,11 +1575,11 @@ export async function handle(home, input, init = {}) {
|
|
|
1561
1575
|
const tools = mcpToolsOf(body)
|
|
1562
1576
|
// the chat's conversation, kept from its last answer, goes on with the
|
|
1563
1577
|
// new messages alone; any other is typed in whole
|
|
1564
|
-
carried = (await agyHelp(agy)).includes("--conversation") ? await carriedOn(home, body.messages, { agy, model, tools }) : null
|
|
1578
|
+
carried = (await agyHelp(agy)).includes("--conversation") ? await carriedOn(home, body.messages, { agy, model: agyModel, tools }) : null
|
|
1565
1579
|
const { prompt, media } = carried ?? turnOf(body.messages)
|
|
1566
1580
|
// agy attaches a video for any model, but only Gemini's see one
|
|
1567
1581
|
if (media.some((m) => kindOf(m.type) === "video") && !/^gemini-/.test(model)) throw refuse(`${model || "this model"} takes no video; a Gemini model does`)
|
|
1568
|
-
turn = await startTurn({ agy, home, model, prompt, media, tools, signal, conversation: carried?.id ?? null, messages: body.messages })
|
|
1582
|
+
turn = await startTurn({ agy, home, model: agyModel, prompt, media, tools, signal, conversation: carried?.id ?? null, messages: body.messages })
|
|
1569
1583
|
} catch (error) {
|
|
1570
1584
|
// a conversation taken for a turn that never began is in a state
|
|
1571
1585
|
// nothing knows
|
|
@@ -1577,6 +1591,11 @@ export async function handle(home, input, init = {}) {
|
|
|
1577
1591
|
|
|
1578
1592
|
// ---- the plugin
|
|
1579
1593
|
|
|
1594
|
+
// modelEntry is a model of foldModels': one agy lists at several levels
|
|
1595
|
+
// has them as its variants, and says the ids it was listed by before
|
|
1596
|
+
// (former), so magpie keeps a pick, group or agent setting of one as the
|
|
1597
|
+
// model's and still sends it here under that id. A variant sends its level
|
|
1598
|
+
// as reasoning_effort, for OpenCode, which says no X-Magpie-Effort.
|
|
1580
1599
|
export function modelEntry(m) {
|
|
1581
1600
|
return {
|
|
1582
1601
|
id: m.id,
|
|
@@ -1584,6 +1603,7 @@ export function modelEntry(m) {
|
|
|
1584
1603
|
npm: NPM,
|
|
1585
1604
|
api: { id: m.id, url: "agy-tui://local", npm: NPM },
|
|
1586
1605
|
limit: { context: CONTEXT, output: 65_536 },
|
|
1606
|
+
...(m.variants?.length ? { reasoning: true, variants: Object.fromEntries(m.variants.map((e) => [e, { reasoningEffort: e }])), former: m.former ?? [] } : {}),
|
|
1587
1607
|
// Gemini's and Claude's see the images agy attaches, as agy-cli says,
|
|
1588
1608
|
// and Gemini's the videos too
|
|
1589
1609
|
...(/^(?: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 } } } : {}),
|
|
@@ -1643,6 +1663,21 @@ export const AgyTuiPlugin = async () => ({
|
|
|
1643
1663
|
},
|
|
1644
1664
|
},
|
|
1645
1665
|
],
|
|
1666
|
+
// magpie's usage hook (OpenCode ignores it): the account's quota as
|
|
1667
|
+
// `agy usage` tells it, the agy-cli plugin's read (usage.mjs). magpie
|
|
1668
|
+
// asks it only when the user refreshes the account's card or row.
|
|
1669
|
+
usage: async (getAuth, _provider, { signal } = {}) => {
|
|
1670
|
+
const auth = typeof getAuth === "function" ? await getAuth() : getAuth
|
|
1671
|
+
const home = homeOfAuth(auth)
|
|
1672
|
+
if (!home || !fs.existsSync(tokenFile(home))) return { windows: [], error: "agy-tui: the account's agy is signed out; sign in again", signIn: "expired" }
|
|
1673
|
+
const agy = findAgy()
|
|
1674
|
+
if (!agy) return { windows: [], error: `agy CLI not found on this machine: ${AGY_MANUAL}`, signIn: "kept" }
|
|
1675
|
+
const version = await agyVersion(agy)
|
|
1676
|
+
if (!agyHasUsageSubcommand(version)) {
|
|
1677
|
+
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" }
|
|
1678
|
+
}
|
|
1679
|
+
return readUsage(agy, home, { env: agyEnv(home), list: (modelLists.get(home) ?? readModelList(home))?.list ?? [], signal })
|
|
1680
|
+
},
|
|
1646
1681
|
loader: async (getAuth) => {
|
|
1647
1682
|
const auth = typeof getAuth === "function" ? await getAuth() : getAuth
|
|
1648
1683
|
const home = homeOfAuth(auth)
|
|
@@ -1666,7 +1701,7 @@ export const AgyTuiPlugin = async () => ({
|
|
|
1666
1701
|
const agy = findAgy()
|
|
1667
1702
|
if (!home || !agy) return {}
|
|
1668
1703
|
const out = {}
|
|
1669
|
-
for (const m of await cachedModels(agy, home, { refresh: ctx?.refresh === true })) out[m.id] = modelEntry(m)
|
|
1704
|
+
for (const m of foldModels(await cachedModels(agy, home, { refresh: ctx?.refresh === true })).models) out[m.id] = modelEntry(m)
|
|
1670
1705
|
return out
|
|
1671
1706
|
},
|
|
1672
1707
|
},
|
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.
|
|
3
|
+
"version": "0.1.15",
|
|
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",
|
|
@@ -19,6 +19,11 @@
|
|
|
19
19
|
"re2-pattern.mjs",
|
|
20
20
|
"array-items.mjs",
|
|
21
21
|
"tool-budget.mjs",
|
|
22
|
+
"efforts.mjs",
|
|
23
|
+
"usage.mjs",
|
|
24
|
+
"usage-report.mjs",
|
|
25
|
+
"model-ids.mjs",
|
|
26
|
+
"account.mjs",
|
|
22
27
|
"opencode.mjs",
|
|
23
28
|
"opencode2.mjs",
|
|
24
29
|
"README.md",
|
|
@@ -44,7 +49,7 @@
|
|
|
44
49
|
"test": "bun test"
|
|
45
50
|
},
|
|
46
51
|
"engines": {
|
|
47
|
-
"magpie": ">=0.1.
|
|
52
|
+
"magpie": ">=0.1.5538"
|
|
48
53
|
},
|
|
49
54
|
"magpie": {
|
|
50
55
|
"maxConcurrency": 4
|
package/usage-report.mjs
ADDED
|
@@ -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(/&/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
|
+
}
|