205 lines
9.0 KiB
Python
Executable File
205 lines
9.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""osmike-int: use any integrated service (Slack, ElevenLabs, ...) from an agent. Generic: one tool for all services.
|
|
|
|
osmike-int list services connected for you (and their state)
|
|
osmike-int catalog [word] every ready integration
|
|
osmike-int <service> what you can do with it (commands, parameters, which ones write)
|
|
osmike-int <service> test check that the connection works
|
|
osmike-int <service> <command> --param value [--param value ...] [--json '{"param": ...}'] [--save FILE]
|
|
|
|
The call runs on the OsMike server with the person's stored keys; you never see or need a key. Files (audio,
|
|
images, PDFs) come back as a link you can give the person. Commands marked [writes] change things at the service
|
|
and only work when the person has switched on "allow writing" for the connection in Mesh → Settings → OsMike Connect.
|
|
If a service is not connected for you: the person connects it by pasting its keys in the chat; Mesh does the rest.
|
|
|
|
Builder only (osmike-integrations):
|
|
osmike-int builder queue | claim <slug> [request_id] | fail <slug> "why"
|
|
osmike-int builder validate spec.json
|
|
osmike-int builder dryrun spec.json <command> --param value (shows the request; no network, no keys)
|
|
osmike-int builder trial spec.json <command> --param value (runs it with the waiting person's keys, server side)
|
|
osmike-int builder publish spec.json [--docs URL] [--notes TEXT] [--alias NAME ...]
|
|
"""
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
try:
|
|
import intengine
|
|
except ImportError: # the engine is only needed for builder validate/dryrun
|
|
intengine = None
|
|
|
|
|
|
def env():
|
|
api, key = os.environ.get('A2A_API', '').rstrip('/'), os.environ.get('A2A_AGENT_KEY', '')
|
|
if not api or not key:
|
|
die('A2A_API and A2A_AGENT_KEY must be set (they are in every agent).')
|
|
return api, key
|
|
|
|
|
|
def die(msg, code=1):
|
|
print(msg, file=sys.stderr)
|
|
sys.exit(code)
|
|
|
|
|
|
def http(method, path, body=None, timeout=120):
|
|
api, key = env()
|
|
req = urllib.request.Request(api + path, data=json.dumps(body).encode() if body is not None else None, method=method,
|
|
headers={'X-API-KEY': key, 'Content-Type': 'application/json'})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return json.load(r)
|
|
except urllib.error.HTTPError as e:
|
|
try:
|
|
detail = json.load(e).get('detail')
|
|
except Exception:
|
|
detail = None
|
|
die('%s (HTTP %s)' % (detail if isinstance(detail, str) else json.dumps(detail) if detail else e.reason, e.code))
|
|
except urllib.error.URLError as e:
|
|
die('Could not reach OsMike: %s' % e.reason)
|
|
|
|
|
|
def parse_params(args):
|
|
params, save, i = {}, None, 0
|
|
while i < len(args):
|
|
a = args[i]
|
|
if a == '--json' and i + 1 < len(args):
|
|
try:
|
|
params.update(json.loads(args[i + 1]))
|
|
except ValueError:
|
|
die('--json must be a JSON object')
|
|
i += 2
|
|
elif a == '--save' and i + 1 < len(args):
|
|
save, i = args[i + 1], i + 2
|
|
elif a.startswith('--') and '=' in a:
|
|
k, v = a[2:].split('=', 1)
|
|
params[k.replace('-', '_')] = v
|
|
i += 1
|
|
elif a.startswith('--') and i + 1 < len(args) and not args[i + 1].startswith('--'):
|
|
params[a[2:].replace('-', '_')] = args[i + 1]
|
|
i += 2
|
|
elif a.startswith('--'):
|
|
params[a[2:].replace('-', '_')] = 'true'
|
|
i += 1
|
|
else:
|
|
die('Unexpected argument %r; parameters are --name value' % a)
|
|
return params, save
|
|
|
|
|
|
def show(res, save=None):
|
|
if res.get('file_url'):
|
|
print(json.dumps({'ok': res['ok'], 'file_url': res['file_url'], 'bytes': res.get('file_bytes')}, indent=1))
|
|
if save:
|
|
urllib.request.urlretrieve(res['file_url'], save)
|
|
print('saved to', save)
|
|
return
|
|
body = res.get('json') if res.get('json') is not None else res.get('text')
|
|
out = json.dumps(body, indent=1, ensure_ascii=False) if not isinstance(body, str) else body
|
|
if save:
|
|
Path(save).write_text(out)
|
|
print('saved to', save)
|
|
else:
|
|
print(out)
|
|
if not res.get('ok'):
|
|
print('(the service answered HTTP %s)' % res.get('status'), file=sys.stderr)
|
|
sys.exit(2)
|
|
|
|
|
|
def load_spec(path):
|
|
try:
|
|
return json.loads(Path(path).read_text())
|
|
except (OSError, ValueError) as e:
|
|
die('Cannot read spec %s: %s' % (path, e))
|
|
|
|
|
|
def builder(args):
|
|
if not args:
|
|
die(__doc__)
|
|
cmd, rest = args[0], args[1:]
|
|
if cmd == 'queue':
|
|
print(json.dumps(http('GET', '/v1/runs/integrations/queue'), indent=1))
|
|
elif cmd == 'claim' and rest:
|
|
print(json.dumps(http('POST', '/v1/runs/integrations/%s/claim' % rest[0], {'request_id': int(rest[1]) if len(rest) > 1 else None}), indent=1))
|
|
elif cmd == 'fail' and len(rest) >= 2:
|
|
print(json.dumps(http('POST', '/v1/runs/integrations/%s/fail' % rest[0], {'error': ' '.join(rest[1:])}), indent=1))
|
|
elif cmd == 'validate' and rest:
|
|
if not intengine:
|
|
die('intengine.py missing next to osmike-int')
|
|
errors = intengine.validate(load_spec(rest[0]))
|
|
print('valid' if not errors else '\n'.join('- ' + e for e in errors))
|
|
sys.exit(1 if errors else 0)
|
|
elif cmd == 'dryrun' and len(rest) >= 2:
|
|
spec = load_spec(rest[0])
|
|
params, _ = parse_params(rest[2:])
|
|
fake = {f.get('name'): 'SECRET-' + f.get('name', 'x').upper() for f in spec.get('credentials', [])}
|
|
fake.update(access_token='SECRET-ACCESS-TOKEN', token='SECRET-TOKEN', api_key=fake.get('api_key', 'SECRET-API-KEY'))
|
|
try:
|
|
method, url, headers, data, out = intengine.build_request(spec, rest[1], params, fake, allow_write=True)
|
|
except intengine.CallError as e:
|
|
die(str(e))
|
|
print(json.dumps({'method': method, 'url': url, 'headers': headers, 'body': data.decode() if data else None,
|
|
'output': out, 'writes': intengine.is_write(spec['commands'][rest[1]])}, indent=1))
|
|
elif cmd == 'trial' and len(rest) >= 2:
|
|
spec = load_spec(rest[0])
|
|
params, _ = parse_params(rest[2:])
|
|
print(json.dumps(http('POST', '/v1/runs/integrations/%s/trial' % spec.get('slug'), {'spec': spec, 'command': rest[1], 'params': params}), indent=1, ensure_ascii=False))
|
|
elif cmd == 'publish' and rest:
|
|
spec = load_spec(rest[0])
|
|
opts, aliases, i = {}, [], 1
|
|
while i < len(rest):
|
|
if rest[i] in ('--docs', '--notes') and i + 1 < len(rest):
|
|
opts[rest[i][2:]] = rest[i + 1]
|
|
i += 2
|
|
elif rest[i] == '--alias' and i + 1 < len(rest):
|
|
aliases.append(rest[i + 1])
|
|
i += 2
|
|
else:
|
|
die('publish spec.json [--docs URL] [--notes TEXT] [--alias NAME]')
|
|
print(json.dumps(http('POST', '/v1/runs/integrations/%s/publish' % spec.get('slug'),
|
|
{'spec': spec, 'docs_url': opts.get('docs'), 'notes': opts.get('notes'), 'aliases': aliases}), indent=1))
|
|
else:
|
|
die(__doc__)
|
|
|
|
|
|
def main(argv):
|
|
if not argv or argv[0] in ('-h', '--help', 'help'):
|
|
print(__doc__)
|
|
return
|
|
if argv[0] == 'builder':
|
|
return builder(argv[1:])
|
|
if argv[0] == 'list':
|
|
rows = http('GET', '/v1/runs/integrations/mine')['connections']
|
|
if not rows:
|
|
print('No services are connected for you yet. A person connects one by pasting its keys in the chat.')
|
|
for r in rows:
|
|
print('%-20s %-10s writing %s (for %s)' % (r['slug'], r['status'], 'on' if r['allow_write'] else 'off', r['person']))
|
|
return
|
|
if argv[0] == 'catalog':
|
|
q = ('?q=' + urllib.request.quote(argv[1])) if len(argv) > 1 else ''
|
|
for r in http('GET', '/v1/runs/integrations/catalog' + q)['integrations']:
|
|
print('%-24s %s' % (r['slug'], r['name']))
|
|
return
|
|
slug, rest = argv[0], argv[1:]
|
|
if not rest or rest[0] in ('-h', '--help', 'help'):
|
|
spec = http('GET', '/v1/runs/integrations/%s/spec' % slug)['spec']
|
|
if intengine:
|
|
print(intengine.describe(spec))
|
|
else:
|
|
print(json.dumps({k: v.get('summary') for k, v in spec['commands'].items()}, indent=1))
|
|
return
|
|
if rest[0] == 'test':
|
|
spec = http('GET', '/v1/runs/integrations/%s/spec' % slug)['spec']
|
|
t = spec['test']
|
|
res = http('POST', '/v1/runs/integrations/%s/call' % slug, {'command': t['command'], 'params': t.get('params') or {}})
|
|
print('%s works (HTTP %s)' % (spec['name'], res['status']) if res['ok'] else '%s did not work (HTTP %s)' % (spec['name'], res['status']))
|
|
sys.exit(0 if res['ok'] else 2)
|
|
params, save = parse_params(rest[1:])
|
|
show(http('POST', '/v1/runs/integrations/%s/call' % slug, {'command': rest[0], 'params': params}), save)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main(sys.argv[1:])
|