summaryrefslogtreecommitdiff
path: root/quota.lua
blob: 7b32a555cb770224951a8e8ad5f045c3e23bfb87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
local uv = require('luv')
local M = {}
local key = 'panto-antigravity:private-profile' -- all configured aliases share ACP's one private profile
local max_bytes, refresh_ms, stale_s = 32768, 60000, 300

local function name(s)
    return #s <= 100 and not s:find('[^ -~]') and s:find('%S')
end

-- agy 1.5.18 bundled changelog and static inspection of printmode.quotaRows,
-- bucketRemaining, bucketReset and headless.writeRows: piped /usage emits
-- group name, bucket name, remaining (%.0f%%, %d or disabled), UTC RFC3339 or empty.
-- There is no header; integer amounts do not establish a denominator.
function M.parse(body, reset_time)
    if type(body) ~= 'string' or #body > max_bytes then return nil end
    local windows, seen, count = {}, {}, 0
    if body == '' then return windows end
    if body:sub(-1) ~= '\n' then return nil end -- the writer terminates every record
    for line in body:gmatch('([^\n]*)\n') do
        local group, bucket, remaining, reset = line:match('^([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)$')
        if not group or (group ~= '' and not name(group)) or not name(bucket) then return nil end
        local id = group .. '\t' .. bucket
        count = count + 1
        if count > 64 or seen[id] then return nil end
        seen[id] = true
        local pct = tonumber(remaining:match('^(%d%d?%d?)%%$'))
        local at
        if reset ~= '' then
            if not reset:match('^%d%d%d%d%-%d%d%-%d%dT%d%d:%d%d:%d%dZ$') then return nil end
            at = reset_time(reset)
            if not at or at < 0 then return nil end
        end
        if pct then
            if pct > 100 or tostring(pct) .. '%' ~= remaining then return nil end
        elseif remaining == 'disabled' then
            if at then return nil end
        elseif not remaining:match('^%-?%d+$') then
            return nil
        end
        if pct or at then
            local label = group ~= '' and group ~= bucket and (group .. ' / ' .. bucket) or bucket
            if group == 'Gemini Models' then
                if bucket == 'Weekly Limit Remaining' then label = '1w'
                elseif bucket == 'Five Hour Limit Remaining' then label = '5h' end
            end
            windows[#windows + 1] = {
                label = pct and label:gsub(' Limit Remaining$', ' Limit Used') or label,
                used_percent = pct and 100 - pct or nil,
                resets_at = at,
            }
        end
    end
    return windows
end

local function close(handle)
    if handle and not handle:is_closing() then handle:close() end
end

function M.activate(ext, footer, acp)
    local state = footer.install(ext)
    if not state or state.closed then return function() end end
    if state.antigravity_refresh then return state.antigravity_refresh end
    local alive, ready, pending, next_run = true, false, nil, 0
    local clock

    local function publish(windows)
        if not alive then return end
        local function section(rows, why)
            return footer.section(ext, 'antigravity', rows, { status = why })
        end
        local render
        if windows and #windows > 0 then
            local sampled = os.time()
            local expires = sampled + stale_s
            local stale = section({}, 'stale')
            local cached, deadline = nil, 0
            render = function(now)
                if now >= expires then return stale(now) end
                if not cached or now >= deadline then
                    local current = {}
                    deadline = expires
                    local expired = false
                    for _, w in ipairs(windows) do
                        if not w.resets_at or w.resets_at > now then
                            current[#current + 1] = w
                            if w.resets_at then deadline = math.min(deadline, w.resets_at) end
                        elseif w.resets_at > sampled then
                            expired = true -- crossed a real reset since this reading
                        end
                    end
                    cached = section(current, (#current == 0 or expired) and 'stale' or nil)
                end
                return cached(now)
            end
        else
            render = section({}, windows and 'unknown' or 'unavailable')
        end
        state.sections[key] = nil -- never leave a previous snapshot on a failed publication
        pcall(footer.publish, ext, key, render)
    end

    -- Only a visible footer needs a sample. Coalesce startup and turn reads.
    local function refresh()
        if not alive or not ready or not state.handle or pending then return end
        local now = uv.hrtime() / 1000000
        if now < next_run then return end
        next_run = now + refresh_ms
        local req, chunks, bytes = {}, {}, 0
        pending = req
        local function finish(windows)
            if req.done then return end
            req.done, chunks = true, nil
            if req.cancel then pcall(req.cancel); req.cancel = nil end
            close(req.timer); close(req.stdout)
            if not windows and req.pid then pcall(uv.kill, -req.pid, 'sigkill') end
            if not req.child then pending = nil end -- don't launch over a child awaiting reap
            publish(windows)
        end
        req.stop = function() finish(nil) end
        local function complete()
            if not req.done and req.eof and req.exited then
                finish(M.parse(table.concat(chunks), footer.reset_time))
            end
        end
        local ok = pcall(function()
            req.timer = assert(uv.new_timer())
            local cancel = acp.probe(function(bin, profile, env)
                if req.done or req.stdout then return end
                req.cancel = nil -- verification has completed
                assert(req.timer:start(15000, 0, req.stop))
                req.stdout = assert(uv.new_pipe(false))
                -- Detached (no controlling tty) + closed input. The CLI's
                -- print-mode auth path returns without interactive login in this case.
                req.child, req.pid = uv.spawn(bin, {
                    args = {'--gemini_dir', profile, '--sandbox', '-p', '/usage'},
                    cwd = profile, env = env, detached = true, stdio = {nil, req.stdout, nil},
                }, function(code, sig)
                    close(req.child); req.child, req.pid = nil, nil
                    if req.done then pending = nil; return end
                    if code ~= 0 or sig ~= 0 then req.stop(); return end
                    req.exited = true
                    complete()
                end)
                if not req.child then req.pid = nil; req.stop(); return end
                assert(req.stdout:read_start(function(err, data)
                    if req.done then return end
                    if err then req.stop(); return end
                    if not data then req.eof = true; close(req.stdout); complete(); return end
                    bytes = bytes + #data
                    if bytes > max_bytes then req.stop(); return end
                    chunks[#chunks + 1] = data
                end))
            end, req.stop)
            if not req.done and not req.stdout then req.cancel = cancel end
        end)
        if not ok then req.stop() end
    end
    ext.on('session_ready', function(event)
        if not alive or ready or event.has_tui == false then return end
        ready = true
        pcall(footer.publish,ext,key,footer.section(ext,'antigravity',{}, {status='loading'}))
        refresh()
        -- A long-running or idle Neon thread may not cross a turn boundary
        -- before the five-minute sample expires. No polling on other models.
        clock = uv.new_timer()
        clock:start(180000, 180000, function()
            if not alive or not state.handle then return end
            local info = ext.session_info()
            local provider = info and info.model and info.model:match('^([^:]+):')
            local cfg = provider and ext.config.providers[provider]
            if cfg and cfg.protocol == 'antigravity-acp' and cfg.usage_footer ~= false then refresh() end
        end)
        clock:unref()
    end)
    state.antigravity_refresh = refresh
    ext.on('session_end', function()
        alive = false
        close(clock)
        if pending then pending.stop() end
        state.antigravity_refresh, state.sections[key] = nil, nil
    end)
    return refresh
end

return M