main
John Lauer v0.2.2: README around asking your AI (prompt + ah screenshots), single-engine runs, current ngspice numbers 13a6244
#!/usr/bin/env python3
"""adom-spice CLI: every verb takes the global --ai-thread "<name>" flag (any position)."""
import glob, json, os, subprocess, sys, time, urllib.request

ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
INST = os.path.expanduser('~/.adom/instances/adom-spice')
os.makedirs(INST, exist_ok=True)
PY = os.environ.get('ADOM_SPICE_PYTHON') or next((p for p in (os.path.expanduser('~/.adom/adom-spice-venv/bin/python'), '/home/adom/spice-venv/bin/python', sys.executable) if os.path.exists(p)), 'python3')
HELP = """adom-spice: one dashboard for ngspice, LTspice and PSpice for TI

  adom-spice --ai-thread "<name>" start [--keep-alive]      start (or reuse) this thread's dashboard server
  adom-spice --ai-thread "<name>" show [--surface wv|hbw|pup|nb]  open the dashboard (default: Hydrogen webview)
  adom-spice --ai-thread "<name>" study <study.json>        load a study (netlists per engine, signals, views, measurements)
  adom-spice --ai-thread "<name>" run ngspice ltspice pspice queue runs; LTspice/PSpice go to the bridge target in Settings
  adom-spice --ai-thread "<name>" ingest <file> --kind csdf|raw|txt --label "<label>" --signals '{"vout":"V(x)"}' [--engine reference]
  adom-spice --ai-thread "<name>" tokens <engine> <tokens> [--tool-calls N]   record the AI tokens a run cost
  adom-spice --ai-thread "<name>" settings [key=value ...]  read or change settings
  adom-spice ls | state | console                           read-only
  adom-spice --ai-thread "<name>" shutdown --reason "<why>"
"""


def args_and_thread(argv):
    th, out, i = os.environ.get('ADOM_AI_THREAD', ''), [], 0
    while i < len(argv):
        if argv[i] == '--ai-thread': th = argv[i + 1]; i += 2; continue
        out.append(argv[i]); i += 1
    return th, out


def flag(a, name, default=None):
    if name in a:
        i = a.index(name); v = a[i + 1]; del a[i:i + 2]; return v
    return default


def instances():
    live = []
    for f in glob.glob(os.path.join(INST, '*.reg.json')):
        d = json.load(open(f))
        try: os.kill(d['pid'], 0); live.append(d)
        except OSError: os.remove(f)
    return live


def mine(th):
    for d in instances():
        if d['thread'] == th: return d
    return None


def call(port, path, body=None):
    req = urllib.request.Request(f'http://127.0.0.1:{port}{path}', data=None if body is None else json.dumps(body).encode(),
                                 headers={'Content-Type': 'application/json'}, method='GET' if body is None else 'POST')
    try:
        with urllib.request.urlopen(req, timeout=60) as r: return json.loads(r.read())
    except urllib.error.HTTPError as e: return json.loads(e.read())


def need(th):
    if not th:
        print(json.dumps({'ok': False, 'errorCode': 'caller_identity_required', 'hint': 'Re-run with: adom-spice --ai-thread "<short name for this conversation>" <verb>'})); sys.exit(2)
    d = mine(th)
    if not d:
        print(json.dumps({'ok': False, 'error': f'no dashboard running for thread "{th}"', 'hint': f'adom-spice --ai-thread "{th}" start'})); sys.exit(2)
    return d['port']


def url_for(port):
    tpl = os.environ.get('VSCODE_PROXY_URI', '')
    return tpl.replace('{{port}}', str(port)) if '{{port}}' in tpl else f'http://localhost:{port}/'


def main():
    th, a = args_and_thread(sys.argv[1:])
    if not a or a[0] in ('-h', '--help', 'help'): print(HELP); return
    v = a.pop(0)
    if v == 'ls':
        for d in instances():
            print(f"port {d['port']}  thread \"{d['thread']}\"  task {d.get('task')}  version {d['version']}  idle {int(time.time() - d['lastActivity'])} s")
        return
    if v == 'start':
        if not th: need(th)
        d = mine(th)
        if d: print(json.dumps({'ok': True, 'port': d['port'], 'reused': True, 'url': url_for(d['port']), 'note': 'already running for this thread; use it'})); return
        env = dict(os.environ, ADOM_SPICE_THREAD=th, PYTHONUNBUFFERED='1')
        logf = open(os.path.join(INST, 'server.log'), 'a')
        p = subprocess.Popen([PY, os.path.join(ROOT, 'adom_spice', 'server.py')] + (['--keep-alive'] if '--keep-alive' in a else []),
                             env=env, stdout=subprocess.PIPE, stderr=logf, start_new_session=True, text=True)
        line = p.stdout.readline()
        while line and not line.startswith('{'):
            line = p.stdout.readline()
        d = json.loads(line)
        d['url'] = url_for(d['port']); print(json.dumps(d)); return
    if v in ('state', 'console'):
        ds = instances(); d = mine(th) if th else (ds[0] if ds else None)
        if not d: print('{"ok": false, "error": "no dashboard running"}'); return
        r = call(d['port'], '/' + v)
        if v == 'state' and '--full' not in a: r.pop('waves', None)
        print(json.dumps(r, indent=1)); return
    port = need(th)
    if v == 'show':
        surface = flag(a, '--surface') or call(port, '/settings')['settings'].get('defaultSurface', 'wv')
        u = url_for(port)
        if surface in ('wv', 'hbw'):
            r = subprocess.run(['adom-cli', 'hydrogen', 'webview', 'open-or-refresh', '--name', 'Adom SPICE', '--url', u], capture_output=True, text=True)
            print(json.dumps({'ok': r.returncode == 0, 'surface': 'wv', 'url': u, 'detail': (r.stdout + r.stderr)[-300:]}))
        else:
            print(json.dumps({'ok': True, 'surface': surface, 'url': u, 'hint': 'open this URL with the pup or nb skill'}))
        return
    if v == 'study': print(json.dumps(call(port, '/study', {'aiThread': th, 'path': os.path.abspath(a[0])}))); return
    if v == 'run': print(json.dumps(call(port, '/run', {'aiThread': th, 'engines': a or ['ngspice']}))); return
    if v == 'ingest':
        kind = flag(a, '--kind', 'txt'); label = flag(a, '--label'); sig = json.loads(flag(a, '--signals', '{}')); eng = flag(a, '--engine', 'reference')
        print(json.dumps(call(port, '/ingest', {'aiThread': th, 'file': os.path.abspath(a[0]), 'kind': kind, 'label': label, 'signals': sig, 'engine': eng}))); return
    if v == 'tokens':
        tc = flag(a, '--tool-calls')
        print(json.dumps(call(port, '/tokens', {'aiThread': th, 'engine': a[0], 'tokens': int(a[1]), 'toolCalls': int(tc) if tc else None}))); return
    if v == 'settings':
        if not a: print(json.dumps(call(port, '/settings'), indent=1)); return
        s = {}
        for kv in a:
            k, _, val = kv.partition('=')
            try: s[k] = json.loads(val)
            except json.JSONDecodeError: s[k] = val
        print(json.dumps(call(port, '/settings', {'aiThread': th, 'set': s}))); return
    if v == 'shutdown':
        print(json.dumps(call(port, '/shutdown', {'aiThread': th, 'reason': flag(a, '--reason')}))); return
    if v == 'ui':
        sub = a.pop(0); print(json.dumps(call(port, '/ui/' + sub, {'aiThread': th, 'selector': a[0] if a else None, 'text': a[0] if a else None}))); return
    print(HELP); sys.exit(2)


if __name__ == '__main__':
    main()