summaryrefslogtreecommitdiff
path: root/acp.lua
blob: f401a7066ed822c3e33f3ae85bbb88875bee521d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
-- 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
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()
        -- 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
        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 function checkpoint_path(id)
    assert(type(id)=='string' and #id>0 and #id<=128 and id:match('^[%w_-]+$'),'Invalid ACP session ID')
    local dir=private_profile()..'/checkpoints'
    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 & 63==0,'Unsafe checkpoint directory')
    return dir..'/'..id
end
function M.checkpoint(id, ...)
    if select('#',...)==0 then
        local ok,data=pcall(function()
            local path=checkpoint_path(id)
            local st=uv.fs_lstat(path); if not st or st.type~='file' or st.uid~=uv.getuid() then return nil end
            local fd=uv.fs_open(path,'r',384); if not fd then return nil end
            local v=uv.fs_read(fd,512,0); uv.fs_close(fd); return v
        end)
        return ok and data or nil
    end
    local value=(...)
    local path=checkpoint_path(id)
    if value==nil then
        local ok,err,code=uv.fs_unlink(path); assert(ok or code=='ENOENT',err); return
    end
    local tmp=path..'.tmp.'..tostring(uv.hrtime())
    local fd=assert(uv.fs_open(tmp,'wx',384))
    local n,err=uv.fs_write(fd,value,0); assert(uv.fs_close(fd))
    if n~=#value then uv.fs_unlink(tmp); error(err or 'Incomplete checkpoint write') end
    local ok,rerr=uv.fs_rename(tmp,path)
    if not ok then uv.fs_unlink(tmp); error(rerr) end
end
-- 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'},timeoutSeconds=1800} 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
    -- Active threads hold an exclusive lock on this Panto session ID.
    local name='panto-'..s.sid: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, 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
        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 active_turn=child and (s.pending or s.cancelling) and s.session
        if active_turn and not s.cancelling then pcall(send,{method='session/cancel',params={sessionId=s.session}}) end
        if cancel_check then cancel_check() end
        if s.agent_path then uv.fs_unlink(s.agent_path); s.agent_path=nil end
        close(stdout)
        if active_turn 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, 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 and not s.cancelling then deadline=uv.now()+idle end end
    local function call(method,params)
        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 not s.cancelling and (s.call or s.issued) 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
    s.cancel=function()
        if closed or not s.prompting or not s.session then return false end
        if not s.cancelling then
            s.cancelling=true
            if not primary_reply or next(steering) then
                send({method='session/cancel',params={sessionId=s.session}})
                deadline=uv.now()+3000; timer:stop(); timer:start(100,100,function()
                    if uv.now()>=deadline then s.fail('ACP timeout: session/cancel') end
                end)
            end
        end
        s.settle()
        return true
    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}}})
        if s.cancelling then
            assert(r.stopReason=='cancelled' or r.stopReason=='end_turn' or r.stopReason=='max_tokens',
                'Turn stopped: '..tostring(r.stopReason))
            s.prompting,s.cancelling=false,false; steer_usage,last_steer=nil,nil
            if s.cancelled then s.cancelled() end
            return
        end
        local reason=({end_turn='end_turn',max_tokens='max_tokens'})[r.stopReason]
        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()
        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
            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
            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
        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
                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
    -- ACP may finish while Panto still owns a tool execution. Join both
    -- sides before committing the turn (including any boundary steering).
    s.settle=function()
        if primary_reply and not s.issued and not next(steering) then
            local co,result=waiting,primary_reply; waiting,primary_reply=nil,nil; timer:stop(); step(co,result)
        end
    end
    local function receive(q)
        assert(q.jsonrpc=='2.0','Invalid ACP envelope')
        if not q.method then
            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(s.cancelling or 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
            s.settle()
            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 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
            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
        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)
            stdin,stdout=uv.new_pipe(false),uv.new_pipe(false)
            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)
                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