osmike-connect request; publish via the bus
This commit is contained in:
parent
a4fcc93dcd
commit
429708a8a9
36
osmike-int
36
osmike-int
@ -1,5 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""osmike-int: use any integrated service (Slack, ElevenLabs, ...) from an agent. Generic: one tool for all services.
|
||||
"""osmike-connect (also: osmike-int): OsMike Connect from an agent. Use any integrated service (Slack, ElevenLabs, ...),
|
||||
and ask for new ones. One generic tool for all services.
|
||||
|
||||
osmike-connect request <service> [--secret NAME[:field] ...] [--reason "why"] [--docs URL]
|
||||
connect a service, optionally with secrets YOU hold in secretz (by name; the
|
||||
values are read on the server and never shown). Unknown services are built.
|
||||
osmike-connect secrets names of the secrets you can use (never values)
|
||||
osmike-connect status <service> built? connected? waiting for your person?
|
||||
|
||||
osmike-int list services connected for you (and their state)
|
||||
osmike-int catalog [word] every ready integration
|
||||
@ -170,6 +177,33 @@ def main(argv):
|
||||
return
|
||||
if argv[0] == 'builder':
|
||||
return builder(argv[1:])
|
||||
if argv[0] == 'request' and len(argv) >= 2:
|
||||
service, rest, secrets_, reason, docs, i = argv[1], argv[2:], [], None, None, 0
|
||||
while i < len(rest):
|
||||
if rest[i] == '--secret' and i + 1 < len(rest):
|
||||
nm, _, fld = rest[i + 1].partition(':')
|
||||
secrets_.append({'name': nm, 'field': fld or None}); i += 2
|
||||
elif rest[i] == '--reason' and i + 1 < len(rest):
|
||||
reason = rest[i + 1]; i += 2
|
||||
elif rest[i] == '--docs' and i + 1 < len(rest):
|
||||
docs = rest[i + 1]; i += 2
|
||||
else:
|
||||
die('request <service> [--secret NAME[:field]] [--reason TEXT] [--docs URL]')
|
||||
d = http('POST', '/v1/runs/integrations/request', {'service': service, 'secrets': secrets_, 'reason': reason, 'docs': docs})
|
||||
print('%s: %s%s' % (d.get('name') or service, d.get('state'), (' — fields: ' + ', '.join(d['fields'])) if d.get('fields') else ''))
|
||||
if d.get('next'):
|
||||
print(d['next'])
|
||||
return
|
||||
if argv[0] == 'secrets':
|
||||
rows = http('GET', '/v1/runs/integrations/secrets')['secrets']
|
||||
if not rows:
|
||||
print('You hold no secrets in secretz. Your person can paste keys in Mesh instead.')
|
||||
for r in rows:
|
||||
print('%-40s %s' % (r.get('name'), r.get('description') or ''))
|
||||
return
|
||||
if argv[0] == 'status' and len(argv) >= 2:
|
||||
print(json.dumps(http('GET', '/v1/runs/integrations/%s/status' % urllib.request.quote(argv[1])), indent=1))
|
||||
return
|
||||
if argv[0] == 'list':
|
||||
rows = http('GET', '/v1/runs/integrations/mine')['connections']
|
||||
if not rows:
|
||||
|
||||
136
osmike-publish
136
osmike-publish
@ -1,14 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Publish to YOUR PRIVATE repo. Printed URL requires the owner's Gitea login."""
|
||||
import os,shutil,subprocess,sys,secrets
|
||||
from pathlib import Path
|
||||
if len(sys.argv)!=2: sys.exit('usage: osmike-publish FILE (private owner repo link)')
|
||||
p=Path(sys.argv[1]).resolve(); root=Path('/data/workspace'); dest=root/'context/published'; dest.mkdir(parents=True,exist_ok=True)
|
||||
if not p.is_file() or p.stat().st_size>10*1024*1024: sys.exit('file must exist and be at most 10MiB')
|
||||
name=secrets.token_hex(8)+'-'+p.name; shutil.copyfile(p,dest/name)
|
||||
for args in [['add','--','context/published/'+name],['-c','user.name='+os.environ['AGENT_NAME'],'-c','user.email='+os.environ['AGENT_NAME']+'@guests.osmike.com','commit','-m','Publish private guest artifact'],['push','origin','HEAD:main']]:
|
||||
r=subprocess.run(['git','-C',str(root)]+args,capture_output=True)
|
||||
if r.returncode: sys.exit('repo publication failed')
|
||||
repo=os.environ['GUEST_REPO'].split(':8771/',1)[1].removesuffix('.git')
|
||||
from urllib.parse import quote
|
||||
print('https://git.osmike.com/'+repo+'/src/branch/main/context/published/'+quote(name))
|
||||
"""osmike-publish - publish a file and print its public https URL (https://charts.osmike.com/...).
|
||||
|
||||
osmike-publish <file> [prefix] [--quiet]
|
||||
|
||||
Types: png jpg jpeg gif webp svg pdf html htm txt md csv json mp4 webm zip. Max 50 MB.
|
||||
The URL is public but unguessable (<prefix>-<unixtime>-<18 hex>.<ext>); don't publish secrets.
|
||||
Images in an a2a message: write  and the ws6 panel shows it inline.
|
||||
|
||||
stdout: the URL only. stderr: a one-line summary (suppressed by --quiet). Exit 0 ok, 2 error.
|
||||
Inside an agent: through the bus with the agent's key (POST /v1/runs/publish). On hosts: ssh with ~/.ssh/mikeos_media.
|
||||
Override the ssh target with $OSMIKE_PUBLISH_RELAY.
|
||||
"""
|
||||
import argparse, os, re, secrets, shlex, subprocess, sys, time
|
||||
|
||||
DEST_DIR = "/var/lib/docker/volumes/deploy_caddy_data/_data/charts"
|
||||
BASE_URL = "https://charts.osmike.com/"
|
||||
MAX_BYTES = 50 * 1024 * 1024
|
||||
TYPES = {"png", "jpg", "jpeg", "gif", "webp", "svg", "pdf", "html", "htm", "txt", "md", "csv", "json",
|
||||
"mp4", "webm", "zip"}
|
||||
SSH_OPTS = ["-o", "BatchMode=yes", "-o", "ConnectTimeout=20", "-o", "StrictHostKeyChecking=accept-new"]
|
||||
|
||||
|
||||
def die(msg):
|
||||
print(f"osmike-publish: {msg}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def relay_argv():
|
||||
"""ssh argv (without the remote command) that reaches relay 242 as root."""
|
||||
override = os.environ.get("OSMIKE_PUBLISH_RELAY")
|
||||
if override:
|
||||
return ["ssh"] + SSH_OPTS + [override]
|
||||
cfg = os.path.expanduser("~/.ssh/config")
|
||||
try:
|
||||
if re.search(r"(?im)^\s*Host\s+(.*\s)?relay242(\s|$)", open(cfg).read()):
|
||||
return ["ssh"] + SSH_OPTS + ["relay242"]
|
||||
except OSError:
|
||||
pass
|
||||
key = os.path.expanduser("~/.ssh/mikeos_media")
|
||||
if os.path.exists(key):
|
||||
return ["ssh"] + SSH_OPTS + ["-i", key, "root@91.98.177.242"]
|
||||
return ["ssh"] + SSH_OPTS + ["relay242"]
|
||||
|
||||
|
||||
def make_name(prefix, ext):
|
||||
p = re.sub(r"[^A-Za-z0-9._-]", "_", prefix).strip("._-")[:40] or "file"
|
||||
return f"{p}-{int(time.time())}-{secrets.token_hex(9)}.{ext}"
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="osmike-publish", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("file")
|
||||
ap.add_argument("prefix", nargs="?", help="name prefix (default: the file name)")
|
||||
ap.add_argument("--quiet", "-q", action="store_true", help="print only the URL")
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
f = a.file
|
||||
if not os.path.isfile(f):
|
||||
die(f"not a readable file: {f}")
|
||||
size = os.path.getsize(f)
|
||||
if size == 0:
|
||||
die(f"empty file: {f}")
|
||||
if size > MAX_BYTES:
|
||||
die(f"too large: {size} bytes (max 50 MB)")
|
||||
ext = os.path.splitext(f)[1].lower().lstrip(".")
|
||||
if ext not in TYPES:
|
||||
die(f"unsupported type '{('.' + ext) if ext else 'no extension'}' (allowed: {' '.join(sorted(TYPES))})")
|
||||
if ext == "jpeg":
|
||||
ext = "jpg"
|
||||
if ext == "htm":
|
||||
ext = "html"
|
||||
api, key = os.environ.get("A2A_API", "").rstrip("/"), os.environ.get("A2A_AGENT_KEY", "")
|
||||
if api and key and not os.environ.get("OSMIKE_PUBLISH_RELAY"):
|
||||
# Inside an agent: upload through the bus with the agent's own key (no SSH to the servers; 2026-11-13).
|
||||
import json, urllib.error, urllib.parse, urllib.request
|
||||
label = (a.prefix or os.path.splitext(os.path.basename(f))[0]) + "." + ext
|
||||
req = urllib.request.Request(api + "/v1/runs/publish?name=" + urllib.parse.quote(label), data=open(f, "rb").read(),
|
||||
headers={"X-API-KEY": key, "Content-Type": "application/octet-stream"}, method="POST")
|
||||
try:
|
||||
d = json.load(urllib.request.urlopen(req, timeout=300))
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
detail = json.load(e).get("detail")
|
||||
except Exception:
|
||||
detail = e.reason
|
||||
die(f"publish failed: {detail} (HTTP {e.code})")
|
||||
except urllib.error.URLError as e:
|
||||
die(f"cannot reach OsMike: {e.reason}")
|
||||
url = d["url"]
|
||||
print(url)
|
||||
if not a.quiet:
|
||||
hint = f" (embed: )" if ext in {"png", "jpg", "gif", "webp", "svg"} else ""
|
||||
print(f"published {os.path.basename(f)} ({size} bytes){hint}", file=sys.stderr)
|
||||
return 0
|
||||
name = make_name(a.prefix or os.path.splitext(os.path.basename(f))[0], ext)
|
||||
dest = f"{DEST_DIR}/{name}"
|
||||
q, qt = shlex.quote(dest), shlex.quote(dest + ".part")
|
||||
remote = (f"umask 022; cat > {qt} && mv {qt} {q} && chmod 644 {q} && "
|
||||
f"(stat -c %s {q} 2>/dev/null || wc -c < {q})")
|
||||
try:
|
||||
with open(f, "rb") as fh:
|
||||
r = subprocess.run(relay_argv() + [remote], stdin=fh, capture_output=True, timeout=300)
|
||||
except subprocess.TimeoutExpired:
|
||||
die("upload timed out (5 min)")
|
||||
except OSError as e:
|
||||
die(f"cannot run ssh: {e}")
|
||||
if r.returncode != 0:
|
||||
err = r.stderr.decode("utf-8", "replace").strip().splitlines()
|
||||
die(f"upload to relay 242 failed (ssh rc {r.returncode}): {err[-1] if err else ''}")
|
||||
got = r.stdout.decode().strip().split()[-1:] or [""]
|
||||
if got[0] != str(size):
|
||||
die(f"size mismatch after upload ({got[0]} != {size})")
|
||||
url = BASE_URL + name
|
||||
print(url)
|
||||
if not a.quiet:
|
||||
hint = f" (embed: )" if ext in {"png", "jpg", "gif", "webp", "svg"} else ""
|
||||
print(f"published {os.path.basename(f)} ({size} bytes){hint}", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Loading…
Reference in New Issue
Block a user