summaryrefslogtreecommitdiff
path: root/tests/fake-agy.lua
blob: 904f3bf1bc9ae6368609124b23f168e19f220ad0 (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
-- 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'
if arg[1] == '--version' then error('unexpected version check') end
if arg[1] ~= 'acp' then
    assert(json.encode({table.unpack(arg)}) == json.encode({
        '--gemini_dir', profile, '--sandbox', '-p', '/usage',
    }), 'unrecognized fake CLI invocation')
    if uv.fs_stat(profile .. '/usage-failure') then os.exit(3) end
    assert(uv.cwd() == profile and uv.guess_handle(0) ~= 'tty')
    print('Gemini\tWeekly\t73%\t2099-02-03T12:00:00Z'); return
end

local function read() return json.decode(assert(io.read('l'), 'ACP input closed')) end
local function send(msg)
    msg.jsonrpc = '2.0'; assert(io.write(json.encode(msg), '\n')); assert(io.flush())
end
local function request(method)
    local q = read(); assert(q.method == method, 'expected ' .. method); return q
end
local function reply(q, result) send({id=q.id, result=result or {}}) end
local function prompt(text)
    local q = request('session/prompt')
    assert(#q.params.prompt == 1 and q.params.prompt[1].type == 'text' and q.params.prompt[1].text == text)
    return q
end
local function finish(q, text)
    if text=='same-session-ok' then
        send({method='session/update',params={sessionId='test-session',update={sessionUpdate='agent_thought_chunk',content={type='text',text='fixture-visible-thinking'}}}})
    end
    send({method='session/update', params={sessionId='test-session', update={
        sessionUpdate='agent_message_chunk', content={type='text', text=text},
    }}})
    local function update(u) send({method='session/update',params={sessionId='test-session',update=u}}) end
    update({sessionUpdate='usage_update',used=1330,size=1048576})
    update({sessionUpdate='tool_call',toolCallId='native-1',name='manage_task',status='in_progress'})
    update({sessionUpdate='tool_call_update',toolCallId='native-1',status='completed'})
    if text=='primary-tool-ok' then update({sessionUpdate='tool_call',toolCallId='mcp-1',name='mcp_pantograph_fixture__echo',status='completed'}) end
    reply(q, {stopReason='end_turn',usage={inputTokens=2166,outputTokens=228,thoughtTokens=117,totalTokens=2394,cachedReadTokens=900}})
end

local function load_catalog(server)
    local input, output = assert(uv.pipe()), assert(uv.pipe())
    local proc = assert(uv.spawn(server.command, {args=server.args, stdio={input.read, output.write, 2}}, function() end))
    uv.fs_close(input.read); uv.fs_close(output.write)
    local function write(id, method, params)
        local line = json.encode({jsonrpc='2.0', id=id, method=method, params=params or {}}) .. '\n'
        assert(uv.fs_write(input.write, line, -1) == #line)
    end
    local function rpc(id, method, params)
        write(id,method,params)
        local buf = ''
        repeat
            local chunk = assert(uv.fs_read(output.read, 4096, -1)); assert(chunk ~= '', 'relay closed'); buf = buf .. chunk
        until buf:sub(-1) == '\n'
        local r = json.decode(buf); assert(r.id == id); return r
    end
    assert(rpc(1, 'initialize').result.serverInfo.name == 'pantograph')
    local tools = rpc(2, 'tools/list').result.tools
    local schemas={}; for _,t in ipairs(tools) do assert(t._meta['antigravity/alwaysLoad']==true); schemas[t.name]=t.inputSchema end
    assert(schemas.std__read and schemas.std__edit and schemas.fixture__echo.properties.rows.items.required[1]=='value')
    return function(late_prompt)
        if late_prompt then
            write(7,'tools/call',{name='fixture__echo',arguments={rows={{value=43}}}})
            while not uv.fs_stat(profile..'/tool-running') do uv.sleep(10) end
            write(nil,'notifications/cancelled',{requestId=7})
            assert(rpc(8,'ping').result) -- cancellation consumed while Panto still owns call 7
            finish(late_prompt,'timeout-handled-ok')
            send({id='barrier',method='fixture/barrier'})
            assert(read().id=='barrier') -- ACP finished before the local tool returned
            local f=assert(io.open(profile..'/return-result','w')); f:close()
            return function() assert(rpc(9,'ping').result) end -- no late reply to 7
        end
        assert(rpc(3, 'tools/call', {name='not_exported', arguments={}}).error.code == -32602)
        assert(rpc(5, 'tools/call', {name='fixture__echo', arguments={rows={{value='bad'}}}}).error.code == -32602)
        local echo=rpc(6, 'tools/call', {name='fixture__echo', arguments={rows={{value=42}}}}).result
        assert(echo.isError==false and echo.content[1].text=='42')
        local r = rpc(4, 'tools/call', {name='std__read', arguments={path=uv.cwd() .. '/.panto/SYSTEM.md'}}).result
        assert(r.isError == false and r.content[1].text:find('Short answers', 1, true))
        -- Push later transcript reseeds past one agy message (acp.message_bytes).
        for i=1,4 do
            local f=rpc(20+i,'tools/call',{name='std__read',arguments={path=uv.cwd()..'/.panto/history-filler.txt'}}).result
            assert(f.isError==false and #f.content[1].text>40000)
        end
        -- Keep the peer connected for subsequent turns.
    end
end

local q = request('initialize')
reply(q, {protocolVersion=1, authMethods={{id='oauth-personal'}}, agentCapabilities={
    sessionCapabilities={resume={}}, _meta={antigravity={systemPrompt={append=true}}},
}})
q = request('authenticate'); assert(json.encode(q.params) == '{"methodId":"oauth-personal"}'); reply(q)
q = read()
local setup, resumed = q.params, q.method == 'session/resume'
assert(setup._meta.disableBuiltInTools == true)
assert(arg[2]=='--agent' and arg[3]:match('^panto%-%x[%x-]+$') and arg[4]=='--include-default-customizations=false')
assert(arg[9]=='--dangerously-skip-permissions')
assert(arg[5]=='--gemini-dir' and arg[6]==profile)
local af=assert(io.open(profile..'/config/agents/'..arg[3]..'.md')); local agent=af:read('a'); af:close()
for _,line in ipairs({'name: '..arg[3],'mainAgent: true','subagent: false','excludeDefaultComponents: true','inheritCustomizations: false','inheritMcp: false','tools: []'}) do assert(agent:find('\n'..line..'\n',1,true),line) end
local servers=json.decode(assert(agent:match('\nmcpServers: ([^\n]+)')))
if uv.fs_stat(profile..'/no-tools') then assert(#servers==0) else assert(#servers==1 and servers[1].name=='pantograph' and servers[1].command=='/usr/bin/nc') end
assert(#setup.mcpServers==#servers)
local server=setup.mcpServers[1]
if server then
    assert(server.timeoutSeconds==1800 and servers[1].timeoutSeconds==1800, 'expected 30-minute timeout in ACP setup and generated agent')
    assert(server.name==servers[1].name and server.command==servers[1].command and json.encode(server.args)==json.encode(servers[1].args) and json.encode(server.env)=='[]')
end
local check_relay=server and not uv.fs_stat(profile..'/skip-list') and load_catalog(server)
assert(not uv.fs_stat(profile..'/antigravity-cli/settings.json'),'extension seeded permission settings')
if resumed then assert(setup.sessionId == 'test-session' and not setup._meta.antigravity)
else assert(q.method == 'session/new' and setup._meta.antigravity.systemPrompt.append:find('Short answers', 1, true)) end
if resumed then -- Older ACP pickers may expose suffixed models instead.
    reply(q, {sessionId='test-session', configOptions={{id='model', options={{name='Gemini test', value='gemini-test-high'}}}}})
    q=request('session/set_config_option'); assert(q.params.configId=='model' and q.params.value=='gemini-test-high')
    reply(q, {configOptions={{id='model', currentValue=q.params.value}}})
end
local function split(model, level, levels)
    local choices={}; for _,v in ipairs(levels) do choices[#choices+1]={value=v,name=v} end
    return {{id='model', currentValue=model, options={{value='gemini-test',name='Gemini test'}}},
        {id='thought_level', currentValue=level, options=choices}}
end
local function set_level(value)
    local req=request('session/set_config_option'); assert(req.params.configId=='thought_level' and req.params.value==value)
    local opts=split('gemini-test',value,{'low','high'})
    send({method='session/update',params={sessionId='test-session',update={sessionUpdate='config_option_update',configOptions=opts}}})
    reply(req,{configOptions=opts})
end
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')
end

if 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
    -- newest part and the request stay in one user message under the agy cap.
    q=request('session/prompt'); assert(#q.params.prompt==1)
    local user=q.params.prompt[1].text; assert(#user<=160000,'user message over the agy cap')
    local head=setup._meta.antigravity.systemPrompt.append:match('^Short answers%.\n\nSelected Panto conversation history, earlier part%. [^\n]+\n\n(.*)\n\nEnd of the earlier part of the selected Panto conversation history%.$')
    local tail,request_text=user:match('^Selected Panto conversation history[^\n]*:\n\n(.*)(\n\nCurrent user request:\n[^\n]+)$')
    assert(tail and (head~=nil)==(user:find('continued from the record',1,true)~=nil),'record and user message disagree')
    local text=(head or '')..tail..request_text
    assert(text:find('[User]: hello',1,true))
    assert(not text:find('same-session-ok',1,true) and not text:find('resumed-ok',1,true),'abandoned branch leaked')
    local current=assert(text:match('Current user request:\n([^\n]+)$'))
    assert(not text:find('[User]: '..current,1,true),'current prompt duplicated')
    if current~='boundary workflow notice' then
        assert(text:find('[Assistant]: primary-tool-ok',1,true)); assert(head and #head>0 and head:sub(-2)=='\n\n' and tail:sub(1,1)=='[','expected the oversized transcript to overflow into the system prompt at an entry boundary')
    end
    if current=='branch-probe' then
        finish(q,'branch-seed-ok'); finish(prompt('warm-probe'),'warm-after-seed-ok')
        local esc=prompt('esc-probe')
        send({method='session/update',params={sessionId='test-session',update={
            sessionUpdate='agent_message_chunk',content={type='text',text='esc-window-open'},
        }}})
        local cancel=request('session/cancel'); assert(cancel.id==nil and cancel.params.sessionId=='test-session')
        reply(esc,{stopReason='cancelled'})
        finish(prompt('after-esc-probe'),'after-esc-ok')
        reply(prompt('cancel-probe'),{stopReason='cancelled'})
    elseif current=='boundary workflow notice' then
        assert(text:find('[User]: boundary steer',1,true) and text:find('[Tool result',1,true)); finish(q,'proceed-recovered-ok')
    else
        assert(current=='cold-probe' and text:find('[Assistant]: warm-after-seed-ok',1,true)
            and text:find('[User]: esc-probe',1,true) and not text:find('esc-window-open',1,true)
            and text:find('[Assistant]: after-esc-ok',1,true)); finish(q,'cold-resume-ok')
    end
else
    q = prompt('hello')
    send({method='session/update',params={sessionId='test-session',update={sessionUpdate='agent_message_chunk',content={type='text',text='steer-window-open'}}}})
    while not uv.fs_stat(profile..'/steer-queued') do uv.sleep(10) end
    send({method='session/update',params={sessionId='test-session',update={sessionUpdate='usage_update',used=8200,size=1048576}}})
    check_relay()
    local steer=request('session/prompt'); assert(steer.id~=q.id and steer.params.sessionId=='test-session')
    local p=steer.params.prompt; assert(#p==2 and p[1].text=='boundary steer' and p[2].text=='boundary workflow notice','steering payload/order')
    while not uv.fs_stat(profile..'/context-visible') do uv.sleep(10) end -- final usage must not drive the live reading
    finish(q, 'primary-tool-ok'); reply(steer,{stopReason='end_turn',usage={inputTokens=1000,outputTokens=6,totalTokens=1006}}) -- out of request order also works
    set_level('high')
    finish(prompt('again'), 'same-session-ok')
    local verify=check_relay(prompt('late-tool'))
    q=prompt('[subagents] Workflow fixture completed. Output below: marker'); verify(); finish(q, 'workflow-notice-ok')
end
for _ in io.lines() do end -- keep the session alive until Panto closes stdin