summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authort <t@tjp.lol>2026-12-05 10:01:32 -0700
committert <t@tjp.lol>2026-12-05 10:02:00 -0700
commit0b5892bc31fb576099421ecddfbdc7a7b243d02d (patch)
tree89193b0bb377e02d449fa591a2f72d58763689b8
parent48b14add01cb106217832e036e3569e494f1d65c (diff)
Allow Antigravity requests from any Panto context
-rw-r--r--README.md20
-rw-r--r--TODOs.md8
-rw-r--r--acp.lua8
-rw-r--r--catalog.lua15
-rw-r--r--check.lua35
-rw-r--r--docs/findings.md2
-rw-r--r--extensions/antigravity-acp.lua132
-rw-r--r--panto-antigravity-0.1.0-1.rockspec2
-rw-r--r--tests/fake-agy.lua14
-rw-r--r--tests/lifecycle.lua56
-rw-r--r--tests/tui.exp2
11 files changed, 203 insertions, 91 deletions
diff --git a/README.md b/README.md
index ad0b694..80b4399 100644
--- a/README.md
+++ b/README.md
@@ -1,9 +1,9 @@
# panto-antigravity
-Chat with Gemini in the Panto TUI through Google's signed Antigravity CLI on macOS. The CLI handles sign-in; you don't need an API key or a separate Panto rig.
+Use Gemini from Panto through Google's signed Antigravity CLI on macOS. The CLI handles sign-in; you don't need an API key or a separate Panto rig.
## Setup
-Install Google's `agy` and use a Panto build with `request.tui_submission`. Add the provider to `config.toml`:
+Install Google's `agy`. Add the provider to `config.toml`:
```toml
[extensions]
@@ -28,6 +28,12 @@ panto -m antigravity:gemini-4-neon -r high
`-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.
+Print a single answer (or omit `-- "..."` to read piped stdin):
+
+```sh
+panto -p -m antigravity:gemini-4-neon -- "What is today's date?"
+```
+
To load a checkout instead of the rock, replace `rocks` with `paths = ["/absolute/path/to/panto-antigravity/extensions"]`.
## Usage and context
@@ -67,16 +73,18 @@ Every ACP chat launch uses `--dangerously-skip-permissions` and `--sandbox`, eve
## 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. Esc sends ACP `session/cancel` to stop the active turn while keeping the warm ACP session for the next prompt (force-killing `agy` if it does not settle within 3s). 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.
+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. Esc sends ACP `session/cancel` to stop the active turn while keeping the warm ACP session for the next prompt (force-killing `agy` if it does not settle within 3s). 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. 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. Exact saved checkpoints record their current tip in the isolated profile and resume natively via ACP `session/resume`. 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. agy keeps only the first ~191 KB of a user message, so when the transcript and request exceed 160 KB the older part of the transcript goes into the new session's system prompt append, marked as a verbatim record rather than instructions, and the newest part stays in the user message with the request. Nothing is dropped, the order is kept and it is still one model call. A single request over ~159 KB is refused. 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.
+Matching live turns keep the warm ACP session. Exact saved checkpoints record their current tip in the isolated profile and resume natively via ACP `session/resume`. Otherwise, the next 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. agy keeps only the first ~191 KB of a user message, so when the transcript and request exceed 160 KB the older part of the transcript goes into the new session's system prompt append, marked as a verbatim record rather than instructions, and the newest part stays in the user message with the request. Nothing is dropped, the order is kept and it is still one model call. A single request over ~159 KB is refused. 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.
## Session 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. An explicit `panto -m antigravity:gemini-4-hydrogen -- "prompt"` in an interactive terminal counts as direct input; an automatic rig `PROMPT.md` does not. No print/proxy calls, child-provider requests, compaction or automatic retries. Direct input 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 adapter sends text and dropped images natively over ACP `session/prompt` (non-image attachments such as PDFs are refused) and relays text/image tool 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.
+The adapter accepts prompts regardless of their source: interactive and print mode, rig startup prompts, ACP clients, `panto serve`, and extension or child-agent requests. Separate Panto contexts have separate ACP sessions and tool relays. Compaction uses a temporary session without tools.
+
+Choose which callers can reach your host and which tools they can invoke. Requests run under your signed-in CLI account. Before sharing a server with others, check the [Antigravity terms](https://antigravity.google/terms/); accepting a request in Panto is not permission to redistribute model access. The adapter sends text and dropped images natively over ACP `session/prompt` (non-image attachments such as PDFs are refused) and relays text/image tool 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 `docs/findings.md` in the source repository for compatibility evidence.
+`PANTO=/path/to/panto mise run check` exercises source and installed-rock loading, renders the real footer with a fake CLI, and checks tool execution, resume, print-mode prompts and provider diagnostics on stderr. No installed `agy` or Google account is used. See `docs/findings.md` in the source repository for compatibility evidence.
diff --git a/TODOs.md b/TODOs.md
index c14608b..ba98b6e 100644
--- a/TODOs.md
+++ b/TODOs.md
@@ -10,11 +10,3 @@
- Verify how `agy` stores and resolves credentials under `--gemini-dir` on Linux (keychain/keyring vs file-backed auth) and confirm `private_profile()` permission checks and `/tmp/panto-antigravity-*` lock/socket paths in `extensions/antigravity-acp.lua` work cleanly there.
- Add a non-macOS sandbox/runner path in `check.lua` (currently `/usr/bin/sandbox-exec`, `/private/tmp`, and `/usr/bin/codesign` stubbing) so `mise run check` can verify both platforms.
- Update `panto-antigravity-0.1.0-1.rockspec` (`supported_platforms`) and `README.md` (macOS-only setup and Keychain notes) once verified end to end.
-
-## Investigate `panto -p` failure (`ProviderProtocolFailed`)
-
-- Symptom: `panto -p --model 'antigravity:gemini-4-hydrogen' -- 'what is todays date?'` exits 1 with `error: turn failed: ProviderProtocolFailed`.
-- Today: `PrintSession` in `../pantograph/src/main.zig` does initialize extensions (`session_ready` fires with `has_tui = false`), so `ready` is true, but `req.tui_submission` is `false` outside the TUI. `extensions/antigravity-acp.lua` rejects non-TUI openings with `terminal('Antigravity requires direct TUI input on a provenance-aware Panto build. No subscription request sent.')`, which `../pantograph/src/lua_provider.zig` maps to `error.ProviderProtocolFailed` — and `check.lua` currently asserts this exact `headless denial` behavior (matching `README.md`: "No print/proxy calls").
-- Open questions and work:
- - Decide whether explicit `panto -p` invocations should remain intentionally blocked or be permitted (and if permitted, how to distinguish direct CLI `-p` runs from headless/automated callers if needed, and update `README.md` + `check.lua`).
- - Surface the extension's `terminal` error message in `PrintSession` (instead of only `error: turn failed: ProviderProtocolFailed`) so intentional rejections aren't indistinguishable from protocol initialization bugs.
diff --git a/acp.lua b/acp.lua
index 286b3ab..dc4abdb 100644
--- a/acp.lua
+++ b/acp.lua
@@ -144,8 +144,7 @@ local function install_agent(s, profile)
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
- -- Active threads hold an exclusive lock on this Panto session ID.
- local name='panto-'..s.sid:lower()
+ local name='panto-'..s.agent_key
local servers=json.array({})
if #s.list>0 then servers[1]=relay(s) end
local data=([[---
@@ -379,7 +378,7 @@ function M.launch(s, first, resume_id)
elseif s.prompting and not s.cancelling 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 not s.cancelling 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
+ if s.observe then pcall(s.observe,u) end -- 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 and not s.cancelling then
s.delta(u.sessionUpdate=='agent_message_chunk' and 'text' or 'thinking',u.content.text)
end
@@ -392,6 +391,9 @@ function M.launch(s, first, resume_id)
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=''
+ -- A warm upstream must not keep a finished print invocation alive.
+ -- The request timer and Panto stream pump drive outstanding work.
+ child:unref(); stdout:unref(); stdin:unref()
assert(stdout:read_start(function(e,data)
if closed then return end; if e or not data then s.fail('ACP stream closed'); return end
buf=buf..data
diff --git a/catalog.lua b/catalog.lua
index d4b0c80..f73530c 100644
--- a/catalog.lua
+++ b/catalog.lua
@@ -39,11 +39,16 @@ function M.catalog(req, names)
if names==nil then
names={}; for name in pairs(all) do names[#names+1]=name end; table.sort(names)
end
- for i,name in ipairs(names) do
- 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] and wire~=M.part_tool.name, 'Invalid or colliding MCP tool name: '..name)
- by[wire]={name=name,schema=s}; list[i]={name=wire,description=t.description,inputSchema=s,_meta={['antigravity/alwaysLoad']=true}}
+ -- An allowlist narrows the caller's declarations; a child or server
+ -- client need not offer every tool allowed in the primary rig.
+ for _,name in ipairs(names) do
+ local t=all[name]
+ if t then
+ 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] and wire~=M.part_tool.name, 'Invalid or colliding MCP tool name: '..name)
+ by[wire]={name=name,schema=s}; list[#list+1]={name=wire,description=t.description,inputSchema=s,_meta={['antigravity/alwaysLoad']=true}}
+ end
end
return by,list
end
diff --git a/check.lua b/check.lua
index eac0f55..51194da 100644
--- a/check.lua
+++ b/check.lua
@@ -21,6 +21,7 @@ local function run(bin, args, opts, timeout)
end
local home = assert(uv.fs_mkdtemp('/private/tmp/panto-agy-XXXXXX'))
local function check()
+ dofile(root..'/tests/lifecycle.lua')
local acp_mod=dofile(root..'/acp.lua'); local usage=acp_mod.usage
local function cut(text,room)
local head,tail=acp_mod.history_split(text,room)
@@ -41,7 +42,7 @@ local function check()
local req={tools={{name='std.read',description='Read',input_schema_json='{"type":"object"}'},
{name='fixture.echo',description='Echo',input_schema_json='{"type":"object"}'}}}
local _,none=catalog(req,{}); assert(#none==0)
- local by,one=catalog(req,{'std.read'}); assert(#one==1 and by.std__read and not by.fixture__echo)
+ local by,one=catalog(req,{'not.offered','std.read'}); assert(#one==1 and one[1].name=='std__read' and by.std__read and not by.fixture__echo)
local configure=dofile(root..'/extensions/antigravity-acp.lua').configure
assert(not pcall(configure,{providers={antigravity={protocol='antigravity-acp',save_session=true}}}))
local cfg, data = home .. '/.panto', home .. '/.local/share/panto'
@@ -111,13 +112,31 @@ end}
for _, a in ipairs(args) do cmd[#cmd+1] = a end
return run('/usr/bin/sandbox-exec', cmd, {cwd=home, env=env, stdio=stdio}, timeout)
end
- local log = home .. '/headless.stderr'
- local fd = assert(uv.fs_open(log, 'w', 384))
- local code = sandbox({panto, '--incognito', '-p', '-m', 'antigravity:fast', '--', 'hello'}, 10000, {nil, 1, fd})
- uv.fs_close(fd)
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)
+ local function print_check(mode, args, input, diagnostic)
+ write(home..'/fixture-mode', mode); write(home..'/stdin', input or '')
+ local inf=assert(uv.fs_open(home..'/stdin','r',384))
+ local out=assert(uv.fs_open(home..'/stdout','w',384))
+ local err=assert(uv.fs_open(home..'/stderr','w',384))
+ local cmd={panto, '--incognito', '-p', '-m', 'antigravity:fast', '-r', diagnostic and 'xhigh' or 'low'}
+ for _,a in ipairs(args) do cmd[#cmd+1]=a end
+ local code=sandbox(cmd, 15000, {inf,out,err})
+ uv.fs_close(inf); uv.fs_close(out); uv.fs_close(err)
+ local stdout,stderr=read(home..'/stdout'),read(home..'/stderr')
+ if diagnostic then
+ assert(code~=0 and stderr:find('reasoning level xhigh',1,true) and not stderr:find('error: turn failed: ProviderProtocolFailed',1,true), stderr)
+ assert(not stdout:find('reasoning level xhigh',1,true) and not stdout:find('headless-',1,true), stdout)
+ else
+ assert(code==0 and stdout:find('headless-'..mode..'-ok',1,true), stdout..'\n'..stderr)
+ end
+ end
+ print_check('argv-probe', {'--','argv-probe'}, 'ignored stdin')
+ print_check('stdin-probe', {}, 'stdin-probe')
+ write(cfg..'/PROMPT.md','rig-probe')
+ print_check('rig-probe', {'--rig',cfg}, '')
+ assert(uv.fs_unlink(cfg..'/PROMPT.md'))
+ print_check('diagnostic', {'--','diagnostic'}, '', true)
+ assert(uv.fs_unlink(home..'/fixture-mode'))
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')
@@ -132,4 +151,4 @@ 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, permissions, native resume, /tree transcript seed, warm follow-up and cold resume')
+print('PASS: headless argv/stdin/rig and provider diagnostic, 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 8b5efd7..8d49701 100644
--- a/docs/findings.md
+++ b/docs/findings.md
@@ -32,7 +32,7 @@ An unauthenticated ACP probe in a temporary profile sent `_meta.disableBuiltInTo
- The operator reported a successful human-driven marker conversation and follow-up. The first answer depended on a fresh Panto Lua result; the second turn stayed in the ACP session. No live transcript, model ID, tier or credentials were recorded. This established the integration pattern, not general rig compatibility or Google approval.
- Offline, signed `agy 1.5.18` advertised ACP v1, native `oauth-personal`, prompt append, and session resume. A fully network-blocked `session/new` stopped at the CLI’s own loopback listener; that was not an authentication result. Saved-session behavior, model-change handling and cancellation were exercised with a fake ACP peer, not a live account.
-- ACP owns the conversation, model selection, permissions and follow-up inference. MCP carries tool calls; ACP tool updates must never execute them a second time. Use the account’s advertised Gemini choices, no transcript replay, proxying, autonomous delegation, account rotation or billing fallback.
+- ACP owns the conversation, model selection, permissions and follow-up inference. MCP carries tool calls; ACP tool updates must never execute them a second time. The spike used only the account’s advertised Gemini choices and did not test transcript reseeding, proxying, autonomous delegation, account rotation or billing fallback.
- A command cannot dispatch tools directly on the borrowed primary agent. Copying tool declarations to an owned child retained the original handler closure but changed its session identity. Waiting in `run_foreground` blocked the primary loop. A local-only Panto protocol instead emitted native tool events on the primary thread; the MCP relay could restart without moving the handler. Interrupting the host removed its private endpoint.
- Additional MCP tools do not imply exclusive dispatch. Neither suppression of native tools nor isolation from other configured servers was established. Do not expose delegation tools on the personal route.
- Reference: [Google ACP editor guide](https://antigravity.google/docs/ide/extensions/acp), [Terms §6](https://antigravity.google/terms), [T3/Zed clarification](https://discuss.ai.google.dev/t/197131/3), [disputed narrower interpretation](https://discuss.ai.google.dev/t/202970/5), [delegation guidance](https://discuss.ai.google.dev/t/203835/7), [pinned T3 adapter](https://github.com/pingdotgg/t3code/blob/6f2e02c1e10a4e4b1d9eb41d55e49ac4b606344b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts#L165-L169). T3’s precedent is an additive instruction and a per-session MCP descriptor, not a replacement system prompt.
diff --git a/extensions/antigravity-acp.lua b/extensions/antigravity-acp.lua
index 1809a19..a8d2229 100644
--- a/extensions/antigravity-acp.lua
+++ b/extensions/antigravity-acp.lua
@@ -9,9 +9,9 @@ local function companion(name)
return require('panto-antigravity.'..name)
end
local catalog,acp=companion('catalog'),companion('acp')
-local active, failed_handoff
-local function stop()
- local s=active; if not s then return end; active=nil
+local sessions, compactions, failed_handoffs = {}, {}, {}
+local function stop(s)
+ if not s or s.pool[s.sid]~=s then return end; s.pool[s.sid]=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
@@ -21,12 +21,16 @@ local function stop()
end
local function send(c,msg) msg.jsonrpc='2.0'; c:write(json.encode(msg)..'\n') end
local function release(id)
- if failed_handoff and failed_handoff.sid==id then failed_handoff=nil end
- if active and active.sid==id then stop() end
+ failed_handoffs[id]=nil
+ stop(sessions[id]); stop(compactions[id])
+end
+local function close_all()
+ for _,pool in ipairs({sessions,compactions}) do for _,s in pairs(pool) do stop(s) end end
+ failed_handoffs={}
end
local function cancel_turn(id)
- if failed_handoff and failed_handoff.sid==id then failed_handoff=nil end
- local s=active; if not s or s.sid~=id or not (s.pending or s.cancelling) then return end
+ failed_handoffs[id]=nil
+ local s=sessions[id]; if not s or not (s.pending or s.cancelling) then return end
if s.card then s.card:unmount(); s.card=nil end
if s.call and s.peer and not s.peer:is_closing() then
pcall(send,s.peer,{id=s.call.id,error={code=-32800,message='Turn cancelled'}})
@@ -36,7 +40,7 @@ local function cancel_turn(id)
s.turn=(s.turn or 0)+1; s.last,s.cancelled_prefix=nil,s.turn_prefix
local ok,kept=false,false
if s.cancel then ok,kept=pcall(s.cancel) end
- if not (ok and kept) then stop() end
+ if not (ok and kept) then stop(s) end
end
local function rpc(s,c,q)
if type(q)~='table' or q.jsonrpc~='2.0' or type(q.method)~='string' then error('Invalid MCP request') end
@@ -67,7 +71,7 @@ local function rpc(s,c,q)
else
if not tool then return fail(-32602,'Tool unavailable') end
local ok,why=catalog.arguments(tool.schema,v); if not ok then return fail(-32602,why or 'Tool arguments rejected') end
- if not s.prompting or s.cancelling then return fail(-32000,'No human turn pending') end
+ if not s.prompting or s.cancelling then return fail(-32000,'No active turn pending') end
if s.call then return fail(-32000,'Another Panto tool call is pending') end
s.seq=s.seq+1; s.call={id=q.id,tag=s.dir:match('[^/]+$')..'-'..s.seq,name=tool.name,input=json.encode(v)}; s.notify(); return
end
@@ -116,34 +120,40 @@ local function native_activity(s)
s.card:invalidate()
end
end
-local function start(req,by,list,signature)
+local function start(pool,req,by,list,signature)
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,results={},notify=req.notify}; active=s
+ local s={pool=pool,sid=req.context,dir=dir,server=uv.new_pipe(false),by=by,list=list,seq=0,results={},notify=req.notify}; pool[s.sid]=s
s.fail=function(msg)
- if active~=s then return end
+ if pool[s.sid]~=s then return end
s.error=tostring(msg):gsub('[%c]',' '):sub(1,512)
- if s.issued then failed_handoff={sid=s.sid,error=s.error} end
- stop()
+ if s.issued then failed_handoffs[s.sid]={tag=s.issued.tag,error=s.error} end
+ stop(s)
end
s.model,s.instructions,s.cwd,s.signature=req.model,req.system_prompt or '',assert(uv.cwd()),signature
- assert(s.sid:match('^[%x-]+$'),'Invalid Panto session ID')
- local lock='/tmp/panto-antigravity-lock-'..uv.getuid()..'-'..s.sid
- assert(uv.fs_mkdir(lock,448),'Saved thread locked: '..lock); s.lock=lock
+ -- Durable threads keep their cross-process lock and agent name. Other
+ -- host contexts (including serve's process-local IDs) get private names;
+ -- never interpolate an opaque context into a path or agent definition.
+ local durable=pool==sessions and #s.sid<=64 and s.sid:match('^[%x-]+$')
+ s.agent_key=durable and s.sid:lower() or dir:sub(-6):gsub('.',function(c) return ('%02x'):format(c:byte()) end)
+ if durable then
+ local lock='/tmp/panto-antigravity-lock-'..uv.getuid()..'-'..s.agent_key
+ assert(uv.fs_mkdir(lock,448),'Saved thread locked: '..lock); s.lock=lock
+ end
assert(s.server:bind(dir..'/mcp')); assert(s.server:listen(1,function(err)
- if err or active~=s then return end
+ if err or pool[s.sid]~=s then return end
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
+ s.peer=c; c:unref(); local buf=''; c:read_start(function(e,chunk)
+ if pool[s.sid]~=s or s.peer~=c or c:is_closing() then return end
if e or not chunk then s.call=nil; s.peer=nil; s.listed=false; c:close(); return end
buf=buf..chunk
- while active==s do
+ while pool[s.sid]==s do
local at=buf:find('\n',1,true); if (at or #buf)>1048576 then s.fail('Oversized MCP request'); return end
if not at then return end
local line=buf:sub(1,at-1); buf=buf:sub(at+1)
if not pcall(function() rpc(s,c,json.decode(line)) end) then s.fail('Malformed MCP request'); return end
end
end)
- end))
+ end)); s.server:unref() -- idle relays must not keep print mode running
return s
end
local function digest(text,h)
@@ -194,39 +204,41 @@ end
return {name='protocol.antigravity-acp',configure=function(config)
for _,cfg in pairs(config.providers or {}) do if cfg.protocol=='antigravity-acp' then validate(cfg) end end
end,activate=function()
- local ready,refresh,offers=false,nil,nil
+ local tui_id,refresh
+ local function current() return tui_id and sessions[tui_id] end
for _,cfg in pairs(ext.config.providers or {}) do
if cfg.protocol=='antigravity-acp' and cfg.usage_footer~=false then
refresh=companion('quota').activate(ext,companion('_usage_footer'),acp); break
end
end
ext.register_command{name='antigravity-status',description='Show local Antigravity connection status (no account request).',handler=function()
+ local active=current()
if not active or not active.session then return 'Antigravity: no connected ACP session. Submit text to start; sign-in is managed by the Google CLI.' end
local model=(active.wire or active.model)..(active.thought and ' ('..active.thought..')' or '')
return ('Antigravity: %s · %s · %d Panto tools · MCP %s · %d calls'):format(model,active.pending and 'turn pending' or active.cancelling and 'cancelling' or 'ready',#active.list,active.listed and 'listed' or 'not listed',active.seq)
end}
ext.register_command{name='antigravity-models',description='List Gemini families and reasoning levels from the last ACP setup (no account request).',handler=function()
+ local offers=(current() or {}).offers
if not offers then return 'No model list yet. Submit a turn to let the Google CLI advertise its available models.' end
return #offers>0 and ('Gemini models: '..table.concat(offers,'; ')) or 'No displayable Gemini models were advertised.'
end}
- ext.on('session_ready',function() ready=true end)
- ext.on('session_end',function() ready=false; offers=nil; failed_handoff=nil; stop() end)
- ext.register_protocol{name='antigravity-acp',effort_levels=acp.effort_levels,close=stop,cancel_turn=cancel_turn,reset_context=release,release_context=release,open=function(req)
- 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
- if s.pending or s.cancelling 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
- if failed_handoff then
- local failure=failed_handoff
- if direct or failure.sid==req.context then failed_handoff=nil end
- if not direct and failure.sid==req.context then return terminal(failure.error) end
+ ext.on('session_ready',function(e) tui_id=e.has_tui and ext.session_info().session_id or nil end)
+ ext.on('session_end',function() tui_id=nil; close_all() end)
+ ext.register_protocol{name='antigravity-acp',effort_levels=acp.effort_levels,close=close_all,cancel_turn=cancel_turn,reset_context=release,release_context=release,open=function(req)
+ local compact=req.purpose=='compaction'
+ local pool=compact and compactions or sessions
+ local s=pool[req.context]; local msgs=req.messages; local last=msgs[#msgs]; local b
+ -- If ACP died after emitting a tool call, surface its failure when
+ -- that result comes back (possibly followed by steering), not on the
+ -- next unrelated submission in this or another context.
+ local failure=not compact and failed_handoffs[req.context]
+ if failure then
+ failed_handoffs[req.context]=nil
+ for i=#msgs,1,-1 do
+ if msgs[i].role~='user' then break end
+ local block=msgs[i].blocks[1]
+ if block and block.type=='tool_result' and block.tool_use_id==failure.tag then return terminal(failure.error) end
+ end
end
-- An emitted tool call belongs to Panto until its result returns,
-- independently of the (cancellable) MCP request that asked for it.
@@ -260,12 +272,18 @@ end,activate=function()
end
s.issued=nil; s.settle()
elseif s and s.pending then
- s.fail('Unexpected Panto continuation'); return terminal(s.error)
+ return terminal('Antigravity already has a pending turn in this context')
else
local parts,bytes=prompt_parts(last)
+ -- A stateless client can return tool results in a *new* context.
+ -- Panto includes that carrier in history_transcript; use it as
+ -- a record, never as a reply to a live MCP request.
+ if not s and not parts and last and last.role=='user' and msgs[#msgs-1] and last.blocks[1] and last.blocks[1].type=='tool_result' then
+ local lead='Continue from the tool results in the selected conversation history.'
+ parts,bytes=json.array({{type='text',text=lead}}),#lead
+ end
if not parts then return terminal(bytes or 'No matching Antigravity tool handoff or text prompt') end
- if not (direct or warm) then return terminal('Antigravity requires direct TUI input on a provenance-aware Panto build. No subscription request sent.') end
- local cfg=ext.config.providers[req.provider]; validate(cfg); local by,list=catalog.catalog(req,cfg.tools)
+ local cfg=ext.config.providers[req.provider]; validate(cfg); local by,list=catalog.catalog(req,compact and {} or cfg.tools)
local sig=('%016x:skip'):format(digest(json.encode({'panto-agent-acp-v2',uv.cwd(),req.provider,req.model,req.system_prompt or '',list})))
-- agy silently drops everything past ~191 KB of one user message's text.
if bytes>acp.message_bytes-1024 then return terminal(('This message is %d bytes; Antigravity keeps only the first ~191 KB of one message. No subscription request sent.'):format(bytes)) end
@@ -280,8 +298,7 @@ end,activate=function()
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 tag.session and acp.checkpoint(tag.session)==tag.turn))) then
- if not direct then return terminal('Extension follow-up requires a matching live Antigravity checkpoint') end
- stop(); s=nil; tag=nil
+ stop(s); 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
@@ -301,18 +318,19 @@ end,activate=function()
end
end
if not s then
- local ok,value=pcall(start,req,by,list,sig); if not ok then stop(); return terminal(tostring(value)) end; s=value
- if tag and acp.checkpoint(tag.session)~=tag.turn then stop(); return terminal('Saved Antigravity checkpoint changed') end
+ local ok,value=pcall(start,pool,req,by,list,sig); if not ok then stop(pool[req.context]); return terminal(tostring(value)) end; s=value
+ if tag and acp.checkpoint(tag.session)~=tag.turn then stop(s); return terminal('Saved Antigravity checkpoint changed') end
end
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
+ local visible=not compact and tui_id==s.sid
+ s.observe=visible and native_activity(s) or nil; s.context_window=nil; s.usage=nil
s.effort=req.effort
local active_session=s.session or (tag and tag.session)
- if active_session then
- local ok,err=pcall(acp.checkpoint,active_session,nil); if not ok then stop(); return terminal(tostring(err)) end
+ if active_session and s.lock then
+ local ok,err=pcall(acp.checkpoint,active_session,nil); if not ok then stop(s); return terminal(tostring(err)) end
end
s.cancelled_prefix=nil; s.turn_prefix=history(msgs,#msgs)
s.pending=true; s.notify=req.notify; s.chunks={}; s.bytes=0; s.response={}; s.prefix=s.turn_prefix
@@ -322,8 +340,8 @@ end,activate=function()
else s.chunks[#s.chunks+1]={kind=kind,text=text} end
s.bytes=s.bytes+#text; s.notify()
end
- s.offered=function(models) offers=models end
- s.refresh=refresh and cfg.usage_footer~=false and refresh or nil
+ s.offered=function(models) s.offers=models end
+ s.refresh=visible and cfg.usage_footer~=false and refresh or nil
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()
@@ -339,9 +357,10 @@ end,activate=function()
end); if not ok then s.fail(err) end
end
s.notify=req.notify; local turn_id=s.turn
- return {next=function()
+ -- Compaction doesn't receive the registration's turn-cancel callback.
+ return {cancel_turn=compact and function() stop(s) end or nil,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 pool[s.sid]~=s then return {type='error',kind='terminal',message='Antigravity session closed'} end
if turn_id~=s.turn then return nil end
if s.issued then return {type='done',termination={reason='tool_use'},metadata=s.context_window and {context_window=s.context_window}} end
if s.bytes>0 then
@@ -351,7 +370,8 @@ end,activate=function()
if s.finished then
local reason=s.finished; s.finished=nil; s.pending=false
if s.refresh then pcall(s.refresh) end
- acp.checkpoint(s.session,s.last)
+ if compact then stop(s); return {type='done',usage=s.usage,termination={reason=reason}} end
+ if s.lock then acp.checkpoint(s.session,s.last) end
return {type='done',usage=s.usage,termination={reason=reason},metadata={context_window=s.context_window,antigravity_acp={thread=s.sid,session=s.session,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
diff --git a/panto-antigravity-0.1.0-1.rockspec b/panto-antigravity-0.1.0-1.rockspec
index 10ae5f1..57cbc4a 100644
--- a/panto-antigravity-0.1.0-1.rockspec
+++ b/panto-antigravity-0.1.0-1.rockspec
@@ -8,7 +8,7 @@ source = {
}
description = {
- summary = "Interactive Gemini chat through Google's Antigravity CLI in Panto",
+ summary = "Gemini for Panto through Google's Antigravity CLI",
homepage = "https://code.tjp.lol/public/panto-antigravity",
license = "MIT",
}
diff --git a/tests/fake-agy.lua b/tests/fake-agy.lua
index 1774dec..e5e8e1f 100644
--- a/tests/fake-agy.lua
+++ b/tests/fake-agy.lua
@@ -1,6 +1,10 @@
-- Offline agy fixture. check.lua installs this with Panto's embedded Lua shebang.
local uv, json = require('luv'), require('panto').ext.json
local profile = assert(os.getenv('HOME')) .. '/.local/share/panto-antigravity/google'
+local function fixture_mode()
+ local f=io.open(os.getenv('HOME')..'/fixture-mode','r'); if not f then return end
+ local mode=f:read('a'); f:close(); return mode
+end
if arg[1] == '--version' then error('unexpected version check') end
if arg[1] ~= 'acp' then
assert(json.encode({table.unpack(arg)}) == json.encode({
@@ -149,10 +153,16 @@ if not resumed then
reply(q,{sessionId='test-session',configOptions=split('gemini-other','high',{'high','xhigh'})})
q=request('session/set_config_option'); assert(q.params.configId=='model' and q.params.value=='gemini-test')
reply(q,{configOptions=split('gemini-test','high',{'low','high'})})
- set_level('low')
+ if fixture_mode()~='diagnostic' then set_level('low') end
end
-if not servers[1] then finish(prompt('no-tools'),'no-tools-ok')
+if fixture_mode()=='diagnostic' then
+ -- Unsupported xhigh fails after model selection, before a prompt is sent.
+ assert(not io.read('l'), 'diagnostic unexpectedly sent an ACP request')
+elseif fixture_mode() then
+ local text=fixture_mode()
+ finish(prompt(text),'headless-'..text..'-ok')
+elseif 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)
-- Oversized history: the older part rides the system prompt append; the
diff --git a/tests/lifecycle.lua b/tests/lifecycle.lua
new file mode 100644
index 0000000..061dbb2
--- /dev/null
+++ b/tests/lifecycle.lua
@@ -0,0 +1,56 @@
+-- Exercise the real protocol lifecycle without launching agy or requiring a UI.
+local uv, real_panto = require('luv'), require('panto')
+local root=assert(uv.fs_realpath(debug.getinfo(1,'S').source:sub(2))):match('^(.*)/tests/[^/]+$')..'/'
+local protocol, launched, events = nil, {}, {}
+local ext={json=real_panto.ext.json,config={providers={test={protocol='antigravity-acp',usage_footer=false}}},
+ register_command=function() end, on=function(name,fn) events[name]=fn end,
+ register_protocol=function(p) protocol=p end,
+ session_info=function() error('non-UI open must not query session_info') end}
+local acp={message_bytes=196608,effort_levels={},checkpoint=function() end,
+ launch=function(s,parts)
+ local key=parts[1].text; assert(not launched[key]); launched[key]=s
+ s.session='stub-'..key; s.shutdown=function() s.stopped=true end
+ end}
+local old_dofile,old_panto=dofile,package.loaded.panto
+package.loaded.panto={ext=ext}
+_G.dofile=function(path) if path==root..'acp.lua' then return acp end; return old_dofile(path) end
+local ok,err=xpcall(function()
+ old_dofile(root..'extensions/antigravity-acp.lua').activate()
+ local function open(context,purpose,text)
+ return protocol.open{context=context,purpose=purpose,provider='test',model='fixture',tools={},
+ messages={{role='user',blocks={{type='text',text=text}}}},notify=function() end}
+ end
+ -- Serve IDs are opaque, while a child may have a durable thread ID.
+ local child=('%x-%x'):format(uv.getpid(),uv.hrtime())
+ local serve=open('serve/opaque:../context','turn','serve')
+ local main=open(child,'turn','child')
+ local compact=open(child,'compaction','compact')
+ local a,b,c=assert(launched.serve),assert(launched.child),assert(launched.compact)
+ assert(a~=b and b~=c and a~=c and not a.lock and b.lock and not c.lock)
+ assert(uv.fs_stat(a.dir) and uv.fs_stat(b.dir) and uv.fs_stat(c.dir) and uv.fs_stat(b.lock))
+ protocol.release_context('serve/opaque:../context')
+ assert(a.stopped and not uv.fs_stat(a.dir) and serve.next().type=='error')
+ assert(not b.stopped and not c.stopped and not main.next() and not compact.next())
+ c.delta('text','compact-only'); c.complete('end_turn')
+ assert(compact.next().text=='compact-only' and compact.next().type=='done')
+ assert(c.stopped and not uv.fs_stat(c.dir) and uv.fs_stat(b.lock) and not main.next())
+ b.delta('text','child-only'); b.complete('end_turn')
+ assert(main.next().text=='child-only' and main.next().type=='done')
+ assert(not b.stopped and uv.fs_stat(b.lock))
+ protocol.release_context(child)
+ assert(b.stopped and not uv.fs_stat(b.dir) and not uv.fs_stat(b.lock))
+
+ -- A fresh HTTP request has no live MCP call. Preserve its tool result
+ -- in the transcript instead of dispatching it or dropping the answer.
+ local transcript='[Tool result (id)]: saved result'
+ protocol.open{context='stateless-request',purpose='turn',provider='test',model='fixture',tools={},
+ history_transcript=transcript,messages={{role='assistant',blocks={{type='tool_use',id='id'}}},
+ {role='user',blocks={{type='tool_result',tool_use_id='id',content={{type='text',text='saved result'}}}}}},notify=function() end}
+ local found=false; for prompt in pairs(launched) do if prompt:find(transcript,1,true) then found=true end end
+ assert(found,'cold tool result did not reach the new session')
+end,debug.traceback)
+if protocol then protocol.close() end
+_G.dofile,package.loaded.panto=old_dofile,old_panto
+uv.run('nowait')
+assert(ok,err)
+print('PASS: overlapping non-UI protocol contexts and cleanup')
diff --git a/tests/tui.exp b/tests/tui.exp
index efa4cda..5e42ef6 100644
--- a/tests/tui.exp
+++ b/tests/tui.exp
@@ -71,7 +71,7 @@ set flag [open "$env(HOME)/.local/share/panto-antigravity/google/no-tools" w]; c
set rig "$env(HOME)/.panto"
set file [open "$rig/PROMPT.md" w]; puts -nonewline $file {no-tools}; close $file
spawn -noecho $env(PANTO) --incognito --rig $rig -m antigravity:fast -r low
-see {requires direct TUI input}; send -- "\003"; expect eof; wait
+see {no-tools-ok}; send -- "\003"; expect eof; wait
spawn -noecho $env(PANTO) --incognito -m antigravity:fast -r low -- no-tools
see {no-tools-ok}
send -- "\003"; expect eof; wait