summaryrefslogtreecommitdiff
path: root/acp.lua
diff options
context:
space:
mode:
Diffstat (limited to 'acp.lua')
-rw-r--r--acp.lua271
1 files changed, 271 insertions, 0 deletions
diff --git a/acp.lua b/acp.lua
new file mode 100644
index 0000000..8a64449
--- /dev/null
+++ b/acp.lua
@@ -0,0 +1,271 @@
+-- One outstanding ACP request. Incoming updates and client requests are serviced
+-- while session/prompt is pending (including while Panto executes an MCP tool).
+local uv, json = require('luv'), require('panto').ext.json
+local M = {}
+local levels = {'low', 'medium', 'high', 'xhigh'}
+M.effort_levels = {}
+for i, level in ipairs(levels) do M.effort_levels[i] = {label=level, detail='Request '..level..' reasoning'} end
+
+-- Preserve unsuffixed and legacy pinned IDs when no effort was requested.
+local function wire_for(selectors, model, effort, split)
+ if selectors[model] and (not effort or split) then return model end
+ effort = effort or 'medium'
+ for _, level in ipairs(levels) do
+ if level == effort then
+ if selectors[model] and model:sub(-#level-1) == '-'..level then return model end
+ local wire = model..'-'..level
+ if selectors[wire] then return wire end
+ end
+ end
+ -- A different model can expose thought_level only after it is selected.
+ if selectors[model] then return model end
+ return nil, 'No advertised Gemini model for '..model..' at '..effort..'; see /antigravity-models'
+end
+
+local function choices(option)
+ local values = {}
+ for _,g in ipairs(option and option.options or {}) do
+ for _,v in ipairs(g.options or {g}) do
+ if type(v.value)=='string' then values[v.value]=v.name or '' end
+ end
+ end
+ return values
+end
+local function config(opts, id)
+ for _,o in ipairs(opts or {}) do if o.id==id then return o end end
+end
+local function thought(opts)
+ for _,o in ipairs(opts or {}) do if o.id=='thought_level' or o.category=='thought_level' then return o end end
+end
+local function families(selectors, current, thought_levels)
+ local groups = {}
+ for wire in pairs(selectors) do
+ local base, suffix = wire:match('^(.+)%-([^-]+)$')
+ local family = wire
+ for _, level in ipairs(levels) do if suffix == level then family = base; break end end
+ groups[family] = true
+ end
+ local names = {}
+ for family in pairs(groups) do
+ local available = {}
+ for _, level in ipairs(levels) do
+ if selectors[family..'-'..level] or (family==current and thought_levels[level]) then available[#available+1] = level end
+ end
+ names[#names+1] = family .. (#available > 0 and ' ('..table.concat(available, ', ')..')' or '')
+ end
+ table.sort(names); return names
+end
+local function close(h) if h and not h:is_closing() then h:close() end end
+local function private_profile()
+ local dir=assert(uv.fs_realpath(assert(os.getenv('HOME'))))
+ local home=assert(uv.fs_stat(dir)); assert(home.type=='directory' and home.uid==uv.getuid() and home.mode & 18==0,'HOME must be owned and not group/world writable')
+ for _,part in ipairs({'.local','share','panto-antigravity','google'}) do
+ dir=dir..'/'..part
+ local st=uv.fs_lstat(dir)
+ if not st then assert(uv.fs_mkdir(dir,448)); st=assert(uv.fs_lstat(dir)) end
+ assert(st.type=='directory' and st.uid==uv.getuid() and st.mode & 18==0,'Google profile path must be owned and not group/world writable')
+ end
+ 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
+ if dir:sub(1,1)=='/' and uv.fs_access(dir..'/agy','X') then return assert(uv.fs_realpath(dir..'/agy')) end
+ end
+ error('agy is not on PATH')
+end
+-- The chat transport and the fixed read-only usage query share this trust boundary.
+-- Neither inherits API keys or a user's default CLI profile.
+local function verified(run, on_error)
+ local finished, checker, watchdog = false, nil, uv.new_timer()
+ local function cancel()
+ if finished then return end
+ finished=true; close(watchdog)
+ if checker then checker:kill('sigkill') end
+ end
+ local ok,err=pcall(function()
+ local bin,profile=executable(),private_profile()
+ local env={'HOME='..profile}
+ for _,k in ipairs({'USER','PATH','TMPDIR','LANG'}) do
+ if os.getenv(k) then env[#env+1]=k..'='..os.getenv(k) end
+ end
+ watchdog:start(15000,0,function() cancel(); on_error('Google CLI signature check timed out') end)
+ checker=assert(uv.spawn('/usr/bin/codesign',{args={'--verify','--strict','-R=anchor apple generic and certificate leaf[subject.OU] = "EQHXZ8M8AV" and identifier "cli"',bin}},function(code,sig)
+ close(checker); checker=nil; if finished then return end
+ finished=true; close(watchdog)
+ if code~=0 or sig~=0 then on_error('Google CLI signature verification failed'); return end
+ local ran,why=pcall(run,bin,profile,env); if not ran then on_error(tostring(why)) end
+ end))
+ end)
+ if not ok then cancel(); on_error(tostring(err)) end
+ 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]]
+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 closed=false
+ local function cleanup()
+ if pid then uv.kill(-pid,9); pid=nil end
+ close(stdin); close(stdout); close(timer)
+ end
+ local function send(msg)
+ msg.jsonrpc='2.0'; assert(stdin:write(json.encode(msg)..'\n',function(e) if e and not closed then s.fail('ACP write failed') end end))
+ end
+ s.shutdown=function()
+ if closed then return end; closed=true
+ 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
+ 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 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()
+ 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
+ end)
+ send({id=serial,method=method,params=params}); return coroutine.yield()
+ end
+ local selectors, opts, configuring = {}, {}, false
+ local function advertised()
+ local model=config(opts,s.selector)
+ s.offered(families(selectors, model and model.currentValue, choices(thought(opts))))
+ end
+ local function level_for(wire, effort)
+ if not effort then return end
+ local o=thought(opts)
+ if not o and wire:sub(-#effort-1)=='-'..effort then return end -- legacy variant
+ if o and choices(o)[effort] then return o end
+ return nil, 'No advertised reasoning level '..effort..' for '..wire..'; see /antigravity-models'
+ end
+ s.resolve = function(effort)
+ local wire,err=wire_for(selectors,s.model,effort,thought(opts))
+ if not wire then return nil,err end
+ if wire==s.wire then
+ local _,why=level_for(wire,effort); if why then return nil,why end
+ end
+ return wire
+ end
+ local function set_option(id,value)
+ opts=assert(call('session/set_config_option',{sessionId=s.session,configId=id,value=value}).configOptions)
+ assert((config(opts,id) or {}).currentValue==value,'ACP did not confirm '..id..'='..value)
+ end
+ local function confirmed()
+ return (config(opts,s.selector) or {}).currentValue==s.wire and
+ (not s.thought or (thought(opts) or {}).currentValue==s.thought)
+ end
+ local function turn(text)
+ local wire = assert(s.resolve(s.effort))
+ configuring=true
+ s.selector,s.wire=selectors[wire],wire
+ if (config(opts,s.selector) or {}).currentValue~=wire then set_option(s.selector,wire) end
+ advertised() -- thought_level choices apply only to the now-selected model
+ local o,err=level_for(wire,s.effort); assert(not err,err)
+ s.thought=o and s.effort
+ if o and o.currentValue~=s.thought then set_option(o.id,s.thought) end
+ assert(confirmed(),'Configured model or reasoning level changed'); configuring=false
+ s.prompting=true
+ 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)
+ end
+ s.submit=function(text) step(coroutine.create(turn),text) end
+ local function setup()
+ local init=call('initialize',{protocolVersion=1,clientInfo={name='panto-antigravity',version='1'},clientCapabilities={}})
+ assert(init.protocolVersion==1,'ACP v1 required'); local caps=init.agentCapabilities or {}
+ 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
+ local session
+ if resume_id then
+ assert((caps.sessionCapabilities or {}).resume,'ACP resume unavailable'); params.sessionId=resume_id
+ session=call('session/resume',params); assert(not session.sessionId or session.sessionId==resume_id,'Wrong resumed session'); s.session=resume_id
+ else
+ if s.instructions~='' then
+ assert(((((caps._meta or {}).antigravity or {}).systemPrompt or {}).append)==true,'Rig instruction append unavailable')
+ params._meta.antigravity={systemPrompt={append=s.instructions}}
+ end
+ session=call('session/new',params); assert(type(session.sessionId)=='string' and #session.sessionId>0,'Missing session ID'); s.session=session.sessionId
+ end
+ opts=session.configOptions or {}
+ for _,o in ipairs(opts) do
+ if o.category=='model' or o.id=='model' then
+ s.selector=o.id
+ for value,name in pairs(choices(o)) do
+ if (value:lower():match('^gemini%-') or name:lower():match('^gemini')) and
+ #value<=128 and not value:find('[^%w/_.:%-]') then selectors[value]=o.id end
+ end
+ end
+ end
+ advertised()
+ turn(first)
+ end
+ 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
+ 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 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()
+ 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)
+ if closed then return end; if e or not data then s.fail('ACP stream closed'); return end
+ buf=buf..data
+ while not closed do local n=buf:find('\n',1,true); if (n or #buf)>4<<20 then s.fail('Oversized ACP frame'); return end
+ if not n then return end; local line=buf:sub(1,n-1); buf=buf:sub(n+1)
+ local parsed,why=pcall(function() receive(json.decode(line)); activity() end); if not parsed then s.fail(tostring(why)); return end
+ end
+ end)); step(coroutine.create(setup))
+ end,s.fail)
+end
+return M