aihub-code 0.2.1__tar.gz → 0.2.2__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aihub-code
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: AI Hub Code para Termux: cliente de terminal (chat, tarefas, memória, projetos) do backend AI Hub
5
5
  License: Proprietary
6
6
  Requires-Python: >=3.9
@@ -18,7 +18,7 @@ Pacote `aihub-code` (traz tudo, inclusive o terminal remoto):
18
18
  pkg install -y python
19
19
  pip install aihub-code
20
20
  # ou, sem PyPI, a partir de um arquivo .whl que você baixou/copiou:
21
- pip install aihub_code-0.2.1-py3-none-any.whl
21
+ pip install aihub_code-0.2.2-py3-none-any.whl
22
22
  aihub setup && aihub login
23
23
  ```
24
24
  Gerar o `.whl` (no repositório): `cd termux && python3 -m pip install build && python3 -m build --wheel`.
@@ -43,6 +43,7 @@ Se `aihub setup` disser que o backend não publicou os dados de login, use:
43
43
  | `aihub notify` | avisa pelo Termux:API quando uma tarefa termina |
44
44
  | `aihub memory list/add/search/rm` | memória persistente (`--kind`, `--project`) |
45
45
  | `aihub projects list/add/rm` | projetos |
46
+ | `/avatar think` · `/avatar run` | (dentro do `aihub`) mostra a animação do avatar por 5 s |
46
47
  | `aihub term` | terminal remoto no Codespace (sair: Ctrl+]) |
47
48
  | `aihub status`, `models`, `history`, `whoami`, `logout` | utilitários |
48
49
 
@@ -51,3 +52,9 @@ Se `aihub setup` disser que o backend não publicou os dados de login, use:
51
52
  - Tokens em `~/.config/aihub-code/session.json` (modo 0600); a senha nunca é gravada.
52
53
  - Só modelos gratuitos aprovados no backend; o cliente não escolhe provedores pagos.
53
54
  - Testes: `python3 -m unittest tests.test_termux_client -v`
55
+
56
+ ## Avatar animado
57
+ Enquanto a IA trabalha, um mini avatar aparece embaixo do texto e o **anel gira**:
58
+ - **laranja** quando ela está respondendo ou pesquisando;
59
+ - **arco-íris** quando ela está executando comandos (`/tasks`, `/status`, …).
60
+ Precisa de terminal com pelo menos 14 linhas; em terminal menor, aparece só o spinner de uma linha.
@@ -8,7 +8,7 @@ Pacote `aihub-code` (traz tudo, inclusive o terminal remoto):
8
8
  pkg install -y python
9
9
  pip install aihub-code
10
10
  # ou, sem PyPI, a partir de um arquivo .whl que você baixou/copiou:
11
- pip install aihub_code-0.2.1-py3-none-any.whl
11
+ pip install aihub_code-0.2.2-py3-none-any.whl
12
12
  aihub setup && aihub login
13
13
  ```
14
14
  Gerar o `.whl` (no repositório): `cd termux && python3 -m pip install build && python3 -m build --wheel`.
@@ -33,6 +33,7 @@ Se `aihub setup` disser que o backend não publicou os dados de login, use:
33
33
  | `aihub notify` | avisa pelo Termux:API quando uma tarefa termina |
34
34
  | `aihub memory list/add/search/rm` | memória persistente (`--kind`, `--project`) |
35
35
  | `aihub projects list/add/rm` | projetos |
36
+ | `/avatar think` · `/avatar run` | (dentro do `aihub`) mostra a animação do avatar por 5 s |
36
37
  | `aihub term` | terminal remoto no Codespace (sair: Ctrl+]) |
37
38
  | `aihub status`, `models`, `history`, `whoami`, `logout` | utilitários |
38
39
 
@@ -41,3 +42,9 @@ Se `aihub setup` disser que o backend não publicou os dados de login, use:
41
42
  - Tokens em `~/.config/aihub-code/session.json` (modo 0600); a senha nunca é gravada.
42
43
  - Só modelos gratuitos aprovados no backend; o cliente não escolhe provedores pagos.
43
44
  - Testes: `python3 -m unittest tests.test_termux_client -v`
45
+
46
+ ## Avatar animado
47
+ Enquanto a IA trabalha, um mini avatar aparece embaixo do texto e o **anel gira**:
48
+ - **laranja** quando ela está respondendo ou pesquisando;
49
+ - **arco-íris** quando ela está executando comandos (`/tasks`, `/status`, …).
50
+ Precisa de terminal com pelo menos 14 linhas; em terminal menor, aparece só o spinner de uma linha.
@@ -21,7 +21,7 @@ import urllib.parse
21
21
  import urllib.request
22
22
  from typing import Any, Callable
23
23
 
24
- VERSION = "0.2.1"
24
+ VERSION = "0.2.2"
25
25
  DEFAULT_BACKEND = "https://aihub-api.vyntrica.com"
26
26
  MAX_HISTORY = 8
27
27
  TERMINAL_STATES = {"completed", "failed", "cancelled"}
@@ -182,7 +182,7 @@ class Client:
182
182
  def backend(self) -> str:
183
183
  b = trusted_backend(self.config()["backend"])
184
184
  if not b:
185
- raise CliError("Endereço do backend inválido. Rode: aihub setup --backend https://SEU-SUBDOMINIO.vyntrica.com")
185
+ raise CliError("Configuração do servidor inválida. Rode: aihub setup")
186
186
  return b
187
187
 
188
188
  def setup(self, backend: str | None, supabase_url: str | None, supabase_key: str | None) -> dict:
@@ -190,7 +190,7 @@ class Client:
190
190
  if backend:
191
191
  b = trusted_backend(backend)
192
192
  if not b:
193
- raise CliError("Endereço do backend deve ser HTTPS de um subdomínio de vyntrica.com.")
193
+ raise CliError("Endereço do servidor não aceito (precisa ser HTTPS de um domínio permitido).")
194
194
  cfg["backend"] = b
195
195
  if not (supabase_url and supabase_key):
196
196
  r = self.transport("GET", self.backend() + "/v1/client-config", {}, None, 30)
@@ -200,7 +200,7 @@ class Client:
200
200
  if supabase_url and supabase_key:
201
201
  s = trusted_supabase(supabase_url)
202
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).")
203
+ raise CliError("Dados de login inválidos (use o endereço do projeto e a chave PUBLICÁVEL).")
204
204
  cfg["supabase_url"], cfg["supabase_key"] = s, supabase_key
205
205
  self.store.write("config.json", cfg)
206
206
  return cfg
@@ -226,7 +226,12 @@ class Client:
226
226
  if r.status == 0:
227
227
  raise CliError("Sem conexão com o servidor de contas.")
228
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).")
229
+ code = d.get("error_code") if isinstance(d, dict) else None
230
+ if code == "email_not_confirmed":
231
+ raise CliError("Seu e-mail ainda não foi confirmado. Confirme pelo link que chegou no e-mail.")
232
+ if r.status == 429 or code in ("over_request_rate_limit", "over_email_send_rate_limit"):
233
+ raise CliError("Muitas tentativas de login. Espere alguns minutos e tente de novo.")
234
+ raise CliError("E-mail ou senha incorretos. Se você costuma entrar pelo Google, a conta pode não ter senha ainda: defina uma no painel de contas.")
230
235
  self._save_session(d)
231
236
 
232
237
  def logout(self) -> None:
@@ -355,12 +360,11 @@ STATUS_TEXT = {
355
360
 
356
361
  def cmd_setup(c: Client, a: argparse.Namespace, out: Callable[[str], None]) -> int:
357
362
  cfg = c.setup(a.backend, a.supabase_url, a.supabase_key)
358
- out("Backend: " + cfg["backend"])
359
363
  if cfg.get("supabase_url"):
360
364
  out("Login configurado.")
361
365
  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>")
366
+ out("Não foi possível obter os dados de login automaticamente. Rode de novo com:")
367
+ out(" aihub setup --supabase-url <endereço do projeto> --supabase-key <chave PUBLICÁVEL>")
364
368
  return 1
365
369
 
366
370
 
@@ -874,6 +878,230 @@ def render_avatar(size: str = "large", color: bool = True, tc: bool | None = Non
874
878
  out.append(line)
875
879
  return out
876
880
 
881
+ # Mini avatar para a animação: MINI_BASE = cores fixas (índices da paleta); MINI_RING = posição no anel
882
+ # (0-v = ângulo em 1/32 de volta; "." = não é anel). Só o anel gira; o "A" e a estrela ficam parados.
883
+ MINI_BASE = [
884
+ " 9999 ",
885
+ " 31 99",
886
+ " 112 99",
887
+ " 52223 999",
888
+ " 833323 9b9 ",
889
+ " 544 444 bbb ",
890
+ " c 555 55bbbb ",
891
+ " c 6888 ccc ",
892
+ " b 888 dddc88 ",
893
+ "9d 888eeedd 8854 ",
894
+ "cfggfffeee 544 ",
895
+ "dfggfff cc 5444 ",
896
+ " eff dd 5555 ",
897
+ " ",
898
+ ]
899
+ MINI_RING = [
900
+ "...............rsst.",
901
+ "..................tt",
902
+ "..................tu",
903
+ ".................uuu",
904
+ "................uuu.",
905
+ "...............vvv..",
906
+ "...f.........0000...",
907
+ "..f.........211.....",
908
+ ".e........6432......",
909
+ "ee.....ba875........",
910
+ "ddddccba9...........",
911
+ "dddccbb.............",
912
+ ".ccc................",
913
+ "....................",
914
+ ]
915
+ RING_ALPHABET = "0123456789abcdefghijklmnopqrstuv"
916
+ RUN_VERBS = ["Executando", "Consultando o executor", "Aguardando o resultado"]
917
+
918
+
919
+ def _hsv(h: float, s: float, v: float) -> tuple[int, int, int]:
920
+ import colorsys
921
+ r, g, b = colorsys.hsv_to_rgb(h % 1.0, s, v)
922
+ return int(r * 255), int(g * 255), int(b * 255)
923
+
924
+
925
+ def _lerp(a: tuple[int, int, int], b: tuple[int, int, int], t: float) -> tuple[int, int, int]:
926
+ t = max(0.0, min(1.0, t))
927
+ return tuple(int(x + (y - x) * t) for x, y in zip(a, b)) # type: ignore[return-value]
928
+
929
+
930
+ def ring_color(angle: float, phase: float, mode: str) -> tuple[int, int, int]:
931
+ """Cor de um pedaço do anel. `think`: giro laranja com cometa; `run`: arco-íris girando."""
932
+ behind = (phase - angle) % 1.0 # 0 = cabeça do cometa, cresce para trás (sentido horário)
933
+ tail = max(0.0, 1.0 - behind * 1.5)
934
+ if mode == "run":
935
+ return _hsv(angle - phase, 0.92, 0.6 + 0.4 * tail)
936
+ c = _lerp((110, 45, 8), (255, 170, 35), 0.12 + 0.88 * tail)
937
+ return _lerp(c, (255, 236, 180), 1.0 - behind / 0.07) if behind < 0.07 else c
938
+
939
+
940
+ def mini_grid(mode: str | None, phase: float) -> list[list[tuple[int, int, int] | None]]:
941
+ grid: list[list[tuple[int, int, int] | None]] = []
942
+ for brow, rrow in zip(MINI_BASE, MINI_RING):
943
+ row: list[tuple[int, int, int] | None] = []
944
+ for b, r in zip(brow, rrow):
945
+ if b == " ":
946
+ row.append(None)
947
+ elif r != "." and mode:
948
+ row.append(ring_color(RING_ALPHABET.index(r) / 32.0, phase, mode))
949
+ else:
950
+ row.append(_rgb(AVATAR_ALPHABET.index(b)))
951
+ grid.append(row)
952
+ return grid
953
+
954
+
955
+ def render_mini(mode: str | None = None, phase: float = 0.0, color: bool = True, tc: bool | None = None) -> list[str]:
956
+ """Avatar pequeno (7 linhas) com o anel animado. Sem cor vira silhueta."""
957
+ tc = truecolor() if tc is None else tc
958
+ grid = mini_grid(mode, phase)
959
+ out = []
960
+ for y in range(0, len(grid), 2):
961
+ top, bot = grid[y], grid[y + 1] if y + 1 < len(grid) else [None] * len(grid[y])
962
+ line = ""
963
+ for t, b in zip(top, bot):
964
+ if t is None and b is None:
965
+ line += " "
966
+ elif not color:
967
+ line += "█" if t and b else "▀" if t else "▄"
968
+ elif t and b:
969
+ line += _fgc(t, tc) + _bgc(b, tc) + "▀" + RESET
970
+ elif t:
971
+ line += _fgc(t, tc) + "▀" + RESET
972
+ else:
973
+ line += _fgc(b, tc) + "▄" + RESET # type: ignore[arg-type]
974
+ out.append(line)
975
+ return out
976
+
977
+
978
+ def _fgc(c: tuple[int, int, int], tc: bool) -> str:
979
+ return f"\x1b[38;2;{c[0]};{c[1]};{c[2]}m" if tc else f"\x1b[38;5;{_to256(*c)}m"
980
+
981
+
982
+ def _bgc(c: tuple[int, int, int], tc: bool) -> str:
983
+ return f"\x1b[48;2;{c[0]};{c[1]};{c[2]}m" if tc else f"\x1b[48;5;{_to256(*c)}m"
984
+
985
+
986
+ class LivePanel:
987
+ """Painel animado embaixo do texto: avatar com o anel girando + status.
988
+
989
+ Fica abaixo do cursor e é redesenhado a cada ~80 ms; o texto da resposta continua saindo acima dele.
990
+ `think` = anel laranja girando (respondendo/pesquisando). `run` = arco-íris girando (executando comandos).
991
+ """
992
+
993
+ HEIGHT = 7
994
+
995
+ def __init__(self, enabled: bool, color: bool = True, tc: bool | None = None, col_fn: Callable[[], int] = lambda: 0,
996
+ write: Callable[[str], Any] | None = None):
997
+ self.enabled, self.color, self.tc, self.col_fn = enabled, color, tc, col_fn
998
+ self.write = write or (lambda s: (sys.stdout.write(s), sys.stdout.flush()))
999
+ self.lock = threading.RLock()
1000
+ self.mode = "think"
1001
+ self._stop, self._t, self._t0, self._i = threading.Event(), None, 0.0, 0
1002
+
1003
+ @staticmethod
1004
+ def status_lines(mode: str, i: int, elapsed: float, color: bool = True) -> list[str]:
1005
+ verbs = RUN_VERBS if mode == "run" else VERBS
1006
+ label = verbs[int(elapsed // 3) % len(verbs)] + "…"
1007
+ star = STARS[i % len(STARS)]
1008
+ if mode == "run":
1009
+ text = "".join((_fgc(_hsv(j / 12 - i * 0.03, 0.8, 1.0), True) + ch + RESET) if color else ch for j, ch in enumerate(label))
1010
+ head = (_fgc(_hsv(-i * 0.03, 0.9, 1.0), True) + star + RESET) if color else star
1011
+ else:
1012
+ hot = (i // 2) % (len(label) + 6)
1013
+ 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))
1014
+ head = paint(star, ACCENT, color=color)
1015
+ return [f"{head} {text}", paint(f"({int(elapsed)}s · Ctrl+C interrompe)", DIM, color=color)]
1016
+
1017
+ def draw_string(self, i: int, elapsed: float, col: int) -> str:
1018
+ av = render_mini(self.mode, (i * 0.045) % 1.0, self.color, self.tc)
1019
+ st = self.status_lines(self.mode, i, elapsed, self.color)
1020
+ w = len(MINI_BASE[0])
1021
+ out = ""
1022
+ for r, a in enumerate(av):
1023
+ side = st[r - 2] if 2 <= r < 2 + len(st) else ""
1024
+ out += "\n\r " + a + " " + side + RESET + "\x1b[K"
1025
+ return out + f"\x1b[{len(av)}A\x1b[{col + 1}G"
1026
+
1027
+ def _draw(self) -> None:
1028
+ cols = shutil.get_terminal_size((80, 24)).columns
1029
+ self.write(self.draw_string(self._i, time.time() - self._t0, min(self.col_fn(), cols - 2)))
1030
+ self._i += 1
1031
+
1032
+ def start(self, mode: str = "think") -> "LivePanel":
1033
+ if self.enabled and not self._t:
1034
+ self.mode = mode
1035
+ self._stop.clear()
1036
+ self._t0, self._i = time.time(), 0
1037
+ with self.lock:
1038
+ self._draw()
1039
+ self._t = threading.Thread(target=self._run, daemon=True)
1040
+ self._t.start()
1041
+ return self
1042
+
1043
+ def _run(self) -> None:
1044
+ while not self._stop.wait(0.08):
1045
+ with self.lock:
1046
+ self._draw()
1047
+
1048
+ def stop(self) -> None:
1049
+ if self._t:
1050
+ self._stop.set()
1051
+ self._t.join()
1052
+ self._t = None
1053
+ with self.lock:
1054
+ self.write("\x1b[J")
1055
+
1056
+
1057
+ class LockedPrinter:
1058
+ """StreamPrinter protegido pelo mesmo lock do painel (cursor e coluna ficam consistentes)."""
1059
+
1060
+ def __init__(self, printer: "StreamPrinter", lock: Any):
1061
+ self.p, self.lock = printer, lock
1062
+
1063
+ @property
1064
+ def col(self) -> int:
1065
+ return self.p.col
1066
+
1067
+ def feed(self, text: str) -> None:
1068
+ with self.lock:
1069
+ self.p.feed(text)
1070
+
1071
+ def finish(self) -> None:
1072
+ with self.lock:
1073
+ self.p.finish()
1074
+
1075
+
1076
+ class quiet_input:
1077
+ """Desliga o eco do teclado enquanto a IA trabalha (o que for digitado não se mistura à resposta)."""
1078
+
1079
+ def __init__(self, enabled: bool):
1080
+ self.enabled, self.old = enabled, None
1081
+
1082
+ def __enter__(self):
1083
+ if self.enabled:
1084
+ try:
1085
+ import termios
1086
+ fd = sys.stdin.fileno()
1087
+ self.old = termios.tcgetattr(fd)
1088
+ new = termios.tcgetattr(fd)
1089
+ new[3] &= ~termios.ECHO
1090
+ termios.tcsetattr(fd, termios.TCSADRAIN, new)
1091
+ except Exception: # noqa: BLE001 - sem termios (ou sem TTY): segue com eco
1092
+ self.old = None
1093
+ return self
1094
+
1095
+ def __exit__(self, *a):
1096
+ if self.old is not None:
1097
+ import termios
1098
+ termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, self.old)
1099
+
1100
+
1101
+ class NoStop:
1102
+ def stop(self) -> None:
1103
+ pass
1104
+
877
1105
 
878
1106
  def _fit(s: str, n: int) -> str:
879
1107
  return s if vis_len(s) <= n else ANSI_RE.sub("", s)[: max(0, n - 1)] + "…"
@@ -886,14 +1114,12 @@ def render_banner(width: int, backend: str, user: str, model: str, color: bool =
886
1114
  size = next((s for s in ("large", "medium") if inner >= len(AVATAR[s][0]) + 2 + 28), "small")
887
1115
  avatar = render_avatar(size, color, tc)
888
1116
  aw = len(AVATAR[size][0])
889
- host = backend.replace("https://", "")
890
1117
  info = [
891
1118
  paint("AI Hub Code", BOLD, ACCENT, color=color) + paint(" v" + VERSION, DIM, color=color),
892
1119
  paint("Bem-vindo de volta!", BOLD, color=color),
893
1120
  "",
894
1121
  paint("conta ", DIM, color=color) + user,
895
1122
  paint("modelo ", DIM, color=color) + model,
896
- paint("backend ", DIM, color=color) + host,
897
1123
  paint("pasta ", DIM, color=color) + os.path.basename(os.getcwd() or "/"),
898
1124
  "",
899
1125
  paint("/help comandos · /exit sair", DIM, color=color),
@@ -1035,6 +1261,7 @@ class StreamPrinter:
1035
1261
  self.w(self._c(RESET))
1036
1262
  if self.col:
1037
1263
  self.w("\n")
1264
+ self.col, self.bol = 0, True
1038
1265
 
1039
1266
 
1040
1267
  def render_answer(text: str, width: int, color: bool = True) -> list[str]:
@@ -1078,7 +1305,7 @@ def render_help(color: bool = True) -> list[str]:
1078
1305
  ("/help", "esta ajuda"), ("/model <id|auto>", "troca o modelo"), ("/clear", "nova conversa"),
1079
1306
  ("/tasks [list|new|run|watch…]", "tarefas dos agentes"), ("/memory [list|add|search|rm]", "memória"),
1080
1307
  ("/projects [list|add|rm]", "projetos"), ("/status", "executor e tarefas"), ("/models", "modelos gratuitos"),
1081
- ("/avatar", "mostra o avatar"), ("/term", "terminal remoto"), ("/exit", "sair"),
1308
+ ("/avatar [think|run]", "avatar; think/run mostram a animação"), ("/term", "terminal remoto"), ("/exit", "sair"),
1082
1309
  ]
1083
1310
  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
1311
 
@@ -1204,8 +1431,19 @@ def cmd_tui(c: Client, a: argparse.Namespace, out: Callable[[str], None] = print
1204
1431
  for ln in render_help(color):
1205
1432
  out(ln)
1206
1433
  elif name == "avatar":
1207
- for ln in render_avatar("large", color):
1208
- out(" " + ln)
1434
+ demo = rest.strip() if rest.strip() in ("think", "run") else None
1435
+ if demo and tty:
1436
+ pn = LivePanel(True, color)
1437
+ out(render_detail("modo " + demo + (" (anel laranja girando)" if demo == "think" else " (arco-íris girando)") + " · 5 s", color))
1438
+ pn.start(demo)
1439
+ try:
1440
+ time.sleep(5)
1441
+ except KeyboardInterrupt:
1442
+ pass
1443
+ pn.stop()
1444
+ else:
1445
+ for ln in render_avatar("large", color):
1446
+ out(" " + ln)
1209
1447
  elif name == "clear":
1210
1448
  history.clear()
1211
1449
  conv = None
@@ -1215,41 +1453,72 @@ def cmd_tui(c: Client, a: argparse.Namespace, out: Callable[[str], None] = print
1215
1453
  out(render_detail("modelo: " + (model or "automático"), color))
1216
1454
  else:
1217
1455
  lines: list[str] = []
1456
+ title = "/" + name + (" " + rest if rest else "")
1457
+ live = tty and shutil.get_terminal_size((80, 24)).lines >= LivePanel.HEIGHT + 7
1458
+ pn = LivePanel(live, color)
1459
+ first = [True]
1460
+
1461
+ def emit(ln: str) -> None:
1462
+ if not live:
1463
+ lines.append(ln)
1464
+ return
1465
+ with pn.lock: # linha a linha, enquanto o anel gira em arco-íris
1466
+ sys.stdout.write("\x1b[J" + (" " + paint("⎿", DIM, color=color) + " " if first[0] else " ") + style_result_line(ln, color) + "\n")
1467
+ sys.stdout.flush()
1468
+ first[0] = False
1469
+
1470
+ if live:
1471
+ out(paint("●", ACCENT, color=color) + " " + paint(title, BOLD, color=color))
1472
+ pn.start("run")
1218
1473
  try:
1219
1474
  sub = build_parser().parse_args([name] + shlex.split(rest))
1220
1475
  if sub.cmd in ("chat", "tui", "notify", "setup", "login"):
1221
1476
  raise CliError("comando não disponível dentro do chat")
1222
- COMMANDS[sub.cmd](c, sub, lines.append)
1477
+ with quiet_input(live and sub.cmd != "term"):
1478
+ COMMANDS[sub.cmd](c, sub, emit)
1223
1479
  except SystemExit:
1224
- lines = ["comando inválido (veja /help)"]
1480
+ emit("comando inválido (veja /help)")
1225
1481
  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)
1482
+ emit("erro: " + str(e))
1483
+ except KeyboardInterrupt:
1484
+ emit("interrompido")
1485
+ finally:
1486
+ pn.stop()
1487
+ if not live:
1488
+ for ln in render_tool(title, lines, color):
1489
+ out(ln)
1229
1490
  out("")
1230
1491
  continue
1231
- sp = Spinner(tty, color)
1492
+ live = tty and shutil.get_terminal_size((80, 24)).lines >= LivePanel.HEIGHT + 7
1232
1493
  buf: list[str] = []
1233
- printer = StreamPrinter(lambda s: (sys.stdout.write(s), sys.stdout.flush()) if tty else buf.append(s), width, color)
1494
+ state: dict = {}
1495
+ panel = LivePanel(live, color, col_fn=lambda: state["p"].col if "p" in state else 0)
1496
+ base_printer = StreamPrinter((lambda s: (sys.stdout.write("\x1b[J" + s), sys.stdout.flush())) if live else (lambda s: (sys.stdout.write(s), sys.stdout.flush())) if tty else buf.append, width - 1, color)
1497
+ printer = LockedPrinter(base_printer, panel.lock) if live else base_printer
1498
+ state["p"] = base_printer
1499
+ sp = NoStop() if live else Spinner(tty, color)
1234
1500
  t0 = time.time()
1235
1501
  r: dict | None = None
1236
1502
  try:
1237
- sp.start()
1238
- r = _stream_turn(c, line, history, model, None, printer, sp)
1503
+ with quiet_input(tty):
1504
+ panel.start("think") if live else sp.start()
1505
+ r = _stream_turn(c, line, history, model, None, printer, sp)
1239
1506
  except KeyboardInterrupt:
1240
- sp.stop()
1241
1507
  printer.finish()
1508
+ panel.stop()
1509
+ sp.stop()
1242
1510
  out(render_detail("interrompido", color))
1243
1511
  out("")
1244
1512
  continue
1245
1513
  except CliError as e:
1514
+ panel.stop()
1246
1515
  sp.stop()
1247
1516
  out(paint(" ✗ ", RED, color=color) + str(e))
1248
1517
  out("")
1249
1518
  continue
1250
- finally:
1251
- sp.stop()
1252
1519
  printer.finish()
1520
+ panel.stop()
1521
+ sp.stop()
1253
1522
  if not tty:
1254
1523
  for ln in "".join(buf).rstrip("\n").split("\n"):
1255
1524
  out(ln)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aihub-code
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: AI Hub Code para Termux: cliente de terminal (chat, tarefas, memória, projetos) do backend AI Hub
5
5
  License: Proprietary
6
6
  Requires-Python: >=3.9
@@ -18,7 +18,7 @@ Pacote `aihub-code` (traz tudo, inclusive o terminal remoto):
18
18
  pkg install -y python
19
19
  pip install aihub-code
20
20
  # ou, sem PyPI, a partir de um arquivo .whl que você baixou/copiou:
21
- pip install aihub_code-0.2.1-py3-none-any.whl
21
+ pip install aihub_code-0.2.2-py3-none-any.whl
22
22
  aihub setup && aihub login
23
23
  ```
24
24
  Gerar o `.whl` (no repositório): `cd termux && python3 -m pip install build && python3 -m build --wheel`.
@@ -43,6 +43,7 @@ Se `aihub setup` disser que o backend não publicou os dados de login, use:
43
43
  | `aihub notify` | avisa pelo Termux:API quando uma tarefa termina |
44
44
  | `aihub memory list/add/search/rm` | memória persistente (`--kind`, `--project`) |
45
45
  | `aihub projects list/add/rm` | projetos |
46
+ | `/avatar think` · `/avatar run` | (dentro do `aihub`) mostra a animação do avatar por 5 s |
46
47
  | `aihub term` | terminal remoto no Codespace (sair: Ctrl+]) |
47
48
  | `aihub status`, `models`, `history`, `whoami`, `logout` | utilitários |
48
49
 
@@ -51,3 +52,9 @@ Se `aihub setup` disser que o backend não publicou os dados de login, use:
51
52
  - Tokens em `~/.config/aihub-code/session.json` (modo 0600); a senha nunca é gravada.
52
53
  - Só modelos gratuitos aprovados no backend; o cliente não escolhe provedores pagos.
53
54
  - Testes: `python3 -m unittest tests.test_termux_client -v`
55
+
56
+ ## Avatar animado
57
+ Enquanto a IA trabalha, um mini avatar aparece embaixo do texto e o **anel gira**:
58
+ - **laranja** quando ela está respondendo ou pesquisando;
59
+ - **arco-íris** quando ela está executando comandos (`/tasks`, `/status`, …).
60
+ Precisa de terminal com pelo menos 14 linhas; em terminal menor, aparece só o spinner de uma linha.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "aihub-code"
7
- version = "0.2.1"
7
+ version = "0.2.2"
8
8
  description = "AI Hub Code para Termux: cliente de terminal (chat, tarefas, memória, projetos) do backend AI Hub"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
File without changes