aihub-code 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
aihub.py ADDED
@@ -0,0 +1,1342 @@
1
+ #!/usr/bin/env python3
2
+ """AI Hub Code para Termux: cliente de linha de comando do backend (Cloudflare Worker).
3
+
4
+ Só biblioteca padrão (o comando `term` usa também `websocket-client`).
5
+ Segredos: a senha nunca é gravada nem impressa; os tokens ficam em arquivo 0600 e nunca são exibidos.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import base64
11
+ import getpass
12
+ import json
13
+ import os
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import time
19
+ import urllib.error
20
+ import urllib.parse
21
+ import urllib.request
22
+ from typing import Any, Callable
23
+
24
+ VERSION = "0.2.0"
25
+ DEFAULT_BACKEND = "https://aihub-api.vyntrica.com"
26
+ MAX_HISTORY = 8
27
+ TERMINAL_STATES = {"completed", "failed", "cancelled"}
28
+
29
+
30
+ # --- validação de endereços (tokens só vão para hosts esperados) ---------------------------------
31
+
32
+ def _clean_https(url: str, suffix: str) -> str | None:
33
+ try:
34
+ u = urllib.parse.urlparse(url.strip())
35
+ except ValueError:
36
+ return None
37
+ host = u.hostname or ""
38
+ if u.scheme != "https" or u.username or u.password or u.port or u.path not in ("", "/") or u.query or u.fragment:
39
+ return None
40
+ if not host.endswith(suffix) or host == suffix.lstrip("."):
41
+ return None
42
+ return "https://" + host
43
+
44
+
45
+ def trusted_backend(url: str) -> str | None:
46
+ return _clean_https(url, ".vyntrica.com")
47
+
48
+
49
+ def trusted_supabase(url: str) -> str | None:
50
+ return _clean_https(url, ".supabase.co")
51
+
52
+
53
+ # --- armazenamento local (0600) ------------------------------------------------------------------
54
+
55
+ class Store:
56
+ def __init__(self, home: str | None = None):
57
+ self.dir = home or os.environ.get("AIHUB_HOME") or os.path.join(os.path.expanduser("~"), ".config", "aihub-code")
58
+
59
+ def _path(self, name: str) -> str:
60
+ return os.path.join(self.dir, name)
61
+
62
+ def read(self, name: str) -> dict | None:
63
+ try:
64
+ with open(self._path(name), encoding="utf-8") as f:
65
+ v = json.load(f)
66
+ return v if isinstance(v, dict) else None
67
+ except (OSError, ValueError):
68
+ return None
69
+
70
+ def write(self, name: str, data: dict) -> None:
71
+ os.makedirs(self.dir, mode=0o700, exist_ok=True)
72
+ try:
73
+ os.chmod(self.dir, 0o700)
74
+ except OSError:
75
+ pass
76
+ tmp = self._path(name + ".tmp")
77
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
78
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
79
+ json.dump(data, f)
80
+ os.replace(tmp, self._path(name))
81
+
82
+ def delete(self, name: str) -> None:
83
+ try:
84
+ os.remove(self._path(name))
85
+ except OSError:
86
+ pass
87
+
88
+
89
+ # --- HTTP ----------------------------------------------------------------------------------------
90
+
91
+ class Response:
92
+ def __init__(self, status: int, body: str, headers: dict[str, str] | None = None):
93
+ self.status, self.body, self.headers = status, body, headers or {}
94
+
95
+ def json(self) -> Any:
96
+ try:
97
+ return json.loads(self.body)
98
+ except ValueError:
99
+ return None
100
+
101
+
102
+ Transport = Callable[[str, str, dict[str, str], bytes | None, int], Response]
103
+
104
+
105
+ def urllib_transport(method: str, url: str, headers: dict[str, str], body: bytes | None, timeout: int) -> Response:
106
+ req = urllib.request.Request(url, data=body, method=method, headers={"User-Agent": "aihub-termux/" + VERSION, **headers})
107
+ try:
108
+ with urllib.request.urlopen(req, timeout=timeout) as r:
109
+ return Response(r.status, r.read().decode("utf-8", "replace"), dict(r.headers))
110
+ except urllib.error.HTTPError as e:
111
+ return Response(e.code, e.read().decode("utf-8", "replace"), dict(e.headers or {}))
112
+ except (urllib.error.URLError, TimeoutError, OSError):
113
+ return Response(0, "")
114
+
115
+
116
+ class StreamResp:
117
+ def __init__(self, status: int, headers: dict[str, str] | None = None, lines: Any = (), body: str = ""):
118
+ self.status, self.headers, self.lines, self.body = status, headers or {}, iter(lines), body
119
+
120
+
121
+ StreamTransport = Callable[[str, str, dict[str, str], bytes | None, int], StreamResp]
122
+
123
+
124
+ def urllib_stream(method: str, url: str, headers: dict[str, str], body: bytes | None, timeout: int) -> StreamResp:
125
+ req = urllib.request.Request(url, data=body, method=method, headers={"User-Agent": "aihub-termux/" + VERSION, **headers})
126
+ try:
127
+ r = urllib.request.urlopen(req, timeout=timeout)
128
+ except urllib.error.HTTPError as e:
129
+ return StreamResp(e.code, dict(e.headers or {}), (), e.read().decode("utf-8", "replace"))
130
+ except (urllib.error.URLError, TimeoutError, OSError):
131
+ return StreamResp(0)
132
+
133
+ def gen():
134
+ try:
135
+ for raw in r:
136
+ yield raw.decode("utf-8", "replace").rstrip("\r\n")
137
+ except (OSError, ValueError):
138
+ return
139
+ finally:
140
+ r.close()
141
+
142
+ return StreamResp(r.status, dict(r.headers), gen())
143
+
144
+
145
+ def parse_sse(lines: Any):
146
+ """Converte linhas SSE em (evento, dados JSON). Ignora blocos sem evento ou com JSON inválido."""
147
+ ev: str | None = None
148
+ data: list[str] = []
149
+ for ln in lines:
150
+ if ln == "":
151
+ if ev and data:
152
+ try:
153
+ obj = json.loads("\n".join(data))
154
+ except ValueError:
155
+ obj = None
156
+ if isinstance(obj, dict):
157
+ yield ev, obj
158
+ ev, data = None, []
159
+ elif ln.startswith("event:"):
160
+ ev = ln[6:].strip()
161
+ elif ln.startswith("data:"):
162
+ data.append(ln[5:].lstrip())
163
+
164
+
165
+ class CliError(Exception):
166
+ pass
167
+
168
+
169
+ # --- cliente -------------------------------------------------------------------------------------
170
+
171
+ class Client:
172
+ def __init__(self, store: Store, transport: Transport = urllib_transport, now: Callable[[], float] = time.time,
173
+ stream_transport: StreamTransport = urllib_stream):
174
+ self.store, self.transport, self.now, self.stream_transport = store, transport, now, stream_transport
175
+
176
+ # configuração
177
+ def config(self) -> dict:
178
+ c = self.store.read("config.json") or {}
179
+ c.setdefault("backend", DEFAULT_BACKEND)
180
+ return c
181
+
182
+ def backend(self) -> str:
183
+ b = trusted_backend(self.config()["backend"])
184
+ if not b:
185
+ raise CliError("Endereço do backend inválido. Rode: aihub setup --backend https://SEU-SUBDOMINIO.vyntrica.com")
186
+ return b
187
+
188
+ def setup(self, backend: str | None, supabase_url: str | None, supabase_key: str | None) -> dict:
189
+ cfg = self.config()
190
+ if backend:
191
+ b = trusted_backend(backend)
192
+ if not b:
193
+ raise CliError("Endereço do backend deve ser HTTPS de um subdomínio de vyntrica.com.")
194
+ cfg["backend"] = b
195
+ if not (supabase_url and supabase_key):
196
+ r = self.transport("GET", self.backend() + "/v1/client-config", {}, None, 30)
197
+ d = r.json() if r.status == 200 else None
198
+ if isinstance(d, dict):
199
+ supabase_url, supabase_key = d.get("supabase_url"), d.get("supabase_publishable_key")
200
+ if supabase_url and supabase_key:
201
+ s = trusted_supabase(supabase_url)
202
+ if not s or len(supabase_key) < 20:
203
+ raise CliError("Dados do Supabase inválidos (use https://<projeto>.supabase.co e a chave PUBLICÁVEL).")
204
+ cfg["supabase_url"], cfg["supabase_key"] = s, supabase_key
205
+ self.store.write("config.json", cfg)
206
+ return cfg
207
+
208
+ # sessão
209
+ def _save_session(self, d: dict) -> None:
210
+ user = d.get("user") if isinstance(d.get("user"), dict) else {}
211
+ self.store.write("session.json", {
212
+ "access_token": d["access_token"], "refresh_token": d.get("refresh_token", ""),
213
+ "expires_at": self.now() + int(d.get("expires_in", 3600)), "user_id": user.get("id", ""),
214
+ })
215
+
216
+ def _auth_call(self, grant: str, payload: dict) -> Response:
217
+ cfg = self.config()
218
+ if not (cfg.get("supabase_url") and cfg.get("supabase_key")):
219
+ raise CliError("Falta configurar o login. Rode: aihub setup")
220
+ url = f"{cfg['supabase_url']}/auth/v1/token?grant_type={grant}"
221
+ return self.transport("POST", url, {"apikey": cfg["supabase_key"], "Content-Type": "application/json"}, json.dumps(payload).encode(), 30)
222
+
223
+ def login(self, email: str, password: str) -> None:
224
+ r = self._auth_call("password", {"email": email, "password": password})
225
+ d = r.json()
226
+ if r.status == 0:
227
+ raise CliError("Sem conexão com o servidor de contas.")
228
+ if r.status != 200 or not isinstance(d, dict) or "access_token" not in d:
229
+ raise CliError("E-mail ou senha incorretos (ou e-mail ainda não confirmado).")
230
+ self._save_session(d)
231
+
232
+ def logout(self) -> None:
233
+ self.store.delete("session.json")
234
+
235
+ def _refresh(self, sess: dict) -> bool:
236
+ if not sess.get("refresh_token"):
237
+ return False
238
+ r = self._auth_call("refresh_token", {"refresh_token": sess["refresh_token"]})
239
+ d = r.json()
240
+ if r.status == 200 and isinstance(d, dict) and "access_token" in d:
241
+ self._save_session(d)
242
+ return True
243
+ return False
244
+
245
+ def token(self, force_refresh: bool = False) -> str:
246
+ sess = self.store.read("session.json")
247
+ if not sess or not sess.get("access_token"):
248
+ raise CliError("Você não está logado. Rode: aihub login")
249
+ if force_refresh or float(sess.get("expires_at", 0)) - self.now() < 60:
250
+ if not self._refresh(sess):
251
+ self.store.delete("session.json")
252
+ raise CliError("Sessão expirada. Rode: aihub login")
253
+ sess = self.store.read("session.json") or sess
254
+ return sess["access_token"]
255
+
256
+ def call(self, method: str, path: str, body: Any = None, headers: dict[str, str] | None = None, timeout: int = 120) -> Response:
257
+ url = self.backend() + path
258
+ data = json.dumps(body).encode() if body is not None else None
259
+ for attempt in (0, 1):
260
+ h = {"Authorization": "Bearer " + self.token(force_refresh=attempt == 1), "Content-Type": "application/json", **(headers or {})}
261
+ r = self.transport(method, url, h, data, timeout)
262
+ if r.status != 401 or attempt == 1:
263
+ return r
264
+ return r # pragma: no cover
265
+
266
+ def stream(self, path: str, body: Any) -> StreamResp:
267
+ url = self.backend() + path
268
+ data = json.dumps(body).encode()
269
+ for attempt in (0, 1):
270
+ h = {"Authorization": "Bearer " + self.token(force_refresh=attempt == 1), "Content-Type": "application/json", "Accept": "text/event-stream"}
271
+ r = self.stream_transport("POST", url, h, data, 90)
272
+ if r.status != 401 or attempt == 1:
273
+ return r
274
+ return r # pragma: no cover
275
+
276
+ def ok(self, method: str, path: str, body: Any = None, headers: dict[str, str] | None = None) -> Any:
277
+ r = self.call(method, path, body, headers)
278
+ if 200 <= r.status < 300:
279
+ return r.json() if r.body else {}
280
+ raise CliError(describe_error(r))
281
+
282
+
283
+ def describe_error(r: Response) -> str:
284
+ if r.status == 0:
285
+ return "Sem conexão com o backend."
286
+ if r.status == 401:
287
+ return "Sem permissão ou sessão expirada. Rode: aihub login"
288
+ if r.status == 429:
289
+ return f"Limite de requisições atingido. Tente de novo em {r.headers.get('Retry-After', 'alguns')} s."
290
+ if r.status == 503:
291
+ return "Serviço indisponível agora (nenhum modelo gratuito respondeu ou recurso não configurado)."
292
+ detail = ""
293
+ d = r.json()
294
+ if isinstance(d, dict) and isinstance(d.get("error"), str):
295
+ detail = ": " + d["error"][:120]
296
+ return f"Erro {r.status}{detail}"
297
+
298
+
299
+ # --- lógica pura (testável) ----------------------------------------------------------------------
300
+
301
+ def finished_tasks(prev: list[dict] | None, nxt: list[dict]) -> list[dict]:
302
+ """Tarefas que passaram de queued/running para completed/failed. A 1ª consulta nunca avisa."""
303
+ if prev is None:
304
+ return []
305
+ before = {t["task_id"]: t.get("status") for t in prev}
306
+ return [t for t in nxt if t.get("status") in ("completed", "failed") and before.get(t["task_id"]) in ("queued", "running")]
307
+
308
+
309
+ def resolve_id(items: list[dict], key: str, prefix: str) -> str:
310
+ hits = [i[key] for i in items if str(i[key]).startswith(prefix)]
311
+ if len(hits) == 1:
312
+ return hits[0]
313
+ raise CliError("Identificador não encontrado." if not hits else "Prefixo ambíguo; use mais caracteres.")
314
+
315
+
316
+ def short(s: str, n: int = 8) -> str:
317
+ return s[:n]
318
+
319
+
320
+ def frame_in(data: bytes) -> str:
321
+ return json.dumps({"t": "in", "d": base64.b64encode(data).decode()})
322
+
323
+
324
+ def frame_resize(cols: int, rows: int) -> str:
325
+ return json.dumps({"t": "resize", "cols": max(2, min(500, cols)), "rows": max(2, min(200, rows))})
326
+
327
+
328
+ def parse_term_frame(raw: str) -> tuple[str, Any] | None:
329
+ try:
330
+ m = json.loads(raw)
331
+ except ValueError:
332
+ return None
333
+ if not isinstance(m, dict):
334
+ return None
335
+ if m.get("t") == "out" and isinstance(m.get("d"), str):
336
+ try:
337
+ return "out", base64.b64decode(m["d"])
338
+ except ValueError:
339
+ return None
340
+ if m.get("t") == "status" and isinstance(m.get("state"), str):
341
+ return "status", m["state"]
342
+ if m.get("t") == "exit":
343
+ return "exit", m.get("code")
344
+ return None
345
+
346
+
347
+ STATUS_TEXT = {
348
+ "waiting_executor": "Acordando o executor (30–90 s)…",
349
+ "connected": "Conectado.",
350
+ "executor_lost": "O executor desconectou.",
351
+ }
352
+
353
+
354
+ # --- comandos ------------------------------------------------------------------------------------
355
+
356
+ def cmd_setup(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
357
+ cfg = c.setup(a.backend, a.supabase_url, a.supabase_key)
358
+ out("Backend: " + cfg["backend"])
359
+ if cfg.get("supabase_url"):
360
+ out("Login configurado.")
361
+ return 0
362
+ out("O backend não publicou os dados de login. Rode de novo com:")
363
+ out(" aihub setup --supabase-url https://<projeto>.supabase.co --supabase-key <chave PUBLICÁVEL>")
364
+ return 1
365
+
366
+
367
+ def cmd_login(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
368
+ if not c.config().get("supabase_url"):
369
+ c.setup(None, None, None)
370
+ email = a.email or input("E-mail: ").strip()
371
+ password = os.environ.get("AIHUB_PASSWORD") or getpass.getpass("Senha: ")
372
+ c.login(email, password)
373
+ out("Login feito.")
374
+ return 0
375
+
376
+
377
+ def cmd_logout(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
378
+ c.logout()
379
+ out("Sessão removida deste aparelho.")
380
+ return 0
381
+
382
+
383
+ def cmd_whoami(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
384
+ sess = c.store.read("session.json")
385
+ if not sess:
386
+ out("Não logado.")
387
+ return 1
388
+ left = int(float(sess.get("expires_at", 0)) - c.now())
389
+ out(f"Logado. Usuário: {sess.get('user_id') or 'desconhecido'}. Token vale mais {max(left, 0)} s (renova sozinho).")
390
+ return 0
391
+
392
+
393
+ def cmd_status(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
394
+ st = c.ok("GET", "/v1/executor/status")
395
+ cs = (st.get("codespaces") or [{}])[0] if isinstance(st, dict) else {}
396
+ out(f"Executor (Codespace): {cs.get('state', 'sem Codespace')}")
397
+ info = st.get("executor_info") or {}
398
+ if info:
399
+ out(f" revisão {info.get('rev', '?')}, terminal {info.get('terminal', '?')}")
400
+ tasks = c.ok("GET", "/v1/tasks?limit=100").get("tasks", [])
401
+ counts: dict[str, int] = {}
402
+ for t in tasks:
403
+ counts[t["status"]] = counts.get(t["status"], 0) + 1
404
+ out("Tarefas: " + (", ".join(f"{k}={v}" for k, v in sorted(counts.items())) or "nenhuma"))
405
+ return 0
406
+
407
+
408
+ def cmd_models(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
409
+ for m in c.ok("GET", "/v1/models").get("models", []):
410
+ out(m)
411
+ return 0
412
+
413
+
414
+ def _chat_once(c: Client, text: str, history: list[dict], model: str | None, project: str | None) -> dict:
415
+ body: dict = {"message": text, "history": history[-MAX_HISTORY:]}
416
+ if model:
417
+ body["model"] = model
418
+ if project:
419
+ body["project"] = project
420
+ return c.ok("POST", "/v1/chat", body)
421
+
422
+
423
+ def cmd_chat(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
424
+ history: list[dict] = []
425
+ conv: str | None = None
426
+
427
+ def turn(text: str) -> None:
428
+ nonlocal conv
429
+ r = _chat_once(c, text, history, a.model, a.project)
430
+ ans = r.get("answer", "")
431
+ out(ans)
432
+ ev = r.get("fallback_event")
433
+ if isinstance(ev, dict) and ev.get("summary_pt"):
434
+ out(f" ↻ {ev['summary_pt']}")
435
+ out(f" via {r.get('model', '?')}")
436
+ history.extend([{"role": "user", "content": text}, {"role": "assistant", "content": ans}])
437
+ if not a.no_save:
438
+ try: # só mensagens aceitas vão para o histórico
439
+ if conv is None:
440
+ created = c.ok("POST", "/v1/conversations", {"project": a.project} if a.project else {})
441
+ conv = created.get("id")
442
+ if conv:
443
+ c.ok("POST", f"/v1/conversations/{conv}/messages", {"role": "user", "content": text})
444
+ c.ok("POST", f"/v1/conversations/{conv}/messages", {"role": "assistant", "content": ans, "model": r.get("model")})
445
+ except CliError:
446
+ out(" (não foi possível salvar no histórico)")
447
+
448
+ if a.message:
449
+ turn(" ".join(a.message))
450
+ return 0
451
+ out("AI Hub Code — chat. Comandos: /sair, /limpar, /modelo <id|auto>")
452
+ while True:
453
+ try:
454
+ line = input("você> ").strip()
455
+ except (EOFError, KeyboardInterrupt):
456
+ out("")
457
+ return 0
458
+ if not line:
459
+ continue
460
+ if line == "/sair":
461
+ return 0
462
+ if line == "/limpar":
463
+ history.clear()
464
+ conv = None
465
+ out("Conversa nova.")
466
+ continue
467
+ if line.startswith("/modelo"):
468
+ arg = line[7:].strip()
469
+ a.model = None if arg in ("", "auto") else arg
470
+ out("Modelo: " + (a.model or "automático"))
471
+ continue
472
+ try:
473
+ turn(line)
474
+ except CliError as e:
475
+ out("erro: " + str(e))
476
+
477
+
478
+ def cmd_history(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
479
+ for cv in c.ok("GET", "/v1/conversations").get("conversations", []):
480
+ out(f"{cv['id']} {cv.get('title', '')[:60]} ({cv.get('messages', 0)} msgs)")
481
+ return 0
482
+
483
+
484
+ def _task_list(c: Client) -> list[dict]:
485
+ return c.ok("GET", "/v1/tasks?limit=100").get("tasks", [])
486
+
487
+
488
+ def cmd_tasks(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
489
+ act = a.action
490
+ if act == "list":
491
+ for t in _task_list(c):
492
+ out(f"{short(t['task_id'])} {t['status']:<10} {t.get('goal', '')[:70]}")
493
+ return 0
494
+ if act == "new":
495
+ goal = " ".join(a.args).strip()
496
+ if not goal:
497
+ raise CliError("Informe a meta: aihub tasks new <meta>")
498
+ body: dict = {"goal": goal}
499
+ if a.project:
500
+ body["project"] = a.project
501
+ t = c.ok("POST", "/v1/tasks", body)
502
+ out(f"Tarefa {short(t['task_id'])} criada ({t['status']}).")
503
+ for s in (t.get("plan") or {}).get("steps", []):
504
+ out(f" - [{s.get('role')}] {s.get('title')}")
505
+ if t.get("failure_reason"):
506
+ out(" falha no planejamento: " + t["failure_reason"])
507
+ return 0
508
+ if not a.args:
509
+ raise CliError("Informe o id da tarefa.")
510
+ tid = resolve_id(_task_list(c), "task_id", a.args[0])
511
+ if act in ("run", "cancel", "pause", "resume"):
512
+ verb = "execute" if act == "run" else act
513
+ t = c.ok("POST", f"/v1/tasks/{tid}/{verb}", {})
514
+ out(f"{short(tid)}: {t['status']}")
515
+ return 0
516
+ if act == "show":
517
+ t = c.ok("GET", f"/v1/tasks/{tid}")
518
+ out(f"{t['task_id']} {t['status']}\n{t.get('goal', '')}")
519
+ for s in (t.get("plan") or {}).get("steps", []):
520
+ out(f" - {s.get('id')} [{s.get('role')}] {s.get('title')}")
521
+ if t.get("failure_reason"):
522
+ out("motivo: " + t["failure_reason"])
523
+ return 0
524
+ if act == "watch":
525
+ return _watch_task(c, tid, out)
526
+ raise CliError("Ação desconhecida.")
527
+
528
+
529
+ def _watch_task(c: Client, tid: str, out: Callable[[str], None], sleep: Callable[[float], None] = time.sleep, max_polls: int = 10_000) -> int:
530
+ cursor = 0
531
+ run_id = c.ok("GET", f"/v1/tasks/{tid}")["run_id"]
532
+ for _ in range(max_polls):
533
+ ev = c.ok("GET", f"/v1/runs/{run_id}/events?after={cursor}&limit=100")
534
+ for e in ev.get("events", []):
535
+ text = (e.get("data") or {}).get("text") or (e.get("data") or {}).get("summary") or ""
536
+ out(f"{e.get('type')}: {text}".rstrip(": "))
537
+ cursor = max(cursor, int(e.get("sequence", cursor)))
538
+ t = c.ok("GET", f"/v1/tasks/{tid}")
539
+ if t["status"] in TERMINAL_STATES:
540
+ out(f"Tarefa {t['status']}.")
541
+ return 0 if t["status"] == "completed" else 1
542
+ sleep(3)
543
+ return 2
544
+
545
+
546
+ def notify(title: str, text: str, run: Callable[..., Any] = subprocess.run, which: Callable[[str], str | None] = shutil.which) -> bool:
547
+ """Notificação do Android via Termux:API, se instalado. Sem ele, não faz nada."""
548
+ exe = which("termux-notification")
549
+ if not exe:
550
+ return False
551
+ run([exe, "--title", title, "--content", text[:200]], check=False, timeout=15)
552
+ return True
553
+
554
+
555
+ def cmd_notify(c: Client, a: argparse.Namespace, out: Callable[[str], None], sleep: Callable[[float], None] = time.sleep, max_polls: int = 10**9) -> int:
556
+ out("Observando tarefas (Ctrl+C para sair)…")
557
+ prev: list[dict] | None = None
558
+ try:
559
+ for _ in range(max_polls):
560
+ cur = _task_list(c)
561
+ for t in finished_tasks(prev, cur):
562
+ title = "Tarefa concluída" if t["status"] == "completed" else "Tarefa falhou"
563
+ out(f"{title}: {t.get('goal', '')[:80]}")
564
+ notify(title, t.get("goal", ""))
565
+ prev = cur
566
+ sleep(8)
567
+ except KeyboardInterrupt:
568
+ pass
569
+ return 0
570
+
571
+
572
+ def cmd_memory(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
573
+ act = a.action
574
+ scope = f"project:{a.project}" if a.project else "global"
575
+ if act == "list":
576
+ q = "/v1/memory?" + urllib.parse.urlencode({"scope": scope, "limit": 100})
577
+ for m in c.ok("GET", q).get("items", []):
578
+ out(f"{m['id']} [{m['kind']}] {m['text'][:90]}")
579
+ return 0
580
+ if act == "add":
581
+ text = " ".join(a.args).strip()
582
+ if not text:
583
+ raise CliError("Informe o texto: aihub memory add <texto>")
584
+ m = c.ok("POST", "/v1/memory", {"kind": a.kind, "text": text, "scope": scope})
585
+ out(f"Salvo: {m.get('id', '?')}")
586
+ return 0
587
+ if act == "search":
588
+ for m in c.ok("GET", "/v1/memory/search?" + urllib.parse.urlencode({"q": " ".join(a.args)})).get("items", []):
589
+ out(f"{m['id']} [{m['kind']}] {m['text'][:90]}")
590
+ return 0
591
+ if act == "rm":
592
+ if not a.args:
593
+ raise CliError("Informe o id: aihub memory rm mem-N")
594
+ c.ok("DELETE", f"/v1/memory/{a.args[0]}")
595
+ out("Apagado.")
596
+ return 0
597
+ raise CliError("Ação desconhecida.")
598
+
599
+
600
+ def cmd_projects(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
601
+ act = a.action
602
+ if act == "list":
603
+ for p in c.ok("GET", "/v1/projects").get("projects", []):
604
+ out(f"{p['id']} {p['name']} {p['repo']}@{p['branch']}")
605
+ return 0
606
+ if act == "add":
607
+ if len(a.args) < 2:
608
+ raise CliError("Uso: aihub projects add <nome> <dono/repo> [branch]")
609
+ body = {"name": a.args[0], "repo": a.args[1]}
610
+ if len(a.args) > 2:
611
+ body["branch"] = a.args[2]
612
+ p = c.ok("POST", "/v1/projects", body)
613
+ out(f"Projeto {p['id']} criado.")
614
+ return 0
615
+ if act == "rm":
616
+ if not a.args:
617
+ raise CliError("Informe o id: aihub projects rm prj-N")
618
+ c.ok("DELETE", f"/v1/projects/{a.args[0]}")
619
+ out("Apagado.")
620
+ return 0
621
+ raise CliError("Ação desconhecida.")
622
+
623
+
624
+ def cmd_term(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int: # pragma: no cover - precisa de TTY e rede
625
+ try:
626
+ import websocket # type: ignore
627
+ import termios
628
+ import tty
629
+ import signal
630
+ except ImportError:
631
+ raise CliError("Falta o módulo: pip install websocket-client")
632
+ if not sys.stdin.isatty():
633
+ raise CliError("O terminal remoto precisa de um terminal interativo.")
634
+ info = c.ok("POST", "/v1/terminal/ticket", {})
635
+ host = urllib.parse.urlparse(c.backend()).hostname
636
+ ws = websocket.create_connection(f"wss://{host}/v1/terminal/app?ticket={info['ticket']}", timeout=300)
637
+ out("Conectando… (sair: Ctrl+])")
638
+ fd = sys.stdin.fileno()
639
+ old = termios.tcgetattr(fd)
640
+ stop = threading.Event()
641
+
642
+ def resize(*_: Any) -> None:
643
+ s = shutil.get_terminal_size()
644
+ try:
645
+ ws.send(frame_resize(s.columns, s.lines))
646
+ except Exception: # noqa: BLE001
647
+ pass
648
+
649
+ def reader() -> None:
650
+ last = ""
651
+ while not stop.is_set():
652
+ try:
653
+ raw = ws.recv()
654
+ except websocket.WebSocketTimeoutException:
655
+ continue
656
+ except Exception: # noqa: BLE001
657
+ break
658
+ p = parse_term_frame(raw) if isinstance(raw, str) else None
659
+ if not p:
660
+ continue
661
+ if p[0] == "out":
662
+ os.write(1, p[1])
663
+ elif p[0] == "status" and p[1] != last:
664
+ last = p[1]
665
+ os.write(2, (STATUS_TEXT.get(p[1], p[1]) + "\r\n").encode())
666
+ elif p[0] == "exit":
667
+ break
668
+ stop.set()
669
+
670
+ try:
671
+ tty.setraw(fd)
672
+ signal.signal(signal.SIGWINCH, resize)
673
+ resize()
674
+ t = threading.Thread(target=reader, daemon=True)
675
+ t.start()
676
+ while not stop.is_set():
677
+ import select
678
+ if select.select([fd], [], [], 0.2)[0]:
679
+ data = os.read(fd, 1024)
680
+ if not data or b"\x1d" in data:
681
+ break
682
+ ws.send(frame_in(data))
683
+ finally:
684
+ stop.set()
685
+ termios.tcsetattr(fd, termios.TCSADRAIN, old)
686
+ try:
687
+ ws.close()
688
+ except Exception: # noqa: BLE001
689
+ pass
690
+ out("\nTerminal encerrado.")
691
+ return 0
692
+
693
+
694
+ # --- interface estilo Claude Code (TUI) ----------------------------------------------------------
695
+
696
+ import re
697
+ import shlex
698
+ import textwrap
699
+
700
+ ACCENT = "\x1b[38;5;208m"
701
+ ACCENT_SOFT = "\x1b[38;5;215m"
702
+ DIM = "\x1b[38;5;244m"
703
+ BOLD = "\x1b[1m"
704
+ CYAN = "\x1b[38;5;110m"
705
+ GREEN = "\x1b[38;5;78m"
706
+ RED = "\x1b[38;5;203m"
707
+ RESET = "\x1b[0m"
708
+ STARS = "✻✽✶✳✢"
709
+ VERBS = ["Pensando", "Consultando modelos", "Organizando ideias", "Escrevendo", "Quase lá"]
710
+ ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
711
+
712
+ # Avatar: a logo do dono em blocos (cada caractere = 2 pixels verticais). Espaço = transparente.
713
+ AVATAR_PALETTE = ["fbfafb", "f2f2f4", "ecebee", "e4e4e8", "dedde3", "d9d4bf", "e7c157", "bdbdc7", "fd9b04", "cf9d51", "fa7c03", "fa6a02", "fa5a02", "f94a03", "fd3b03", "f43803"]
714
+ AVATAR_ALPHABET = " 123456789abcdefg"
715
+ AVATAR = {
716
+ "large": [
717
+ " 9999999999 ",
718
+ " 9999 999999999 ",
719
+ " 21 999999 ",
720
+ " 4113 999999 ",
721
+ " 11116 9999999",
722
+ " 211112 999999",
723
+ " 51111113 999999",
724
+ " 111111115 9999999",
725
+ " 3111111211 999999 ",
726
+ " 812222222213 9999999 ",
727
+ " a1222222222215 9999999 ",
728
+ " 41222222222221 9999999 ",
729
+ " 8133332223222313 99b9999 ",
730
+ " g a13333333423333315 9bbbb99 ",
731
+ " e 534333415 23333331 bbbbb99 ",
732
+ " dd 824444434 514344423 bbbbbb9b ",
733
+ " c 825544443 43444423 bbbbbbbb ",
734
+ " c 555555536 344335 bbbbbbb ",
735
+ " bc 645555555 5135 bbbcbbbb ",
736
+ " bc 45555555 5 bbbcccbb ",
737
+ " bc 555555658 cbcccbcc ",
738
+ " bc 558888858 ccccccbc ",
739
+ " bc 58888885 dccccccc ",
740
+ " 9cd 888888888 ddcddcccc 88 ",
741
+ " 9bd 888888888 ddddddcdd 88888 ",
742
+ " bde 88888888 eedddddddd 88888855 ",
743
+ " 9dde 8888888 eedddddddd 888888853 ",
744
+ " 9bddg 8888 eeeeeeeedee 8888885542 ",
745
+ " 9deef geeeeeeeeeee 8885555513 ",
746
+ "9beeffgg gggeeeeeeeeeee 655554441 ",
747
+ "9deeffffggggffffffffffeeeg b 8455444432 ",
748
+ "9defffgggfffffffffffefg bb 5454444414 ",
749
+ "beeffgggggggggffffffg bbb 344444451 ",
750
+ "bdfffggggggggfffgg cccccbb 5254455543 ",
751
+ " cdfffgggffffggg dddcccdc 5455555524 ",
752
+ " cdefffgggg eddd 355555553 ",
753
+ " ed 5254555554 ",
754
+ " e 5555555845 ",
755
+ " ",
756
+ " ",
757
+ ],
758
+ "medium": [
759
+ " 99999999 ",
760
+ " 3 99999 ",
761
+ " 11 99999",
762
+ " 1114 9999",
763
+ " 31111 9999",
764
+ " 5111112 99999",
765
+ " 21222213 9999 ",
766
+ " 612222221 99999 ",
767
+ " 81322222212 99999 ",
768
+ " 433323323314 b9b99 ",
769
+ " 824433 513332 bbbb9 ",
770
+ " c 8254425 434314 bbbbb ",
771
+ " c 555545 224 bbbbbb ",
772
+ " c 555555 54 bbcbb ",
773
+ " c 565658 cbcccc ",
774
+ " c 588858 dccccc ",
775
+ " bd 888888 ddcccc 88 ",
776
+ " bd 888888 dddddd 8888 ",
777
+ " 9ce 88888 eeddddd 8888844 ",
778
+ " bee 8 geeeedee 888552 ",
779
+ "9defg geeeeeeee 8555432 ",
780
+ "beffffgggfffffeee b 5444414 ",
781
+ "beffggffffffffg bb 244442 ",
782
+ "ceffgggffffgg ccccc 5345544 ",
783
+ " deffffggg dcd 5455535 ",
784
+ " d 5144452 ",
785
+ " g 55685 ",
786
+ " ",
787
+ ],
788
+ "small": [
789
+ " 9999 ",
790
+ " 1 999",
791
+ " 112 999",
792
+ " 41113 999",
793
+ " 812121 999 ",
794
+ " 3333322 b99 ",
795
+ " 5335 411 b9b ",
796
+ " 8455 2 cbbb ",
797
+ " bc 565 cbc ",
798
+ " c 8558 dcc 88 ",
799
+ " c 8888 eddd 8855 ",
800
+ "bdg gfeee 8553 ",
801
+ "cffggffeee 4433 ",
802
+ "defffgf cc 2524 ",
803
+ " f ed 5455 ",
804
+ " ",
805
+ ],
806
+ }
807
+
808
+
809
+ def vis_len(s: str) -> int:
810
+ return len(ANSI_RE.sub("", s))
811
+
812
+
813
+ def term_width() -> int:
814
+ return max(24, min(shutil.get_terminal_size((80, 24)).columns, 100))
815
+
816
+
817
+ def paint(s: str, *codes: str, color: bool = True) -> str:
818
+ return ("".join(codes) + s + RESET) if color else s
819
+
820
+
821
+ def truecolor() -> bool:
822
+ return os.environ.get("COLORTERM", "").lower() in ("truecolor", "24bit")
823
+
824
+
825
+ def _to256(r: int, g: int, b: int) -> int:
826
+ if abs(r - g) < 10 and abs(g - b) < 10:
827
+ gray = (r + g + b) // 3
828
+ if gray < 8:
829
+ return 16
830
+ if gray > 238:
831
+ return 231
832
+ return 232 + min(23, (gray - 8) // 10)
833
+ q = lambda v: 0 if v < 48 else 1 if v < 115 else min(5, (v - 35) // 40)
834
+ return 16 + 36 * q(r) + 6 * q(g) + q(b)
835
+
836
+
837
+ def _rgb(i: int) -> tuple[int, int, int]:
838
+ h = AVATAR_PALETTE[i - 1]
839
+ return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
840
+
841
+
842
+ def _fg(i: int, tc: bool) -> str:
843
+ r, g, b = _rgb(i)
844
+ return f"\x1b[38;2;{r};{g};{b}m" if tc else f"\x1b[38;5;{_to256(r, g, b)}m"
845
+
846
+
847
+ def _bg(i: int, tc: bool) -> str:
848
+ r, g, b = _rgb(i)
849
+ return f"\x1b[48;2;{r};{g};{b}m" if tc else f"\x1b[48;5;{_to256(r, g, b)}m"
850
+
851
+
852
+ def render_avatar(size: str = "large", color: bool = True, tc: bool | None = None) -> list[str]:
853
+ """Logo em arte de blocos (▀ ▄ █). Sem cor, vira silhueta."""
854
+ tc = truecolor() if tc is None else tc
855
+ rows = AVATAR[size]
856
+ idx = AVATAR_ALPHABET.index
857
+ out = []
858
+ for y in range(0, len(rows), 2):
859
+ top = rows[y]
860
+ bot = rows[y + 1] if y + 1 < len(rows) else " " * len(top)
861
+ line = ""
862
+ for t, b in zip(top, bot):
863
+ ti, bi = idx(t), idx(b)
864
+ if not ti and not bi:
865
+ line += " "
866
+ elif not color:
867
+ line += "█" if ti and bi else "▀" if ti else "▄"
868
+ elif ti and bi:
869
+ line += _fg(ti, tc) + _bg(bi, tc) + "▀" + RESET
870
+ elif ti:
871
+ line += _fg(ti, tc) + "▀" + RESET
872
+ else:
873
+ line += _fg(bi, tc) + "▄" + RESET
874
+ out.append(line)
875
+ return out
876
+
877
+
878
+ def _fit(s: str, n: int) -> str:
879
+ return s if vis_len(s) <= n else ANSI_RE.sub("", s)[: max(0, n - 1)] + "…"
880
+
881
+
882
+ def render_banner(width: int, backend: str, user: str, model: str, color: bool = True, tc: bool | None = None) -> list[str]:
883
+ """Caixa de boas-vindas: avatar ao lado das informações (ou empilhado em telas estreitas)."""
884
+ box_w = min(width, 100)
885
+ inner = box_w - 4
886
+ size = next((s for s in ("large", "medium") if inner >= len(AVATAR[s][0]) + 2 + 28), "small")
887
+ avatar = render_avatar(size, color, tc)
888
+ aw = len(AVATAR[size][0])
889
+ host = backend.replace("https://", "")
890
+ info = [
891
+ paint("AI Hub Code", BOLD, ACCENT, color=color) + paint(" v" + VERSION, DIM, color=color),
892
+ paint("Bem-vindo de volta!", BOLD, color=color),
893
+ "",
894
+ paint("conta ", DIM, color=color) + user,
895
+ paint("modelo ", DIM, color=color) + model,
896
+ paint("backend ", DIM, color=color) + host,
897
+ paint("pasta ", DIM, color=color) + os.path.basename(os.getcwd() or "/"),
898
+ "",
899
+ paint("/help comandos · /exit sair", DIM, color=color),
900
+ ]
901
+ rows: list[str] = []
902
+ if inner >= aw + 2 + 24:
903
+ h = max(len(avatar), len(info))
904
+ a_off, i_off = (h - len(avatar)) // 2, (h - len(info)) // 2
905
+ for y in range(h):
906
+ a = avatar[y - a_off] if 0 <= y - a_off < len(avatar) else ""
907
+ i = info[y - i_off] if 0 <= y - i_off < len(info) else ""
908
+ rows.append(a + " " * (aw - vis_len(a) + 2) + _fit(i, inner - aw - 2))
909
+ else:
910
+ if inner >= aw: # telas minúsculas: só texto
911
+ for a in avatar:
912
+ rows.append(" " * ((inner - aw) // 2) + a)
913
+ rows.append("")
914
+ rows.extend(_fit(i, inner) for i in info)
915
+ title = " AI Hub Code "
916
+ out = [paint("╭─", ACCENT, color=color) + paint(title, BOLD, ACCENT, color=color) + paint("─" * max(0, box_w - 3 - len(title)) + "╮", ACCENT, color=color)]
917
+ for r in rows:
918
+ out.append(paint("│", ACCENT, color=color) + " " + r + " " * max(0, inner - vis_len(r)) + " " + paint("│", ACCENT, color=color))
919
+ out.append(paint("╰" + "─" * (box_w - 2) + "╯", ACCENT, color=color))
920
+ return out
921
+
922
+
923
+ class StreamPrinter:
924
+ """Imprime a resposta aos poucos: quebra de linha por palavra, **negrito**, `código` e blocos ```."""
925
+
926
+ def __init__(self, write: Callable[[str], None], width: int, color: bool = True, indent: int = 2):
927
+ self.w, self.width, self.color, self.indent = write, max(20, width), color, indent
928
+ self.col = 0
929
+ self.word = ""
930
+ self.wlen = 0
931
+ self.space = False
932
+ self.bold = self.code = self.star = False
933
+ self.bol = True
934
+ self.head = ""
935
+ self.mode = "normal" # normal | fence_open | fence
936
+ self.fline = ""
937
+ self.started = False
938
+
939
+ def _c(self, s: str) -> str:
940
+ return s if self.color else ""
941
+
942
+ def start(self) -> None:
943
+ self.w(self._c(ACCENT) + "●" + self._c(RESET) + " ")
944
+ self.col, self.bol, self.started = self.indent, False, True
945
+
946
+ def feed(self, text: str) -> None:
947
+ if not self.started:
948
+ self.start()
949
+ for ch in text:
950
+ self._ch(ch)
951
+
952
+ def _newline(self) -> None:
953
+ self.w("\n")
954
+ self.col, self.bol, self.space = 0, True, False
955
+
956
+ def _flush_word(self) -> None:
957
+ if not self.wlen:
958
+ return
959
+ need = (1 if self.space and self.col > self.indent else 0) + self.wlen
960
+ if self.col > self.indent and self.col + need > self.width:
961
+ self.w("\n" + " " * self.indent)
962
+ self.col, self.space = self.indent, False
963
+ elif self.col == 0:
964
+ self.w(" " * self.indent)
965
+ self.col = self.indent
966
+ if self.space and self.col > self.indent:
967
+ self.w(" ")
968
+ self.col += 1
969
+ self.w(self.word)
970
+ self.col += self.wlen
971
+ self.word, self.wlen, self.space = "", 0, False
972
+
973
+ def _style(self) -> None:
974
+ self.word += self._c(RESET + (BOLD if self.bold else "") + (CYAN if self.code else ""))
975
+
976
+ def _ch(self, ch: str) -> None:
977
+ if self.mode == "fence_open": # engole o resto da linha de abertura (```python)
978
+ if ch == "\n":
979
+ self.mode, self.fline = "fence", ""
980
+ return
981
+ if self.mode == "fence":
982
+ if ch != "\n":
983
+ self.fline += ch
984
+ return
985
+ if self.fline.strip().startswith("```"):
986
+ self.mode, self.bol = "normal", True
987
+ else:
988
+ self.w(" " + self._c(DIM) + self.fline + self._c(RESET) + "\n")
989
+ self.fline = ""
990
+ return
991
+ if self.bol:
992
+ self.head += ch
993
+ if "```".startswith(self.head):
994
+ if self.head == "```":
995
+ self.head, self.mode = "", "fence_open"
996
+ return
997
+ pending, self.head = self.head, ""
998
+ self.bol = False
999
+ for c in pending:
1000
+ self._normal(c)
1001
+ return
1002
+ self._normal(ch)
1003
+
1004
+ def _normal(self, ch: str) -> None:
1005
+ if self.star and ch != "*":
1006
+ self.word += "*"
1007
+ self.wlen += 1
1008
+ self.star = False
1009
+ if ch == "\n":
1010
+ self._flush_word()
1011
+ self._newline()
1012
+ elif ch == " ":
1013
+ self._flush_word()
1014
+ self.space = True
1015
+ elif ch == "`":
1016
+ self.code = not self.code
1017
+ self._style()
1018
+ elif ch == "*":
1019
+ if self.star:
1020
+ self.bold, self.star = not self.bold, False
1021
+ self._style()
1022
+ else:
1023
+ self.star = True
1024
+ else:
1025
+ self.word += ch
1026
+ self.wlen += 1
1027
+
1028
+ def finish(self) -> None:
1029
+ if self.mode == "fence" and self.fline:
1030
+ self.w(" " + self._c(DIM) + self.fline + self._c(RESET) + "\n")
1031
+ elif self.bol and self.head:
1032
+ for c in self.head:
1033
+ self._normal(c)
1034
+ self._flush_word()
1035
+ self.w(self._c(RESET))
1036
+ if self.col:
1037
+ self.w("\n")
1038
+
1039
+
1040
+ def render_answer(text: str, width: int, color: bool = True) -> list[str]:
1041
+ buf: list[str] = []
1042
+ p = StreamPrinter(buf.append, width, color)
1043
+ p.feed(text.strip("\n"))
1044
+ p.finish()
1045
+ return "".join(buf).rstrip("\n").split("\n")
1046
+
1047
+
1048
+ def render_detail(text: str, color: bool = True, width: int | None = None) -> str:
1049
+ """Linha de detalhe ` ⎿ texto`; com `width`, quebra por palavras mantendo o recuo."""
1050
+ parts = [text] if not width else (textwrap.wrap(text, max(10, width - 5)) or [""])
1051
+ rows = [(" " + paint("⎿", DIM, color=color) + " " if i == 0 else " ") + paint(t, DIM, color=color) for i, t in enumerate(parts)]
1052
+ return "\n".join(rows)
1053
+
1054
+
1055
+ STATUS_GLYPH = {"running": ("◐", ACCENT), "completed": ("✓", GREEN), "failed": ("✗", RED), "queued": ("○", DIM),
1056
+ "planned": ("○", DIM), "paused": ("◌", DIM), "cancelled": ("⊘", DIM)}
1057
+ TASK_LINE = re.compile(r"^([0-9a-f]{8})\s+(\w+)\s+(.*)$")
1058
+
1059
+
1060
+ def style_result_line(line: str, color: bool = True) -> str:
1061
+ m = TASK_LINE.match(line)
1062
+ if m and m.group(2) in STATUS_GLYPH:
1063
+ g, col = STATUS_GLYPH[m.group(2)]
1064
+ return f"{paint(g, col, color=color)} {paint(m.group(1), DIM, color=color)} {m.group(3)}"
1065
+ return line
1066
+
1067
+
1068
+ def render_tool(title: str, lines: list[str], color: bool = True) -> list[str]:
1069
+ """Bloco no formato de ferramenta do Claude Code: `● título` + resultado com ⎿."""
1070
+ out = [paint("●", ACCENT, color=color) + " " + paint(title, BOLD, color=color)]
1071
+ for i, ln in enumerate(lines or ["(vazio)"]):
1072
+ out.append(" " + (paint("⎿", DIM, color=color) if i == 0 else " ") + " " + style_result_line(ln, color))
1073
+ return out
1074
+
1075
+
1076
+ def render_help(color: bool = True) -> list[str]:
1077
+ rows = [
1078
+ ("/help", "esta ajuda"), ("/model <id|auto>", "troca o modelo"), ("/clear", "nova conversa"),
1079
+ ("/tasks [list|new|run|watch…]", "tarefas dos agentes"), ("/memory [list|add|search|rm]", "memória"),
1080
+ ("/projects [list|add|rm]", "projetos"), ("/status", "executor e tarefas"), ("/models", "modelos gratuitos"),
1081
+ ("/avatar", "mostra o avatar"), ("/term", "terminal remoto"), ("/exit", "sair"),
1082
+ ]
1083
+ return [paint(" Comandos", BOLD, color=color)] + [f" {paint(a, ACCENT, color=color)}{' ' * max(1, 32 - len(a))}{paint(b, DIM, color=color)}" for a, b in rows]
1084
+
1085
+
1086
+ class Spinner:
1087
+ """✻ Pensando… (3s) com brilho que percorre o texto. Só anima em terminal interativo."""
1088
+
1089
+ def __init__(self, enabled: bool, color: bool = True):
1090
+ self.enabled, self.color = enabled, color
1091
+ self._stop, self._t, self._t0 = threading.Event(), None, 0.0
1092
+
1093
+ def start(self) -> "Spinner":
1094
+ if self.enabled and not self._t:
1095
+ self._stop.clear()
1096
+ self._t0 = time.time()
1097
+ self._t = threading.Thread(target=self._run, daemon=True)
1098
+ self._t.start()
1099
+ return self
1100
+
1101
+ @staticmethod
1102
+ def frame(i: int, elapsed: float, color: bool = True) -> str:
1103
+ label = VERBS[int(elapsed // 3) % len(VERBS)] + "…"
1104
+ hot = (i // 2) % (len(label) + 6)
1105
+ text = "".join(paint(ch, BOLD, color=color) if abs(j - hot) <= 1 else paint(ch, ACCENT_SOFT, color=color) for j, ch in enumerate(label))
1106
+ return f"{paint(STARS[i % len(STARS)], ACCENT, color=color)} {text} {paint(f'({int(elapsed)}s · Ctrl+C interrompe)', DIM, color=color)}"
1107
+
1108
+ def _run(self) -> None:
1109
+ i = 0
1110
+ while not self._stop.wait(0.09):
1111
+ sys.stdout.write("\r" + self.frame(i, time.time() - self._t0, self.color) + "\x1b[K")
1112
+ sys.stdout.flush()
1113
+ i += 1
1114
+
1115
+ def stop(self) -> None:
1116
+ if self._t:
1117
+ self._stop.set()
1118
+ self._t.join()
1119
+ self._t = None
1120
+ sys.stdout.write("\r\x1b[K")
1121
+ sys.stdout.flush()
1122
+
1123
+
1124
+ def read_boxed(prompt: str, left: str, right: str, width: int, tty: bool, color: bool = True) -> str:
1125
+ """Campo de entrada entre duas réguas, com rodapé (dica à esquerda, modelo à direita)."""
1126
+ if not tty:
1127
+ return input(prompt)
1128
+ rule = paint("─" * width, DIM, color=color)
1129
+ gap = max(1, width - 4 - len(left) - len(right))
1130
+ foot = " " + paint(left, DIM, color=color) + " " * gap + paint(right, DIM, color=color)
1131
+ sys.stdout.write(f"{rule}\n\n{rule}\n{foot}\x1b[2A\r")
1132
+ sys.stdout.flush()
1133
+ try:
1134
+ line = input(paint(prompt, ACCENT, color=color))
1135
+ finally:
1136
+ sys.stdout.write("\x1b[1B\x1b[2K\r")
1137
+ sys.stdout.flush()
1138
+ return line
1139
+
1140
+
1141
+ def _stream_turn(c: Client, text: str, history: list[dict], model: str | None, project: str | None,
1142
+ printer: "StreamPrinter", spinner: Spinner) -> dict:
1143
+ """Uma rodada de chat em streaming. Devolve {answer, model, fallback_event, error}."""
1144
+ body: dict = {"message": text, "history": history[-MAX_HISTORY:]}
1145
+ if model:
1146
+ body["model"] = model
1147
+ if project:
1148
+ body["project"] = project
1149
+ resp = c.stream("/v1/chat/stream", body)
1150
+ if resp.status == 404: # Worker antigo sem a rota: usa a resposta inteira
1151
+ r = _chat_once(c, text, history, model, project)
1152
+ spinner.stop()
1153
+ printer.feed(r.get("answer", ""))
1154
+ return {"answer": r.get("answer", ""), "model": r.get("model"), "fallback_event": r.get("fallback_event"), "error": None}
1155
+ if resp.status != 200:
1156
+ raise CliError(describe_error(Response(resp.status, resp.body, resp.headers)))
1157
+ res: dict = {"answer": "", "model": None, "fallback_event": None, "error": None}
1158
+ for name, d in parse_sse(resp.lines):
1159
+ if name == "meta":
1160
+ res["model"], res["fallback_event"] = d.get("model"), d.get("fallback_event")
1161
+ elif name == "delta" and isinstance(d.get("t"), str):
1162
+ spinner.stop()
1163
+ printer.feed(d["t"])
1164
+ res["answer"] += d["t"]
1165
+ elif name == "error":
1166
+ res["error"] = d.get("error", "erro")
1167
+ return res
1168
+
1169
+
1170
+ def cmd_tui(c: Client, a: argparse.Namespace, out: Callable[[str], None] = print, read: Callable[[str], str] | None = None,
1171
+ animate: bool | None = None) -> int:
1172
+ tty = sys.stdout.isatty() and sys.stdin.isatty() and read is None
1173
+ color = tty or os.environ.get("AIHUB_COLOR") == "1"
1174
+ animate = tty if animate is None else animate
1175
+ width = term_width()
1176
+ sess = c.store.read("session.json")
1177
+ if not sess:
1178
+ out("Você ainda não entrou. Rode: aihub setup && aihub login")
1179
+ return 1
1180
+ model: str | None = None
1181
+ history: list[dict] = []
1182
+ conv: str | None = None
1183
+ user = (sess.get("user_id") or "?")[:8]
1184
+ for ln in render_banner(width, c.config()["backend"], user, "automático", color):
1185
+ out(ln)
1186
+ if animate:
1187
+ time.sleep(0.035)
1188
+ out("")
1189
+ reader = read or (lambda prompt: read_boxed(prompt, "? /help · /exit sai", "modelo: " + (model or "automático"), width, tty, color))
1190
+ while True:
1191
+ try:
1192
+ line = reader("> ").strip()
1193
+ except (EOFError, KeyboardInterrupt):
1194
+ out(paint("✻ Até logo!", ACCENT, color=color))
1195
+ return 0
1196
+ if not line:
1197
+ continue
1198
+ if line.startswith("/"):
1199
+ name, _, rest = line[1:].partition(" ")
1200
+ if name in ("exit", "sair", "quit"):
1201
+ out(paint("✻ Até logo!", ACCENT, color=color))
1202
+ return 0
1203
+ if name == "help":
1204
+ for ln in render_help(color):
1205
+ out(ln)
1206
+ elif name == "avatar":
1207
+ for ln in render_avatar("large", color):
1208
+ out(" " + ln)
1209
+ elif name == "clear":
1210
+ history.clear()
1211
+ conv = None
1212
+ out(render_detail("conversa nova", color))
1213
+ elif name == "model":
1214
+ model = None if rest.strip() in ("", "auto") else rest.strip()
1215
+ out(render_detail("modelo: " + (model or "automático"), color))
1216
+ else:
1217
+ lines: list[str] = []
1218
+ try:
1219
+ sub = build_parser().parse_args([name] + shlex.split(rest))
1220
+ if sub.cmd in ("chat", "tui", "notify", "setup", "login"):
1221
+ raise CliError("comando não disponível dentro do chat")
1222
+ COMMANDS[sub.cmd](c, sub, lines.append)
1223
+ except SystemExit:
1224
+ lines = ["comando inválido (veja /help)"]
1225
+ except CliError as e:
1226
+ lines = ["erro: " + str(e)]
1227
+ for ln in render_tool("/" + name + (" " + rest if rest else ""), lines, color):
1228
+ out(ln)
1229
+ out("")
1230
+ continue
1231
+ sp = Spinner(tty, color)
1232
+ buf: list[str] = []
1233
+ printer = StreamPrinter(lambda s: (sys.stdout.write(s), sys.stdout.flush()) if tty else buf.append(s), width, color)
1234
+ t0 = time.time()
1235
+ r: dict | None = None
1236
+ try:
1237
+ sp.start()
1238
+ r = _stream_turn(c, line, history, model, None, printer, sp)
1239
+ except KeyboardInterrupt:
1240
+ sp.stop()
1241
+ printer.finish()
1242
+ out(render_detail("interrompido", color))
1243
+ out("")
1244
+ continue
1245
+ except CliError as e:
1246
+ sp.stop()
1247
+ out(paint(" ✗ ", RED, color=color) + str(e))
1248
+ out("")
1249
+ continue
1250
+ finally:
1251
+ sp.stop()
1252
+ printer.finish()
1253
+ if not tty:
1254
+ for ln in "".join(buf).rstrip("\n").split("\n"):
1255
+ out(ln)
1256
+ ev = r.get("fallback_event")
1257
+ if isinstance(ev, dict) and ev.get("summary_pt"):
1258
+ out(render_detail("↻ " + ev["summary_pt"], color, width))
1259
+ if r.get("error"):
1260
+ out(render_detail("a resposta foi interrompida no meio", color))
1261
+ out(render_detail(f"via {r.get('model') or '?'} · {time.time() - t0:.1f}s", color, width))
1262
+ out("")
1263
+ if not r.get("answer"):
1264
+ continue
1265
+ history.extend([{"role": "user", "content": line}, {"role": "assistant", "content": r["answer"]}])
1266
+ history[:] = history[-MAX_HISTORY:]
1267
+ if r.get("error"):
1268
+ continue
1269
+ try:
1270
+ if conv is None:
1271
+ conv = c.ok("POST", "/v1/conversations", {}).get("id")
1272
+ if conv:
1273
+ c.ok("POST", f"/v1/conversations/{conv}/messages", {"role": "user", "content": line})
1274
+ c.ok("POST", f"/v1/conversations/{conv}/messages", {"role": "assistant", "content": r["answer"], "model": r.get("model")})
1275
+ except CliError:
1276
+ pass
1277
+
1278
+
1279
+ # --- entrada -------------------------------------------------------------------------------------
1280
+
1281
+ def build_parser() -> argparse.ArgumentParser:
1282
+ p = argparse.ArgumentParser(prog="aihub", description="AI Hub Code para Termux")
1283
+ p.add_argument("--version", action="version", version="aihub " + VERSION)
1284
+ sub = p.add_subparsers(dest="cmd")
1285
+ s = sub.add_parser("setup", help="configura o backend e o login")
1286
+ s.add_argument("--backend")
1287
+ s.add_argument("--supabase-url")
1288
+ s.add_argument("--supabase-key", help="chave PUBLICÁVEL (nunca a secreta)")
1289
+ s = sub.add_parser("login", help="entra com e-mail e senha")
1290
+ s.add_argument("--email")
1291
+ sub.add_parser("logout")
1292
+ sub.add_parser("whoami")
1293
+ sub.add_parser("status", help="executor e tarefas")
1294
+ sub.add_parser("models")
1295
+ s = sub.add_parser("chat", help="conversa com os modelos gratuitos")
1296
+ s.add_argument("message", nargs="*")
1297
+ s.add_argument("--model")
1298
+ s.add_argument("--project")
1299
+ s.add_argument("--no-save", action="store_true")
1300
+ sub.add_parser("history", help="conversas salvas")
1301
+ s = sub.add_parser("tasks", help="tarefas dos agentes")
1302
+ s.add_argument("action", choices=["list", "new", "show", "run", "cancel", "pause", "resume", "watch"])
1303
+ s.add_argument("args", nargs="*")
1304
+ s.add_argument("--project")
1305
+ sub.add_parser("notify", help="avisa (Termux:API) quando uma tarefa terminar")
1306
+ s = sub.add_parser("memory", help="memória persistente")
1307
+ s.add_argument("action", choices=["list", "add", "search", "rm"])
1308
+ s.add_argument("args", nargs="*")
1309
+ s.add_argument("--project")
1310
+ s.add_argument("--kind", default="fact", choices=["fact", "preference", "project", "decision"])
1311
+ s = sub.add_parser("projects", help="projetos")
1312
+ s.add_argument("action", choices=["list", "add", "rm"])
1313
+ s.add_argument("args", nargs="*")
1314
+ sub.add_parser("term", help="terminal remoto no Codespace")
1315
+ return p
1316
+
1317
+
1318
+ COMMANDS = {
1319
+ "setup": cmd_setup, "login": cmd_login, "logout": cmd_logout, "whoami": cmd_whoami, "status": cmd_status,
1320
+ "models": cmd_models, "chat": cmd_chat, "history": cmd_history, "tasks": cmd_tasks, "notify": cmd_notify,
1321
+ "memory": cmd_memory, "projects": cmd_projects, "term": cmd_term, "tui": cmd_tui,
1322
+ }
1323
+
1324
+
1325
+ def main(argv: list[str] | None = None, client: Client | None = None, out: Callable[[str], None] = print) -> int:
1326
+ a = build_parser().parse_args(argv)
1327
+ c = client or Client(Store())
1328
+ try:
1329
+ return COMMANDS[a.cmd or "tui"](c, a, out)
1330
+ except CliError as e:
1331
+ out("erro: " + str(e))
1332
+ return 1
1333
+ except KeyboardInterrupt:
1334
+ return 130
1335
+
1336
+
1337
+ def cli() -> None:
1338
+ sys.exit(main())
1339
+
1340
+
1341
+ if __name__ == "__main__":
1342
+ cli()