-- The native provider owns the ACP subprocess and renders into Panto's existing turn. local p, uv = require('panto'), require('luv') local ext, json = p.ext, p.ext.json -- A checkout has one discoverable file in extensions/. LuaRocks puts helpers -- in its package namespace; don't resolve generic names from another extension. local root=debug.getinfo(1,'S').source:match('^@(.*/)extensions/[^/]+$') local function companion(name) if root then return dofile(root..name..'.lua') end return require('panto-antigravity.'..name) end 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.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) if s.lock then uv.fs_rmdir(s.lock) end if s.notify then s.notify() end end local function release(id) if active and active.sid==id then stop() end end local function send(c,msg) msg.jsonrpc='2.0'; c:write(json.encode(msg)..'\n') 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 if q.method=='notifications/cancelled' and s.call and q.params and q.params.requestId==s.call.id then s.fail('MCP call cancelled'); return end if q.id==nil then return end assert(type(q.id)=='string' or math.type(q.id)=='integer','Invalid MCP request ID') local function fail(code,msg) send(c,{id=q.id,error={code=code,message=msg}}) end local result if q.method=='initialize' then result={protocolVersion='2025-06-18',capabilities={tools={}},serverInfo={name='pantograph',version='0.1'}} elseif q.method=='ping' then result={} elseif q.method=='tools/list' then s.listed=true; result={tools=s.list} elseif q.method=='tools/call' then local args=q.params or {}; local tool=s.by[args.name]; local v=args.arguments if v==nil then v={} end 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 then return fail(-32000,'No human 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 else return fail(-32601,'Unsupported method') end send(c,{id=q.id,result=result}) 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 s.fail=function(msg) if active==s then s.error=tostring(msg):gsub('[%c]',' '):sub(1,512); stop() end end s.model,s.instructions,s.cwd,s.signature,s.save=req.model,req.system_prompt or '',assert(uv.cwd()),signature,save if save then 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 end s.key='antigravity_acp.checkpoint.'..s.sid assert(s.server:bind(dir..'/mcp')); assert(s.server:listen(1,function(err) if err or active~=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 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 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 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)) return s 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 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 local function terminal(message) return {next=function() return {type='error',kind='terminal',message=message} end} end local function validate(cfg) for _,key in ipairs({'save_session','usage_footer'}) do assert(cfg[key]==nil or type(cfg[key])=='boolean',key..' must be a boolean') end if cfg.tools~=nil then assert(type(cfg.tools)=='table','tools must be a list of Panto tool names') for i,name in pairs(cfg.tools) do assert(math.type(i)=='integer' and i>=1 and i<=#cfg.tools and type(name)=='string' and name~='', 'Invalid tools list') end end 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 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() 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 '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() 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; stop() end) ext.register_protocol{name='antigravity-acp',effort_levels=acp.effort_levels,close=stop,cancel_turn=release,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 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.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 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 ((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.') end end if not s then local ok,value=pcall(start,req,by,list,sig,cfg.save_session==true); if not ok then stop(); return terminal(tostring(value)) end; s=value if tag and s.save and ext.state.get(key)~=tag.turn then stop(); 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 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() 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) 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 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 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 return terminal('Antigravity requires direct TUI input on a provenance-aware Panto build. No subscription request sent.') end s.notify=req.notify 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.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)}}} end local call=s.call; if not call then return nil end if call.sent then return {type='done',termination={reason='tool_use'}} end call.sent=true; return {type='tool_call',id=call.tag,name=call.name,input_json=call.input} end} end} end}