From 8c1c5786ebfe8dda40a70571f332e876b184ad4d Mon Sep 17 00:00:00 2001 From: t Date: Tue, 1 Dec 2026 16:31:43 -0700 Subject: Isolate ACP via custom agent and add steering, usage, reseed, and footer updates Replace the osascript permission dialog and settings.json permission seed with a per-thread generated custom main agent (excludeDefaultComponents, tools: [], no inherited customizations or MCP) launched with --agent, --include-default-customizations=false, and --dangerously-skip-permissions. Keep HOME unchanged (isolating via --gemini-dir only) so macOS finds the login Keychain, mark exported tools with antigravity/alwaysLoad, and require the relay to serve tools/list before the first prompt. Add ACP turn steering for queued user and workflow text at tool boundaries, preserve agent_thought_chunk thinking blocks with block-aware checkpoint hashing, report live usage_update context snapshots and deduplicated final plus steering token usage, and mount a live above-input native tool activity component for up to six non-MCP ACP calls. Support reseeding a new ACP session from history_transcript after /tree or cold resume, allow direct submissions to take over an idle session from another thread, and let extension follow-ups continue a matching warm session. Update the usage footer with startup and three-minute timer refreshes, 1w/5h labels, per-letter antigravity colors, and expired-bucket handling. --- acp.lua | 132 +++++++++++++++++++++++++++++++++++++++++++++------------------- 1 file changed, 93 insertions(+), 39 deletions(-) (limited to 'acp.lua') diff --git a/acp.lua b/acp.lua index 8a64449..18dfaa7 100644 --- a/acp.lua +++ b/acp.lua @@ -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 /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) -- cgit v1.3