Purpose-built scripts and the TKTail workflow - the source
tktail/tktail_driver.py
SHA-256 (LF line endings, as in the source ZIP): 93a6774fcc0cdf7a0dddee0079f703b5eb65830f6c57f59e0b41a0b840121fde · MIT license (the benchmark suite only)
"""competitive-bench-v1 - TKTail driven through its product interface for AI clients: MCP over stdio
(`TKTail.exe mcp --stdio`, the tools an AI assistant calls - tktail_search with "aggregate", projection and counts).
The TKTail it drives is isolated from any TKTail the user runs: a portable copy (TKTail.portable beside it - its own
data folder, nothing written to the user's settings) started with `--internal-instance-scope` (a test-isolation switch:
its own single-instance family; it changes nothing in how TKTail opens, reads or searches files). The copy's settings
allow AI access (MCP) - the same setting as Settings > AI Access (MCP) > Allow AI access. No license: TKTail Free.
"""
import ctypes
import ctypes.wintypes
import json
import os
import shutil
import subprocess
import time
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
psapi = ctypes.WinDLL('psapi')
class FILETIME(ctypes.Structure):
_fields_ = [('lo', ctypes.wintypes.DWORD), ('hi', ctypes.wintypes.DWORD)]
class PROCESS_MEMORY_COUNTERS(ctypes.Structure):
_fields_ = [('cb', ctypes.wintypes.DWORD), ('PageFaultCount', ctypes.wintypes.DWORD),
('PeakWorkingSetSize', ctypes.c_size_t), ('WorkingSetSize', ctypes.c_size_t),
('QuotaPeakPagedPoolUsage', ctypes.c_size_t), ('QuotaPagedPoolUsage', ctypes.c_size_t),
('QuotaPeakNonPagedPoolUsage', ctypes.c_size_t), ('QuotaNonPagedPoolUsage', ctypes.c_size_t),
('PagefileUsage', ctypes.c_size_t), ('PeakPagefileUsage', ctypes.c_size_t)]
kernel32.GetProcessTimes.argtypes = [ctypes.wintypes.HANDLE] + [ctypes.POINTER(FILETIME)] * 4
psapi.GetProcessMemoryInfo.argtypes = [ctypes.wintypes.HANDLE, ctypes.POINTER(PROCESS_MEMORY_COUNTERS), ctypes.wintypes.DWORD]
def process_cpu_ms(handle):
"""User + kernel CPU time of a process (also after it exited, while its handle is open)."""
c, e, k, u = FILETIME(), FILETIME(), FILETIME(), FILETIME()
if not kernel32.GetProcessTimes(int(handle), ctypes.byref(c), ctypes.byref(e), ctypes.byref(k), ctypes.byref(u)):
return None
return ((k.hi << 32 | k.lo) + (u.hi << 32 | u.lo)) / 10_000
def process_peak_ws(handle):
m = PROCESS_MEMORY_COUNTERS()
m.cb = ctypes.sizeof(m)
if not psapi.GetProcessMemoryInfo(int(handle), ctypes.byref(m), m.cb):
return None
return m.PeakWorkingSetSize
class Mcp:
"""One MCP stdio session: JSON-RPC lines over a child's stdin / stdout."""
def __init__(self, exe, scope):
self.proc = subprocess.Popen([exe, '--internal-instance-scope', scope, 'mcp', '--stdio'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, bufsize=0)
self.next_id = 1
self.request('initialize', {'protocolVersion': '2025-11-25', 'capabilities': {},
'clientInfo': {'name': 'competitive-bench', 'version': '1'}})
self.send({'jsonrpc': '2.0', 'method': 'notifications/initialized'})
def send(self, message):
self.proc.stdin.write((json.dumps(message, separators=(',', ':')) + '\n').encode('utf-8'))
self.proc.stdin.flush()
def request(self, method, params):
rid = self.next_id
self.next_id += 1
self.send({'jsonrpc': '2.0', 'id': rid, 'method': method, 'params': params})
while True:
line = self.proc.stdout.readline()
if not line:
raise RuntimeError(f'TKTail MCP ended during {method}')
msg = json.loads(line)
if msg.get('id') == rid:
if 'error' in msg:
raise RuntimeError(f'{method}: {msg["error"]}')
return msg['result'], len(line)
def tool(self, name, arguments):
"""(the tool's answer object, its JSON bytes as the model reads them, the JSON-RPC line's bytes)."""
result, wire = self.request('tools/call', {'name': name, 'arguments': arguments})
text = result['content'][0]['text']
answer = json.loads(text)
if result.get('isError'):
raise RuntimeError(f'{name} refused: {text[:400]}')
return answer, len(text.encode('utf-8')), wire
def close(self):
try:
self.proc.stdin.close()
self.proc.wait(10)
except Exception:
self.proc.kill()
class TKTail:
"""A portable TKTail copy in `workdir`, started with the files to investigate."""
def __init__(self, exe, workdir, scope='TKTailCompetitiveBench'):
self.scope = scope
os.makedirs(os.path.join(workdir, 'data'), exist_ok=True)
self.exe = os.path.join(workdir, 'TKTail.exe')
shutil.copy2(exe, self.exe)
open(os.path.join(workdir, 'TKTail.portable'), 'w').close()
with open(os.path.join(workdir, 'data', 'settings.ini'), 'w', encoding='utf-8', newline='\n') as f:
f.write('schema=3\ngeneral.restoreWorkspace=0\nalerts.definitionsMigrated=1\nmcp.allowWindow=1\n')
self.gui = None
self.mcp = None
def start(self, files):
self.gui = subprocess.Popen([self.exe, '--internal-instance-scope', self.scope] + list(files), cwd=os.path.dirname(self.exe))
deadline = time.monotonic() + 120
while True:
try:
self.mcp = Mcp(self.exe, self.scope)
status, _, _ = self.mcp.tool('tktail_status', {})
if status.get('connection', {}).get('mode') == 'gui':
break
self.mcp.close()
except Exception:
if self.mcp:
self.mcp.close()
if time.monotonic() > deadline:
raise RuntimeError('TKTail did not answer over MCP')
time.sleep(0.05)
def wait_source(self, name, timeout=120):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
sources, _, _ = self.mcp.tool('tktail_list_sources', {'kinds': ['file']})
for s in sources.get('sources', []):
if s.get('displayName') == name and s.get('file', {}).get('state') == 'ok':
return s
time.sleep(0.05)
raise RuntimeError(f'{name} did not open in TKTail')
def wait_idle(self, quiet_ms=2000, timeout=600):
"""Until TKTail's own background work (the line index of a new file) has finished: CPU below 2 % for quiet_ms."""
deadline = time.monotonic() + timeout
last = process_cpu_ms(self.gui._handle)
quiet_since = time.monotonic()
while time.monotonic() < deadline:
time.sleep(0.25)
now = process_cpu_ms(self.gui._handle)
if now - last > 0.25 * 1000 * 0.02:
quiet_since = time.monotonic()
last = now
if (time.monotonic() - quiet_since) * 1000 >= quiet_ms:
return
raise RuntimeError('TKTail did not become idle')
def search(self, definition, aggregate=None, max_results=0, extra=None):
"""Runs one search to its end: (the final answer, answer bytes of every call, calls made)."""
args = {'definition': definition, 'waitMs': 5000, 'maxResults': max_results}
if aggregate is not None:
args['aggregate'] = aggregate
if extra:
args.update(extra)
answer, size, _ = self.mcp.tool('tktail_search', args)
total, calls = size, 1
while not answer.get('finished'):
answer, size, _ = self.mcp.tool('tktail_get_search', {'searchId': answer['searchId'], 'waitMs': 5000,
'maxResults': max_results, **(extra or {})})
total += size
calls += 1
if answer.get('state') != 'completed':
raise RuntimeError(f'the search ended {answer.get("state")}: {answer.get("message")}')
return answer, total, calls
def cpu_ms(self):
total = process_cpu_ms(self.gui._handle) or 0
if self.mcp:
total += process_cpu_ms(self.mcp.proc._handle) or 0
return total
def peak_ws(self):
return process_peak_ws(self.gui._handle)
def exit(self):
if self.mcp:
self.mcp.close()
self.mcp = None
if self.gui and self.gui.poll() is None:
subprocess.run([self.exe, '--internal-instance-scope', self.scope, 'app', 'exit'], timeout=60)
try:
self.gui.wait(60)
except subprocess.TimeoutExpired:
self.gui.kill()
self.gui.wait(10)