diff options
| -rw-r--r-- | README.md | 23 | ||||
| -rw-r--r-- | _quota_selfcheck.lua | 28 | ||||
| -rw-r--r-- | _usage_footer.lua | 6 | ||||
| -rw-r--r-- | acp.lua | 132 | ||||
| -rw-r--r-- | catalog.lua | 2 | ||||
| -rw-r--r-- | check.lua | 37 | ||||
| -rw-r--r-- | docs/findings.md | 20 | ||||
| -rw-r--r-- | extensions/antigravity-acp.lua | 123 | ||||
| -rw-r--r-- | quota.lua | 33 | ||||
| -rw-r--r-- | tests/fake-agy.lua | 126 | ||||
| -rw-r--r-- | tests/tui.exp | 66 |
11 files changed, 445 insertions, 151 deletions
@@ -17,12 +17,27 @@ reasoning_levels = ["low", "medium", "high", "xhigh"] `-r high` or Ctrl+R requests `high` for the next turn. On `agy` 1.5.19 the provider selects the ACP model first, then checks that model’s `thought_level` choices and confirms the requested level before prompting. Without an explicit level it leaves the ACP setting alone. Pickers that advertise suffixed model IDs still use those variants (exact configured ID, otherwise `medium` when no level is requested). Panto currently shows the protocol-wide levels in Ctrl+R, so a narrower family can reject an unavailable level; the provider never silently substitutes one. The same configuration works in a rig. For a locally built rock (`luarocks --lua-version 5.4 --tree <Panto rock tree> make`), use `rocks = ["panto-antigravity"]` instead of `paths`. Nothing is published or installed globally by the checks. -**Usage footer (TUI only):** One shared row across aliases alongside Claude, Codex, Copilot and OpenCode Go. It shows **percent used**, a five-cell bar and reset countdown per reported bucket (73% remaining → `27% ━────`). No account request on startup. An authenticated direct turn refreshes through the CLI’s fixed read-only `/usage` command, at most once a minute. The extension reads only the signed CLI’s stdout: it never calls Google quota endpoints or reads account tokens. [Google’s `/usage` command](https://antigravity.google/docs/cli/commands/usage/) may itself refresh from Google’s backend. Malformed or failed reads show unavailable; expired/reset readings aren't shown as current. No token-count estimates or raw CLI messages. `usage_footer = false` opts a provider out. The footer validates the `/usage` output, not the CLI version. +**Top-line stats:** ACP's final `session/prompt` usage feeds Panto's session totals, cache hit rate and model pricing once per completed turn, including turns with multiple tool calls. Set `input`, `output`, `cache_read` and `cache_write` (USD per million tokens) in the model's `models.toml` table to estimate cost. This is not a subscription charge. `usage_update` reports a separate context snapshot (`used`, `size`); a Panto build supporting `metadata.context_window` uses it instead of mistaking summed prompt inputs for context occupancy. The adapter publishes the latest snapshot at Panto tool boundaries as well as at final completion. A long turn can still show no reading (or the last reading) if agy hasn't sent a new snapshot; the adapter doesn't substitute cumulative cache traffic for occupancy. Missing or inconsistent token totals aren't estimated. -**Setup & diagnostics:** `/antigravity-status` shows local connection state; `/antigravity-models` lists advertised families; for split ACP settings, levels are shown only for the selected model. Neither contacts Google. The isolated profile is `~/.local/share/panto-antigravity/google`. For native login once that directory exists: `profile="$HOME/.local/share/panto-antigravity/google"; HOME="$profile" agy acp --gemini-dir "$profile" --login`. When upgrading from the prototype, update your extension path, protocol and model selection, then start a new thread. No credentials or old checkpoints are migrated automatically. +**Usage footer (TUI only):** One shared row across aliases alongside Claude, Codex, Copilot and OpenCode Go. It shows **percent used**, a five-cell bar and reset countdown per reported bucket (73% remaining → `27% ━────`). The TUI requests an initial reading on startup using the CLI’s fixed read-only `/usage` command, without sending a model prompt. While an enabled Antigravity model is selected, a three-minute timer refreshes the row even when no turn starts or finishes. Startup, timer and turn reads share a one-minute cooldown and never overlap. The extension reads only the signed CLI’s stdout: it never calls Google quota endpoints or reads account tokens. [Google’s `/usage` command](https://antigravity.google/docs/cli/commands/usage/) may itself refresh from Google’s backend. Malformed or failed reads show unavailable; expired/reset readings aren't shown as current. No token-count estimates or raw CLI messages. `usage_footer = false` opts a provider out. The footer validates the `/usage` output, not the CLI version. -**Tools:** By default the `pantograph` MCP server exports the active Panto tools, including extension tools. They run with Panto's permissions, not agy's shell sandbox. Use a trusted rig; if it contains tools you don't want Neon to run, narrow `tools` or disable those extensions in the rig. Full input schemas are listed, including nested arrays and objects; an unsupported schema constraint rejects the call rather than disabling the catalog. On `session/new` and `session/resume`, the adapter requests `_meta.disableBuiltInTools = true` (recognized by agy 1.5.19). Before launching ACP with tools, the extension creates `antigravity-cli/settings.json` in its isolated profile if absent, allowing `mcp(pantograph/*)` so exported tools don't prompt by default. Existing settings are never overwritten. To restore prompts, replace that allow rule with an `ask` rule for the same server. Other servers and native tools receive no grant. After restarting Panto, start a **fresh thread**, ask Neon to read `README.md`, and check for the Panto read card. `/antigravity-status` distinguishes configured tools from an actual MCP list request and counts accepted MCP calls. +**Setup & diagnostics:** `/antigravity-status` shows local connection state; `/antigravity-models` lists advertised families; for split ACP settings, levels are shown only for the selected model. Neither contacts Google. The isolated profile is `~/.local/share/panto-antigravity/google`. For native login once that directory exists: `agy acp --gemini-dir "$HOME/.local/share/panto-antigravity/google" --login`. Keep `HOME` unchanged so the CLI can find the macOS login Keychain. When upgrading from the prototype, update your extension path, protocol and model selection, then start a new thread. No credentials or old checkpoints are migrated automatically. -**Boundaries:** Direct idle text submissions only: no startup prompts, print/proxy calls, child agents, compaction, queued input or automatic retries. Enter identifies a TUI path, not proof of personhood; don't automate this route. Keep the profile free of delegation hooks/servers and exclude delegation tools from the rig or use an explicit allowlist on this personal route. The relay supports text/image results. Unexpected ACP permission requests still show a macOS allow-once/deny dialog. Turns share one warm ACP process. Optional `save_session = true` resumes a completed matching checkpoint (writes local state even under `--incognito`); no transcript replay. Force-kill can leave a stale socket or lock: confirm the owner is gone before removing it. +**Tools:** By default the `pantograph` MCP server exports the active Panto tools, including extension tools. They run with Panto's permissions, not agy's shell sandbox. Use a trusted rig; if it contains tools you don't want Neon to run, narrow `tools` or disable those extensions in the rig. Full input schemas are listed, including nested arrays and objects; an unsupported schema constraint rejects the call rather than disabling the catalog. ACP now selects a per-thread [custom main agent](https://antigravity.google/docs/subagents/) with `excludeDefaultComponents: true`, `tools: []`, and no inherited customizations or MCP. The agent file in the isolated profile declares only the thread's `pantograph` relay (none for `tools = []`); each exported tool requests eager loading so agy need not read schema files with a native tool. The same relay is passed explicitly to ACP `session/new` or `session/resume` so agy discovers it during setup. With tools exported, the adapter requires a live relay that served `tools/list` before sending the first prompt. Schema-cache timestamps are not used. The Panto rig prompt still uses ACP's advertised append extension. + +**Native tool visibility:** During a prompt, reported ACP native calls such as `manage_task` appear above the input with their name and status. The component shows the latest six calls until the next prompt or session close; it isn't saved transcript history. It never executes tools or prints raw inputs/results. Calls through the Panto relay still get their ordinary Panto cards, not duplicates. + +**Live acceptance check:** Restart Panto after each config change and use a fresh thread in a disposable workspace without other agents, hooks or MCP servers. Generate a fresh marker with `uuidgen > panto-probe.txt` before each test; don't paste its contents into chat. + +1. Set `tools = ["std.read"]`. Ask Neon to read `panto-probe.txt` and return its contents. Require the exact marker **and** a Panto read card; `/antigravity-status` should count a call. +2. Set `tools = []`, regenerate the marker, and ask again, expressly allowing a native read or shell if available. Neon should not obtain the new marker. An exact match is an isolation failure. A refusal is behavioral evidence, not a complete inventory of tool declarations. + +**Approval:** Every ACP chat launch uses `--dangerously-skip-permissions` and `--sandbox`, even with `tools = []`. This skips agy's approvals for native tools as well as MCP tools. Use a trusted rig. The Panto tool allowlist still applies, and the separate read-only `/usage` query is unchanged. + +**Steering and thinking:** Plain Enter during a tool-using turn steers at the next tool boundary. Queued text and workflow notices go to the same live agy session as user input, not as tool output. Ctrl+Enter queues a separate follow-up. If an earlier failure left an unanswered text message, resume that Panto thread and press Ctrl+P (`/proceed`) in the idle TUI to send the pending message once; this requires the Panto build with direct `/proceed` provenance. Reload alone does not retry it. Ctrl+K shows thinking text **if agy sends it**; reasoning-token counts are not displayable text. + +**Branch and resume:** Matching live turns keep the warm ACP session. With `save_session = true`, an exact saved checkpoint can resume natively (local state is written even under `--incognito`). Otherwise, the next direct submission after `/tree` or a cold resume starts a new ACP session: Panto sends its selected `history_transcript` as background and the new request once, in a single user message. Past tool calls and results are text, not dispatches. If Panto cannot supply the transcript for existing history, the turn fails rather than silently dropping context. + +**Boundaries:** Only a direct idle TUI submission can start, resume or reseed an ACP session. Once a turn completes, extension-submitted text (including workflow completion notices) can continue the same live primary thread if its checkpoint still matches. This checks session continuity, not the text prefix or which extension submitted it. No startup prompts, print/proxy calls, child-provider requests, compaction or automatic retries. Enter identifies a TUI path, not proof of personhood; don't automate this route. Keep the profile free of delegation hooks/servers and exclude delegation tools from the rig or use an explicit allowlist on this personal route. The relay supports text/image results. Force-kill can leave a stale socket, lock or generated `config/agents/panto-*.md` in the isolated profile: confirm the owner is gone before removing it. **Offline release check:** `PANTO=/path/to/provenance-aware/panto mise run check` exercises source and installed-rock loading, renders the real footer with a fake CLI, and checks tool execution, resume, and headless rejection. No installed `agy` or Google account is used. See [evidence and compatibility](docs/findings.md). diff --git a/_quota_selfcheck.lua b/_quota_selfcheck.lua index 510bddf..488f1d2 100644 --- a/_quota_selfcheck.lua +++ b/_quota_selfcheck.lua @@ -6,15 +6,16 @@ os.time = function() return wall end local reset = os.date('!%Y-%m-%dT%H:%M:%SZ', wall + 60) local sample = 'Gemini\tPro\t72%\t' .. reset .. '\n' .. 'Gemini\tFlash\t100%\t\nOther\tLimited\t0%\t\n' + .. 'Inactive\tLegacy\t100%\t1970-01-01T00:00:00Z\n' .. 'Credits\tCount only\t150\t' .. reset .. '\nGemini\tOff\tdisabled\t\n' local function parse(s) return quota.parse(s, footer.reset_time) end local limits = assert(parse('Gemini Models\tWeekly Limit Remaining\t73%\t\nGemini Models\tFive Hour Limit Remaining\t100%\t\n')) -assert(limits[1].label == 'Gemini Models / Weekly Limit Used' and limits[1].used_percent == 27) -assert(limits[2].label == 'Gemini Models / Five Hour Limit Used' and limits[2].used_percent == 0) +assert(limits[1].label == '1w' and limits[1].used_percent == 27) +assert(limits[2].label == '5h' and limits[2].used_percent == 0) local rows = assert(parse(sample)) -assert(#rows == 4 and rows[1].label == 'Gemini / Pro' and rows[1].used_percent == 28) +assert(#rows == 5 and rows[1].label == 'Gemini / Pro' and rows[1].used_percent == 28) assert(rows[1].resets_at == wall + 60 and rows[2].used_percent == 0 and rows[3].used_percent == 100) -assert(rows[4].used_percent == nil and rows[4].resets_at == wall + 60) +assert(rows[5].used_percent == nil and rows[5].resets_at == wall + 60) assert(#assert(parse('')) == 0 and #assert(parse('Gemini\tOff\tdisabled\t\n')) == 0) for _, bad in ipairs({ 'Gemini\tPro\t101%\t\n', 'Gemini\tPro\t072%\t\n', 'Gemini\tPro\t0.72\t\n', 'Gemini\tPro\tused 72%\t\n', @@ -64,15 +65,23 @@ end hooks.session_ready[1]({has_tui = false}) refresh() assert(rendered() == 'native footer' and probes == 0, 'headless quota read or placeholder') +local model = 'other:test' +ext.config={providers={alias={protocol='antigravity-acp'}}}; ext.session_info=function() return {model=model} end +local new_timer, clock = uv.new_timer +uv.new_timer=function() clock=new_timer(); return clock end hooks.session_ready[1]({has_tui = true}) +uv.new_timer=new_timer +assert(clock:get_repeat()==180000) footer.publish(ext, 'peer', 'peer usage footer') -assert(rendered():find('antigravity usage: awaiting first turn',1,true) and rendered():find('peer usage footer',1,true) and probes == 0) +assert(table.concat(component:render(132), '\n'):find('\27[34ma\27[31mn\27[33mt\27[34mi\27[32mg\27[31mr\27[34ma\27[31mv\27[33mi\27[34mt\27[32my',1,true), 'missing per-letter footer colors') +assert(rendered():find('antigravity usage: loading',1,true) and rendered():find('peer usage footer',1,true) and probes == 1) refresh(); refresh(); assert(probes == 1 and spawns == 0) verified('/fake-agy', profile, env); refresh(); uv.run(); refresh() assert(probes == 1 and spawns == 1) local line = rendered() assert(line:find('antigravity usage: Gemini / Pro 28%', 1, true) and line:find('Count only ?%', 1, true)) assert(line:find('reset in 1m', 1, true) and line:find('peer usage footer', 1, true)) +assert(not line:find('Legacy',1,true) and not line:find('stale',1,true),'expired CLI buckets tainted a fresh sample') assert(select(2, line:gsub('antigravity usage:', '')) == 1) wall = wall + 60 line = rendered() @@ -81,6 +90,11 @@ wall = wall + 240 assert(rendered():find('antigravity usage: stale', 1, true)) assert(not rendered():find('Flash', 1, true)) +-- Exercise the actual timer callback, without waiting three minutes or sending a turn. +advance=advance+180*10^9 +clock:set_repeat(1); clock:again(); clock:ref(); uv.sleep(3); uv.run('nowait'); assert(probes==1) +model='alias:neon'; uv.sleep(3); uv.run('nowait'); clock:stop(); assert(probes==2) +verified('/fake-agy',profile,env); uv.run(); assert(spawns==2 and rendered():find('Flash 0%',1,true)) local function retry(body, code) output, exit_status, advance = body, code, advance + 61 * 10^9 refresh(); verified('/fake-agy', profile, env); uv.run() @@ -94,9 +108,9 @@ assert(rendered():find('antigravity usage: unavailable', 1, true)) retry('', 0) assert(rendered():find('antigravity usage: unknown', 1, true)) advance = advance + 61 * 10^9 -refresh(); assert(probes == 6 and spawns == 5) +refresh(); assert(probes == 7 and spawns == 6) for _, end_session in ipairs(hooks.session_end) do end_session() end verified('/fake-agy', profile, env); refresh(); uv.run() -assert(cancelled == 1 and spawns == 5 and not uv.loop_alive()) +assert(cancelled == 1 and spawns == 6 and not uv.loop_alive()) assert(rendered() == 'native footer\npeer usage footer') print('PASS: exact /usage TSV, fake CLI gate and coalescing, stale/errors and shared footer') diff --git a/_usage_footer.lua b/_usage_footer.lua index 421afd5..b2859a7 100644 --- a/_usage_footer.lua +++ b/_usage_footer.lua @@ -61,6 +61,12 @@ function M.section(ext, label, windows, opts) opts = type(opts) == "table" and opts or { status = opts } label = text(label):gsub("^%S+", string.lower) local provider = (label:match("^(.-) %(") or label):lower() + if label == "antigravity" then + local colors = {34, 31, 33, 34, 32, 31} -- blue, red, yellow, blue, green, red + label = label:gsub("()(.)", function(i, letter) + return ("\27[%dm%s"):format(colors[(i - 1) % #colors + 1], letter) + end) + end local status = opts.status and text(opts.status) or nil local snapshot = {} for _, window in ipairs(windows or {}) do @@ -68,22 +68,6 @@ local function private_profile() local st=assert(uv.fs_lstat(dir)); assert(st.mode & 63==0 and uv.fs_access(dir,'W') and uv.fs_access(dir,'X'),'Google profile must be private and writable') return dir end --- Supply an agy default only in our private profile. Publish a complete file --- without replacing settings a user (or another Panto process) already created. -local function seed_tool_permissions(profile) - local dir=profile..'/antigravity-cli' - local made,err,code=uv.fs_mkdir(dir,448); assert(made or code=='EEXIST',err) - local st=assert(uv.fs_lstat(dir)); assert(st.type=='directory' and st.uid==uv.getuid() and st.mode & 18==0,'Unsafe agy settings directory') - local path=dir..'/settings.json' - if uv.fs_lstat(path) then return end - local fd,tmp=uv.fs_mkstemp(dir..'/.settings-XXXXXX'); assert(fd,tmp) - local data='{"permissions":{"allow":["mcp(pantograph/*)"]}}\n' - local n,why=uv.fs_write(fd,data,0); local closed,close_err=uv.fs_close(fd) - if n==#data and closed then - made,err,code=uv.fs_link(tmp,path) - else made,err,code=nil,why or close_err or 'Incomplete agy settings write',nil end - assert(uv.fs_unlink(tmp)); assert(made or code=='EEXIST',err) -end local function executable() assert(uv.os_uname().sysname=='Darwin','Google signature verification requires macOS') for dir in (os.getenv('PATH') or ''):gmatch('[^:]+') do @@ -102,7 +86,9 @@ local function verified(run, on_error) end local ok,err=pcall(function() local bin,profile=executable(),private_profile() - local env={'HOME='..profile} + -- Isolate CLI settings via --gemini-dir, not HOME: macOS needs the + -- user's home to find the default login Keychain. + local env={'HOME='..assert(os.getenv('HOME'))} for _,k in ipairs({'USER','PATH','TMPDIR','LANG'}) do if os.getenv(k) then env[#env+1]=k..'='..os.getenv(k) end end @@ -118,13 +104,53 @@ local function verified(run, on_error) return cancel end M.probe = verified -local dialog=[[on run argv -set choice to display dialog (item 1 of argv) with title "Panto: Antigravity permission" buttons {"Deny", "Allow once"} default button "Deny" cancel button "Deny" giving up after 60 -if (gave up of choice) or (button returned of choice) is not "Allow once" then error number -128 -end run]] +-- agy discovers named agents under <gemini-dir>/config/agents. Declare the +-- relay on the agent itself: session/new MCP servers need not be inherited by +-- custom agents. Never edit the user's agents or global MCP configuration. +local function relay(s) return {name='pantograph',command='/usr/bin/nc',args={'-U',s.dir..'/mcp'}} end +local function install_agent(s, profile) + local dir=profile + for _,part in ipairs({'config','agents'}) do + dir=dir..'/'..part + local made,err,code=uv.fs_mkdir(dir,448); assert(made or code=='EEXIST',err) + local st=assert(uv.fs_lstat(dir)); assert(st.type=='directory' and st.uid==uv.getuid() and st.mode & 18==0,'Unsafe agy agent directory') + end + -- Saved sessions already hold an exclusive lock on this thread ID. + local name='panto-'..(s.save and s.sid or s.dir:match('([^/]+)$')):lower() + local servers=json.array({}) + if #s.list>0 then servers[1]=relay(s) end + local data=([[--- +name: %s +description: Antigravity in Panto +mainAgent: true +subagent: false +excludeDefaultComponents: true +inheritCustomizations: false +inheritMcp: false +tools: [] +mcpServers: %s +--- +Use the configured pantograph tools for workspace actions, if available. +]]):format(name,json.encode(servers)) + local path=dir..'/'..name..'.md' + local fd=assert(uv.fs_open(path,'wx',384)); s.agent_path=path + local n,err=uv.fs_write(fd,data,0); assert(uv.fs_close(fd)); assert(n==#data,err or 'Incomplete agy agent definition') + return name +end +-- agy reports the combined usage of every inference inside one ACP prompt. +-- Compare against its total rather than counting cached input or thought twice. +local function count(v) return math.type(v)=='integer' and v>=0 and v<=0xffffffff end +function M.usage(u) + if type(u)~='table' then return end + local i,o,t=u.inputTokens,u.outputTokens,u.totalTokens + local r,w,h=u.cachedReadTokens or 0,u.cachedWriteTokens or 0,u.thoughtTokens or 0 + if not (count(i) and count(o) and count(t) and count(r) and count(w) and count(h)) or h>o then return end + if i+o==t and r+w<=i then i=i-r-w elseif i+o+r+w~=t then return end + return {input=i,output=o,cache_read=r,cache_write=w,reasoning=h} +end function M.launch(s, first, resume_id) local cancel_check - local child, pid, approval, stdin, stdout, waiting, timer, serial=nil,nil,nil,nil,nil,nil,uv.new_timer(),0 + local child, pid, stdin, stdout, waiting, timer, serial=nil,nil,nil,nil,nil,uv.new_timer(),0 local closed=false local function cleanup() if pid then uv.kill(-pid,9); pid=nil end @@ -138,17 +164,23 @@ function M.launch(s, first, resume_id) local cancel=child and s.pending and s.session if cancel then pcall(send,{method='session/cancel',params={sessionId=s.session}}) end if cancel_check then cancel_check() end - if approval and not approval:is_closing() then approval:kill('sigkill') end + if s.agent_path then uv.fs_unlink(s.agent_path); s.agent_path=nil end close(stdout) if cancel then timer:stop(); timer:start(500,0,cleanup) else cleanup() end end local function step(co,...) local ok,err=coroutine.resume(co,...); if not ok then s.fail(tostring(err)) end end - local deadline, idle + local deadline, idle, request_id, primary_reply + local steering,steer_usage,last_steer={},nil,nil + s.steer=function(parts) + assert(s.prompting and waiting,'No active ACP prompt to steer') + serial=serial+1; steering[serial]=true + send({id=serial,method='session/prompt',params={sessionId=s.session,prompt=parts}}) + end local function activity() if waiting then deadline=uv.now()+idle end end local function call(method,params) - assert(not waiting,'Overlapping ACP requests'); serial=serial+1; waiting=coroutine.running() + assert(not waiting,'Overlapping ACP requests'); serial=serial+1; request_id=serial; waiting=coroutine.running() idle=(method=='session/prompt' or method=='authenticate') and 600000 or 60000 activity(); timer:start(1000,1000,function() if s.call then activity() elseif uv.now()>=deadline then s.fail('ACP timeout: '..method) end @@ -197,7 +229,12 @@ function M.launch(s, first, resume_id) if s.refresh then pcall(s.refresh) end local r=call('session/prompt',{sessionId=s.session,prompt={{type='text',text=text}}}) local reason=({end_turn='end_turn',max_tokens='max_tokens'})[r.stopReason] - assert(reason,'Turn stopped: '..tostring(r.stopReason)); s.prompting=false; s.complete(reason) + assert(reason,'Turn stopped: '..tostring(r.stopReason)) + local usage=M.usage(r.usage) + if steer_usage then + if usage then for k,v in pairs(steer_usage) do usage[k]=usage[k]+v end else usage=steer_usage end + end + s.prompting=false; s.complete(last_steer and last_steer.reason or reason,usage); steer_usage,last_steer=nil,nil end s.submit=function(text) step(coroutine.create(turn),text) end local function setup() @@ -206,7 +243,9 @@ function M.launch(s, first, resume_id) local personal=false; for _,a in ipairs(init.authMethods or {}) do if a.id=='oauth-personal' then personal=true end end assert(personal,'Native personal sign-in unavailable'); call('authenticate',{methodId='oauth-personal'}) local params={cwd=s.cwd,mcpServers=json.array({}),_meta={disableBuiltInTools=true}} - if #s.list>0 then params.mcpServers[1]={name='pantograph',command='/usr/bin/nc',args={'-U',s.dir..'/mcp'},env=json.array({})} end + if #s.list>0 then + local server=relay(s); server.env=json.array({}); params.mcpServers[1]=server + end local session if resume_id then assert((caps.sessionCapabilities or {}).resume,'ACP resume unavailable'); params.sessionId=resume_id @@ -218,6 +257,7 @@ function M.launch(s, first, resume_id) end session=call('session/new',params); assert(type(session.sessionId)=='string' and #session.sessionId>0,'Missing session ID'); s.session=session.sessionId end + assert(#s.list==0 or (s.peer and s.listed),'ACP setup completed without listing the pantograph MCP catalog; prompt not sent') opts=session.configOptions or {} for _,o in ipairs(opts) do if o.category=='model' or o.id=='model' then @@ -234,28 +274,42 @@ function M.launch(s, first, resume_id) local function receive(q) assert(q.jsonrpc=='2.0','Invalid ACP envelope') if not q.method then - assert(waiting and q.id==serial,'Unexpected ACP reply'); assert(not q.error,(q.error or {}).message or 'ACP error') - local co=waiting; waiting=nil; timer:stop(); step(co,assert(q.result)); return + assert(waiting,'Unexpected ACP reply'); assert(not q.error,(q.error or {}).message or 'ACP error') + if steering[q.id] then + local r=assert(q.result); local reason=r.stopReason + assert(not reason or reason=='end_turn' or reason=='max_tokens','ACP steering rejected: '..tostring(reason)) + if reason and (not last_steer or q.id>last_steer.id) then last_steer={id=q.id,reason=reason} end + local u=M.usage(r.usage); if u then + if steer_usage then for k,v in pairs(u) do steer_usage[k]=steer_usage[k]+v end else steer_usage=u end + end + steering[q.id]=nil + else + assert(q.id==request_id and not primary_reply,'Unexpected ACP reply'); primary_reply=assert(q.result) + end + if primary_reply and not next(steering) then + local co,result=waiting,primary_reply; waiting,primary_reply=nil,nil; timer:stop(); step(co,result) + end + return end local p=q.params or {}; local ours=s.session and p.sessionId==s.session if q.method=='session/update' and ours then local u=p.update if u.sessionUpdate=='config_option_update' and s.wire and not configuring then opts=u.configOptions or {}; assert(confirmed(),'Configured model or reasoning level changed'); advertised() - elseif u.sessionUpdate=='agent_message_chunk' and u.content.type=='text' and s.prompting then s.delta(u.content.text) end - elseif q.method=='session/request_permission' and q.id~=nil then - local option; for _,o in ipairs(p.options or {}) do if o.kind=='allow_once' then option=o.optionId; break end end - local at=s.turn - local function answer(allow) if not closed then send({id=q.id,result={outcome=allow and s.prompting and s.turn==at and {outcome='selected',optionId=option} or {outcome='cancelled'}}}) end end - local detail=json.encode(p.toolCall or {}); if not p.toolCall or not ours or not s.prompting or not option or approval or #detail>4096 then answer(false); return end - approval=uv.spawn('/usr/bin/osascript',{args={'-e',dialog,'--',detail}},function(code,sig) close(approval); approval=nil; answer(code==0 and sig==0) end) - if not approval then answer(false) end + elseif s.prompting and u.sessionUpdate=='usage_update' and count(u.used) and count(u.size) and u.size>0 and u.used<=u.size then + s.context_window={used=u.used,size=u.size} + elseif s.prompting and (u.sessionUpdate=='tool_call' or u.sessionUpdate=='tool_call_update') then + pcall(s.observe,u) -- a cosmetic mount failure must not cancel an agy turn + elseif (u.sessionUpdate=='agent_message_chunk' or u.sessionUpdate=='agent_thought_chunk') and u.content.type=='text' and s.prompting then + s.delta(u.sessionUpdate=='agent_message_chunk' and 'text' or 'thinking',u.content.text) + end elseif q.id~=nil then send({id=q.id,error={code=-32601,message='Unsupported client method'}}) end end cancel_check=verified(function(bin,profile,env) - if #s.list>0 then seed_tool_permissions(profile) end stdin,stdout=uv.new_pipe(false),uv.new_pipe(false) - child,pid=uv.spawn(bin,{args={'acp','--gemini-dir',profile,'--sandbox','--disable-telemetry'},cwd=s.cwd,env=env,detached=true,stdio={stdin,stdout,nil}},function() + local agent=install_agent(s,profile) + local args={'acp','--agent',agent,'--include-default-customizations=false','--gemini-dir',profile,'--sandbox','--disable-telemetry','--dangerously-skip-permissions'} + child,pid=uv.spawn(bin,{args=args,cwd=s.cwd,env=env,detached=true,stdio={stdin,stdout,nil}},function() close(child); child=nil; if closed then cleanup() else s.fail('Antigravity exited; not replaying') end end); if not child then local err=pid; pid=nil; error(tostring(err)) end; local buf='' assert(stdout:read_start(function(e,data) diff --git a/catalog.lua b/catalog.lua index ef10bdf..31297d0 100644 --- a/catalog.lua +++ b/catalog.lua @@ -10,7 +10,7 @@ function M.catalog(req, names) local t=assert(all[name], 'Tool not in active rig: '..name); local s=json.decode(t.input_schema_json) assert(s.type=='object','Expected MCP object input schema for '..name) local wire=name:gsub('%.','__'); assert(wire:match('^[%w_-]+$') and #wire<=128 and not by[wire], 'Invalid or colliding MCP tool name: '..name) - by[wire]={name=name,schema=s}; list[i]={name=wire,description=t.description,inputSchema=s} + by[wire]={name=name,schema=s}; list[i]={name=wire,description=t.description,inputSchema=s,_meta={['antigravity/alwaysLoad']=true}} end return by,list end @@ -21,6 +21,10 @@ local function run(bin, args, opts, timeout) end local home = assert(uv.fs_mkdtemp('/private/tmp/panto-agy-XXXXXX')) local function check() + local usage=dofile(root..'/acp.lua').usage + local u={inputTokens=155,outputTokens=41,thoughtTokens=8,cachedReadTokens=55,cachedWriteTokens=10,totalTokens=196} + local v=usage(u); assert(v.input==90 and v.output==41 and v.cache_read==55 and v.cache_write==10 and v.reasoning==8) + u.totalTokens=261; assert(usage(u).input==155); u.totalTokens=99; assert(not usage(u) and not usage({}) and not usage(nil)) local catalog=dofile(root..'/catalog.lua').catalog local req={tools={{name='std.read',description='Read',input_schema_json='{"type":"object"}'}, {name='fixture.echo',description='Echo',input_schema_json='{"type":"object"}'}}} @@ -40,7 +44,7 @@ local function check() protocol="antigravity-acp" save_session=true ]]) - write(cfg .. '/models.toml', '[antigravity.fast]\nmodel="gemini-test"\n') + write(cfg .. '/models.toml', '[antigravity.fast]\nmodel="gemini-test"\ninput=10.0\noutput=10.0\ncache_read=1.0\ncache_write=10.0\n') write(cfg .. '/SYSTEM.md', 'Short answers.') local exe = home .. '/agy' assert(uv.fs_symlink(panto, home .. '/panto')) -- short, space-free shebang path @@ -51,13 +55,23 @@ local uv = require('luv'); local spawn = uv.spawn uv.spawn = function(bin, opts, cb) if bin == '/usr/bin/codesign' and opts.args[4] == os.getenv('HOME') .. '/agy' then bin, opts = '/usr/bin/true', {args={}} - elseif bin == '/usr/bin/osascript' then bin, opts = '/usr/bin/false', {args={}} end + end return spawn(bin, opts, cb) end return {name='test.signature', activate=function() - require('panto').ext.register_tool{name='fixture.echo',description='Return a nested value.', + local ext=require('panto').ext + ext.on('render_thinking_complete',function(e) + if e.text=='fixture-visible-thinking' then local f=assert(io.open(os.getenv('HOME')..'/thinking-rendered','w')); f:close() end + end) + ext.register_command{name='fixture-notice',description='Queue a workflow completion',handler=function() + ext.agent:submit('[subagents] Workflow fixture completed. Output below: marker') + end} + ext.register_tool{name='fixture.echo',description='Return a nested value.', schema={type='object',properties={rows={type='array',minItems=1,items={type='object',properties={value={type='integer'}},required={'value'}}}},required={'rows'}}, - handler=function(input) return tostring(input.rows[1].value) end} + handler=function(input) + if not uv.fs_stat(os.getenv('HOME')..'/.local/share/panto-antigravity/google/usage-failure') then ext.agent:submit('boundary workflow notice') end + return tostring(input.rows[1].value) + end} end} ]]) local env = {'HOME=' .. home, 'QUOTA_LOG=' .. home .. '/screen', 'TMPDIR=' .. home, @@ -79,16 +93,17 @@ end} local google = home .. '/.local/share/panto-antigravity/google' local stderr = read(log) assert(code ~= 0 and stderr:find('ProviderProtocolFailed', 1, true) and not uv.fs_stat(google), stderr) - -- Fake agy also runs `panto lua`, but under the isolated Google HOME. Reuse - -- the staged rocks there so the interpreter never needs a first-run install. - assert(run('/bin/mkdir', {'-p', '-m', '700', google}) == 0) - assert(run('/bin/mkdir', {'-p', google .. '/.local/share/panto'}) == 0) - assert(uv.fs_symlink(data .. '/rocks', google .. '/.local/share/panto/rocks')) - assert(sandbox({'/usr/bin/expect', root .. '/tests/tui.exp'}, 45000) == 0, 'TUI check failed') + local tui=sandbox({'/usr/bin/expect', root .. '/tests/tui.exp'}, 65000) + if tui~=0 then error('TUI check failed: '..read(home..'/screen'):gsub('\27%[[0-9;?]*[A-Za-z]', ''):sub(-3500)) end + assert(uv.fs_stat(home..'/thinking-rendered'),'ACP thought did not reach the native thinking component') + local agents = assert(uv.fs_scandir(google .. '/config/agents')); assert(not uv.fs_scandir_next(agents), 'Generated agent left in private profile') local screen = read(home .. '/screen'):gsub('\27%[[0-9;?]*[A-Za-z]', '') + assert(screen:find('1.3k/1M ctx',1,true),'expected ACP context occupancy, not summed turn inputs') + assert(screen:find('3.4k tok',1,true),'expected primary and steering usage counted exactly once') + assert(screen:find('agy native: manage_task [completed]',1,true) and not screen:find('agy native: mcp_pantograph_',1,true),'native activity missing or MCP call duplicated') assert(screen:find('27%%%s+━'), 'expected 27% used and a filled bar in the rendered footer') end local ok, err = xpcall(check, debug.traceback) assert(run('/bin/rm', {'-rf', home}) == 0) assert(ok, err) -print('PASS: headless denial, native TUI, quota meter, model alias, primary MCP tool, follow-up and saved resume') +print('PASS: headless denial, native TUI, quota meter, model alias, primary MCP tool, permissions, native resume, /tree transcript seed, warm follow-up and cold resume') diff --git a/docs/findings.md b/docs/findings.md index c1ee609..a519a4b 100644 --- a/docs/findings.md +++ b/docs/findings.md @@ -1,9 +1,29 @@ # Antigravity provider evidence +## Steering and thinking (agy 1.5.21) + +A live, isolated Neon Low turn returned its MCP marker plus both independently injected words: one from plain Enter while busy, one from `ext.agent:submit` inside the tool. The adapter sends the ordered text tail after the matched result as a concurrent ACP `session/prompt`, then returns the original MCP result once. Each request gets its own ID and only the original and all steering replies together complete the Panto turn. Both replies can carry distinct usage (observed 833 + 1044 tokens); the footer sums reported counts once. See [Google’s ACP steering contract](https://antigravity.google/docs/cli/acp/). + +Agent-sent `agent_thought_chunk` text routes separately to Panto’s thinking component, preserving its position among answer chunks and tools. A fake ACP peer verified the render event and checkpoint continuity. Neither the live Low probe nor a High arithmetic follow-up emitted a thought chunk; choosing a reasoning level does not guarantee displayable text. No reconstruction from logs or token counts. + ## Subscription meter (offline) The bundled `agy` changelog for 1.1.11 documents `-p "/usage"` as a read-only print command that spends no model turn. Static inspection of **1.5.18** (`printmode.quotaRows`, `bucketRemaining`, `bucketReset`, `headless.writeRows`) established the piped record: group, bucket, **remaining**, UTC reset. A raw count has no denominator and cannot yield a percentage. This is an allowance reading, not ACP context occupancy or an estimate from token counts. The signed CLI also returned four-column TSV with `--gemini_dir <private profile> --sandbox -p /usage` in 1.5.19. Print mode rejects the ACP flags `--gemini-dir` and `--disable-telemetry`. The footer checks the exit status and records directly, without asking for a version. +## ACP isolation (agy 1.5.21) + +The installed CLI's `agy help acp` advertises `--agent` and `--include-default-customizations`. Its bundled changelog documents `excludeDefaultComponents` (1.2.1) and the MCP `antigravity/alwaysLoad` tool hint (1.3.3). A network-blocked `initialize` advertised system-prompt **append**, not override or a tool-inventory query. In a temporary home, `agy agents` listed a main-agent definition with an explicit stdio MCP entry. Discovery is not proof that the executor loaded its tools. + +In an authenticated startup probe with an inert local relay, `session/new` with the relay only in the agent definition went 11 seconds without `tools/list`. With the same descriptor also in ACP `mcpServers`, fresh processes called `tools/list` before replying to both `session/new` and `session/resume`. No `session/prompt` was sent. The adapter now uses that handshake rather than waiting for rewrites in a shared on-disk cache. + +The provider selects a custom main agent, disallows inherited tools/customizations in its definition, and puts the one relay directly in that definition rather than expecting the selected agent to inherit `session/new.mcpServers`. The offline TUI fixture launches that relay and dispatches a tool on new and resumed sessions. It does not run Google's executor. Use the fresh-marker checks in the README when upgrading; agy may retain infrastructure declarations even if native workspace actions are absent. A model listing names, a `tools/list` request, and successful execution are three different observations. + +Live Rex checks on `agy` 1.5.21 with a fresh `antigravity:gemini-4-neon -r low` verified a first-turn Panto `std.read` card and the correct file line. Neon described the Panto role and tool guidance and reported three unprefixed declarations: `list_resources`, `read_resource`, `manage_task`. A disposable rig adding `excludeFundamentalComponents`, `disallowedTools` and `disabledTools` to the agent frontmatter produced the same three names; none of those trial keys shipped. With the production agent definition and `tools = []`, Neon reported only `manage_task` and could not retrieve a fresh file marker. The frontend tool list is self-reported, not an ACP inventory. The usage footer showed numbers before any prompt through the signed CLI's `/usage` command. + +A subsequent 1.5.21 Rex probe called `manage_task` (list only) and `mcp_pantograph_std__read` in one turn. ACP sent distinct tool-call IDs and start/completion statuses for both. `session/prompt` returned `inputTokens=2166`, `outputTokens=228`, `thoughtTokens=117`, `totalTokens=2394` with zero cache reads/writes. The latest `usage_update` instead said `used=1330, size=1048576`. A one-word follow-up returned 1418 total tokens: the prompt totals are not cumulative session usage. Panto records usage on final completion only and prices it from model config, not Google endpoints. Real nonzero cache splits have not been independently audited. + +Current [Terms §6](https://antigravity.google/terms/) explicitly permit supported ACP, headless, MCP and custom-agent interfaces while separately prohibiting direct entitlement use and raw-model proxying. `agy` owns the turn and asks Panto for tool results over MCP. The older references below are historical, not a promise about enforcement. + ## Native tool switch (agy 1.5.19) An unauthenticated ACP probe in a temporary profile sent `_meta.disableBuiltInTools` with both `session/new` and `session/resume`. Both methods rejected a string with `-32602` (expected bool at `_meta.disableBuiltInTools`); `true` passed decoding and reached `Authentication required`. A string at the top level or under `_meta.antigravity` was ignored. This verifies the wire field, not the tool inventory of a signed-in Neon turn. `check.lua` tests both outbound envelopes and actual MCP listing/dispatch through the Panto TUI with a fake peer. For the live check use the read-card and `/antigravity-status` procedure in the README. diff --git a/extensions/antigravity-acp.lua b/extensions/antigravity-acp.lua index 98ab958..8484bce 100644 --- a/extensions/antigravity-acp.lua +++ b/extensions/antigravity-acp.lua @@ -12,6 +12,7 @@ local catalog,acp=companion('catalog'),companion('acp') local active local function stop() local s=active; if not s then return end; active=nil + if s.card then s.card:unmount() end if s.shutdown then s.shutdown() end if s.peer and not s.peer:is_closing() then s.peer:close() end s.server:close(); uv.fs_unlink(s.dir..'/mcp'); uv.fs_rmdir(s.dir) @@ -41,6 +42,37 @@ local function rpc(s,c,q) else return fail(-32601,'Unsupported method') end send(c,{id=q.id,result=result}) end +-- ACP tool notifications are observations, NOT Panto tool invocations. Keep +-- a small live component for the current/last prompt; never enter tool dispatch. +local function native_activity(s) + local rows={} + local statuses={pending='pending',in_progress='running',completed='completed',failed='failed'} + return function(u) + local id=u.toolCallId + if type(id)~='string' or #id>256 then return end + local row; for _,v in ipairs(rows) do if v.id==id then row=v; break end end + if not row then + local name=u.name or (type(u.title)=='string' and u.title:match('^Run ([%w_.-]+)$')) + if type(name)~='string' or #name>96 or not name:match('^[%w_.-]+$') then return end + if s.by[name:match('^mcp_pantograph_(.+)$') or false] then return end + row={id=id,name=name,status='reported'}; rows[#rows+1]=row + if #rows>6 then table.remove(rows,1) end + end + local input=type(u.rawInput)=='table' and u.rawInput or {} + if row.name=='manage_task' and type(input.Action)=='string' and ({list=true,kill=true,status=true,send_input=true})[input.Action] then + row.action=input.Action + end + row.status=statuses[u.status] or row.status + if not s.card then + s.card=ext.mount({render=function(_,width) + local lines={}; for i,v in ipairs(rows) do + lines[i]=('agy native: '..v.name..(v.action and ' ('..v.action..')' or '')..' ['..v.status..']'):sub(1,width) + end; return lines + end},'above_input') + end + s.card:invalidate() + end +end local function start(req,by,list,signature,save) local dir=assert(uv.fs_mkdtemp('/tmp/panto-antigravity-XXXXXX')) local s={sid=req.context,dir=dir,server=uv.new_pipe(false),by=by,list=list,seq=0,notify=req.notify}; active=s @@ -57,7 +89,7 @@ local function start(req,by,list,signature,save) local c=uv.new_pipe(false); if not s.server:accept(c) or s.peer then c:close(); return end s.peer=c; local buf=''; c:read_start(function(e,chunk) if active~=s or s.peer~=c or c:is_closing() then return end - if e or not chunk then if s.call then s.fail('MCP disconnected during tool call') else s.peer=nil; c:close() end; return end + if e or not chunk then if s.call then s.fail('MCP disconnected during tool call') else s.peer=nil; s.listed=false; c:close() end; return end buf=buf..chunk while active==s do local at=buf:find('\n',1,true); if (at or #buf)>1048576 then s.fail('Oversized MCP request'); return end @@ -72,6 +104,20 @@ end local function digest(text,h) h=h or 0xcbf29ce484222325; for i=1,#text do h=(h ~ text:byte(i))*0x100000001b3 end; return h end +-- Preserve legacy all-text checkpoints. For mixed replies, hash the ordered +-- typed runs, independent of how ACP and the TUI split their chunks. +local function append_reply(r,kind,text) + if text=='' then return end + if r.kind~=kind then + if r.kind then r.prefix=digest(('%s:%016x'):format(r.kind,r.tail),r.prefix) end + r.kind,r.tail=kind,nil + end + r.tail=digest(text,r.tail) +end +local function reply_key(r) + if not r.prefix and r.kind~='thinking' then return ('%016x'):format(r.tail or digest('')) end + return ('blocks:%016x'):format(digest(('%s:%016x'):format(r.kind,r.tail),r.prefix)) +end local function history(msgs,n) local h; for i=1,n do h=digest(json.encode({msgs[i].role,msgs[i].blocks}),h) end; return ('%016x'):format(h or 0) end @@ -109,18 +155,36 @@ end,activate=function() local info=ext.session_info() if not ready or not info or req.purpose~='turn' or info.session_id~=req.context then return terminal('Interactive primary thread required') end local msgs=req.messages; local last=msgs[#msgs]; local b=last and last.blocks[1]; local s=active - if s and s.sid~=req.context then return terminal('Another thread owns this session') end - if req.tui_submission==true and last and last.role=='user' and #last.blocks==1 and b.type=='text' then + if s and s.sid~=req.context then + if s.pending or not req.tui_submission then return terminal('Another thread owns this session') end + stop(); s=nil + end + local direct=req.tui_submission==true + -- Panto extensions submit workflow completions as ordinary user text. + -- They may continue a matching live turn, never open or reseed one. + local warm=s and not s.pending and s.last~=nil + local awaiting=s and s.pending and s.call and s.call.sent + if not awaiting and (direct or warm) and last and last.role=='user' and #last.blocks==1 and b.type=='text' then if s and s.pending then return terminal('An Antigravity turn is already pending') end local cfg=ext.config.providers[req.provider]; validate(cfg); local by,list=catalog.catalog(req,cfg.tools) - local sig=('%016x'):format(digest(json.encode({'mcp-only-v1',uv.cwd(),req.provider,req.model,req.system_prompt or '',list}))) + local sig=('%016x:skip'):format(digest(json.encode({'panto-agent-acp-v2',uv.cwd(),req.provider,req.model,req.system_prompt or '',list}))) + local prompt=b.text local prior=msgs[#msgs-1]; local tag=prior and prior.metadata and prior.metadata.antigravity_acp local key='antigravity_acp.checkpoint.'..req.context if prior or s then - local reply=''; for _,v in ipairs(prior and prior.blocks or {}) do if v.type=='text' then reply=reply..v.text else reply=nil; break end end - if not (tag and tag.thread==req.context and tag.signature==sig and tag.history==history(msgs,#msgs-2) and reply and tag.response==('%016x'):format(digest(reply)) and + local reply={}; for _,v in ipairs(prior and prior.blocks or {}) do + if v.type~='text' and v.type~='thinking' then reply=nil; break end + append_reply(reply,v.type,v.text) + end + if not (tag and tag.thread==req.context and tag.signature==sig and tag.history==history(msgs,#msgs-2) and reply and tag.response==reply_key(reply) and ((s and s.last==tag.turn) or (not s and cfg.save_session==true and tag.session and ext.state.get(key)==tag.turn))) then - stop(); return terminal('No matching Antigravity history checkpoint. Start a new Panto thread; nothing was replayed.') + if not direct then return terminal('Extension follow-up requires a matching live Antigravity checkpoint') end + stop(); s=nil; tag=nil + if prior then + local transcript=req.history_transcript + if type(transcript)~='string' or transcript=='' then return terminal('Cannot continue: Panto did not supply the selected history transcript.') end + prompt='Selected Panto conversation history (background only; do not repeat past actions):\n\n'..transcript..'\n\nCurrent user request:\n'..b.text + end end end if not s then @@ -130,28 +194,46 @@ end,activate=function() if s.resolve then local wire,why=s.resolve(req.effort); if not wire then return terminal(why) end end + if s.card then s.card:unmount(); s.card=nil end + s.observe=native_activity(s); s.context_window=nil; s.usage=nil s.effort=req.effort if s.save then local ok,err=ext.state.set(key,nil); if not ok then stop(); return terminal(tostring(err)) end end - s.pending=true; s.notify=req.notify; s.buffer=''; s.response=digest(''); s.prefix=history(msgs,#msgs) - s.delta=function(text) - assert(type(text)=='string' and #s.buffer+#text<=4<<20,'Invalid ACP text'); s.buffer=s.buffer..text; s.notify() + s.pending=true; s.notify=req.notify; s.chunks={}; s.bytes=0; s.response={}; s.prefix=history(msgs,#msgs) + s.delta=function(kind,text) + assert(type(text)=='string' and s.bytes+#text<=4<<20,'Invalid ACP text'); if text=='' then return end + local tail=s.chunks[#s.chunks]; if tail and tail.kind==kind then tail.text=tail.text..text + else s.chunks[#s.chunks+1]={kind=kind,text=text} end + s.bytes=s.bytes+#text; s.notify() end - -- Only an authenticated direct turn is allowed to request a quota read. s.offered=function(models) offers=models end s.refresh=refresh and cfg.usage_footer~=false and refresh or nil - s.complete=function(reason) + s.complete=function(reason,usage) + s.usage=usage assert(not s.call,'Prompt ended with an outstanding MCP call'); s.last=s.dir..':'..tostring(s.turn); s.finished=reason; s.notify() end s.turn=(s.turn or 0)+1 - local ok,err=pcall(function() if s.submit then s.submit(b.text) else acp.launch(s,b.text,tag and tag.session) end end); if not ok then s.fail(err) end - elseif s and s.pending and s.call and s.call.sent and last and last.role=='user' and #last.blocks==1 and b.type=='tool_result' and b.tool_use_id==s.call.tag then - s.prefix=history(msgs,#msgs); s.response=digest('') + local ok,err=pcall(function() if s.submit then s.submit(prompt) else acp.launch(s,prompt,tag and tag.session) end end); if not ok then s.fail(err) end + elseif awaiting then + -- Panto may append one or more user messages after the single tool + -- result. Never search past other roles/results for a reusable tag. + local i=#msgs; local steer=json.array({}) + while i>0 and msgs[i].role=='user' and msgs[i].blocks[1] and msgs[i].blocks[1].type=='text' do i=i-1 end + local carrier=msgs[i]; b=carrier and carrier.blocks[1] + if not (carrier and carrier.role=='user' and #carrier.blocks==1 and b.type=='tool_result' and b.tool_use_id==s.call.tag) then + s.fail('Missing matching tool result at ACP continuation'); return terminal(s.error) + end + for j=i+1,#msgs do for _,v in ipairs(msgs[j].blocks) do + if v.type~='text' then s.fail('Only text can steer an active ACP turn'); return terminal(s.error) end + steer[#steer+1]={type='text',text=v.text} + end end + s.prefix=history(msgs,#msgs); s.response={} local parts=json.array({}); local failed=b.is_error for _,v in ipairs(b.content) do if v.type=='text' then parts[#parts+1]={type='text',text=v.text} elseif v.type=='media' and v.media_type:match('^image/') then parts[#parts+1]={type='image',mimeType=v.media_type,data=v.data} else failed=true; parts[#parts+1]={type='text',text='Unsupported tool result content'} end end + if #steer>0 then s.steer(steer) end send(s.peer,{id=s.call.id,result={isError=failed,content=parts}}); s.call=nil else if s and s.pending then s.fail('Unexpected Panto continuation') end @@ -161,15 +243,20 @@ end,activate=function() return {next=function() if s.error then return {type='error',kind='terminal',message=s.error} end if active~=s then return {type='error',kind='terminal',message='Antigravity session closed'} end - if s.buffer~='' then local text=s.buffer; s.buffer=''; s.response=digest(text,s.response); return {type='text_delta',text=text} end + if s.bytes>0 then + local chunk=table.remove(s.chunks,1); s.bytes=s.bytes-#chunk.text; append_reply(s.response,chunk.kind,chunk.text) + return {type=chunk.kind..'_delta',text=chunk.text} + end if s.finished then local reason=s.finished; s.finished=nil; s.pending=false if s.refresh then pcall(s.refresh) end if s.save then assert(ext.state.set(s.key,s.last)) end - return {type='done',termination={reason=reason},metadata={antigravity_acp={thread=s.sid,session=s.save and s.session or nil,turn=s.last,signature=s.signature,history=s.prefix,response=('%016x'):format(s.response)}}} + return {type='done',usage=s.usage,termination={reason=reason},metadata={context_window=s.context_window,antigravity_acp={thread=s.sid,session=s.save and s.session or nil,turn=s.last,signature=s.signature,history=s.prefix,response=reply_key(s.response)}}} end local call=s.call; if not call then return nil end - if call.sent then return {type='done',termination={reason='tool_use'}} end + -- A single ACP prompt can span many Panto messages. Publish its + -- latest occupancy at tool boundaries too, without billing a turn. + if call.sent then return {type='done',termination={reason='tool_use'},metadata=s.context_window and {context_window=s.context_window}} end call.sent=true; return {type='tool_call',id=call.tag,name=call.name,input_json=call.input} end} end} @@ -39,6 +39,10 @@ function M.parse(body, reset_time) 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, @@ -58,6 +62,7 @@ function M.activate(ext, footer, acp) 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 @@ -66,7 +71,8 @@ function M.activate(ext, footer, acp) end local render if windows and #windows > 0 then - local expires = os.time() + stale_s + local sampled = os.time() + local expires = sampled + stale_s local stale = section({}, 'stale') local cached, deadline = nil, 0 render = function(now) @@ -74,13 +80,16 @@ function M.activate(ext, footer, acp) 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 < #windows and 'stale' or nil) + cached = section(current, (#current == 0 or expired) and 'stale' or nil) end return cached(now) end @@ -91,8 +100,7 @@ function M.activate(ext, footer, acp) pcall(footer.publish, ext, key, render) end - -- The caller supplies direct-turn provenance. Only a visible footer needs - -- a sample. Drop duplicate calls in flight or inside the cooldown; no polling. + -- 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 @@ -151,13 +159,24 @@ function M.activate(ext, footer, acp) ext.on('session_ready', function(event) if not alive or ready or event.has_tui == false then return end ready = true - -- Show a placeholder without touching the account; only a direct turn - -- may replace it with an actual reading. - pcall(footer.publish,ext,key,footer.section(ext,'antigravity',{}, {status='awaiting first turn'})) + 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) diff --git a/tests/fake-agy.lua b/tests/fake-agy.lua index cd4f460..ae671c3 100644 --- a/tests/fake-agy.lua +++ b/tests/fake-agy.lua @@ -1,13 +1,13 @@ -- Offline agy fixture. check.lua installs this with Panto's embedded Lua shebang. local uv, json = require('luv'), require('panto').ext.json -local home = assert(os.getenv('HOME')) +local profile = assert(os.getenv('HOME')) .. '/.local/share/panto-antigravity/google' if arg[1] == '--version' then error('unexpected version check') end if arg[1] ~= 'acp' then assert(json.encode({table.unpack(arg)}) == json.encode({ - '--gemini_dir', home, '--sandbox', '-p', '/usage', + '--gemini_dir', profile, '--sandbox', '-p', '/usage', }), 'unrecognized fake CLI invocation') - if uv.fs_stat(home .. '/usage-failure') then os.exit(3) end - assert(uv.cwd() == home and home:match('/google$') and uv.guess_handle(0) ~= 'tty') + if uv.fs_stat(profile .. '/usage-failure') then os.exit(3) end + assert(uv.cwd() == profile and uv.guess_handle(0) ~= 'tty') print('Gemini\tWeekly\t73%\t2099-02-03T12:00:00Z'); return end @@ -25,10 +25,46 @@ local function prompt(text) return q end local function finish(q, text) + if text=='same-session-ok' then + send({method='session/update',params={sessionId='test-session',update={sessionUpdate='agent_thought_chunk',content={type='text',text='fixture-visible-thinking'}}}}) + end send({method='session/update', params={sessionId='test-session', update={ sessionUpdate='agent_message_chunk', content={type='text', text=text}, }}}) - reply(q, {stopReason='end_turn'}) + local function update(u) send({method='session/update',params={sessionId='test-session',update=u}}) end + update({sessionUpdate='usage_update',used=1330,size=1048576}) + update({sessionUpdate='tool_call',toolCallId='native-1',name='manage_task',status='in_progress'}) + update({sessionUpdate='tool_call_update',toolCallId='native-1',status='completed'}) + if text=='primary-tool-ok' then update({sessionUpdate='tool_call',toolCallId='mcp-1',name='mcp_pantograph_fixture__echo',status='completed'}) end + reply(q, {stopReason='end_turn',usage={inputTokens=2166,outputTokens=228,thoughtTokens=117,totalTokens=2394,cachedReadTokens=900}}) +end + +local function load_catalog(server) + local input, output = assert(uv.pipe()), assert(uv.pipe()) + local proc = assert(uv.spawn(server.command, {args=server.args, stdio={input.read, output.write, 2}}, function() end)) + uv.fs_close(input.read); uv.fs_close(output.write) + local function rpc(id, method, params) + local line = json.encode({jsonrpc='2.0', id=id, method=method, params=params or {}}) .. '\n' + assert(uv.fs_write(input.write, line, -1) == #line) + local buf = '' + repeat + local chunk = assert(uv.fs_read(output.read, 4096, -1)); assert(chunk ~= '', 'relay closed'); buf = buf .. chunk + until buf:sub(-1) == '\n' + local r = json.decode(buf); assert(r.id == id); return r + end + assert(rpc(1, 'initialize').result.serverInfo.name == 'pantograph') + local tools = rpc(2, 'tools/list').result.tools + local schemas={}; for _,t in ipairs(tools) do assert(t._meta['antigravity/alwaysLoad']==true); schemas[t.name]=t.inputSchema end + assert(schemas.std__read and schemas.std__edit and schemas.fixture__echo.properties.rows.items.required[1]=='value') + return function() + assert(rpc(3, 'tools/call', {name='not_exported', arguments={}}).error.code == -32602) + assert(rpc(5, 'tools/call', {name='fixture__echo', arguments={rows={{value='bad'}}}}).error.code == -32602) + local echo=rpc(6, 'tools/call', {name='fixture__echo', arguments={rows={{value=42}}}}).result + assert(echo.isError==false and echo.content[1].text=='42') + local r = rpc(4, 'tools/call', {name='std__read', arguments={path=uv.cwd() .. '/.panto/SYSTEM.md'}}).result + assert(r.isError == false and r.content[1].text:find('Short answers', 1, true)) + proc:kill('sigkill'); uv.fs_close(input.write); uv.fs_close(output.read); uv.run(); proc:close() + end end local q = request('initialize') @@ -38,15 +74,21 @@ reply(q, {protocolVersion=1, authMethods={{id='oauth-personal'}}, agentCapabilit q = request('authenticate'); assert(json.encode(q.params) == '{"methodId":"oauth-personal"}'); reply(q) q = read() local setup, resumed = q.params, q.method == 'session/resume' -assert(#setup.mcpServers == 1 and setup.mcpServers[1].name=='pantograph' and setup._meta.disableBuiltInTools == true) -local settings=home..'/antigravity-cli/settings.json' -local f=assert(io.open(settings,'r')); local policy=json.decode(f:read('a')); f:close() -if resumed or uv.fs_stat(home..'/usage-failure') then - assert(policy.permissions.ask[1]=='mcp(pantograph/*)', 'existing settings replaced') -else - assert(json.encode(policy)=='{"permissions":{"allow":["mcp(pantograph/*)"]}}', 'missing scoped agy default') - f=assert(io.open(settings,'w')); assert(f:write('{"permissions":{"ask":["mcp(pantograph/*)"]}}')); assert(f:close()) +assert(setup._meta.disableBuiltInTools == true) +assert(arg[2]=='--agent' and arg[3]:match('^panto%-%x[%x-]+$') and arg[4]=='--include-default-customizations=false') +assert(arg[9]=='--dangerously-skip-permissions') +assert(arg[5]=='--gemini-dir' and arg[6]==profile) +local af=assert(io.open(profile..'/config/agents/'..arg[3]..'.md')); local agent=af:read('a'); af:close() +for _,line in ipairs({'name: '..arg[3],'mainAgent: true','subagent: false','excludeDefaultComponents: true','inheritCustomizations: false','inheritMcp: false','tools: []'}) do assert(agent:find('\n'..line..'\n',1,true),line) end +local servers=json.decode(assert(agent:match('\nmcpServers: ([^\n]+)'))) +if uv.fs_stat(profile..'/no-tools') then assert(#servers==0) else assert(#servers==1 and servers[1].name=='pantograph' and servers[1].command=='/usr/bin/nc') end +assert(#setup.mcpServers==#servers) +local server=setup.mcpServers[1] +if server then + assert(server.name==servers[1].name and server.command==servers[1].command and json.encode(server.args)==json.encode(servers[1].args) and json.encode(server.env)=='[]') end +local check_relay=server and not uv.fs_stat(profile..'/skip-list') and load_catalog(server) +assert(not uv.fs_stat(profile..'/antigravity-cli/settings.json'),'extension seeded permission settings') if resumed then assert(setup.sessionId == 'test-session' and not setup._meta.antigravity) else assert(q.method == 'session/new' and setup._meta.antigravity.systemPrompt.append:find('Short answers', 1, true)) end if resumed then -- Older ACP pickers may expose suffixed models instead. @@ -72,40 +114,36 @@ if not resumed then set_level('low') end -local function check_relay(server) - local input, output = assert(uv.pipe()), assert(uv.pipe()) - local proc = assert(uv.spawn(server.command, {args=server.args, stdio={input.read, output.write, 2}}, function() end)) - uv.fs_close(input.read); uv.fs_close(output.write) - local function rpc(id, method, params) - local line = json.encode({jsonrpc='2.0', id=id, method=method, params=params or {}}) .. '\n' - assert(uv.fs_write(input.write, line, -1) == #line) - local buf = '' - repeat - local chunk = assert(uv.fs_read(output.read, 4096, -1)); assert(chunk ~= '', 'relay closed'); buf = buf .. chunk - until buf:sub(-1) == '\n' - local r = json.decode(buf); assert(r.id == id); return r +if not servers[1] then finish(prompt('no-tools'),'no-tools-ok') +elseif resumed then local resumed_prompt=prompt('resume'); check_relay(); finish(resumed_prompt, 'resumed-ok') elseif uv.fs_stat(profile..'/usage-failure') then + assert(not resumed) + q=request('session/prompt'); local blocks=q.params.prompt; assert(#blocks==1) + local text=blocks[1].text + assert(text:find('[User]: hello',1,true)) + assert(not text:find('same-session-ok',1,true) and not text:find('resumed-ok',1,true),'abandoned branch leaked') + local current=assert(text:match('Current user request:\n([^\n]+)$')) + assert(not text:find('[User]: '..current,1,true),'current prompt duplicated') + if current~='boundary workflow notice' then assert(text:find('[Assistant]: primary-tool-ok',1,true)) end + if current=='branch-probe' then + finish(q,'branch-seed-ok'); finish(prompt('warm-probe'),'warm-after-seed-ok') + reply(prompt('cancel-probe'),{stopReason='cancelled'}) + elseif current=='boundary workflow notice' then + assert(text:find('[User]: boundary steer',1,true) and text:find('[Tool result',1,true)); finish(q,'proceed-recovered-ok') + else + assert(current=='cold-probe' and text:find('[Assistant]: warm-after-seed-ok',1,true)); finish(q,'cold-resume-ok') end - assert(rpc(1, 'initialize').result.serverInfo.name == 'pantograph') - local tools = rpc(2, 'tools/list').result.tools - local schemas={}; for _,t in ipairs(tools) do schemas[t.name]=t.inputSchema end - assert(schemas.std__read and schemas.std__edit and schemas.fixture__echo.properties.rows.items.required[1]=='value') - assert(rpc(3, 'tools/call', {name='not_exported', arguments={}}).error.code == -32602) - assert(rpc(5, 'tools/call', {name='fixture__echo', arguments={rows={{value='bad'}}}}).error.code == -32602) - local echo=rpc(6, 'tools/call', {name='fixture__echo', arguments={rows={{value=42}}}}).result - assert(echo.isError==false and echo.content[1].text=='42') - local r = rpc(4, 'tools/call', {name='std__read', arguments={path=uv.cwd() .. '/.panto/SYSTEM.md'}}).result - assert(r.isError == false and r.content[1].text:find('Short answers', 1, true)) - proc:kill('sigkill'); uv.fs_close(input.write); uv.fs_close(output.read); uv.run(); proc:close() -end - -if resumed then finish(prompt('resume'), 'resumed-ok') else +else q = prompt('hello') - send({id='perm', method='session/request_permission', params={sessionId='test-session', - toolCall={title='Read local file'}, options={{kind='allow_once', optionId='once'}}, - }}) - assert(json.encode(read().result.outcome) == '{"outcome":"cancelled"}') - check_relay(setup.mcpServers[1]); finish(q, 'primary-tool-ok') + send({method='session/update',params={sessionId='test-session',update={sessionUpdate='agent_message_chunk',content={type='text',text='steer-window-open'}}}}) + while not uv.fs_stat(profile..'/steer-queued') do uv.sleep(10) end + send({method='session/update',params={sessionId='test-session',update={sessionUpdate='usage_update',used=8200,size=1048576}}}) + check_relay() + local steer=request('session/prompt'); assert(steer.id~=q.id and steer.params.sessionId=='test-session') + local p=steer.params.prompt; assert(#p==2 and p[1].text=='boundary steer' and p[2].text=='boundary workflow notice','steering payload/order') + while not uv.fs_stat(profile..'/context-visible') do uv.sleep(10) end -- final usage must not drive the live reading + finish(q, 'primary-tool-ok'); reply(steer,{stopReason='end_turn',usage={inputTokens=1000,outputTokens=6,totalTokens=1006}}) -- out of request order also works set_level('high') finish(prompt('again'), 'same-session-ok') + finish(prompt('[subagents] Workflow fixture completed. Output below: marker'), 'workflow-notice-ok') end for _ in io.lines() do end -- keep the session alive until Panto closes stdin diff --git a/tests/tui.exp b/tests/tui.exp index 4f79c31..b8cdf4d 100644 --- a/tests/tui.exp +++ b/tests/tui.exp @@ -1,44 +1,70 @@ set timeout 12 +set stty_init "rows 32 columns 180" log_user 0 log_file -a $env(QUOTA_LOG) match_max 32000 spawn -noecho $env(PANTO) -m antigravity:fast -r low proc see {pattern} {expect { -re $pattern {} - timeout {puts stderr "timeout awaiting $pattern: $expect_out(buffer)"; exit 1} + timeout {puts stderr "timeout awaiting $pattern"; exit 1} eof {puts stderr "early exit: $expect_out(buffer)"; exit 1} }} -see {antigravity:} +see {antigravity:}; see {27%} foreach {prompt answer} {hello primary-tool-ok again same-session-ok} { send -- $prompt; see $prompt; send -- "\r" if {$prompt == "hello"} { - set reply 0; set quota 0 - while {!$reply || !$quota} { - expect { - -exact "primary-tool-ok" {set reply 1} - -exact "27%" {set quota 1} - timeout {puts stderr "first turn: reply=$reply quota=$quota"; exit 1} - eof {exit 1} - } - } + see {steer-window-open}; send -- "boundary steer"; see {boundary steer}; send -- "\r"; see {1 steering} + set flag [open "$env(HOME)/.local/share/panto-antigravity/google/steer-queued" w]; close $flag + see {8\.2k/1M ctx}; set flag [open "$env(HOME)/.local/share/panto-antigravity/google/context-visible" w]; close $flag + see $answer send -- "/reasoning high"; see {/reasoning high}; send -- "\r"; see {reasoning -> high} } else {see $answer} } +send -- "/fixture-notice "; see {/fixture-notice }; send -- "\r"; see {workflow-notice-ok} send -- "\003"; expect eof; wait set flag [open "$env(HOME)/.local/share/panto-antigravity/google/usage-failure" w]; close $flag spawn -noecho $env(PANTO) resume -m antigravity:fast -r high -see {antigravity:}; send -- "resume"; see {resume}; send -- "\r" -set reply 0; set quota 0 -while {!$reply || !$quota} { - expect { - -exact "resumed-ok" {set reply 1} - -exact "unavailable" {set quota 1} - timeout {puts stderr "resume: reply=$reply quota=$quota"; exit 1} - eof {exit 1} - } +see {antigravity:}; see {unavailable}; send -- "resume"; see {resume}; send -- "\r"; see {resumed-ok} +send -- "\003"; expect eof; wait + +# Select an earlier answer (not the resumed tip), then cold-resume after an +# unsuccessful turn. +spawn -noecho $env(PANTO) resume -m antigravity:fast -r low +see {antigravity:}; send -- "/tree "; see {/tree }; send -- "\r"; see {session tree} +send -- "primary-tool-ok"; after 150; send -- "\r"; see {branched from} +foreach {query answer} {branch-probe branch-seed-ok warm-probe warm-after-seed-ok cancel-probe {stopped: cancelled}} { + send -- $query; see $query; send -- "\r"; see $answer +} +send -- "\003"; expect eof; wait +spawn -noecho $env(PANTO) resume -m antigravity:fast -r low +see {antigravity:}; send -- "cold-probe"; see {cold-probe}; send -- "\r"; see {cold-resume-ok} +send -- "\003"; expect eof; wait + +# Recreate the saved tail from the original failure using this fake home's +# real session log: tool result, steering text, workflow text, no answer. +set recovered 0 +foreach path [glob $env(HOME)/.local/share/panto/sessions/*/*.jsonl] { + set fd [open $path r]; set records [split [read $fd] "\n"]; close $fd + set end [lsearch -glob $records {*"text":"boundary workflow notice"*}]; if {$end < 0} continue + set fd [open $path w]; puts $fd [join [lrange $records 0 $end] "\n"]; close $fd + spawn -noecho $env(PANTO) resume [file rootname [file tail $path]] -m antigravity:fast -r low + see {antigravity:}; send -- "\030"; see {\[reloaded\]}; send -- "\020"; see {proceed-recovered-ok} + send -- "\003"; expect eof; wait; set recovered 1; break } +if {!$recovered} {error "no persisted steering fixture"} + +# Setup that never lists the relay must fail without submitting. +set flag [open "$env(HOME)/.local/share/panto-antigravity/google/skip-list" w]; close $flag +spawn -noecho $env(PANTO) --incognito -m antigravity:fast -r low +see {antigravity:}; send -- "stall"; see {stall}; send -- "\r"; see {prompt not sent} send -- "\003"; expect eof; wait +# Also check unconditional launch flags when nothing is exported. +set cfg [open "$env(HOME)/.panto/config.toml" a]; puts $cfg {tools=[]}; close $cfg +set flag [open "$env(HOME)/.local/share/panto-antigravity/google/no-tools" w]; close $flag +spawn -noecho $env(PANTO) --incognito -m antigravity:fast -r low +see {antigravity:}; send -- "no-tools"; see {no-tools}; send -- "\r"; see {no-tools-ok} +send -- "\003"; expect eof; wait # xhigh exists before switching models, but not on gemini-test. spawn -noecho $env(PANTO) --incognito -m antigravity:fast -r xhigh see {antigravity:}; send -- "unsupported"; see {unsupported}; send -- "\r" |
