Each request runs in its own systemd user unit and survives the shell restarting; the chat reopens on a running job or an unseen result. Auto picks the subscription with the most usage left (ai-usagebar). Runs are snapshotted so Undo can restore files and revert commits. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
710 lines
29 KiB
Python
710 lines
29 KiB
Python
#!/usr/bin/env python3
|
|
"""Quick fix: hands a short request to a coding agent and keeps its final reply.
|
|
|
|
JSON protocol for the shell (one request in argv, one reply on stdout); argv-only
|
|
execution. Each request runs in its own transient systemd user unit, so it
|
|
survives the shell restarting under it (a rebuild restarts the shell). Sessions
|
|
are JSON files below the state directory; the shell watches state.json.
|
|
"""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import fcntl
|
|
import hashlib
|
|
import re
|
|
import shutil
|
|
import signal
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.request
|
|
|
|
HOME = Path.home()
|
|
STATE = Path(os.environ.get('XDG_STATE_HOME') or HOME / '.local/state') / 'glassMxrph' / 'quickfix'
|
|
CONFIG = Path(os.environ.get('XDG_CONFIG_HOME') or HOME / '.config') / 'glassMxrph'
|
|
RULES = CONFIG / 'quickfix' / 'AGENTS.md'
|
|
SESSIONS = STATE / 'sessions'
|
|
SNAPSHOTS = STATE / 'snapshots'
|
|
KEEP_SESSIONS = 50
|
|
KEEP_SNAPSHOTS = 10
|
|
UNIT = 'glassmxrph-quickfix'
|
|
PROVIDERS = ('claude', 'gpt', 'local')
|
|
ID = re.compile(r'^[0-9]{8}-[0-9]{6}-[0-9a-f]{4}$')
|
|
TIMEOUT = 60 * 60
|
|
MAX_FILE = 20 * 1024 * 1024 # larger untracked files are not snapshotted
|
|
|
|
DEFAULT_RULES = """# Quick fix rules
|
|
|
|
You are run from the desktop shell for small, well-defined changes. Nobody can
|
|
answer questions while you work: make a sensible choice and finish the job.
|
|
|
|
Describe here where your configuration lives, how changes are applied
|
|
(for example the rebuild command) and what may be committed or pushed.
|
|
"""
|
|
|
|
PROTOCOL = """You were started from a desktop quick-fix box. Work on your own until the request is done; you cannot ask questions.
|
|
Reply with the final result only: one or two short plain sentences, no headings, lists, code blocks or preamble.
|
|
Start the reply with "OK: " if everything asked for is done and applied, or "FAILED: " if it is not, followed by the message, e.g. "OK: Installed Heroic Launcher." or "FAILED: The rebuild stopped on a hash mismatch in heroic.nix; nothing was applied."
|
|
Never reply OK unless the commands that apply the change finished successfully. If something fails and you cannot fix it, put your own edits back the way they were."""
|
|
|
|
# Commands that throw away work or the machine's state are refused outright.
|
|
DENY = ['git reset --hard', 'git clean', 'git checkout -- ', 'git restore', 'git stash', 'git push --force',
|
|
'git push -f', 'sudo rm', 'rm -rf /', 'rm -rf ~', 'mkfs', 'dd ', 'nix-collect-garbage', 'nh clean',
|
|
'zcli cleanup', 'docker system prune', 'docker volume', 'systemctl poweroff', 'systemctl reboot',
|
|
'reboot', 'shutdown', 'poweroff']
|
|
|
|
|
|
# Files -----------------------------------------------------------------------
|
|
|
|
def write_json(path, value):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = path.with_name(path.name + f'.{os.getpid()}.part')
|
|
tmp.write_text(json.dumps(value, ensure_ascii=False))
|
|
tmp.replace(path)
|
|
|
|
|
|
def read_json(path, fallback=None):
|
|
try:
|
|
return json.loads(path.read_text())
|
|
except (OSError, ValueError):
|
|
return fallback
|
|
|
|
|
|
class locked:
|
|
"""Serialises read-modify-write between the shell's calls and the worker."""
|
|
def __enter__(self):
|
|
STATE.mkdir(parents=True, exist_ok=True)
|
|
self.file = open(STATE / 'lock', 'w')
|
|
fcntl.flock(self.file, fcntl.LOCK_EX)
|
|
|
|
def __exit__(self, *_):
|
|
self.file.close()
|
|
|
|
|
|
def session_path(id_):
|
|
if not isinstance(id_, str) or not ID.match(id_):
|
|
raise ValueError('Invalid session')
|
|
return SESSIONS / f'{id_}.json'
|
|
|
|
|
|
def load_session(id_):
|
|
session = read_json(session_path(id_))
|
|
if not session:
|
|
raise ValueError('That conversation no longer exists')
|
|
return session
|
|
|
|
|
|
def save_session(session):
|
|
write_json(session_path(session['id']), session)
|
|
|
|
|
|
def read_state():
|
|
return read_json(STATE / 'state.json', {}) or {}
|
|
|
|
|
|
def save_state(**changes):
|
|
state = read_state()
|
|
state.update(changes)
|
|
state['serial'] = state.get('serial', 0) + 1
|
|
write_json(STATE / 'state.json', state)
|
|
|
|
|
|
def ensure_rules():
|
|
if not RULES.exists():
|
|
RULES.parent.mkdir(parents=True, exist_ok=True)
|
|
RULES.write_text(DEFAULT_RULES)
|
|
return RULES.read_text()
|
|
|
|
|
|
def new_id():
|
|
return time.strftime('%Y%m%d-%H%M%S') + '-' + os.urandom(2).hex()
|
|
|
|
|
|
# Units -----------------------------------------------------------------------
|
|
|
|
def unit_active(id_):
|
|
r = subprocess.run(['systemctl', '--user', 'is-active', f'{UNIT}-{id_}.service'], capture_output=True, text=True)
|
|
return r.stdout.strip() in ('active', 'activating', 'deactivating')
|
|
|
|
|
|
def start_unit(id_, action):
|
|
# A follow-up may arrive before the previous run's unit has gone.
|
|
for _ in range(30):
|
|
if not unit_active(id_):
|
|
break
|
|
time.sleep(0.1)
|
|
command = ['systemd-run', '--user', '--collect', '--quiet', f'--unit={UNIT}-{id_}',
|
|
'--description=glassMxrph quick fix', '--property=KillMode=mixed', '--property=TimeoutStopSec=10',
|
|
f'--working-directory={HOME}']
|
|
for key in ('PATH', 'XDG_STATE_HOME', 'XDG_CONFIG_HOME', 'SSH_AUTH_SOCK', 'GLASSMXRPH_QUICKFIX_TEST'):
|
|
if os.environ.get(key):
|
|
command.append(f'--setenv={key}={os.environ[key]}')
|
|
r = subprocess.run(command + [sys.executable, os.path.abspath(__file__), action, id_],
|
|
capture_output=True, text=True)
|
|
if r.returncode:
|
|
raise ValueError((r.stderr or 'Could not start the job').strip()[-300:])
|
|
|
|
|
|
# Providers -------------------------------------------------------------------
|
|
|
|
def remaining():
|
|
"""Percent left per subscription, limited by its tightest window."""
|
|
result = {}
|
|
if not shutil.which('ai-usagebar'):
|
|
return result
|
|
try:
|
|
r = subprocess.run(['ai-usagebar', 'usage', '--json'], capture_output=True, text=True, timeout=25)
|
|
entries = json.loads(r.stdout).get('entries', [])
|
|
except (subprocess.TimeoutExpired, OSError, ValueError, AttributeError):
|
|
return result
|
|
for entry in entries:
|
|
name = {'anthropic': 'claude', 'openai': 'gpt'}.get(entry.get('id'))
|
|
used = [m['percent'] for m in entry.get('metrics') or [] if isinstance(m.get('percent'), (int, float))]
|
|
if name and used and entry.get('status') == 'ready':
|
|
result[name] = max(0, 100 - max(used))
|
|
return result
|
|
|
|
|
|
def local_models(options):
|
|
url = options.get('localUrl', '')
|
|
if not re.match(r'^https?://', url):
|
|
return []
|
|
try:
|
|
with urllib.request.urlopen(url.rstrip('/') + '/models', timeout=2) as response:
|
|
return [m['id'] for m in json.load(response).get('data') or [] if m.get('id')]
|
|
except (OSError, ValueError, KeyError, TypeError):
|
|
return []
|
|
|
|
|
|
def installed():
|
|
return {'claude': bool(shutil.which('claude')), 'gpt': bool(shutil.which('codex')),
|
|
'local': bool(shutil.which('opencode'))}
|
|
|
|
|
|
def choose(provider, options):
|
|
"""The provider to use, or ValueError saying why none works."""
|
|
have = installed()
|
|
if provider == 'auto':
|
|
left = remaining()
|
|
usable = [p for p in ('claude', 'gpt') if have[p] and left.get(p, 1) > 0]
|
|
# Unknown usage ranks below any known remainder.
|
|
if usable:
|
|
return max(usable, key=lambda p: left.get(p, 0.5)), left
|
|
if have['local'] and local_models(options):
|
|
return 'local', left
|
|
raise ValueError('No usage left on Claude or GPT, and no local model is running')
|
|
if provider not in PROVIDERS:
|
|
raise ValueError('Unknown provider')
|
|
if not have[provider]:
|
|
raise ValueError({'claude': 'claude', 'gpt': 'codex', 'local': 'opencode'}[provider] + ' is not installed')
|
|
if provider == 'local' and not local_models(options):
|
|
raise ValueError('No local model server at ' + options.get('localUrl', ''))
|
|
return provider, {}
|
|
|
|
|
|
def transcript(session, provider):
|
|
"""Earlier messages, for an agent that has not seen this conversation."""
|
|
earlier = [m for m in session['messages'][:-2] if m.get('text')]
|
|
if not earlier or session['agents'].get(provider):
|
|
return ''
|
|
lines = [('User: ' if m['role'] == 'user' else 'Reply: ') + m['text'] for m in earlier[-10:]]
|
|
return 'Earlier in this conversation:\n' + '\n'.join(lines) + '\n\n'
|
|
|
|
|
|
REMINDER = '\n\n(Work on your own, then reply in one or two short sentences starting with "OK: " or "FAILED: ".)'
|
|
|
|
|
|
def build_command(provider, session, prompt, options, last_file):
|
|
"""argv and extra environment for one run."""
|
|
resume = session['agents'].get(provider)
|
|
if resume:
|
|
prompt += REMINDER
|
|
rules = PROTOCOL + '\n\n' + ensure_rules()
|
|
if provider == 'claude':
|
|
command = ['claude', '-p', '--output-format', 'json', '--permission-mode', 'auto',
|
|
'--append-system-prompt', rules]
|
|
command += ['--allowedTools', *options['allow']] if options.get('allow') else []
|
|
command += ['--disallowedTools', *(f'Bash({d.strip()}:*)' for d in DENY)]
|
|
if options.get('claudeModel'):
|
|
command += ['--model', options['claudeModel']]
|
|
if resume:
|
|
command += ['--resume', resume]
|
|
return command, {}, prompt
|
|
if provider == 'gpt':
|
|
command = ['codex', 'exec']
|
|
if resume:
|
|
command += ['resume', resume]
|
|
command += ['--json', '--skip-git-repo-check', '-o', str(last_file)]
|
|
# Runs on its own: the automatic reviewer answers approval requests.
|
|
command += ['-c', 'approval_policy="on-request"', '-c', 'approvals_reviewer="auto_review"',
|
|
'-c', 'sandbox_mode="workspace-write"', '-c', 'sandbox_workspace_write.network_access=true']
|
|
if options.get('gptModel'):
|
|
command += ['-m', options['gptModel']]
|
|
# "-" reads the prompt from stdin.
|
|
return command + ['-'], {}, prompt if resume else rules + '\n\n# Request\n\n' + prompt
|
|
models = local_models(options)
|
|
model = options.get('localModel') or (models[0] if models else '')
|
|
deny = {'*': 'allow'}
|
|
deny.update({d.strip() + '*': 'deny' for d in DENY})
|
|
config = {
|
|
'provider': {'quickfix': {'npm': '@ai-sdk/openai-compatible', 'name': 'Local',
|
|
'options': {'baseURL': options.get('localUrl')}, 'models': {model: {}}}},
|
|
'permission': {'bash': deny}}
|
|
command = ['opencode', 'run', '--format', 'json', '--auto', '--dir', str(HOME), '-m', 'quickfix/' + model]
|
|
if resume:
|
|
command += ['-s', resume]
|
|
return command, {'OPENCODE_CONFIG_CONTENT': json.dumps(config)}, \
|
|
prompt if resume else rules + '\n\n# Request\n\n' + prompt
|
|
|
|
|
|
def parse_output(provider, out, last_file):
|
|
"""(final text, agent session id, agent-reported error)"""
|
|
text, agent, error = '', '', False
|
|
if provider == 'claude':
|
|
for line in reversed(out.strip().splitlines()):
|
|
try:
|
|
value = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(value, dict) and value.get('type') == 'result':
|
|
return str(value.get('result') or ''), value.get('session_id') or '', bool(value.get('is_error'))
|
|
return '', '', True
|
|
for line in out.splitlines():
|
|
try:
|
|
event = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
if not isinstance(event, dict):
|
|
continue
|
|
if provider == 'gpt':
|
|
if event.get('type') == 'thread.started':
|
|
agent = event.get('thread_id') or agent
|
|
elif event.get('type') in ('error', 'turn.failed'):
|
|
error = True
|
|
detail = event.get('error')
|
|
text = event.get('message') or (detail.get('message') if isinstance(detail, dict) else '') or text
|
|
elif event.get('type') == 'turn.completed':
|
|
error = False
|
|
else:
|
|
agent = event.get('sessionID') or agent
|
|
part = event.get('part') or {}
|
|
if event.get('type') == 'text' and part.get('text'):
|
|
text = part['text']
|
|
elif event.get('type') == 'error':
|
|
error = True
|
|
if provider == 'gpt' and not error:
|
|
try:
|
|
text = last_file.read_text()
|
|
except OSError:
|
|
pass
|
|
return text, agent, error
|
|
|
|
|
|
def tidy(text):
|
|
"""(ok or None when the agent did not say, message)"""
|
|
text = text.strip()
|
|
match = re.match(r'^\**(OK|FAILED)\**\s*[:.\-–—]\**\s*', text)
|
|
if not match:
|
|
return None, text
|
|
return match[1] == 'OK', text[match.end():].strip() or ('Done.' if match[1] == 'OK' else 'It did not work.')
|
|
|
|
|
|
# Snapshots and undo ------------------------------------------------------------
|
|
|
|
def git(repo, *args, check=True, **kwargs):
|
|
r = subprocess.run(['git', '-C', str(repo), *args], capture_output=True, timeout=120, **kwargs)
|
|
if check and r.returncode:
|
|
raise ValueError(r.stderr.decode(errors='replace').strip()[-300:] or 'git failed')
|
|
return r.stdout
|
|
|
|
|
|
def repositories(options):
|
|
found = []
|
|
for entry in options.get('repositories') or []:
|
|
path = Path(entry).expanduser()
|
|
if (path / '.git').exists():
|
|
found.append(path)
|
|
return found
|
|
|
|
|
|
def digest(path):
|
|
if path.is_symlink():
|
|
return 'link:' + os.readlink(path)
|
|
try:
|
|
return hashlib.sha256(path.read_bytes()).hexdigest() + (':x' if os.access(path, os.X_OK) else '')
|
|
except OSError:
|
|
return ''
|
|
|
|
|
|
def listing(repo):
|
|
"""Every tracked or untracked (not ignored) file and its digest."""
|
|
names = git(repo, 'ls-files', '-z', '--cached', '--others', '--exclude-standard').decode(errors='surrogateescape')
|
|
files = {}
|
|
for name in set(filter(None, names.split('\0'))):
|
|
path = repo / name
|
|
if path.is_symlink() or path.is_file():
|
|
if path.is_symlink() or path.stat().st_size <= MAX_FILE:
|
|
files[name] = digest(path)
|
|
return files
|
|
|
|
|
|
def snapshot(run, options):
|
|
"""Copies each repository's files aside, so a run can be undone even where
|
|
changes are never committed."""
|
|
record = {'repos': []}
|
|
for number, repo in enumerate(repositories(options)):
|
|
files = listing(repo)
|
|
target = SNAPSHOTS / run / str(number)
|
|
# Files identical to the last commit come back from git; only the rest
|
|
# (edited or untracked) need a copy.
|
|
dirty = git(repo, 'diff', '--name-only', '-z', 'HEAD', check=False) + \
|
|
git(repo, 'ls-files', '-z', '--others', '--exclude-standard')
|
|
for name in set(dirty.decode(errors='surrogateescape').split('\0')) & set(files):
|
|
copy = target / name
|
|
copy.parent.mkdir(parents=True, exist_ok=True)
|
|
copy_file(repo / name, copy)
|
|
record['repos'].append({'path': str(repo), 'head': git(repo, 'rev-parse', 'HEAD', check=False).decode().strip(),
|
|
'before': files})
|
|
write_json(SNAPSHOTS / run / 'record.json', record)
|
|
old = sorted(p for p in SNAPSHOTS.iterdir() if p.is_dir())[:-KEEP_SNAPSHOTS]
|
|
for path in old:
|
|
shutil.rmtree(path, ignore_errors=True)
|
|
return record
|
|
|
|
|
|
def copy_file(source, target):
|
|
shutil.copy2(source, target, follow_symlinks=False)
|
|
|
|
|
|
def finish_snapshot(run, record):
|
|
"""Records what the run changed; True when there is something to undo."""
|
|
changed = False
|
|
for repo in record['repos']:
|
|
path = Path(repo['path'])
|
|
before, after = repo.pop('before'), listing(path)
|
|
# `git add` may be all that changed for a file; contents are what count.
|
|
repo['files'] = {n: {'before': before.get(n, ''), 'after': after.get(n, '')}
|
|
for n in set(before) | set(after) if before.get(n, '') != after.get(n, '')}
|
|
head = git(path, 'rev-parse', 'HEAD', check=False).decode().strip()
|
|
repo['commits'] = []
|
|
if head != repo['head'] and repo['head']:
|
|
repo['commits'] = git(path, 'rev-list', f"{repo['head']}..{head}", check=False).decode().split()
|
|
changed = changed or bool(repo['files'] or repo['commits'])
|
|
write_json(SNAPSHOTS / run / 'record.json', record)
|
|
return changed
|
|
|
|
|
|
def undo(run, options):
|
|
"""Puts a run's files back and reverts its commits. Refuses, before touching
|
|
anything, when a file was edited again afterwards."""
|
|
record = read_json(SNAPSHOTS / run / 'record.json')
|
|
if not record:
|
|
raise ValueError('The snapshot for this change is gone')
|
|
plans, conflicts = [], []
|
|
for number, repo in enumerate(record['repos']):
|
|
path = Path(repo['path'])
|
|
commits = repo.get('commits') or []
|
|
committed = set()
|
|
for commit in commits:
|
|
committed |= set(filter(None, git(path, 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', commit)
|
|
.decode(errors='surrogateescape').split('\0')))
|
|
# Lock files move on with every update, so that is no reason to refuse.
|
|
for name, state in repo['files'].items():
|
|
if name != 'flake.lock' and digest(path / name) != state['after']:
|
|
conflicts.append(f'{path.name}/{name}')
|
|
if commits and git(path, 'status', '--porcelain', '--untracked-files=no', check=False).strip():
|
|
conflicts.append(f'{path.name} (uncommitted changes)')
|
|
plans.append((SNAPSHOTS / run / str(number), path, repo, commits, committed))
|
|
if conflicts:
|
|
raise ValueError('Changed again since, so it was left alone: ' + ', '.join(conflicts[:4]))
|
|
for _, path, _, commits, _ in plans:
|
|
for commit in commits: # newest first
|
|
try:
|
|
git(path, 'revert', '--no-edit', commit)
|
|
except ValueError:
|
|
git(path, 'revert', '--abort', check=False)
|
|
raise
|
|
for copy, path, repo, _, committed in plans:
|
|
for name, state in repo['files'].items():
|
|
if name in committed:
|
|
continue
|
|
target = path / name
|
|
if state['before']:
|
|
if not os.path.lexists(copy / name):
|
|
git(path, 'restore', '--source', repo['head'], '--worktree', '--', name)
|
|
continue
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = target.with_name(target.name + '.quickfix-undo')
|
|
copy_file(copy / name, tmp)
|
|
tmp.replace(target)
|
|
else:
|
|
target.unlink(missing_ok=True)
|
|
# Forget an intent-to-add entry left by the run.
|
|
git(path, 'rm', '--cached', '--quiet', '--ignore-unmatch', '--', name, check=False)
|
|
pushed = []
|
|
for _, path, _, commits, _ in plans:
|
|
if commits:
|
|
r = subprocess.run(['git', '-C', str(path), 'push'], capture_output=True, text=True, timeout=180)
|
|
if r.returncode:
|
|
pushed.append(path.name)
|
|
return pushed
|
|
|
|
|
|
# Worker (inside the transient unit) ----------------------------------------------
|
|
|
|
def finish(session, ok, text, **extra):
|
|
with locked():
|
|
session = load_session(session['id'])
|
|
message = session['messages'][-1]
|
|
agent = extra.pop('agent', '')
|
|
message.update(text=text, status='ok' if ok else 'failed' if ok is False else 'done',
|
|
finished=int(time.time()), **extra)
|
|
if agent:
|
|
session['agents'][message['provider']] = agent
|
|
session['running'] = False
|
|
save_session(session)
|
|
save_state(current=session['id'], running=False, seen=False)
|
|
|
|
|
|
def system_generation():
|
|
return os.path.realpath('/run/current-system')
|
|
|
|
|
|
def worker(id_):
|
|
session = load_session(id_)
|
|
options = session['options']
|
|
run = session['messages'][-1]['run']
|
|
prompt = session['messages'][-2]['text']
|
|
stopped = []
|
|
child = []
|
|
|
|
def stop(*_):
|
|
stopped.append(True)
|
|
for process in child:
|
|
try:
|
|
os.killpg(process.pid, signal.SIGTERM)
|
|
except ProcessLookupError:
|
|
pass
|
|
signal.signal(signal.SIGTERM, stop)
|
|
record, generation = None, system_generation()
|
|
last_file = STATE / f'{id_}.last'
|
|
try:
|
|
provider, _ = choose(session['provider'], options)
|
|
with locked():
|
|
session = load_session(id_)
|
|
session['messages'][-1]['provider'] = provider
|
|
save_session(session)
|
|
save_state(current=id_, running=True, seen=False)
|
|
record = snapshot(run, options)
|
|
prompt = transcript(session, provider) + prompt
|
|
command, env, text = build_command(provider, session, prompt, options, last_file)
|
|
last_file.unlink(missing_ok=True)
|
|
if stopped:
|
|
raise InterruptedError
|
|
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
text=True, cwd=HOME, start_new_session=True, env={**os.environ, **env})
|
|
child.append(process)
|
|
if stopped:
|
|
stop()
|
|
try:
|
|
out, err = process.communicate(text, timeout=TIMEOUT)
|
|
except subprocess.TimeoutExpired:
|
|
os.killpg(process.pid, signal.SIGKILL)
|
|
out, err = process.communicate()
|
|
err = 'It took longer than an hour and was stopped.'
|
|
if stopped:
|
|
raise InterruptedError
|
|
text, agent, error = parse_output(provider, out, last_file)
|
|
ok, text = tidy(text)
|
|
if error or process.returncode or not text:
|
|
ok = False
|
|
text = text or (err.strip().splitlines() or ['The agent gave no reply.'])[-1][-300:]
|
|
except InterruptedError:
|
|
ok, text, agent = False, 'Stopped.', ''
|
|
except Exception as error: # always leave a result behind
|
|
ok, text, agent = False, str(error) or type(error).__name__, ''
|
|
finally:
|
|
last_file.unlink(missing_ok=True)
|
|
changed = False
|
|
if record:
|
|
signal.signal(signal.SIGTERM, signal.SIG_IGN)
|
|
try:
|
|
changed = finish_snapshot(run, record)
|
|
except (OSError, ValueError, subprocess.SubprocessError):
|
|
pass
|
|
finish(session, ok, text, agent=agent, changed=changed, rebuilt=system_generation() != generation)
|
|
|
|
|
|
def undo_worker(id_):
|
|
session = load_session(id_)
|
|
run = session['messages'][-1]['undoes']
|
|
generation = system_generation()
|
|
try:
|
|
unpushed = undo(run, session['options'])
|
|
text, ok = 'Undone.', True
|
|
apply = session['options'].get('applyCommand') or []
|
|
if apply:
|
|
r = subprocess.run(apply, capture_output=True, text=True, timeout=TIMEOUT, cwd=HOME, stdin=subprocess.DEVNULL)
|
|
if r.returncode:
|
|
ok = False
|
|
text = 'The files are back, but applying them failed: ' + \
|
|
((r.stderr or r.stdout).strip().splitlines() or ['unknown error'])[-1][-200:]
|
|
if unpushed:
|
|
ok, text = False, text + ' Could not push ' + ', '.join(unpushed) + '.'
|
|
with locked():
|
|
session = load_session(id_)
|
|
for message in session['messages']:
|
|
if message.get('run') == run:
|
|
message['undone'] = True
|
|
save_session(session)
|
|
except Exception as error:
|
|
ok, text = False, str(error) or type(error).__name__
|
|
finish(session, ok, text, rebuilt=system_generation() != generation)
|
|
|
|
|
|
# Requests from the shell -----------------------------------------------------------
|
|
|
|
def clean_options(value):
|
|
value = value if isinstance(value, dict) else {}
|
|
strings = lambda key: [s for s in value.get(key) or [] if isinstance(s, str) and s]
|
|
options = {key: strings(key) for key in ('repositories', 'allow', 'applyCommand')}
|
|
for key in ('claudeModel', 'gptModel', 'localUrl', 'localModel'):
|
|
options[key] = value.get(key) if isinstance(value.get(key), str) else ''
|
|
if options[key].startswith('-'):
|
|
raise ValueError('Invalid ' + key)
|
|
return options
|
|
|
|
|
|
def recover():
|
|
"""Marks a run whose unit died (power loss, crash) as failed."""
|
|
state = read_state()
|
|
if not state.get('running') or not state.get('current'):
|
|
return
|
|
id_ = state['current']
|
|
if time.time() - state.get('started', 0) < 5 or unit_active(id_):
|
|
return
|
|
with locked():
|
|
if not read_state().get('running'):
|
|
return
|
|
session = read_json(session_path(id_))
|
|
if session and session.get('running'):
|
|
session['running'] = False
|
|
session['messages'][-1].update(text='It was interrupted before it finished.', status='failed',
|
|
finished=int(time.time()))
|
|
save_session(session)
|
|
save_state(running=False, seen=False)
|
|
|
|
|
|
def begin(session, request_messages, action):
|
|
with locked():
|
|
if read_state().get('running'):
|
|
raise ValueError('Something is already running')
|
|
session['messages'] += request_messages
|
|
session['running'] = True
|
|
session['updated'] = int(time.time())
|
|
save_session(session)
|
|
save_state(current=session['id'], running=True, seen=False, started=int(time.time()))
|
|
try:
|
|
start_unit(session['id'], action)
|
|
except (OSError, ValueError) as error:
|
|
finish(session, False, str(error))
|
|
return load_session(session['id'])
|
|
|
|
|
|
def handle(request):
|
|
op = request.get('op')
|
|
recover()
|
|
if op == 'state':
|
|
state = read_state()
|
|
session = read_json(session_path(state['current'])) if state.get('current') else None
|
|
return {'session': session, 'running': bool(state.get('running')), 'seen': bool(state.get('seen', True))}
|
|
if op == 'send':
|
|
text = str(request.get('text') or '').strip()
|
|
if not text or len(text) > 8000:
|
|
raise ValueError('Type what to do')
|
|
options = clean_options(request.get('options'))
|
|
provider = request.get('provider')
|
|
if provider != 'auto' and provider not in PROVIDERS:
|
|
raise ValueError('Unknown provider')
|
|
if request.get('session'):
|
|
session = load_session(request['session'])
|
|
else:
|
|
session = {'id': new_id(), 'created': int(time.time()), 'title': text.splitlines()[0][:80],
|
|
'messages': [], 'agents': {}}
|
|
session.update(provider=provider, options=options)
|
|
now = int(time.time())
|
|
session = begin(session, [{'role': 'user', 'text': text, 'time': now},
|
|
{'role': 'agent', 'text': '', 'status': 'running', 'time': now,
|
|
'provider': '' if provider == 'auto' else provider, 'run': new_id()}], 'worker')
|
|
prune()
|
|
return {'session': session}
|
|
if op == 'undo':
|
|
session = load_session(request.get('session'))
|
|
session['options'] = clean_options(request.get('options'))
|
|
run = request.get('run')
|
|
if not any(m.get('run') == run and m.get('changed') and not m.get('undone') for m in session['messages']):
|
|
raise ValueError('Nothing to undo')
|
|
now = int(time.time())
|
|
return {'session': begin(session, [{'role': 'user', 'text': 'Undo', 'time': now},
|
|
{'role': 'agent', 'text': '', 'status': 'running', 'time': now,
|
|
'provider': 'undo', 'undoes': run}], 'undo')}
|
|
if op == 'stop':
|
|
session_path(request.get('session'))
|
|
subprocess.run(['systemctl', '--user', 'stop', '--no-block', f"{UNIT}-{request['session']}.service"],
|
|
capture_output=True, timeout=10)
|
|
return {}
|
|
if op == 'seen':
|
|
with locked():
|
|
state = read_state()
|
|
if not state.get('running') and state.get('current') == request.get('session'):
|
|
save_state(seen=True)
|
|
return {}
|
|
if op == 'load':
|
|
return {'session': load_session(request.get('session'))}
|
|
if op == 'history':
|
|
rows = []
|
|
for path in sorted(SESSIONS.glob('*.json'), reverse=True)[:KEEP_SESSIONS] if SESSIONS.is_dir() else []:
|
|
session = read_json(path)
|
|
if session:
|
|
rows.append({'id': session['id'], 'title': session.get('title', ''),
|
|
'updated': session.get('updated', session.get('created', 0)),
|
|
'status': session['messages'][-1].get('status', '') if session['messages'] else ''})
|
|
return {'history': sorted(rows, key=lambda r: r['updated'], reverse=True)}
|
|
if op == 'clearHistory':
|
|
with locked():
|
|
state = read_state()
|
|
for path in SESSIONS.glob('*.json') if SESSIONS.is_dir() else []:
|
|
if not (state.get('running') and path.stem == state.get('current')):
|
|
path.unlink(missing_ok=True)
|
|
return {'history': []}
|
|
if op == 'providers':
|
|
options = clean_options(request.get('options'))
|
|
have = installed()
|
|
have['local'] = have['local'] and bool(local_models(options))
|
|
return {'available': have, 'remaining': remaining()}
|
|
if op == 'rules':
|
|
ensure_rules()
|
|
return {'path': str(RULES)}
|
|
raise ValueError('Unknown operation')
|
|
|
|
|
|
def prune():
|
|
for path in sorted(SESSIONS.glob('*.json'))[:-KEEP_SESSIONS]:
|
|
path.unlink(missing_ok=True)
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) == 3 and sys.argv[1] in ('worker', 'undo'):
|
|
(worker if sys.argv[1] == 'worker' else undo_worker)(sys.argv[2])
|
|
return
|
|
try:
|
|
result = handle(json.loads(sys.argv[1]))
|
|
result['ok'] = True
|
|
except (OSError, ValueError, IndexError, KeyError, TypeError, subprocess.SubprocessError) as error:
|
|
result = {'ok': False, 'error': str(error) or type(error).__name__}
|
|
print(json.dumps(result))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|