@hiperplano/aluy-cli 1.0.0-rc.32 → 1.0.0-rc.33

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.
@@ -0,0 +1,438 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ aluy-mem0-server — servidor HTTP stdlib para o Mem0 OSS local.
4
+
5
+ EST-1138 · ADR-0123 §8-emenda E2/E3 · C4.
6
+ Implementa EXATAMENTE os endpoints que `mem0-memory-engine.ts` chama.
7
+
8
+ Bind: 127.0.0.1 (loopback, CA-G2-6), porta via --port (default 11435).
9
+ Uma instância de Memory() — criada UMA vez no boot.
10
+
11
+ Endpoints:
12
+ GET /health → 200 {"ok":true}
13
+ POST /v1/memories/ → mem.add(...) → {"id":"..."}
14
+ GET /v1/memories/?... → mem.search(...) → {"results":[...]}
15
+ GET /v1/users/ → lista scopes → {"users":[...]}
16
+ DELETE /v1/memories/?... → mem.delete_all(...) → 204
17
+
18
+ Dependências: mem0ai, chromadb (já no venv provisionado).
19
+ Embedder: nomic-embed-text via Ollama em 127.0.0.1:11434.
20
+ Store: chromadb em ~/.aluy/memory.
21
+ """
22
+
23
+ import argparse
24
+ import json
25
+ import os
26
+ import signal
27
+ import sys
28
+ import traceback
29
+ from http.server import HTTPServer, BaseHTTPRequestHandler
30
+ from pathlib import Path
31
+ from socketserver import ThreadingMixIn
32
+ from typing import Any
33
+
34
+ # ── Constantes ────────────────────────────────────────────────────────────
35
+ DEFAULT_PORT = 11435
36
+ DEFAULT_HOST = "127.0.0.1"
37
+ ALUY_MEMORY_DIR = os.path.expanduser("~/.aluy/memory")
38
+ OLLAMA_BASE_URL = "http://127.0.0.1:11434"
39
+ EMBEDDER_MODEL = "nomic-embed-text"
40
+ # LLM local p/ extração de fatos (mem0 add infer=True). SEM isto o mem0 cai no
41
+ # default OpenAI → 401. Local-first: tudo via Ollama loopback, zero credencial.
42
+ LLM_MODEL = "qwen2.5:0.5b"
43
+ USERS_FILE = os.path.join(ALUY_MEMORY_DIR, "aluy_users.json")
44
+
45
+
46
+ # ── Mem0 config ───────────────────────────────────────────────────────────
47
+ def _build_mem0_config() -> dict[str, Any]:
48
+ """Monta a config do mem0ai com paths locais absolutos."""
49
+ return {
50
+ # history em ~/.aluy/memory (não no default ~/.mem0): TODO o estado do mem0 fica num
51
+ # único lugar ⇒ limpar ~/.aluy/memory no self-heal recria TUDO fresco. Antes o history
52
+ # ia p/ ~/.mem0/history.db e, de uma versão antiga, dava `no such column: prev_value`.
53
+ "history_db_path": os.path.join(ALUY_MEMORY_DIR, "history.db"),
54
+ "vector_store": {
55
+ "provider": "chroma",
56
+ "config": {
57
+ "collection_name": "mem0",
58
+ "path": ALUY_MEMORY_DIR,
59
+ },
60
+ },
61
+ "embedder": {
62
+ "provider": "ollama",
63
+ "config": {
64
+ "model": EMBEDDER_MODEL,
65
+ "ollama_base_url": OLLAMA_BASE_URL,
66
+ },
67
+ },
68
+ "llm": {
69
+ "provider": "ollama",
70
+ "config": {
71
+ "model": LLM_MODEL,
72
+ "ollama_base_url": OLLAMA_BASE_URL,
73
+ },
74
+ },
75
+ }
76
+
77
+
78
+ # ── Tracking de usuários ──────────────────────────────────────────────────
79
+ def _load_users() -> dict[str, dict[str, Any]]:
80
+ """Carrega o tracking de usuários do disco (JSON simples)."""
81
+ try:
82
+ if os.path.exists(USERS_FILE):
83
+ with open(USERS_FILE, "r", encoding="utf-8") as f:
84
+ return json.load(f)
85
+ except Exception:
86
+ pass
87
+ return {}
88
+
89
+
90
+ def _save_users(users: dict[str, dict[str, Any]]) -> None:
91
+ """Persiste o tracking de usuários."""
92
+ os.makedirs(ALUY_MEMORY_DIR, mode=0o700, exist_ok=True)
93
+ tmp = USERS_FILE + ".tmp"
94
+ with open(tmp, "w", encoding="utf-8") as f:
95
+ json.dump(users, f)
96
+ os.replace(tmp, USERS_FILE)
97
+ os.chmod(USERS_FILE, 0o600)
98
+
99
+
100
+ def _track_user(users: dict[str, dict[str, Any]], user_id: str) -> None:
101
+ """Registra um user_id se ainda não existe no tracking."""
102
+ if user_id not in users:
103
+ users[user_id] = {"created_at": None}
104
+ _save_users(users)
105
+
106
+
107
+ def _untrack_user(users: dict[str, dict[str, Any]], user_id: str) -> None:
108
+ """Remove um user_id do tracking."""
109
+ if user_id in users:
110
+ del users[user_id]
111
+ _save_users(users)
112
+
113
+
114
+ # ── Handler HTTP ──────────────────────────────────────────────────────────
115
+ class Mem0Handler(BaseHTTPRequestHandler):
116
+ """
117
+ Handler HTTP que traduz requests REST ↔ chamadas ao Memory() do mem0ai.
118
+ """
119
+
120
+ # Injectados pelo servidor (antes de start).
121
+ memory: Any = None
122
+ users: dict[str, dict[str, Any]] = {}
123
+
124
+ # ── Helpers ────────────────────────────────────────────────────────
125
+
126
+ def _send_json(self, status: int, body: Any) -> None:
127
+ self.send_response(status)
128
+ self.send_header("Content-Type", "application/json; charset=utf-8")
129
+ self.send_header("Access-Control-Allow-Origin", "*")
130
+ self.end_headers()
131
+ self.wfile.write(json.dumps(body, default=str).encode("utf-8"))
132
+
133
+ def _send_no_content(self) -> None:
134
+ self.send_response(204)
135
+ self.send_header("Access-Control-Allow-Origin", "*")
136
+ self.end_headers()
137
+
138
+ def _read_body(self) -> dict[str, Any]:
139
+ length = int(self.headers.get("Content-Length", "0"))
140
+ if length == 0:
141
+ return {}
142
+ raw = self.rfile.read(length)
143
+ return json.loads(raw)
144
+
145
+ def _parse_qs(self) -> dict[str, str]:
146
+ """Extrai query params da URL (simples, sem dependência)."""
147
+ path = self.path
148
+ qs: dict[str, str] = {}
149
+ if "?" in path:
150
+ query_string = path.split("?", 1)[1]
151
+ for pair in query_string.split("&"):
152
+ if "=" in pair:
153
+ k, v = pair.split("=", 1)
154
+ qs[k] = v
155
+ elif pair:
156
+ qs[pair] = ""
157
+ return qs
158
+
159
+ # ── Routing ────────────────────────────────────────────────────────
160
+
161
+ def _route_path(self) -> str:
162
+ """Devolve o path sem query string."""
163
+ return self.path.split("?", 1)[0].rstrip("/")
164
+
165
+ def do_GET(self) -> None:
166
+ path = self._route_path()
167
+ try:
168
+ if path == "/health":
169
+ self._handle_health()
170
+ elif path == "/v1/memories":
171
+ self._handle_search()
172
+ elif path == "/v1/users":
173
+ self._handle_list_users()
174
+ else:
175
+ self._send_json(404, {"error": "not found"})
176
+ except Exception:
177
+ traceback.print_exc()
178
+ self._send_json(500, {"error": traceback.format_exc()})
179
+
180
+ def do_POST(self) -> None:
181
+ path = self._route_path()
182
+ try:
183
+ if path == "/v1/memories":
184
+ self._handle_add()
185
+ else:
186
+ self._send_json(404, {"error": "not found"})
187
+ except Exception:
188
+ traceback.print_exc()
189
+ self._send_json(500, {"error": traceback.format_exc()})
190
+
191
+ def do_DELETE(self) -> None:
192
+ path = self._route_path()
193
+ try:
194
+ if path == "/v1/memories":
195
+ self._handle_delete()
196
+ else:
197
+ self._send_json(404, {"error": "not found"})
198
+ except Exception:
199
+ traceback.print_exc()
200
+ self._send_json(500, {"error": traceback.format_exc()})
201
+
202
+ def do_OPTIONS(self) -> None:
203
+ self.send_response(200)
204
+ self.send_header("Access-Control-Allow-Origin", "*")
205
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
206
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
207
+ self.end_headers()
208
+
209
+ # ── Handlers ───────────────────────────────────────────────────────
210
+
211
+ def _handle_health(self) -> None:
212
+ """GET /health → 200 {"ok":true} (handshake do boot)."""
213
+ self._send_json(200, {"ok": True})
214
+
215
+ def _handle_add(self) -> None:
216
+ """POST /v1/memories/ → mem.add(...) → {"id":"..."}."""
217
+ body = self._read_body()
218
+ user_id = body.get("user_id", "default")
219
+ messages = body.get("messages", [])
220
+ metadata = body.get("metadata")
221
+
222
+ if not messages:
223
+ self._send_json(400, {"error": "messages é obrigatório"})
224
+ return
225
+
226
+ # infer=False: armazena o conteúdo DIRETO (embed+store), sem extração por LLM.
227
+ # Semântica da porta MemoryEngine = "guarda o que recebe"; e o judge local
228
+ # (qwen2.5:0.5b) é fraco demais p/ a extração de fatos do mem0 (retornaria vazio).
229
+ result = self.memory.add(messages, user_id=user_id, metadata=metadata, infer=False)
230
+
231
+ # mem0ai 2.0.7 retorna {"results":[{"id",...}]}; o TS espera {"id": "..."}.
232
+ first_id = None
233
+ if isinstance(result, dict):
234
+ res_list = result.get("results")
235
+ if isinstance(res_list, list) and res_list:
236
+ first_id = res_list[0].get("id")
237
+ else:
238
+ first_id = result.get("id")
239
+ elif isinstance(result, list) and result:
240
+ first_id = result[0].get("id")
241
+
242
+ # Track user
243
+ _track_user(self.users, user_id)
244
+
245
+ self._send_json(200, {"id": first_id})
246
+
247
+ def _handle_search(self) -> None:
248
+ """GET /v1/memories/?user_id&query&limit → mem.search(...) → {"results":[...]}."""
249
+ qs = self._parse_qs()
250
+ user_id = qs.get("user_id", "default")
251
+ query = qs.get("query", "")
252
+ limit = int(qs.get("limit", "10"))
253
+
254
+ # mem0ai 2.0.7: entity params via filters=, paginação via top_k= (não user_id/limit).
255
+ resp = self.memory.search(query, filters={"user_id": user_id}, top_k=limit)
256
+
257
+ # mem0ai.search retorna {"results": [...]}
258
+ results = resp.get("results", []) if isinstance(resp, dict) else []
259
+
260
+ self._send_json(200, {"results": results})
261
+
262
+ def _handle_list_users(self) -> None:
263
+ """GET /v1/users/ → lista scopes com memory_count."""
264
+ # Reconcilia tracking file com o estado real (get_all de cada user).
265
+ users_list = []
266
+ for user_id in list(self.users.keys()):
267
+ try:
268
+ # mem0ai 2.0.7: get_all usa filters= e retorna {"results": [...]}.
269
+ all_mems = self.memory.get_all(filters={"user_id": user_id})
270
+ except Exception:
271
+ # F100 — erro TRANSITÓRIO no get_all NÃO é "scope vazio". Conflar os dois
272
+ # (count=0 ⇒ untrack) DESTRÓI o tracking de um scope COM memórias num hiccup
273
+ # do backend — o scope some da lista (memórias intactas, mas invisíveis) até
274
+ # o próximo add. CA-MA8: degrada, não destrói estado. Preserva o tracking e
275
+ # OMITE só desta resposta (reaparece no próximo list bem-sucedido).
276
+ continue
277
+
278
+ if isinstance(all_mems, dict):
279
+ count = len(all_mems.get("results", []))
280
+ elif isinstance(all_mems, list):
281
+ count = len(all_mems)
282
+ else:
283
+ count = 0
284
+
285
+ created_at = self.users[user_id].get("created_at")
286
+ entry: dict[str, Any] = {
287
+ "user_id": user_id,
288
+ "memory_count": count,
289
+ }
290
+ if created_at:
291
+ entry["created_at"] = created_at
292
+
293
+ # Vazio COMPROVADO (get_all OK retornando 0) ⇒ foi deletado: untrack.
294
+ if count > 0:
295
+ users_list.append(entry)
296
+ else:
297
+ _untrack_user(self.users, user_id)
298
+
299
+ self._send_json(200, {"users": users_list})
300
+
301
+ def _handle_delete(self) -> None:
302
+ """DELETE /v1/memories/?user_id=X → mem.delete_all(user_id=X)."""
303
+ qs = self._parse_qs()
304
+ user_id = qs.get("user_id", "default")
305
+
306
+ self.memory.delete_all(user_id=user_id)
307
+ _untrack_user(self.users, user_id)
308
+
309
+ self._send_no_content()
310
+
311
+ # Suprime logs por request (stderr polui a TUI).
312
+ def log_message(self, format: str, *args: Any) -> None:
313
+ pass
314
+
315
+
316
+ # ── ThreadingHTTPServer ───────────────────────────────────────────────────
317
+ class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
318
+ """HTTPServer com thread por request (stdlib apenas)."""
319
+ daemon_threads = True
320
+
321
+
322
+ # ── Main ──────────────────────────────────────────────────────────────────
323
+ def _reset_incompatible_stores() -> None:
324
+ """Move os stores de memória p/ backup, p/ recriar frescos. Chamado quando a versão atual
325
+ do chromadb/mem0 não lê o store de uma versão anterior (KeyError '_type' no chromadb /
326
+ sqlite 'no such column' no history). Best-effort — nunca lança. Limpa OS DOIS lugares:
327
+ `~/.aluy/memory` (chromadb + history novo) E `~/.mem0/history.db` (history default ANTIGO,
328
+ de antes de consolidarmos o path — senão a 2ª tentativa ainda bate nele)."""
329
+ import time
330
+ try:
331
+ ts = int(time.time())
332
+ except Exception: # noqa: BLE001
333
+ ts = 0
334
+ targets = [ALUY_MEMORY_DIR, os.path.expanduser("~/.mem0/history.db")]
335
+ for path in targets:
336
+ if not os.path.exists(path):
337
+ continue
338
+ try:
339
+ os.rename(path, f"{path}.incompat-{ts}")
340
+ except OSError:
341
+ # rename pode falhar (cross-device/permissão) ⇒ apaga o conteúdo problemático.
342
+ import shutil
343
+ try:
344
+ if os.path.isdir(path):
345
+ shutil.rmtree(path, ignore_errors=True)
346
+ else:
347
+ os.remove(path)
348
+ except Exception: # noqa: BLE001
349
+ pass
350
+
351
+
352
+ def main() -> None:
353
+ parser = argparse.ArgumentParser(description="aluy-mem0-server")
354
+ parser.add_argument("--port", type=int, default=DEFAULT_PORT,
355
+ help=f"Porta loopback (default: {DEFAULT_PORT})")
356
+ parser.add_argument("--host", type=str, default=DEFAULT_HOST,
357
+ help=f"Host (default: {DEFAULT_HOST})")
358
+ args = parser.parse_args()
359
+
360
+ # Import lazy — só depois do venv estar configurado.
361
+ try:
362
+ from mem0 import Memory # type: ignore[import-untyped]
363
+ except ImportError:
364
+ print("ERRO: mem0ai não instalado. Rode `aluy init` primeiro.", file=sys.stderr)
365
+ sys.exit(1)
366
+
367
+ # Garante o dir de store com perms corretas.
368
+ os.makedirs(ALUY_MEMORY_DIR, mode=0o700, exist_ok=True)
369
+
370
+ # Instancia Memory() UMA vez. SELF-HEAL de upgrade: um store gravado por uma versão
371
+ # ANTERIOR do chromadb/mem0 pode ser ilegível pela atual (ex.: chromadb `KeyError: '_type'`
372
+ # na config da collection; sqlite `no such column: prev_value` no history). Em vez de
373
+ # CRASHAR (deixando o sidecar "fora" sem causa visível), movemos os stores antigos p/
374
+ # backup e RECRIAMOS frescos. Perde-se memória antiga (já ilegível de qualquer forma),
375
+ # mas o serviço SOBE. Achado ao vivo na máquina do dono (dois stores de jun/antigo).
376
+ config = _build_mem0_config()
377
+ try:
378
+ memory = Memory.from_config(config)
379
+ except Exception as exc: # noqa: BLE001 — qualquer erro ao ler o store antigo
380
+ if os.environ.get("ALUY_MEM0_RESET_DONE") == "1":
381
+ # JÁ resetamos uma vez e AINDA falha ⇒ não é store velho; propaga (não loopa).
382
+ raise
383
+ sys.stderr.write(
384
+ f"aluy-mem0: store incompatível ({type(exc).__name__}: {exc}); "
385
+ "movendo p/ backup e reiniciando fresco…\n"
386
+ )
387
+ _reset_incompatible_stores()
388
+ # RE-EXEC em vez de retry in-process: o chromadb CACHEIA o client/conexão por
389
+ # processo, então um 2º `from_config` no MESMO processo reusa o store velho. Reiniciar
390
+ # o processo garante chromadb/mem0 FRESCOS. `ALUY_MEM0_RESET_DONE` evita loop infinito.
391
+ # CROSS-SO: o supervisor health-checa a PORTA (não o PID), então trocar de processo é OK
392
+ # em Linux/macOS/Windows. `os.execv` no Windows pode falhar em casos raros (path/quoting)
393
+ # — então caímos p/ um respawn via subprocess + saída limpa; e, em último caso, p/ um
394
+ # retry in-process (melhor um chromadb possivelmente cacheado do que o sidecar morto).
395
+ os.environ["ALUY_MEM0_RESET_DONE"] = "1"
396
+ try:
397
+ os.execv(sys.executable, [sys.executable, *sys.argv])
398
+ except Exception: # noqa: BLE001 — execv indisponível/falhou (ex.: Windows)
399
+ try:
400
+ import subprocess
401
+
402
+ subprocess.Popen([sys.executable, *sys.argv], close_fds=True)
403
+ os._exit(0) # encerra ESTE processo; o novo assume a porta
404
+ except Exception: # noqa: BLE001 — sem respawn possível: tenta in-process
405
+ os.makedirs(ALUY_MEMORY_DIR, mode=0o700, exist_ok=True)
406
+ memory = Memory.from_config(config)
407
+ else:
408
+ return # inalcançável após _exit — só p/ o type-checker
409
+ else:
410
+ return # inalcançável (execv substitui o processo) — só p/ o type-checker
411
+
412
+ # Injeta no handler.
413
+ Mem0Handler.memory = memory
414
+ Mem0Handler.users = _load_users()
415
+
416
+ # Cria servidor com bind explícito em loopback.
417
+ server = ThreadingHTTPServer((args.host, args.port), Mem0Handler)
418
+
419
+ # Graceful shutdown no SIGTERM (boot-supervisor mata com SIGTERM).
420
+ def _shutdown(signum: int, frame: Any) -> None:
421
+ print(f"\naluy-mem0-server: recebido sinal {signum}, desligando...", file=sys.stderr)
422
+ server.shutdown()
423
+ signal.signal(signal.SIGTERM, _shutdown)
424
+ signal.signal(signal.SIGINT, _shutdown)
425
+
426
+ print(f"aluy-mem0-server: escutando em http://{args.host}:{args.port}", file=sys.stderr)
427
+
428
+ try:
429
+ server.serve_forever()
430
+ except KeyboardInterrupt:
431
+ pass
432
+ finally:
433
+ server.server_close()
434
+ print("aluy-mem0-server: parado.", file=sys.stderr)
435
+
436
+
437
+ if __name__ == "__main__":
438
+ main()
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var hU=Object.defineProperty;var p=(t,e,o)=>()=>{if(o)throw o[0];try{return t&&(e=t(t=0)),e}catch(n){throw o=[n],n}};var ut=(t,e)=>{for(var o in e)hU(t,o,{get:e[o],enumerable:!0})};import{homedir as gU}from"node:os";import{join as yU}from"node:path";function bc(t=gU()){return yU(t,".aluy")}var $u=p(()=>{"use strict"});var vc,LA=p(()=>{"use strict";vc="1.0.0-rc.32"});function cr(t,e){return t.decide(e)}var Os=p(()=>{"use strict"});var On,lr,dr=p(()=>{"use strict";On="remember",lr="recall"});var tg,bU,ji,og=p(()=>{"use strict";tg=class{id;horizon;label;parentId;children;dependencies;pinned;closed;createdAt;lastAccessedAt;accessCount;context;constructor(e,o,n,r,s){this.id=e,this.horizon=o,this.label=n,this.parentId=r,this.children=new Set,this.dependencies=new Set,this.pinned=!1,this.closed=!1,this.createdAt=s,this.lastAccessedAt=s,this.accessCount=0,this.context=[]}touch(e){this.lastAccessedAt=e,this.accessCount+=1}snapshot(){return{id:this.id,horizon:this.horizon,label:this.label,parentId:this.parentId,children:[...this.children],dependencies:[...this.dependencies],pinned:this.pinned,closed:this.closed,createdAt:this.createdAt,lastAccessedAt:this.lastAccessedAt,accessCount:this.accessCount,contextSize:this.context.length}}},bU=200,ji=class{nodes=new Map;maxBoxes;now;constructor(e){this.maxBoxes=e?.maxBoxes??bU,this.now=e?.clock??Date.now}static boxId(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,60)}-${o.toString(36)}`}openBox(e,o,n,r){let s=this.nodes.get(e);if(s)return s.touch(this.now()),{box:s.snapshot(),created:!1};if(this.nodes.size>=this.maxBoxes&&(this.evictOne(),this.nodes.size>=this.maxBoxes))return null;let i=this.now(),a=new tg(e,o,n,r??null,i);if(r){let c=this.nodes.get(r);c&&c.children.add(e)}return this.nodes.set(e,a),{box:a.snapshot(),created:!0}}closeBox(e){let o=this.nodes.get(e);return o?(o.closed=!0,o.touch(this.now()),o.snapshot()):null}isClosed(e){let o=this.nodes.get(e);return o?o.closed:!1}reopenBox(e){let o=this.nodes.get(e);return o?(o.closed=!1,o.touch(this.now()),o.snapshot()):null}setHorizon(e,o){let n=this.nodes.get(e);return n?(n.horizon=o,n.touch(this.now()),n.snapshot()):null}setParent(e,o){let n=this.nodes.get(e);return n?n.parentId===o?n.snapshot():o!==null&&this.wouldCreateCycle(e,o)?null:(n.parentId&&this.nodes.get(n.parentId)?.children.delete(e),n.parentId=o,o&&this.nodes.get(o)?.children.add(e),n.touch(this.now()),n.snapshot()):null}wouldCreateCycle(e,o){let n=new Set,r=o;for(;r!==null;){if(r===e||n.has(r))return!0;n.add(r),r=this.nodes.get(r)?.parentId??null}return!1}getBox(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),o.snapshot()):null}listBoxes(e="lastAccessedAt"){let o=[...this.nodes.values()].map(n=>n.snapshot());switch(e){case"createdAt":return o.sort((n,r)=>n.createdAt-r.createdAt);case"accessCount":return o.sort((n,r)=>r.accessCount-n.accessCount);default:return o.sort((n,r)=>r.lastAccessedAt-n.lastAccessedAt)}}get size(){return this.nodes.size}addContext(e,o){let n=this.nodes.get(e);return n?(n.context.push({ts:this.now(),text:o}),n.touch(this.now()),n.snapshot()):null}getContext(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),[...o.context]):[]}getContextChain(e){let o=[],n=new Set,r=e;for(;r&&!n.has(r);){n.add(r);let s=this.nodes.get(r);if(!s)break;s.touch(this.now()),o.push({boxId:s.id,entries:[...s.context]}),r=s.parentId}return o}addDependency(e,o){let n=this.nodes.get(e);return!n||!this.nodes.has(o)||n.id===o?!1:(n.dependencies.add(o),n.touch(this.now()),!0)}getDependencies(e){let o=this.nodes.get(e);return o?[...o.dependencies]:[]}pinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!0,o.touch(this.now()),o.snapshot()):null}unpinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!1,o.touch(this.now()),o.snapshot()):null}evictOne(){let e=[];for(let n of this.nodes.values())n.horizon==="longo"||n.pinned||e.push(n);if(e.length===0)return null;e.sort((n,r)=>{let s=n.horizon==="curto"?0:1,i=r.horizon==="curto"?0:1;if(s!==i)return s-i;let a=n.closed?0:1,c=r.closed?0:1;return a!==c?a-c:n.lastAccessedAt!==r.lastAccessedAt?n.lastAccessedAt-r.lastAccessedAt:n.accessCount-r.accessCount});let o=e[0];return this.removeNode(o)}forceEvict(e){let o=this.nodes.get(e);return!o||o.horizon==="longo"||o.pinned?null:this.removeNode(o)}removeBox(e){let o=this.nodes.get(e);return o?this.removeNode(o):null}removeNode(e){if(e.parentId){let o=this.nodes.get(e.parentId);o&&o.children.delete(e.id)}return this.nodes.delete(e.id),e.snapshot()}}});function Fu(t){let e=[];for(let o of t){e.push({step:o,depth:0});for(let n of o.substeps??[])e.push({step:n,depth:1})}return e}function NA(t,e){let o,n="pending",r;if(typeof t=="string")o=t;else if(t!==null&&typeof t=="object"){let i=t,a=i.title??i.step??i.text??i.name??i.content;if(typeof a=="string"&&(o=a),typeof i.status=="string"&&vU.has(i.status)&&(n=i.status),e){let c=i.substeps??i.subtasks??i.subpassos??i.children;if(Array.isArray(c)&&c.length>0){let l=[];for(let d of c){let m=NA(d,!1);if(typeof m=="string")return m;l.push(m)}r=l}}}if(o===void 0||o.trim()==="")return xU;let s=o.trim().slice(0,kU);return r?{title:s,status:n,substeps:r}:{title:s,status:n}}function SU(t){let e=t.steps??t.plan??t.todos??t.items;if(!Array.isArray(e))return{error:'update_plan: passe "steps" como uma LISTA de passos (string ou {title,status}).'};if(e.length===0)return{error:"update_plan: a lista de passos est\xE1 vazia."};let o=[];for(let i of e){let a=NA(i,!0);if(typeof a=="string")return{error:a};o.push(a)}let n=new Set,r=i=>{if(!n.has(i))return n.add(i),i;for(let a=2;;a++){let c=`${i} #${a}`;if(!n.has(c))return n.add(c),c}};for(let i=0;i<o.length;i++){let a=o[i],c=r(a.title),l=a.substeps?.map(d=>({...d,title:r(d.title)}));o[i]=l!==void 0?{...a,title:c,substeps:l}:{...a,title:c}}let s=Fu(o).length;return s>PA?{error:`update_plan: no m\xE1ximo ${PA} passos (recebidos ${s}).`}:{steps:o}}function wU(t){let e=Fu(t),o=e.filter(r=>r.step.status==="completed").length,n=e.map(r=>`${" ".repeat(r.depth)}${DA[r.step.status]} ${r.step.title}`).join(`
2
+ var hU=Object.defineProperty;var p=(t,e,o)=>()=>{if(o)throw o[0];try{return t&&(e=t(t=0)),e}catch(n){throw o=[n],n}};var ut=(t,e)=>{for(var o in e)hU(t,o,{get:e[o],enumerable:!0})};import{homedir as gU}from"node:os";import{join as yU}from"node:path";function bc(t=gU()){return yU(t,".aluy")}var $u=p(()=>{"use strict"});var vc,LA=p(()=>{"use strict";vc="1.0.0-rc.33"});function cr(t,e){return t.decide(e)}var Os=p(()=>{"use strict"});var On,lr,dr=p(()=>{"use strict";On="remember",lr="recall"});var tg,bU,ji,og=p(()=>{"use strict";tg=class{id;horizon;label;parentId;children;dependencies;pinned;closed;createdAt;lastAccessedAt;accessCount;context;constructor(e,o,n,r,s){this.id=e,this.horizon=o,this.label=n,this.parentId=r,this.children=new Set,this.dependencies=new Set,this.pinned=!1,this.closed=!1,this.createdAt=s,this.lastAccessedAt=s,this.accessCount=0,this.context=[]}touch(e){this.lastAccessedAt=e,this.accessCount+=1}snapshot(){return{id:this.id,horizon:this.horizon,label:this.label,parentId:this.parentId,children:[...this.children],dependencies:[...this.dependencies],pinned:this.pinned,closed:this.closed,createdAt:this.createdAt,lastAccessedAt:this.lastAccessedAt,accessCount:this.accessCount,contextSize:this.context.length}}},bU=200,ji=class{nodes=new Map;maxBoxes;now;constructor(e){this.maxBoxes=e?.maxBoxes??bU,this.now=e?.clock??Date.now}static boxId(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,60)}-${o.toString(36)}`}openBox(e,o,n,r){let s=this.nodes.get(e);if(s)return s.touch(this.now()),{box:s.snapshot(),created:!1};if(this.nodes.size>=this.maxBoxes&&(this.evictOne(),this.nodes.size>=this.maxBoxes))return null;let i=this.now(),a=new tg(e,o,n,r??null,i);if(r){let c=this.nodes.get(r);c&&c.children.add(e)}return this.nodes.set(e,a),{box:a.snapshot(),created:!0}}closeBox(e){let o=this.nodes.get(e);return o?(o.closed=!0,o.touch(this.now()),o.snapshot()):null}isClosed(e){let o=this.nodes.get(e);return o?o.closed:!1}reopenBox(e){let o=this.nodes.get(e);return o?(o.closed=!1,o.touch(this.now()),o.snapshot()):null}setHorizon(e,o){let n=this.nodes.get(e);return n?(n.horizon=o,n.touch(this.now()),n.snapshot()):null}setParent(e,o){let n=this.nodes.get(e);return n?n.parentId===o?n.snapshot():o!==null&&this.wouldCreateCycle(e,o)?null:(n.parentId&&this.nodes.get(n.parentId)?.children.delete(e),n.parentId=o,o&&this.nodes.get(o)?.children.add(e),n.touch(this.now()),n.snapshot()):null}wouldCreateCycle(e,o){let n=new Set,r=o;for(;r!==null;){if(r===e||n.has(r))return!0;n.add(r),r=this.nodes.get(r)?.parentId??null}return!1}getBox(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),o.snapshot()):null}listBoxes(e="lastAccessedAt"){let o=[...this.nodes.values()].map(n=>n.snapshot());switch(e){case"createdAt":return o.sort((n,r)=>n.createdAt-r.createdAt);case"accessCount":return o.sort((n,r)=>r.accessCount-n.accessCount);default:return o.sort((n,r)=>r.lastAccessedAt-n.lastAccessedAt)}}get size(){return this.nodes.size}addContext(e,o){let n=this.nodes.get(e);return n?(n.context.push({ts:this.now(),text:o}),n.touch(this.now()),n.snapshot()):null}getContext(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),[...o.context]):[]}getContextChain(e){let o=[],n=new Set,r=e;for(;r&&!n.has(r);){n.add(r);let s=this.nodes.get(r);if(!s)break;s.touch(this.now()),o.push({boxId:s.id,entries:[...s.context]}),r=s.parentId}return o}addDependency(e,o){let n=this.nodes.get(e);return!n||!this.nodes.has(o)||n.id===o?!1:(n.dependencies.add(o),n.touch(this.now()),!0)}getDependencies(e){let o=this.nodes.get(e);return o?[...o.dependencies]:[]}pinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!0,o.touch(this.now()),o.snapshot()):null}unpinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!1,o.touch(this.now()),o.snapshot()):null}evictOne(){let e=[];for(let n of this.nodes.values())n.horizon==="longo"||n.pinned||e.push(n);if(e.length===0)return null;e.sort((n,r)=>{let s=n.horizon==="curto"?0:1,i=r.horizon==="curto"?0:1;if(s!==i)return s-i;let a=n.closed?0:1,c=r.closed?0:1;return a!==c?a-c:n.lastAccessedAt!==r.lastAccessedAt?n.lastAccessedAt-r.lastAccessedAt:n.accessCount-r.accessCount});let o=e[0];return this.removeNode(o)}forceEvict(e){let o=this.nodes.get(e);return!o||o.horizon==="longo"||o.pinned?null:this.removeNode(o)}removeBox(e){let o=this.nodes.get(e);return o?this.removeNode(o):null}removeNode(e){if(e.parentId){let o=this.nodes.get(e.parentId);o&&o.children.delete(e.id)}return this.nodes.delete(e.id),e.snapshot()}}});function Fu(t){let e=[];for(let o of t){e.push({step:o,depth:0});for(let n of o.substeps??[])e.push({step:n,depth:1})}return e}function NA(t,e){let o,n="pending",r;if(typeof t=="string")o=t;else if(t!==null&&typeof t=="object"){let i=t,a=i.title??i.step??i.text??i.name??i.content;if(typeof a=="string"&&(o=a),typeof i.status=="string"&&vU.has(i.status)&&(n=i.status),e){let c=i.substeps??i.subtasks??i.subpassos??i.children;if(Array.isArray(c)&&c.length>0){let l=[];for(let d of c){let m=NA(d,!1);if(typeof m=="string")return m;l.push(m)}r=l}}}if(o===void 0||o.trim()==="")return xU;let s=o.trim().slice(0,kU);return r?{title:s,status:n,substeps:r}:{title:s,status:n}}function SU(t){let e=t.steps??t.plan??t.todos??t.items;if(!Array.isArray(e))return{error:'update_plan: passe "steps" como uma LISTA de passos (string ou {title,status}).'};if(e.length===0)return{error:"update_plan: a lista de passos est\xE1 vazia."};let o=[];for(let i of e){let a=NA(i,!0);if(typeof a=="string")return{error:a};o.push(a)}let n=new Set,r=i=>{if(!n.has(i))return n.add(i),i;for(let a=2;;a++){let c=`${i} #${a}`;if(!n.has(c))return n.add(c),c}};for(let i=0;i<o.length;i++){let a=o[i],c=r(a.title),l=a.substeps?.map(d=>({...d,title:r(d.title)}));o[i]=l!==void 0?{...a,title:c,substeps:l}:{...a,title:c}}let s=Fu(o).length;return s>PA?{error:`update_plan: no m\xE1ximo ${PA} passos (recebidos ${s}).`}:{steps:o}}function wU(t){let e=Fu(t),o=e.filter(r=>r.step.status==="completed").length,n=e.map(r=>`${" ".repeat(r.depth)}${DA[r.step.status]} ${r.step.title}`).join(`
3
3
  `);return`plano (${o}/${e.length}):
4
4
  ${n}`}function EU(t,e){return e<0?"m\xE9dio":t===e?"curto":t>e?"longo":"m\xE9dio"}function TU(t,e){let o=new Map;for(let i of e.listBoxes())o.set(i.label,i.id);let n=t.findIndex(i=>i.status==="in_progress"||(i.substeps??[]).some(a=>a.status==="in_progress")),r=(i,a,c)=>{let l=i.status==="in_progress"?"curto":c,d=o.get(i.title),m=d??ji.boxId(i.title,0);return d?(i.status!=="completed"&&e.isClosed(d)&&e.reopenBox(d),e.setHorizon(d,l),e.setParent(d,a)):e.openBox(m,l,i.title,a),i.status==="completed"&&!e.isClosed(m)&&e.closeBox(m),o.set(i.title,m),m};t.forEach((i,a)=>{let c=EU(a,n),l=r(i,null,c);for(let d of i.substeps??[])r(d,l,c)});let s=new Set;for(let i of t){s.add(i.title);for(let a of i.substeps??[])s.add(a.title)}for(let i of e.listBoxes())s.has(i.label)||e.removeBox(i.id)}function _U(t,e){if(!e)return wU(t);let o=new Map;for(let l of e.listBoxes())o.set(l.label,l);let n=new Map;for(let l of e.listBoxes())n.set(l.id,l);let r=new Map,s=(l,d=new Set)=>{let m=r.get(l);if(m!==void 0)return m;let u=n.get(l);if(!u||!u.parentId||d.has(l))return r.set(l,0),0;let h=s(u.parentId,new Set(d).add(l))+1;return r.set(l,h),h},i=Fu(t),c=[`plano (${i.filter(l=>l.step.status==="completed").length}/${i.length}):`];for(let{step:l,depth:d}of i){let m=o.get(l.title),u=m?AU[m.horizon]:"",h=m?s(m.id):d,g=" ".repeat(h),y=DA[l.status];c.push(`${g}${u} ${y} ${l.title}`)}return c.join(`
5
5
  `)}var kc,vU,PA,kU,xU,DA,AU,IA,RU,$A,Bu=p(()=>{"use strict";og();kc="update_plan";vU=new Set(["pending","in_progress","completed"]),PA=30,kU=120,xU="update_plan: cada passo precisa de um t\xEDtulo (texto) n\xE3o-vazio.";DA={pending:"\u2610",in_progress:"\u25B6",completed:"\u2611"};AU={longo:"[\u{1F4D0}]",m\u00E9dio:"[\u{1F4CB}]",curto:"[\u{1F4CC}]"};IA=Object.freeze({type:"string",enum:["pending","in_progress","completed"],description:"pending (a fazer) \xB7 in_progress (em curso) \xB7 completed (feito)."}),RU=Object.freeze({type:"object",properties:{steps:{type:"array",description:"A lista COMPLETA de passos do plano (re-emita TODOS a cada atualiza\xE7\xE3o \u2014 substitui o anterior).",items:{type:"object",properties:{title:{type:"string",description:"O passo, curto e no imperativo."},status:IA,substeps:{type:"array",description:"OPCIONAL: sub-passos que detalham este passo (1 n\xEDvel). Aparecem indentados sob o passo e seguem o foco dele. Use quando um passo tem a\xE7\xF5es menores distintas.",items:{type:"object",properties:{title:{type:"string",description:"O sub-passo, curto e no imperativo."},status:IA},required:["title"],additionalProperties:!1}}},required:["title"],additionalProperties:!1}}},required:["steps"],additionalProperties:!1}),$A={name:kc,effect:"read",description:"Declara/atualiza um PLANO vis\xEDvel (checklist de passos). Use ao iniciar uma tarefa com V\xC1RIOS passos e a cada progresso: re-emita a lista TODA marcando o status de cada passo (pending/in_progress/completed). Mantenha 1 passo in_progress por vez. N\xE3o tem efeito no sistema \u2014 \xE9 s\xF3 o seu plano, para voc\xEA e para o usu\xE1rio acompanharem.",parameters:RU,async run(t,e){let o=SU(t);return"error"in o?{ok:!1,observation:o.error}:(e.graph&&TU(o.steps,e.graph),e.plan&&e.plan.set(Fu(o.steps).map(r=>({title:r.step.title,status:r.step.status}))),{ok:!0,observation:_U(o.steps,e.graph)})}}});function FA(t){let e=t.question??t.prompt??t.text??t.message;if(typeof e!="string"||e.trim()==="")return{error:'perguntar: passe "question" (a pergunta em texto). Para escolha, passe tamb\xE9m "options".'};let o=e.trim().slice(0,2e3),n=t.header??t.title,r=typeof n=="string"&&n.trim()!==""?n.trim().slice(0,200):void 0,s=t.options??t.choices,i=Array.isArray(s)?OU(s):void 0;if(typeof i=="string")return{error:i};let a,c=t.kind??t.type;if(typeof c=="string"&&CU.has(c))a=c;else{if(typeof c=="string"&&c.trim()!=="")return{error:`perguntar: "kind" inv\xE1lido "${c}". Use "single", "multi" ou "text".`};a=i!==void 0&&i.length>0?"single":"text"}if((a==="single"||a==="multi")&&(i===void 0||i.length===0))return{error:`perguntar: kind "${a}" requer "options" (uma lista de ao menos 1 op\xE7\xE3o).`};let l=t.allowOther!==!1;return{spec:{kind:a,question:o,...r!==void 0?{header:r}:{},...a!=="text"&&i!==void 0?{options:i}:{},...a!=="text"?{allowOther:l}:{}}}}function OU(t){if(t.length===0)return'perguntar: a lista de "options" est\xE1 vazia.';if(t.length>12)return`perguntar: no m\xE1ximo 12 op\xE7\xF5es (recebidas ${t.length}).`;let e=[];for(let o of t){let n,r;if(typeof o=="string")n=o;else if(o!==null&&typeof o=="object"){let s=o,i=s.label??s.text??s.value??s.name??s.title;typeof i=="string"&&(n=i),typeof s.description=="string"&&s.description.trim()!==""&&(r=s.description.trim().slice(0,300))}if(n===void 0||n.trim()==="")return'perguntar: cada op\xE7\xE3o precisa de um "label" (texto) n\xE3o-vazio.';e.push({label:n.trim().slice(0,200),...r!==void 0?{description:r}:{}})}return e}function MU(t){switch(t.kind){case"choice":return t.label;case"choices":return t.labels.length===0?"(nenhuma)":t.labels.join(", ");case"text":{let e=t.text.split(`
@@ -152,7 +152,7 @@ ${t.trim()}`}}function $C(t,e,o=Ll){let{older:n,recent:r}=lf(t,o);if(n.length===
152
152
  `);let i=no(process.execPath,[n,"-p",o,"--yolo","--no-self-check"],{stdio:"inherit",timeout:9e5,env:{...process.env,ALUY_OVERWRITE_RENDER:"0",ALUY_SYNC_OUTPUT:"0",ALUY_NO_WEAK_YOLO_WARN:"1",ALUY_PRINT_VERBOSE:"1"}});if(t==="mem0")try{let c=ve(Vo(),kr),l=ve(c,yn);ze(c)&&Nf($f(),l)}catch{}t==="ollama"&&(await jG(),HG()),process.stderr.write(`
153
153
  verificando "${t}"\u2026 (alguns segundos; a pr\xF3xima etapa vem em seguida)
154
154
  `);let a=await l0(t,process.platform,!0);for(let c=0;c<FG&&!a;c++)await UG(BG),a=await l0(t,process.platform,!0);return{target:t,hashOk:a,installed:a,message:a?`complemento "${t}" instalado e verificado.`:`o complemento "${t}" ainda n\xE3o respondeu como esperado. O Aluy CLI funciona sem ele; voc\xEA pode tentar de novo depois com \`aluy bootstrap\`.`}}function UG(t){return new Promise(e=>setTimeout(e,t))}async function jG(){for(let t of[gn,Js])try{await(await fetch(`http://${zo}:${$n}/api/pull`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({name:t,stream:!1})})).text()}catch{}}function HG(){if(process.platform!=="win32")try{let t=no("sh",["-lc","command -v ollama"],{encoding:"utf8",timeout:1e4});if(t.status===0&&(t.stdout??"").trim()!=="")return;let e=Df(),n=["/usr/local/bin/ollama","/usr/bin/ollama","/opt/homebrew/bin/ollama",ve(e,".ollama","bin","ollama"),ve(Vo(),Qr,"bin","ollama")].find(i=>ze(i));if(n===void 0)return;let r=ve(e,".local","bin");fk(r,{recursive:!0});let s=ve(r,"ollama");try{if(s0(s)===s0(n))return;kG(s)}catch{}try{vG(n,s)}catch{}}catch{}}function qG(){try{return no("python3",["-m","venv","--help"],{timeout:1e4}).status===0}catch{return!1}}function WG(){try{return no("python3",["-m","pip","--version"],{timeout:1e4}).status===0}catch{return!1}}function GG(t){let e=[],o=[];if(t.has("ollama")&&(u0()||(e.push("zstd (extrair o Ollama)"),o.push("zstd")),m0()||(e.push("tar (extrair o Ollama)"),o.push("tar"))),t.has("mem0")||t.has("headroom")){let r=hk();r.ok?(qG()||(e.push("m\xF3dulo venv do Python (mem0/headroom criam um virtualenv)"),o.push("python3-venv")),WG()||(e.push("pip do Python (mem0/headroom instalam pacotes)"),o.push("python3-pip"))):(e.push(`python3 >= ${Nl} para mem0/headroom (encontrado: ${r.version||"nenhum"})`),o.push("python3","python3-venv","python3-pip"))}if(e.length===0)return[];let n=[...new Set(o)];return["Faltam pr\xE9-requisitos para o modo turbo (o que conseguir, instala; o resto fica de fora):",...e.map(r=>` \u2022 ${r}`),`Instale e rode \`aluy bootstrap\` de novo: sudo apt install -y ${n.join(" ")}`,""]}async function p0(t,e,o){let n=t??"turbo",r=xr(e??{}),s=o?.useAgent!==!1,i=new mk({...o?.platform?{platform:o.platform}:{},...s?{agentInstaller:$G}:{}});if(!s)for(let a of GG(r))process.stderr.write(a+`
155
- `);return i.provisionAll(n,r)}var d0,Sa,AG,yn,a0,mk,c0,NG,FG,BG,gk=p(()=>{"use strict";N();d0=".aluy",Sa=448,AG=384;yn="aluy-mem0-server.py";a0="application/vnd.ollama.image.model";mk=class{platform;agentInstaller;constructor(e={}){this.platform=e.platform??process.platform,this.agentInstaller=e.agentInstaller}hasPinnedArtifact(){return this.platform==="linux"}async isProvisioned(e){switch(e){case"ollama":{let o=ve(Vo(),Qr,"bin","ollama");return ze(o)}case"mem0":{let o=ve(Vo(),kr,"bin","python3");return ze(o)&&Yl(o)}case"headroom":{let o=ve(Vo(),Zr,"bin","headroom");return ze(o)}default:return!1}}async provision(e,o){let n=SG().uid;if(Mv(n))return{target:e,hashOk:!1,installed:!1,message:"RECUSA ROOT (uid=0): provisionamento de sidecars \xE9 user-space. Execute como usu\xE1rio normal."};if(this.agentInstaller)return this.agentInstaller(e,o);if(!this.hasPinnedArtifact())return{target:e,hashOk:!1,installed:!1,message:`SO '${this.platform}' sem artefato pinado p/ provisionamento direto. Rode \`aluy bootstrap\` (o aluy instala via o pr\xF3prio agente, \u26A0 --yolo) ou instale manualmente.`};switch(e){case"ollama":return CG();case"mem0":return PG();case"headroom":return IG();default:return{target:e,hashOk:!1,installed:!1,message:`Alvo desconhecido: ${String(e)}`}}}async provisionAll(e,o){if(!$l(e))return{profile:e,targets:[],anySuccess:!1,allFailed:!1};let n=[],r=[...o];for(let a=0;a<r.length;a++){let c=r[a],l={index:a+1,total:r.length,plan:r};try{n.push(await this.provision(c,l))}catch(d){let m=d instanceof Error?d.message:String(d);n.push({target:c,hashOk:!1,installed:!1,message:`falha inesperada ao provisionar \u2014 seguindo p/ os pr\xF3ximos (${m}).`})}}let s=n.some(a=>a.installed),i=n.length>0&&n.every(a=>!a.installed);return{profile:e,targets:n,anySuccess:s,allFailed:i}}},c0="na faixa 3.10\u20133.12 (N\xC3O use 3.13+/3.14 \u2014 as depend\xEAncias nativas n\xE3o t\xEAm wheels e o pip falha ao compilar; no Windows prefira `py -3.12` ou `py -3.11`). Se N\xC3O houver um Python 3.10\u20133.12 instalado, INSTALE primeiro (no Windows: `winget install -e --id Python.Python.3.12 --accept-source-agreements --accept-package-agreements`; no Linux/macOS use o gerenciador do sistema). Se j\xE1 existir um venv nesse caminho numa vers\xE3o incompat\xEDvel (ex.: 3.14), APAGUE e recrie com a vers\xE3o certa",NG="IMPORTANTE \u2014 o usu\xE1rio quer ACOMPANHAR: antes de cada passo, diga em 1 linha o que vai fazer; rode os comandos de instala\xE7\xE3o de forma VIS\xCDVEL (N\xC3O silencie pip/apt/curl com -q; mostre a sa\xEDda/progresso). Sem modo silencioso. ";FG=24,BG=5e3});var Bn,Vl=p(()=>{"use strict";Bn="1.0.0-rc.32"});var v0={};ut(v0,{HELP_TEXT:()=>g0,parseArgs:()=>yk,suggestFlag:()=>VG,versionText:()=>y0});function rt(t,e,o={}){let n=`--${e}=`;for(let r=0;r<t.length;r++){let s=t[r];if(s===`--${e}`){let i=t[r+1];return i===void 0||(o.allowDashValue?i.startsWith("--"):i.startsWith("-"))?void 0:i}if(s!==void 0&&s.startsWith(n))return s.slice(n.length)}}function zG(t,e){let o=`-${e}=`;for(let n=0;n<t.length;n++){let r=t[n];if(r===`-${e}`){let s=t[n+1];return s!==void 0&&!s.startsWith("-")?s:void 0}if(r!==void 0&&r.startsWith(o))return r.slice(o.length)}}function y0(){return`aluy ${Bn} (@hiperplano/aluy-cli-core ${vc})`}function YG(t,e){let o=t.length,n=e.length,r=Array.from({length:n+1},(s,i)=>i);for(let s=1;s<=o;s++){let i=[s];for(let a=1;a<=n;a++){let c=t[s-1]===e[a-1]?0:1;i[a]=Math.min(r[a]+1,i[a-1]+1,r[a-1]+c)}r=i}return r[n]}function VG(t){let e,o=3;for(let n of b0){let r=YG(t,n);r<o&&(o=r,e=n)}return e}function XG(t,e){let o=[];for(let n=0;n<t.length;n++){let r=t[n];if(r==="--")break;if(!r.startsWith("--")||r.length===2||e.has(n))continue;let s=r.slice(2).split("=",1)[0];s===""||b0.has(s)||o.push(`--${s}`)}return o}function yk(t){let e=t[0];if(e==="login"&&!t.includes("-h")&&!t.includes("--help")){let H=t.slice(1),he=rt(H,"token"),Qe=rt(H,"org"),gt=H.includes("--device"),xt=rt(H,"provider"),Et=H.includes("--oauth");return{kind:"login",forceDeviceFlow:gt,...he!==void 0?{token:he}:{},...Qe!==void 0?{org:Qe}:{},...xt!==void 0?{provider:xt}:{},...Et?{oauth:!0}:{}}}if(e==="logout"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"logout"};if(e==="whoami"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"whoami"};if(e==="doctor"&&!t.includes("-h")&&!t.includes("--help")){let H=t.includes("--deep")||t.includes("--test"),he=t.includes("--json");return{kind:"doctor",deep:H,json:he}}if(e==="agents"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"agents"};if(e==="bootstrap"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"bootstrap",agent:!t.includes("--no-agent")};if(e==="uninstall"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"uninstall",agent:t.includes("--agent")};if(e==="onboard"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"onboard"};if(e==="skills"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"skills"};if(e==="workflows"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"workflows"};if((e==="models"||e==="providers")&&!t.includes("-h")&&!t.includes("--help")){let H=t.includes("--json"),he=t.findIndex(gt=>gt==="--backend"||gt.startsWith("--backend=")),Qe="both";if(he!==-1){let xt=(t[he].includes("=")?t[he].slice(10):t[he+1]??"").trim().toLowerCase();xt==="local"?Qe="local":xt==="broker"&&(Qe="broker")}return{kind:"models",scope:Qe,json:H,which:e==="providers"?"providers":"models"}}if(e==="telegram"&&!t.includes("-h")&&!t.includes("--help")){let H=t[1];if(H===void 0||!["login","logout","allow","deny","status"].includes(H))return{kind:"usage-error",message:"uso: aluy telegram <login|logout|allow|deny|status>",exitCode:2};let Qe=t.slice(2);if(H==="login"){let gt=rt(Qe,"token");return{kind:"telegram",sub:"login",...gt!==void 0?{token:gt}:{}}}if(H==="allow"||H==="deny"){let gt=Qe.find(Et=>!Et.startsWith("-")),xt=gt!==void 0&&/^-?\d+$/.test(gt)?Number(gt):void 0;return xt===void 0?{kind:"usage-error",message:`uso: aluy telegram ${H} <chat-id> (um inteiro)`,exitCode:2}:{kind:"telegram",sub:H,chatId:xt}}return{kind:"telegram",sub:H}}if(e==="mcp"&&t[1]==="search"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"mcp-search",query:t.slice(2).filter(he=>!he.startsWith("-")).join(" ").trim()};if(e==="mcp")return{kind:"mcp",argv:t.slice(1)};if(e==="cron")return{kind:"cron",argv:t.slice(1)};if(t.includes("-v")||t.includes("--version"))return{kind:"version",text:y0()};if(t.includes("-h")||t.includes("--help"))return{kind:"help",text:g0};let o=t.includes("--plan"),n=t.includes("--unsafe"),r=t.includes("--yolo")||n,s=o?"plan":r?"unsafe":"normal",i=t.includes("--dense"),a=t.includes("--ascii"),c=t.includes("--split")||t.includes("--view")?!0:void 0,l=t.includes("--fullscreen")||t.includes("--cockpit")?!0:void 0,d=t.includes("--no-budget")?!1:t.includes("--budget")?!0:void 0,m=rt(t,"tier"),u=rt(t,"lang"),h=rt(t,"max-tokens"),g=rt(t,"max-iterations"),y=rt(t,"max-output-tokens"),b=!(t.includes("--no-subagents")||t.includes("--no-subagent")),w=t.includes("--no-self-check")?"0":t.includes("--self-check")?"1":void 0,T=t.includes("--no-autocompact")?"off":rt(t,"autocompact-at"),E=t.includes("--quiet")?!0:void 0,L=t.includes("--cycle")?!0:void 0,B=rt(t,"cycles"),j=rt(t,"cycle-for"),z=rt(t,"backend"),V=rt(t,"local-provider"),I=rt(t,"local-model"),J=rt(t,"local-auth"),Q=rt(t,"local-base-url"),K=rt(t,"model"),D=rt(t,"provider");if((t.includes("--provider")||t.some(H=>H.startsWith("--provider=")))&&(K===void 0||K.trim()===""))return{kind:"usage-error",message:"aluy: --provider exige --model (ex.: --provider <provider> --model <slug>)",exitCode:2};if((K===void 0||K.trim()==="")&&m!==void 0&&m.trim().toLowerCase()==="custom")return{kind:"usage-error",message:"aluy: --tier custom exige --model <slug> (ex.: --model deepseek-v4-pro). A via Custom precisa do slug do modelo; sem ele use um tier can\xF4nico (aluy-flux, aluy-granito, \u2026).",exitCode:2};let Oe=rt(t,"effort"),Y=t.includes("--effort")||t.some(H=>H.startsWith("--effort=")),le;if(Oe!==void 0){if(Oe.trim()==="")return{kind:"usage-error",message:"aluy: --effort requer um valor (ex.: --effort low)",exitCode:2};if(Oe.length>32)return{kind:"usage-error",message:"aluy: --effort aceita no m\xE1ximo 32 caracteres",exitCode:2};le=Oe}else if(Y)return{kind:"usage-error",message:"aluy: --effort requer um valor (ex.: --effort low)",exitCode:2};let O=t.includes("-p")||t.includes("--print")||t.includes("--exec")||t.some(H=>H.startsWith("-p=")||H.startsWith("--print=")||H.startsWith("--exec=")),se=O?rt(t,"print",{allowDashValue:!0})??rt(t,"exec",{allowDashValue:!0})??zG(t,"p")??void 0:void 0,de=O?rt(t,"output-format"):void 0,ye=t.includes("--new"),Z=t.includes("--continue"),te=t.indexOf("--resume"),Me=t.find(H=>H.startsWith("--resume=")),Ht=te>=0||Me!==void 0,pt;if(Me!==void 0)pt=Me.slice(9);else if(te>=0){let H=t[te+1];H!==void 0&&!H.startsWith("-")&&(pt=H)}let at=m!==void 0?t.indexOf("--tier")+1:-1,dt=u!==void 0&&!t.some(H=>H.startsWith("--lang="))?t.indexOf("--lang")+1:-1,ht=pt!==void 0&&Me===void 0?te+1:-1,W=h!==void 0&&!t.some(H=>H.startsWith("--max-tokens="))?t.indexOf("--max-tokens")+1:-1,ue=g!==void 0&&!t.some(H=>H.startsWith("--max-iterations="))?t.indexOf("--max-iterations")+1:-1,et=B!==void 0&&!t.some(H=>H.startsWith("--cycles="))?t.indexOf("--cycles")+1:-1,Ro=j!==void 0&&!t.some(H=>H.startsWith("--cycle-for="))?t.indexOf("--cycle-for")+1:-1,oe=y!==void 0&&!t.some(H=>H.startsWith("--max-output-tokens="))?t.indexOf("--max-output-tokens")+1:-1,k=T!==void 0&&!t.includes("--no-autocompact")&&!t.some(H=>H.startsWith("--autocompact-at="))?t.indexOf("--autocompact-at")+1:-1,Co=z!==void 0&&!t.some(H=>H.startsWith("--backend="))?t.indexOf("--backend")+1:-1,Ie=(H,he)=>he!==void 0&&!t.some(Qe=>Qe.startsWith(`--${H}=`))?t.indexOf(`--${H}`)+1:-1,_s=Ie("local-provider",V),Pi=Ie("local-model",I),qt=Ie("local-auth",J),Nr=Ie("local-base-url",Q),Cs=K!==void 0&&!t.some(H=>H.startsWith("--model="))?t.indexOf("--model")+1:-1,jo=D!==void 0&&!t.some(H=>H.startsWith("--provider="))?t.indexOf("--provider")+1:-1,dn=le!==void 0&&!t.some(H=>H.startsWith("--effort="))?t.indexOf("--effort")+1:-1,po=de!==void 0&&!t.some(H=>H.startsWith("--output-format="))?t.indexOf("--output-format")+1:-1,Zt=se!==void 0&&!t.some(H=>H.startsWith("-p=")||H.startsWith("--print=")||H.startsWith("--exec="))?Math.max(t.indexOf("-p"),t.indexOf("--print"),t.indexOf("--exec"))+1:-1,Ho=t.find((H,he)=>!H.startsWith("-")&&he!==at&&he!==dt&&he!==Co&&he!==_s&&he!==Pi&&he!==qt&&he!==Nr&&he!==Cs&&he!==jo&&he!==dn&&he!==po&&he!==Zt&&he!==ht&&he!==W&&he!==ue&&he!==oe&&he!==k&&he!==et&&he!==Ro),Ii=Z?{kind:"continue"}:Ht?{kind:"resume",...pt!==void 0?{id:pt}:{}}:void 0,Dr=new Set([at,dt,Co,_s,Pi,qt,Nr,Cs,jo,dn,po,Zt,ht,W,ue,oe,k,et,Ro].filter(H=>H>=0));for(let H of KG){let he=t.indexOf(H);he>=0&&!t[he].includes("=")&&Dr.add(he+1)}let un=XG(t,Dr);return{kind:"launch",mode:s,unsafe:s==="unsafe",unsafeAliasUsed:n,...un.length>0?{unknownFlags:un}:{},dense:i,fresh:ye,subAgents:b,safeGlyphs:a,print:O,...c!==void 0?{split:c}:{},...l!==void 0?{fullscreen:l}:{},...d!==void 0?{budget:d}:{},...Ho!==void 0?{goal:Ho}:{},...m!==void 0?{tier:m}:{},...z!==void 0?{backend:z}:{},...V!==void 0?{localProvider:V}:{},...I!==void 0?{localModel:I}:{},...J!==void 0?{localAuth:J}:{},...Q!==void 0?{localBaseUrl:Q}:{},...K!==void 0?{model:K}:{},...D!==void 0?{provider:D}:{},...le!==void 0?{effort:le}:{},...se!==void 0?{printArg:se}:{},...de!==void 0?{outputFormat:de}:{},...u!==void 0?{lang:u}:{},...Ii!==void 0?{resume:Ii}:{},...h!==void 0?{maxTokens:h}:{},...g!==void 0?{maxIterations:g}:{},...y!==void 0?{maxOutputTokens:y}:{},...w!==void 0?{selfCheck:w}:{},...T!==void 0?{autoCompactAt:T}:{},...E!==void 0?{quiet:E}:{},...L!==void 0?{cycle:L}:{},...B!==void 0?{cycles:B}:{},...j!==void 0?{cycleFor:j}:{}}}var g0,b0,KG,bk=p(()=>{"use strict";N();Vl();g0=`aluy \u2014 agente de terminal que roda na sua m\xE1quina, com o seu provider de LLM
155
+ `);return i.provisionAll(n,r)}var d0,Sa,AG,yn,a0,mk,c0,NG,FG,BG,gk=p(()=>{"use strict";N();d0=".aluy",Sa=448,AG=384;yn="aluy-mem0-server.py";a0="application/vnd.ollama.image.model";mk=class{platform;agentInstaller;constructor(e={}){this.platform=e.platform??process.platform,this.agentInstaller=e.agentInstaller}hasPinnedArtifact(){return this.platform==="linux"}async isProvisioned(e){switch(e){case"ollama":{let o=ve(Vo(),Qr,"bin","ollama");return ze(o)}case"mem0":{let o=ve(Vo(),kr,"bin","python3");return ze(o)&&Yl(o)}case"headroom":{let o=ve(Vo(),Zr,"bin","headroom");return ze(o)}default:return!1}}async provision(e,o){let n=SG().uid;if(Mv(n))return{target:e,hashOk:!1,installed:!1,message:"RECUSA ROOT (uid=0): provisionamento de sidecars \xE9 user-space. Execute como usu\xE1rio normal."};if(this.agentInstaller)return this.agentInstaller(e,o);if(!this.hasPinnedArtifact())return{target:e,hashOk:!1,installed:!1,message:`SO '${this.platform}' sem artefato pinado p/ provisionamento direto. Rode \`aluy bootstrap\` (o aluy instala via o pr\xF3prio agente, \u26A0 --yolo) ou instale manualmente.`};switch(e){case"ollama":return CG();case"mem0":return PG();case"headroom":return IG();default:return{target:e,hashOk:!1,installed:!1,message:`Alvo desconhecido: ${String(e)}`}}}async provisionAll(e,o){if(!$l(e))return{profile:e,targets:[],anySuccess:!1,allFailed:!1};let n=[],r=[...o];for(let a=0;a<r.length;a++){let c=r[a],l={index:a+1,total:r.length,plan:r};try{n.push(await this.provision(c,l))}catch(d){let m=d instanceof Error?d.message:String(d);n.push({target:c,hashOk:!1,installed:!1,message:`falha inesperada ao provisionar \u2014 seguindo p/ os pr\xF3ximos (${m}).`})}}let s=n.some(a=>a.installed),i=n.length>0&&n.every(a=>!a.installed);return{profile:e,targets:n,anySuccess:s,allFailed:i}}},c0="na faixa 3.10\u20133.12 (N\xC3O use 3.13+/3.14 \u2014 as depend\xEAncias nativas n\xE3o t\xEAm wheels e o pip falha ao compilar; no Windows prefira `py -3.12` ou `py -3.11`). Se N\xC3O houver um Python 3.10\u20133.12 instalado, INSTALE primeiro (no Windows: `winget install -e --id Python.Python.3.12 --accept-source-agreements --accept-package-agreements`; no Linux/macOS use o gerenciador do sistema). Se j\xE1 existir um venv nesse caminho numa vers\xE3o incompat\xEDvel (ex.: 3.14), APAGUE e recrie com a vers\xE3o certa",NG="IMPORTANTE \u2014 o usu\xE1rio quer ACOMPANHAR: antes de cada passo, diga em 1 linha o que vai fazer; rode os comandos de instala\xE7\xE3o de forma VIS\xCDVEL (N\xC3O silencie pip/apt/curl com -q; mostre a sa\xEDda/progresso). Sem modo silencioso. ";FG=24,BG=5e3});var Bn,Vl=p(()=>{"use strict";Bn="1.0.0-rc.33"});var v0={};ut(v0,{HELP_TEXT:()=>g0,parseArgs:()=>yk,suggestFlag:()=>VG,versionText:()=>y0});function rt(t,e,o={}){let n=`--${e}=`;for(let r=0;r<t.length;r++){let s=t[r];if(s===`--${e}`){let i=t[r+1];return i===void 0||(o.allowDashValue?i.startsWith("--"):i.startsWith("-"))?void 0:i}if(s!==void 0&&s.startsWith(n))return s.slice(n.length)}}function zG(t,e){let o=`-${e}=`;for(let n=0;n<t.length;n++){let r=t[n];if(r===`-${e}`){let s=t[n+1];return s!==void 0&&!s.startsWith("-")?s:void 0}if(r!==void 0&&r.startsWith(o))return r.slice(o.length)}}function y0(){return`aluy ${Bn} (@hiperplano/aluy-cli-core ${vc})`}function YG(t,e){let o=t.length,n=e.length,r=Array.from({length:n+1},(s,i)=>i);for(let s=1;s<=o;s++){let i=[s];for(let a=1;a<=n;a++){let c=t[s-1]===e[a-1]?0:1;i[a]=Math.min(r[a]+1,i[a-1]+1,r[a-1]+c)}r=i}return r[n]}function VG(t){let e,o=3;for(let n of b0){let r=YG(t,n);r<o&&(o=r,e=n)}return e}function XG(t,e){let o=[];for(let n=0;n<t.length;n++){let r=t[n];if(r==="--")break;if(!r.startsWith("--")||r.length===2||e.has(n))continue;let s=r.slice(2).split("=",1)[0];s===""||b0.has(s)||o.push(`--${s}`)}return o}function yk(t){let e=t[0];if(e==="login"&&!t.includes("-h")&&!t.includes("--help")){let H=t.slice(1),he=rt(H,"token"),Qe=rt(H,"org"),gt=H.includes("--device"),xt=rt(H,"provider"),Et=H.includes("--oauth");return{kind:"login",forceDeviceFlow:gt,...he!==void 0?{token:he}:{},...Qe!==void 0?{org:Qe}:{},...xt!==void 0?{provider:xt}:{},...Et?{oauth:!0}:{}}}if(e==="logout"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"logout"};if(e==="whoami"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"whoami"};if(e==="doctor"&&!t.includes("-h")&&!t.includes("--help")){let H=t.includes("--deep")||t.includes("--test"),he=t.includes("--json");return{kind:"doctor",deep:H,json:he}}if(e==="agents"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"agents"};if(e==="bootstrap"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"bootstrap",agent:!t.includes("--no-agent")};if(e==="uninstall"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"uninstall",agent:t.includes("--agent")};if(e==="onboard"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"onboard"};if(e==="skills"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"skills"};if(e==="workflows"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"workflows"};if((e==="models"||e==="providers")&&!t.includes("-h")&&!t.includes("--help")){let H=t.includes("--json"),he=t.findIndex(gt=>gt==="--backend"||gt.startsWith("--backend=")),Qe="both";if(he!==-1){let xt=(t[he].includes("=")?t[he].slice(10):t[he+1]??"").trim().toLowerCase();xt==="local"?Qe="local":xt==="broker"&&(Qe="broker")}return{kind:"models",scope:Qe,json:H,which:e==="providers"?"providers":"models"}}if(e==="telegram"&&!t.includes("-h")&&!t.includes("--help")){let H=t[1];if(H===void 0||!["login","logout","allow","deny","status"].includes(H))return{kind:"usage-error",message:"uso: aluy telegram <login|logout|allow|deny|status>",exitCode:2};let Qe=t.slice(2);if(H==="login"){let gt=rt(Qe,"token");return{kind:"telegram",sub:"login",...gt!==void 0?{token:gt}:{}}}if(H==="allow"||H==="deny"){let gt=Qe.find(Et=>!Et.startsWith("-")),xt=gt!==void 0&&/^-?\d+$/.test(gt)?Number(gt):void 0;return xt===void 0?{kind:"usage-error",message:`uso: aluy telegram ${H} <chat-id> (um inteiro)`,exitCode:2}:{kind:"telegram",sub:H,chatId:xt}}return{kind:"telegram",sub:H}}if(e==="mcp"&&t[1]==="search"&&!t.includes("-h")&&!t.includes("--help"))return{kind:"mcp-search",query:t.slice(2).filter(he=>!he.startsWith("-")).join(" ").trim()};if(e==="mcp")return{kind:"mcp",argv:t.slice(1)};if(e==="cron")return{kind:"cron",argv:t.slice(1)};if(t.includes("-v")||t.includes("--version"))return{kind:"version",text:y0()};if(t.includes("-h")||t.includes("--help"))return{kind:"help",text:g0};let o=t.includes("--plan"),n=t.includes("--unsafe"),r=t.includes("--yolo")||n,s=o?"plan":r?"unsafe":"normal",i=t.includes("--dense"),a=t.includes("--ascii"),c=t.includes("--split")||t.includes("--view")?!0:void 0,l=t.includes("--fullscreen")||t.includes("--cockpit")?!0:void 0,d=t.includes("--no-budget")?!1:t.includes("--budget")?!0:void 0,m=rt(t,"tier"),u=rt(t,"lang"),h=rt(t,"max-tokens"),g=rt(t,"max-iterations"),y=rt(t,"max-output-tokens"),b=!(t.includes("--no-subagents")||t.includes("--no-subagent")),w=t.includes("--no-self-check")?"0":t.includes("--self-check")?"1":void 0,T=t.includes("--no-autocompact")?"off":rt(t,"autocompact-at"),E=t.includes("--quiet")?!0:void 0,L=t.includes("--cycle")?!0:void 0,B=rt(t,"cycles"),j=rt(t,"cycle-for"),z=rt(t,"backend"),V=rt(t,"local-provider"),I=rt(t,"local-model"),J=rt(t,"local-auth"),Q=rt(t,"local-base-url"),K=rt(t,"model"),D=rt(t,"provider");if((t.includes("--provider")||t.some(H=>H.startsWith("--provider=")))&&(K===void 0||K.trim()===""))return{kind:"usage-error",message:"aluy: --provider exige --model (ex.: --provider <provider> --model <slug>)",exitCode:2};if((K===void 0||K.trim()==="")&&m!==void 0&&m.trim().toLowerCase()==="custom")return{kind:"usage-error",message:"aluy: --tier custom exige --model <slug> (ex.: --model deepseek-v4-pro). A via Custom precisa do slug do modelo; sem ele use um tier can\xF4nico (aluy-flux, aluy-granito, \u2026).",exitCode:2};let Oe=rt(t,"effort"),Y=t.includes("--effort")||t.some(H=>H.startsWith("--effort=")),le;if(Oe!==void 0){if(Oe.trim()==="")return{kind:"usage-error",message:"aluy: --effort requer um valor (ex.: --effort low)",exitCode:2};if(Oe.length>32)return{kind:"usage-error",message:"aluy: --effort aceita no m\xE1ximo 32 caracteres",exitCode:2};le=Oe}else if(Y)return{kind:"usage-error",message:"aluy: --effort requer um valor (ex.: --effort low)",exitCode:2};let O=t.includes("-p")||t.includes("--print")||t.includes("--exec")||t.some(H=>H.startsWith("-p=")||H.startsWith("--print=")||H.startsWith("--exec=")),se=O?rt(t,"print",{allowDashValue:!0})??rt(t,"exec",{allowDashValue:!0})??zG(t,"p")??void 0:void 0,de=O?rt(t,"output-format"):void 0,ye=t.includes("--new"),Z=t.includes("--continue"),te=t.indexOf("--resume"),Me=t.find(H=>H.startsWith("--resume=")),Ht=te>=0||Me!==void 0,pt;if(Me!==void 0)pt=Me.slice(9);else if(te>=0){let H=t[te+1];H!==void 0&&!H.startsWith("-")&&(pt=H)}let at=m!==void 0?t.indexOf("--tier")+1:-1,dt=u!==void 0&&!t.some(H=>H.startsWith("--lang="))?t.indexOf("--lang")+1:-1,ht=pt!==void 0&&Me===void 0?te+1:-1,W=h!==void 0&&!t.some(H=>H.startsWith("--max-tokens="))?t.indexOf("--max-tokens")+1:-1,ue=g!==void 0&&!t.some(H=>H.startsWith("--max-iterations="))?t.indexOf("--max-iterations")+1:-1,et=B!==void 0&&!t.some(H=>H.startsWith("--cycles="))?t.indexOf("--cycles")+1:-1,Ro=j!==void 0&&!t.some(H=>H.startsWith("--cycle-for="))?t.indexOf("--cycle-for")+1:-1,oe=y!==void 0&&!t.some(H=>H.startsWith("--max-output-tokens="))?t.indexOf("--max-output-tokens")+1:-1,k=T!==void 0&&!t.includes("--no-autocompact")&&!t.some(H=>H.startsWith("--autocompact-at="))?t.indexOf("--autocompact-at")+1:-1,Co=z!==void 0&&!t.some(H=>H.startsWith("--backend="))?t.indexOf("--backend")+1:-1,Ie=(H,he)=>he!==void 0&&!t.some(Qe=>Qe.startsWith(`--${H}=`))?t.indexOf(`--${H}`)+1:-1,_s=Ie("local-provider",V),Pi=Ie("local-model",I),qt=Ie("local-auth",J),Nr=Ie("local-base-url",Q),Cs=K!==void 0&&!t.some(H=>H.startsWith("--model="))?t.indexOf("--model")+1:-1,jo=D!==void 0&&!t.some(H=>H.startsWith("--provider="))?t.indexOf("--provider")+1:-1,dn=le!==void 0&&!t.some(H=>H.startsWith("--effort="))?t.indexOf("--effort")+1:-1,po=de!==void 0&&!t.some(H=>H.startsWith("--output-format="))?t.indexOf("--output-format")+1:-1,Zt=se!==void 0&&!t.some(H=>H.startsWith("-p=")||H.startsWith("--print=")||H.startsWith("--exec="))?Math.max(t.indexOf("-p"),t.indexOf("--print"),t.indexOf("--exec"))+1:-1,Ho=t.find((H,he)=>!H.startsWith("-")&&he!==at&&he!==dt&&he!==Co&&he!==_s&&he!==Pi&&he!==qt&&he!==Nr&&he!==Cs&&he!==jo&&he!==dn&&he!==po&&he!==Zt&&he!==ht&&he!==W&&he!==ue&&he!==oe&&he!==k&&he!==et&&he!==Ro),Ii=Z?{kind:"continue"}:Ht?{kind:"resume",...pt!==void 0?{id:pt}:{}}:void 0,Dr=new Set([at,dt,Co,_s,Pi,qt,Nr,Cs,jo,dn,po,Zt,ht,W,ue,oe,k,et,Ro].filter(H=>H>=0));for(let H of KG){let he=t.indexOf(H);he>=0&&!t[he].includes("=")&&Dr.add(he+1)}let un=XG(t,Dr);return{kind:"launch",mode:s,unsafe:s==="unsafe",unsafeAliasUsed:n,...un.length>0?{unknownFlags:un}:{},dense:i,fresh:ye,subAgents:b,safeGlyphs:a,print:O,...c!==void 0?{split:c}:{},...l!==void 0?{fullscreen:l}:{},...d!==void 0?{budget:d}:{},...Ho!==void 0?{goal:Ho}:{},...m!==void 0?{tier:m}:{},...z!==void 0?{backend:z}:{},...V!==void 0?{localProvider:V}:{},...I!==void 0?{localModel:I}:{},...J!==void 0?{localAuth:J}:{},...Q!==void 0?{localBaseUrl:Q}:{},...K!==void 0?{model:K}:{},...D!==void 0?{provider:D}:{},...le!==void 0?{effort:le}:{},...se!==void 0?{printArg:se}:{},...de!==void 0?{outputFormat:de}:{},...u!==void 0?{lang:u}:{},...Ii!==void 0?{resume:Ii}:{},...h!==void 0?{maxTokens:h}:{},...g!==void 0?{maxIterations:g}:{},...y!==void 0?{maxOutputTokens:y}:{},...w!==void 0?{selfCheck:w}:{},...T!==void 0?{autoCompactAt:T}:{},...E!==void 0?{quiet:E}:{},...L!==void 0?{cycle:L}:{},...B!==void 0?{cycles:B}:{},...j!==void 0?{cycleFor:j}:{}}}var g0,b0,KG,bk=p(()=>{"use strict";N();Vl();g0=`aluy \u2014 agente de terminal que roda na sua m\xE1quina, com o seu provider de LLM
156
156
 
157
157
  Uso:
158
158
  aluy ["objetivo"] [--plan | --yolo] [--dense] [--tier <tier>] [--lang <pt-BR|en>]
@@ -1,4 +1,4 @@
1
- var TN=Object.defineProperty;var S=(t,e,o)=>()=>{if(o)throw o[0];try{return t&&(e=t(t=0)),e}catch(n){throw o=[n],n}};var Wf=(t,e)=>{for(var o in e)TN(t,o,{get:e[o],enumerable:!0})};var ca,Ax=S(()=>{"use strict";ca="1.0.0-rc.32"});function Pn(t,e){return t.decide(e)}var qr=S(()=>{"use strict"});var en,Nn,In=S(()=>{"use strict";en="remember",Nn="recall"});var Gf,_N,Ws,zf=S(()=>{"use strict";Gf=class{id;horizon;label;parentId;children;dependencies;pinned;closed;createdAt;lastAccessedAt;accessCount;context;constructor(e,o,n,r,s){this.id=e,this.horizon=o,this.label=n,this.parentId=r,this.children=new Set,this.dependencies=new Set,this.pinned=!1,this.closed=!1,this.createdAt=s,this.lastAccessedAt=s,this.accessCount=0,this.context=[]}touch(e){this.lastAccessedAt=e,this.accessCount+=1}snapshot(){return{id:this.id,horizon:this.horizon,label:this.label,parentId:this.parentId,children:[...this.children],dependencies:[...this.dependencies],pinned:this.pinned,closed:this.closed,createdAt:this.createdAt,lastAccessedAt:this.lastAccessedAt,accessCount:this.accessCount,contextSize:this.context.length}}},_N=200,Ws=class{nodes=new Map;maxBoxes;now;constructor(e){this.maxBoxes=e?.maxBoxes??_N,this.now=e?.clock??Date.now}static boxId(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,60)}-${o.toString(36)}`}openBox(e,o,n,r){let s=this.nodes.get(e);if(s)return s.touch(this.now()),{box:s.snapshot(),created:!1};if(this.nodes.size>=this.maxBoxes&&(this.evictOne(),this.nodes.size>=this.maxBoxes))return null;let i=this.now(),a=new Gf(e,o,n,r??null,i);if(r){let c=this.nodes.get(r);c&&c.children.add(e)}return this.nodes.set(e,a),{box:a.snapshot(),created:!0}}closeBox(e){let o=this.nodes.get(e);return o?(o.closed=!0,o.touch(this.now()),o.snapshot()):null}isClosed(e){let o=this.nodes.get(e);return o?o.closed:!1}reopenBox(e){let o=this.nodes.get(e);return o?(o.closed=!1,o.touch(this.now()),o.snapshot()):null}setHorizon(e,o){let n=this.nodes.get(e);return n?(n.horizon=o,n.touch(this.now()),n.snapshot()):null}setParent(e,o){let n=this.nodes.get(e);return n?n.parentId===o?n.snapshot():o!==null&&this.wouldCreateCycle(e,o)?null:(n.parentId&&this.nodes.get(n.parentId)?.children.delete(e),n.parentId=o,o&&this.nodes.get(o)?.children.add(e),n.touch(this.now()),n.snapshot()):null}wouldCreateCycle(e,o){let n=new Set,r=o;for(;r!==null;){if(r===e||n.has(r))return!0;n.add(r),r=this.nodes.get(r)?.parentId??null}return!1}getBox(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),o.snapshot()):null}listBoxes(e="lastAccessedAt"){let o=[...this.nodes.values()].map(n=>n.snapshot());switch(e){case"createdAt":return o.sort((n,r)=>n.createdAt-r.createdAt);case"accessCount":return o.sort((n,r)=>r.accessCount-n.accessCount);default:return o.sort((n,r)=>r.lastAccessedAt-n.lastAccessedAt)}}get size(){return this.nodes.size}addContext(e,o){let n=this.nodes.get(e);return n?(n.context.push({ts:this.now(),text:o}),n.touch(this.now()),n.snapshot()):null}getContext(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),[...o.context]):[]}getContextChain(e){let o=[],n=new Set,r=e;for(;r&&!n.has(r);){n.add(r);let s=this.nodes.get(r);if(!s)break;s.touch(this.now()),o.push({boxId:s.id,entries:[...s.context]}),r=s.parentId}return o}addDependency(e,o){let n=this.nodes.get(e);return!n||!this.nodes.has(o)||n.id===o?!1:(n.dependencies.add(o),n.touch(this.now()),!0)}getDependencies(e){let o=this.nodes.get(e);return o?[...o.dependencies]:[]}pinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!0,o.touch(this.now()),o.snapshot()):null}unpinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!1,o.touch(this.now()),o.snapshot()):null}evictOne(){let e=[];for(let n of this.nodes.values())n.horizon==="longo"||n.pinned||e.push(n);if(e.length===0)return null;e.sort((n,r)=>{let s=n.horizon==="curto"?0:1,i=r.horizon==="curto"?0:1;if(s!==i)return s-i;let a=n.closed?0:1,c=r.closed?0:1;return a!==c?a-c:n.lastAccessedAt!==r.lastAccessedAt?n.lastAccessedAt-r.lastAccessedAt:n.accessCount-r.accessCount});let o=e[0];return this.removeNode(o)}forceEvict(e){let o=this.nodes.get(e);return!o||o.horizon==="longo"||o.pinned?null:this.removeNode(o)}removeBox(e){let o=this.nodes.get(e);return o?this.removeNode(o):null}removeNode(e){if(e.parentId){let o=this.nodes.get(e.parentId);o&&o.children.delete(e.id)}return this.nodes.delete(e.id),e.snapshot()}}});function sd(t){let e=[];for(let o of t){e.push({step:o,depth:0});for(let n of o.substeps??[])e.push({step:n,depth:1})}return e}function _x(t,e){let o,n="pending",r;if(typeof t=="string")o=t;else if(t!==null&&typeof t=="object"){let i=t,a=i.title??i.step??i.text??i.name??i.content;if(typeof a=="string"&&(o=a),typeof i.status=="string"&&RN.has(i.status)&&(n=i.status),e){let c=i.substeps??i.subtasks??i.subpassos??i.children;if(Array.isArray(c)&&c.length>0){let l=[];for(let d of c){let f=_x(d,!1);if(typeof f=="string")return f;l.push(f)}r=l}}}if(o===void 0||o.trim()==="")return ON;let s=o.trim().slice(0,CN);return r?{title:s,status:n,substeps:r}:{title:s,status:n}}function MN(t){let e=t.steps??t.plan??t.todos??t.items;if(!Array.isArray(e))return{error:'update_plan: passe "steps" como uma LISTA de passos (string ou {title,status}).'};if(e.length===0)return{error:"update_plan: a lista de passos est\xE1 vazia."};let o=[];for(let i of e){let a=_x(i,!0);if(typeof a=="string")return{error:a};o.push(a)}let n=new Set,r=i=>{if(!n.has(i))return n.add(i),i;for(let a=2;;a++){let c=`${i} #${a}`;if(!n.has(c))return n.add(c),c}};for(let i=0;i<o.length;i++){let a=o[i],c=r(a.title),l=a.substeps?.map(d=>({...d,title:r(d.title)}));o[i]=l!==void 0?{...a,title:c,substeps:l}:{...a,title:c}}let s=sd(o).length;return s>Ex?{error:`update_plan: no m\xE1ximo ${Ex} passos (recebidos ${s}).`}:{steps:o}}function LN(t){let e=sd(t),o=e.filter(r=>r.step.status==="completed").length,n=e.map(r=>`${" ".repeat(r.depth)}${Rx[r.step.status]} ${r.step.title}`).join(`
1
+ var TN=Object.defineProperty;var S=(t,e,o)=>()=>{if(o)throw o[0];try{return t&&(e=t(t=0)),e}catch(n){throw o=[n],n}};var Wf=(t,e)=>{for(var o in e)TN(t,o,{get:e[o],enumerable:!0})};var ca,Ax=S(()=>{"use strict";ca="1.0.0-rc.33"});function Pn(t,e){return t.decide(e)}var qr=S(()=>{"use strict"});var en,Nn,In=S(()=>{"use strict";en="remember",Nn="recall"});var Gf,_N,Ws,zf=S(()=>{"use strict";Gf=class{id;horizon;label;parentId;children;dependencies;pinned;closed;createdAt;lastAccessedAt;accessCount;context;constructor(e,o,n,r,s){this.id=e,this.horizon=o,this.label=n,this.parentId=r,this.children=new Set,this.dependencies=new Set,this.pinned=!1,this.closed=!1,this.createdAt=s,this.lastAccessedAt=s,this.accessCount=0,this.context=[]}touch(e){this.lastAccessedAt=e,this.accessCount+=1}snapshot(){return{id:this.id,horizon:this.horizon,label:this.label,parentId:this.parentId,children:[...this.children],dependencies:[...this.dependencies],pinned:this.pinned,closed:this.closed,createdAt:this.createdAt,lastAccessedAt:this.lastAccessedAt,accessCount:this.accessCount,contextSize:this.context.length}}},_N=200,Ws=class{nodes=new Map;maxBoxes;now;constructor(e){this.maxBoxes=e?.maxBoxes??_N,this.now=e?.clock??Date.now}static boxId(e,o){return`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,60)}-${o.toString(36)}`}openBox(e,o,n,r){let s=this.nodes.get(e);if(s)return s.touch(this.now()),{box:s.snapshot(),created:!1};if(this.nodes.size>=this.maxBoxes&&(this.evictOne(),this.nodes.size>=this.maxBoxes))return null;let i=this.now(),a=new Gf(e,o,n,r??null,i);if(r){let c=this.nodes.get(r);c&&c.children.add(e)}return this.nodes.set(e,a),{box:a.snapshot(),created:!0}}closeBox(e){let o=this.nodes.get(e);return o?(o.closed=!0,o.touch(this.now()),o.snapshot()):null}isClosed(e){let o=this.nodes.get(e);return o?o.closed:!1}reopenBox(e){let o=this.nodes.get(e);return o?(o.closed=!1,o.touch(this.now()),o.snapshot()):null}setHorizon(e,o){let n=this.nodes.get(e);return n?(n.horizon=o,n.touch(this.now()),n.snapshot()):null}setParent(e,o){let n=this.nodes.get(e);return n?n.parentId===o?n.snapshot():o!==null&&this.wouldCreateCycle(e,o)?null:(n.parentId&&this.nodes.get(n.parentId)?.children.delete(e),n.parentId=o,o&&this.nodes.get(o)?.children.add(e),n.touch(this.now()),n.snapshot()):null}wouldCreateCycle(e,o){let n=new Set,r=o;for(;r!==null;){if(r===e||n.has(r))return!0;n.add(r),r=this.nodes.get(r)?.parentId??null}return!1}getBox(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),o.snapshot()):null}listBoxes(e="lastAccessedAt"){let o=[...this.nodes.values()].map(n=>n.snapshot());switch(e){case"createdAt":return o.sort((n,r)=>n.createdAt-r.createdAt);case"accessCount":return o.sort((n,r)=>r.accessCount-n.accessCount);default:return o.sort((n,r)=>r.lastAccessedAt-n.lastAccessedAt)}}get size(){return this.nodes.size}addContext(e,o){let n=this.nodes.get(e);return n?(n.context.push({ts:this.now(),text:o}),n.touch(this.now()),n.snapshot()):null}getContext(e){let o=this.nodes.get(e);return o?(o.touch(this.now()),[...o.context]):[]}getContextChain(e){let o=[],n=new Set,r=e;for(;r&&!n.has(r);){n.add(r);let s=this.nodes.get(r);if(!s)break;s.touch(this.now()),o.push({boxId:s.id,entries:[...s.context]}),r=s.parentId}return o}addDependency(e,o){let n=this.nodes.get(e);return!n||!this.nodes.has(o)||n.id===o?!1:(n.dependencies.add(o),n.touch(this.now()),!0)}getDependencies(e){let o=this.nodes.get(e);return o?[...o.dependencies]:[]}pinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!0,o.touch(this.now()),o.snapshot()):null}unpinBox(e){let o=this.nodes.get(e);return o?(o.pinned=!1,o.touch(this.now()),o.snapshot()):null}evictOne(){let e=[];for(let n of this.nodes.values())n.horizon==="longo"||n.pinned||e.push(n);if(e.length===0)return null;e.sort((n,r)=>{let s=n.horizon==="curto"?0:1,i=r.horizon==="curto"?0:1;if(s!==i)return s-i;let a=n.closed?0:1,c=r.closed?0:1;return a!==c?a-c:n.lastAccessedAt!==r.lastAccessedAt?n.lastAccessedAt-r.lastAccessedAt:n.accessCount-r.accessCount});let o=e[0];return this.removeNode(o)}forceEvict(e){let o=this.nodes.get(e);return!o||o.horizon==="longo"||o.pinned?null:this.removeNode(o)}removeBox(e){let o=this.nodes.get(e);return o?this.removeNode(o):null}removeNode(e){if(e.parentId){let o=this.nodes.get(e.parentId);o&&o.children.delete(e.id)}return this.nodes.delete(e.id),e.snapshot()}}});function sd(t){let e=[];for(let o of t){e.push({step:o,depth:0});for(let n of o.substeps??[])e.push({step:n,depth:1})}return e}function _x(t,e){let o,n="pending",r;if(typeof t=="string")o=t;else if(t!==null&&typeof t=="object"){let i=t,a=i.title??i.step??i.text??i.name??i.content;if(typeof a=="string"&&(o=a),typeof i.status=="string"&&RN.has(i.status)&&(n=i.status),e){let c=i.substeps??i.subtasks??i.subpassos??i.children;if(Array.isArray(c)&&c.length>0){let l=[];for(let d of c){let f=_x(d,!1);if(typeof f=="string")return f;l.push(f)}r=l}}}if(o===void 0||o.trim()==="")return ON;let s=o.trim().slice(0,CN);return r?{title:s,status:n,substeps:r}:{title:s,status:n}}function MN(t){let e=t.steps??t.plan??t.todos??t.items;if(!Array.isArray(e))return{error:'update_plan: passe "steps" como uma LISTA de passos (string ou {title,status}).'};if(e.length===0)return{error:"update_plan: a lista de passos est\xE1 vazia."};let o=[];for(let i of e){let a=_x(i,!0);if(typeof a=="string")return{error:a};o.push(a)}let n=new Set,r=i=>{if(!n.has(i))return n.add(i),i;for(let a=2;;a++){let c=`${i} #${a}`;if(!n.has(c))return n.add(c),c}};for(let i=0;i<o.length;i++){let a=o[i],c=r(a.title),l=a.substeps?.map(d=>({...d,title:r(d.title)}));o[i]=l!==void 0?{...a,title:c,substeps:l}:{...a,title:c}}let s=sd(o).length;return s>Ex?{error:`update_plan: no m\xE1ximo ${Ex} passos (recebidos ${s}).`}:{steps:o}}function LN(t){let e=sd(t),o=e.filter(r=>r.step.status==="completed").length,n=e.map(r=>`${" ".repeat(r.depth)}${Rx[r.step.status]} ${r.step.title}`).join(`
2
2
  `);return`plano (${o}/${e.length}):
3
3
  ${n}`}function NN(t,e){return e<0?"m\xE9dio":t===e?"curto":t>e?"longo":"m\xE9dio"}function IN(t,e){let o=new Map;for(let i of e.listBoxes())o.set(i.label,i.id);let n=t.findIndex(i=>i.status==="in_progress"||(i.substeps??[]).some(a=>a.status==="in_progress")),r=(i,a,c)=>{let l=i.status==="in_progress"?"curto":c,d=o.get(i.title),f=d??Ws.boxId(i.title,0);return d?(i.status!=="completed"&&e.isClosed(d)&&e.reopenBox(d),e.setHorizon(d,l),e.setParent(d,a)):e.openBox(f,l,i.title,a),i.status==="completed"&&!e.isClosed(f)&&e.closeBox(f),o.set(i.title,f),f};t.forEach((i,a)=>{let c=NN(a,n),l=r(i,null,c);for(let d of i.substeps??[])r(d,l,c)});let s=new Set;for(let i of t){s.add(i.title);for(let a of i.substeps??[])s.add(a.title)}for(let i of e.listBoxes())s.has(i.label)||e.removeBox(i.id)}function DN(t,e){if(!e)return LN(t);let o=new Map;for(let l of e.listBoxes())o.set(l.label,l);let n=new Map;for(let l of e.listBoxes())n.set(l.id,l);let r=new Map,s=(l,d=new Set)=>{let f=r.get(l);if(f!==void 0)return f;let u=n.get(l);if(!u||!u.parentId||d.has(l))return r.set(l,0),0;let p=s(u.parentId,new Set(d).add(l))+1;return r.set(l,p),p},i=sd(t),c=[`plano (${i.filter(l=>l.step.status==="completed").length}/${i.length}):`];for(let{step:l,depth:d}of i){let f=o.get(l.title),u=f?PN[f.horizon]:"",p=f?s(f.id):d,h=" ".repeat(p),g=Rx[l.status];c.push(`${h}${u} ${g} ${l.title}`)}return c.join(`
4
4
  `)}var la,RN,Ex,CN,ON,Rx,PN,Tx,$N,Cx,id=S(()=>{"use strict";zf();la="update_plan";RN=new Set(["pending","in_progress","completed"]),Ex=30,CN=120,ON="update_plan: cada passo precisa de um t\xEDtulo (texto) n\xE3o-vazio.";Rx={pending:"\u2610",in_progress:"\u25B6",completed:"\u2611"};PN={longo:"[\u{1F4D0}]",m\u00E9dio:"[\u{1F4CB}]",curto:"[\u{1F4CC}]"};Tx=Object.freeze({type:"string",enum:["pending","in_progress","completed"],description:"pending (a fazer) \xB7 in_progress (em curso) \xB7 completed (feito)."}),$N=Object.freeze({type:"object",properties:{steps:{type:"array",description:"A lista COMPLETA de passos do plano (re-emita TODOS a cada atualiza\xE7\xE3o \u2014 substitui o anterior).",items:{type:"object",properties:{title:{type:"string",description:"O passo, curto e no imperativo."},status:Tx,substeps:{type:"array",description:"OPCIONAL: sub-passos que detalham este passo (1 n\xEDvel). Aparecem indentados sob o passo e seguem o foco dele. Use quando um passo tem a\xE7\xF5es menores distintas.",items:{type:"object",properties:{title:{type:"string",description:"O sub-passo, curto e no imperativo."},status:Tx},required:["title"],additionalProperties:!1}}},required:["title"],additionalProperties:!1}}},required:["steps"],additionalProperties:!1}),Cx={name:la,effect:"read",description:"Declara/atualiza um PLANO vis\xEDvel (checklist de passos). Use ao iniciar uma tarefa com V\xC1RIOS passos e a cada progresso: re-emita a lista TODA marcando o status de cada passo (pending/in_progress/completed). Mantenha 1 passo in_progress por vez. N\xE3o tem efeito no sistema \u2014 \xE9 s\xF3 o seu plano, para voc\xEA e para o usu\xE1rio acompanharem.",parameters:$N,async run(t,e){let o=MN(t);return"error"in o?{ok:!1,observation:o.error}:(e.graph&&IN(o.steps,e.graph),e.plan&&e.plan.set(sd(o.steps).map(r=>({title:r.step.title,status:r.step.status}))),{ok:!0,observation:DN(o.steps,e.graph)})}}});function Ox(t){let e=t.question??t.prompt??t.text??t.message;if(typeof e!="string"||e.trim()==="")return{error:'perguntar: passe "question" (a pergunta em texto). Para escolha, passe tamb\xE9m "options".'};let o=e.trim().slice(0,2e3),n=t.header??t.title,r=typeof n=="string"&&n.trim()!==""?n.trim().slice(0,200):void 0,s=t.options??t.choices,i=Array.isArray(s)?BN(s):void 0;if(typeof i=="string")return{error:i};let a,c=t.kind??t.type;if(typeof c=="string"&&FN.has(c))a=c;else{if(typeof c=="string"&&c.trim()!=="")return{error:`perguntar: "kind" inv\xE1lido "${c}". Use "single", "multi" ou "text".`};a=i!==void 0&&i.length>0?"single":"text"}if((a==="single"||a==="multi")&&(i===void 0||i.length===0))return{error:`perguntar: kind "${a}" requer "options" (uma lista de ao menos 1 op\xE7\xE3o).`};let l=t.allowOther!==!1;return{spec:{kind:a,question:o,...r!==void 0?{header:r}:{},...a!=="text"&&i!==void 0?{options:i}:{},...a!=="text"?{allowOther:l}:{}}}}function BN(t){if(t.length===0)return'perguntar: a lista de "options" est\xE1 vazia.';if(t.length>12)return`perguntar: no m\xE1ximo 12 op\xE7\xF5es (recebidas ${t.length}).`;let e=[];for(let o of t){let n,r;if(typeof o=="string")n=o;else if(o!==null&&typeof o=="object"){let s=o,i=s.label??s.text??s.value??s.name??s.title;typeof i=="string"&&(n=i),typeof s.description=="string"&&s.description.trim()!==""&&(r=s.description.trim().slice(0,300))}if(n===void 0||n.trim()==="")return'perguntar: cada op\xE7\xE3o precisa de um "label" (texto) n\xE3o-vazio.';e.push({label:n.trim().slice(0,200),...r!==void 0?{description:r}:{}})}return e}function UN(t){switch(t.kind){case"choice":return t.label;case"choices":return t.labels.length===0?"(nenhuma)":t.labels.join(", ");case"text":{let e=t.text.split(`
@@ -135,7 +135,7 @@ ${t.trim()}`}}function AT(t,e,o=gc){let{older:n,recent:r}=Cu(t,o);if(n.length===
135
135
  \u2026[truncado: ${t.length-Dy} chars omitidos]`}function TB(t){return t.length<=Fy?t:`${t.slice(0,Fy)}\u2026`}function a_(t){let e=i_(t.server,t.descriptor.name),o=TB(t.descriptor.description.trim()),n=`[tool de um SERVER MCP de terceiro "${t.server}" \u2014 efeito n\xE3o-confi\xE1vel, passa pela catraca] ${o||"(sem descri\xE7\xE3o)"}`,r=t.descriptor.inputSchema,s=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0;return{name:e,effect:"mcp",description:n,...s?{parameters:s}:{},async run(i,a,c){try{let l=await t.transport.callTool(t.descriptor.name,i,c?.signal),d=Ue(l.content);return l.ok?{ok:!0,observation:s_(d),display:`${e}(${_B(i)})`}:{ok:!1,observation:s_(`MCP "${e}" erro: ${d}`)}}catch(l){return{ok:!1,observation:`MCP "${e}" falhou: ${l instanceof Error?l.message:String(l)}`}}}}}function By(t,e){let o=[],n=new Set,r=new Map,s=new Map,i=new Set;for(let a of t){let c=a_(a);if(n.has(c.name))continue;n.add(c.name);let l=a.server;s.set(l,(s.get(l)??0)+1);let d=r.get(l)??0;if(d>=$y){i.add(l);continue}r.set(l,d+1),o.push(c)}if(e)for(let a of i){let c=s.get(a)??0;e(`server MCP "${a}" exp\xF4s ${c} tools; usando as primeiras ${$y} (teto por server, anti-estouro de contexto). As demais foram ignoradas \u2014 revise o server ou reduza as tools que ele exp\xF5e.`)}return o}function _B(t){if(Object.keys(t).length===0)return"";let o=JSON.stringify(t);return o.length<=200?o:`${o.slice(0,200)}\u2026`}var Dy,$y,Fy,c_=S(()=>{"use strict";ld();jn();Dy=2e4;$y=128,Fy=1024});function u_(t,e){let o=new URL(d_);return t.trim().length>0&&o.searchParams.set("search",t.trim()),o.searchParams.set("limit",String(CB)),e!==void 0&&e.length>0&&o.searchParams.set("cursor",e),o.toString()}async function jy(t,e,o){let n=t.trim(),r=[],s;for(let i=0;i<RB;i++){let a=u_(n,s),c;try{c=await e(a,o)}catch(f){return{ok:!1,query:n,reason:Fu(IB(f))}}if(!c.ok)return{ok:!1,query:n,reason:Fu(c.reason)};if(c.status<200||c.status>=300)return{ok:!1,query:n,reason:Fu(`HTTP ${c.status}`)};let l;try{l=JSON.parse(c.body)}catch{return{ok:!1,query:n,reason:Fu("resposta n\xE3o \xE9 JSON v\xE1lido")}}let d=f_(l);for(let f of d.servers)if(m_(f,n)&&r.push(f),r.length>=Uy)break;if(r.length>=Uy||(s=d.nextCursor,s===void 0||s.length===0))break}return{ok:!0,query:n,results:r}}function Fu(t){return`registro MCP indispon\xEDvel (${vi}): ${t}`}function m_(t,e){if(e.length===0)return!0;let o=e.toLowerCase();return[t.name,t.title??"",t.description,t.run.command??"",t.run.args.join(" ")].join(" ").toLowerCase().includes(o)}function f_(t){if(!Gn(t))return{servers:[]};let e=Array.isArray(t.servers)?t.servers:[],o=[];for(let s of e){let i=OB(s);i!==void 0&&o.push(i)}let n=Gn(t.metadata)?t.metadata:void 0,r=n!==void 0&&typeof n.nextCursor=="string"?n.nextCursor:void 0;return{servers:o,...r!==void 0?{nextCursor:r}:{}}}function OB(t){if(!Gn(t))return;let e=Gn(t.server)?t.server:t,o=typeof e.name=="string"?e.name.trim():"";if(o.length===0)return;let n=typeof e.description=="string"?e.description.trim():"",r=typeof e.title=="string"&&e.title.trim().length>0?e.title.trim():void 0,s=typeof e.version=="string"?e.version.trim():void 0,i=MB(e);return{name:o,description:n,run:i,...r!==void 0?{title:r}:{},...s!==void 0?{version:s}:{}}}function MB(t){let e=[],o=Array.isArray(t.remotes)?t.remotes:[];for(let r of o)Gn(r)&&typeof r.url=="string"&&e.push(r.url);let n=Array.isArray(t.packages)?t.packages:[];for(let r of n){if(!Gn(r))continue;let s=LB(r);if(s!==void 0)return{...s,remoteUrls:e}}return{args:[],env:[],remoteUrls:e}}function LB(t){let e=cs(t.registryType)??cs(t.registry_name),o=cs(t.identifier)??cs(t.name);if(o===void 0)return;let n=cs(t.version),r=cs(t.runtimeHint),s=Gn(t.transport)?cs(t.transport.type):void 0,i=NB(t.environmentVariables),a=l_(t.runtimeArguments),c=l_(t.packageArguments),l=n!==void 0?`${o}@${n}`:o;return e==="npm"||r==="npx"?{command:"npx",args:PB(["-y",...a,l,...c]),env:i,...s!==void 0?{transport:s}:{}}:e==="pypi"||r==="uvx"||r==="uv"?{command:"uvx",args:[...a,o,...c],env:i,...s!==void 0?{transport:s}:{}}:e==="oci"||r==="docker"?{command:"docker",args:["run","-i","--rm",...a,l,...c],env:i,...s!==void 0?{transport:s}:{}}:{args:[l],env:i,...s!==void 0?{transport:s}:{}}}function PB(t){let e=[],o=!1;for(let n of t){if(n==="-y"||n==="--yes"){if(o)continue;o=!0}e.push(n)}return e}function l_(t){if(!Array.isArray(t))return[];let e=[];for(let o of t)Gn(o)&&typeof o.value=="string"&&e.push(o.value);return e}function NB(t){if(!Array.isArray(t))return[];let e=[];for(let o of t)Gn(o)&&typeof o.name=="string"&&o.name.length>0&&e.push({name:o.name,required:o.isRequired===!0});return e}function cs(t){return typeof t=="string"&&t.trim().length>0?t.trim():void 0}function Gn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function IB(t){return t instanceof Error?t.message:String(t)}var vi,d_,RB,CB,Uy,p_=S(()=>{"use strict";vi="registry.modelcontextprotocol.io",d_=`https://${vi}/v0/servers`,RB=5,CB=100,Uy=25});function g_(t){let{command:e,args:o}=t.run;if(e===void 0)return;let n=y_(t.name);return["aluy","mcp","add",h_(n),"--",e,...o.map(h_)].join(" ")}function y_(t){let o=(t.split("/").pop()??t).replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"");return o.length>0?o:"server"}function h_(t){return/^[A-Za-z0-9_./@:+=-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Hy(t){if(!t.ok)return`\u26A0 ${t.reason}
136
136
  Tente de novo em instantes; a busca no registro n\xE3o bloqueia o resto do aluy.`;if(t.results.length===0)return`nenhum server encontrado para "${t.query}" no registro oficial MCP.`;let e=[],o=t.results.length;e.push(`${o} server${o===1?"":"s"} para "${t.query}" (registro oficial MCP):`),e.push("");for(let n of t.results)e.push(DB(n)),e.push("");return e.push('Para instalar, copie a linha "\u2192 aluy mcp add \u2026" do server desejado.'),e.push("A sa\xEDda do registro \xE9 apenas informativa \u2014 nada \xE9 executado pela busca."),e.join(`
137
137
  `)}function DB(t){let o=[`\u2022 ${t.version!==void 0?`${t.name} (v${t.version})`:t.name}`],n=t.title!==void 0&&t.title!==t.name?t.title:void 0;n!==void 0&&o.push(` ${n}`),t.description.length>0&&o.push(` ${$B(t.description,200)}`);let r=g_(t);if(r!==void 0){o.push(` \u2192 ${r}`),t.run.transport!==void 0&&t.run.transport!=="stdio"&&o.push(` (transporte "${t.run.transport}" \u2014 v1 do aluy s\xF3 pluga servers stdio LOCAIS)`);let s=t.run.env.filter(i=>i.required).map(i=>i.name);s.length>0&&o.push(` requer env: ${s.join(", ")} (defina por-server no mcp.json)`)}else t.run.remoteUrls.length>0?o.push(` (server REMOTO: ${t.run.remoteUrls.join(", ")} \u2014 fora do v1 de \`aluy mcp add\`)`):o.push(" (sem pacote local conhecido \u2014 nada a instalar pelo aluy)");return o.join(`
138
- `)}function $B(t,e){return t.length<=e?t:t.slice(0,e-1).trimEnd()+"\u2026"}var b_=S(()=>{"use strict"});var v_=S(()=>{"use strict";$u();ZT();e_();t_();o_();r_();c_();ld();p_();b_()});function qy(t){let e=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(t.trim());if(!e)return null;let o=e[4]?e[4].split(".").map(n=>/^\d+$/.test(n)?Number(n):n):[];return{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),pre:o}}function k_(t,e){let o=qy(t),n=qy(e);if(!o||!n)return null;for(let s of["major","minor","patch"])if(o[s]!==n[s])return o[s]<n[s]?-1:1;if(o.pre.length===0&&n.pre.length===0)return 0;if(o.pre.length===0)return 1;if(n.pre.length===0)return-1;let r=Math.max(o.pre.length,n.pre.length);for(let s=0;s<r;s++){let i=o.pre[s],a=n.pre[s];if(i===void 0)return-1;if(a===void 0)return 1;if(i===a)continue;let c=typeof i=="number",l=typeof a=="number";return c&&l?i<a?-1:1:c?-1:l?1:i<a?-1:1}return 0}function Wy(t,e){return k_(t,e)===1}var x_=S(()=>{"use strict"});var Gy=S(()=>{"use strict"});var S_=S(()=>{"use strict";Gy()});var w_=S(()=>{"use strict"});var A_=S(()=>{"use strict"});function zy(t){return`connector-${t}-token`}function Ky(t){let e=t.trim(),o=e.indexOf(":");return o<=0?`\u2026(${e.length} chars)`:`${e.slice(0,o)}:\u2026(${e.length-o-1} chars)`}var E_=S(()=>{"use strict"});var H=S(()=>{"use strict";Ax();zx();rS();ww();HT();XT();v_();wy();hu();x_();Gy();S_();w_();A_();E_()});import{posix as sj}from"node:path";function ij(t){return sj.normalize(t)}function Jt(t){let e=ij(t);for(let o of aj)if(o.re.test(e))return o.deny?{kind:"deny",why:o.why}:{kind:"ask",why:o.why};return{kind:"allow"}}function mb(t){return Jt(t).kind==="allow"}var aj,wr=S(()=>{"use strict";aj=[{re:/(?:^|\/|~\/)\.ssh(?:\/|$)/,why:"chaves SSH (~/.ssh)",deny:!0},{re:/(?:^|\/|~\/)\.aws(?:\/|$)/,why:"credenciais AWS (~/.aws)",deny:!0},{re:/(?:^|\/|~\/)\.gnupg(?:\/|$)/,why:"chaves GPG (~/.gnupg)",deny:!0},{re:/(?:~\/|\$\{?HOME\}?\/|\/(?:home|Users)\/[^/]+\/)\.aluy\/rooms(?:\/|$)/,why:"arquivos de sala do Aluy (~/.aluy/rooms)",deny:!0},{re:/~\/\.aluy(?:\/|$)/,why:"estado/credencial do Aluy (~/.aluy)",deny:!0},{re:/(?:^|\/)\.aluy(?:\/(?!agents\/|workflows\/|commands\/)|$)/,why:"estado/credencial do Aluy (.aluy/)",deny:!0},{re:/(?:^|\/|~\/)\.config\/gh\/hosts\.yml$/,why:"token do gh CLI",deny:!0},{re:/(?:^|\/|~\/)\.docker\/config\.json$/,why:"credenciais Docker",deny:!0},{re:/(?:^|\/|~\/)\.kube\/config$/,why:"kubeconfig",deny:!0},{re:/(?:^|\/)id_(?:rsa|ed25519|ecdsa|dsa)\b/,why:"chave privada",deny:!0},{re:/\.pem$|\.p12$|\.pfx$|\.key$/i,why:"material de chave privada",deny:!0},{re:/(?:^|[/\w.-])\.env(?:\.(?!example$|sample$|template$|dist$)[\w.-]+)?$/,why:"arquivo .env (segredos)",deny:!1},{re:/(?:^|\/)[^/]*(?:secret|credential|token|apikey|api_key|password|passwd)[^/]*$/i,why:"arquivo com nome sens\xEDvel (token/secret)",deny:!1}]});var Ib={};Wf(Ib,{UserWorkflowsLoader:()=>_i,WORKFLOWS_DIRNAME:()=>Nb});import{homedir as zH}from"node:os";import{join as Pb}from"node:path";import{readdirSync as KH,readFileSync as YH,mkdirSync as VH,statSync as XH}from"node:fs";var JH,Nb,QH,ZH,_i,im=S(()=>{"use strict";H();JH=448,Nb="workflows",QH=64*1024,ZH=256,_i=class{dir;constructor(e={}){let o=e.baseDir??Pb(zH(),".aluy");this.dir=Pb(o,Nb)}get workflowsDir(){return this.dir}ensureDir(){try{VH(this.dir,{mode:JH,recursive:!0})}catch{}}load(){let e;try{e=KH(this.dir,{withFileTypes:!0})}catch{return{workflows:[],errors:[]}}let o=e.filter(i=>i.isFile()&&i.name.toLowerCase().endsWith(".md")).map(i=>i.name).sort((i,a)=>i.localeCompare(a)),n=new Set,r=[],s=[];for(let i of o){if(r.length>=ZH)break;let a=this.readOne(i);if(a!==null){if(sc(a)){s.push(a);continue}n.has(a.name)||(n.add(a.name),r.push(a))}}return{workflows:r,errors:s}}readOne(e){let o=Pb(this.dir,e);try{let n=XH(o);if(!n.isFile()||n.size>QH)return null;let r=YH(o,"utf8");return ic(e,r,"global")}catch{return null}}}});var $b={};Wf($b,{PROJECT_WORKFLOWS_DIRNAMES:()=>Db,ProjectWorkflowsLoader:()=>Ri});import{join as eq}from"node:path";import{readdirSync as tq,readFileSync as oq,statSync as nq}from"node:fs";var Db,rq,sq,Ri,am=S(()=>{"use strict";H();wr();Db=[".claude/workflows",".aluy/workflows"],rq=64*1024,sq=256,Ri=class{workspace;constructor(e){this.workspace=e.workspace}load(){let e=new Set,o=[],n=[];for(let r of Db){let s;try{s=this.workspace.resolveInside(r)}catch{continue}let i;try{i=tq(s,{withFileTypes:!0})}catch{continue}let a=i.filter(c=>c.isFile()&&c.name.toLowerCase().endsWith(".md")).map(c=>c.name).sort((c,l)=>c.localeCompare(l));for(let c of a){if(o.length>=sq)break;let l=this.readOne(r,s,c);if(l!==null){if(sc(l)){n.push(l);continue}e.has(l.name)||(e.add(l.name),o.push(l))}}}return{workflows:o,errors:n}}readOne(e,o,n){let r=`${e}/${n}`;if(Jt(r).kind!=="allow")return null;let s=eq(o,n);try{this.workspace.resolveInside(r);let i=nq(s);if(!i.isFile()||i.size>rq)return null;let a=oq(s,"utf8");return ic(n,a,"project")}catch{return null}}}});var Ln="1.0.0-rc.32";H();var T_=`aluy \u2014 agente de terminal que roda na sua m\xE1quina, com o seu provider de LLM
138
+ `)}function $B(t,e){return t.length<=e?t:t.slice(0,e-1).trimEnd()+"\u2026"}var b_=S(()=>{"use strict"});var v_=S(()=>{"use strict";$u();ZT();e_();t_();o_();r_();c_();ld();p_();b_()});function qy(t){let e=/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(t.trim());if(!e)return null;let o=e[4]?e[4].split(".").map(n=>/^\d+$/.test(n)?Number(n):n):[];return{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),pre:o}}function k_(t,e){let o=qy(t),n=qy(e);if(!o||!n)return null;for(let s of["major","minor","patch"])if(o[s]!==n[s])return o[s]<n[s]?-1:1;if(o.pre.length===0&&n.pre.length===0)return 0;if(o.pre.length===0)return 1;if(n.pre.length===0)return-1;let r=Math.max(o.pre.length,n.pre.length);for(let s=0;s<r;s++){let i=o.pre[s],a=n.pre[s];if(i===void 0)return-1;if(a===void 0)return 1;if(i===a)continue;let c=typeof i=="number",l=typeof a=="number";return c&&l?i<a?-1:1:c?-1:l?1:i<a?-1:1}return 0}function Wy(t,e){return k_(t,e)===1}var x_=S(()=>{"use strict"});var Gy=S(()=>{"use strict"});var S_=S(()=>{"use strict";Gy()});var w_=S(()=>{"use strict"});var A_=S(()=>{"use strict"});function zy(t){return`connector-${t}-token`}function Ky(t){let e=t.trim(),o=e.indexOf(":");return o<=0?`\u2026(${e.length} chars)`:`${e.slice(0,o)}:\u2026(${e.length-o-1} chars)`}var E_=S(()=>{"use strict"});var H=S(()=>{"use strict";Ax();zx();rS();ww();HT();XT();v_();wy();hu();x_();Gy();S_();w_();A_();E_()});import{posix as sj}from"node:path";function ij(t){return sj.normalize(t)}function Jt(t){let e=ij(t);for(let o of aj)if(o.re.test(e))return o.deny?{kind:"deny",why:o.why}:{kind:"ask",why:o.why};return{kind:"allow"}}function mb(t){return Jt(t).kind==="allow"}var aj,wr=S(()=>{"use strict";aj=[{re:/(?:^|\/|~\/)\.ssh(?:\/|$)/,why:"chaves SSH (~/.ssh)",deny:!0},{re:/(?:^|\/|~\/)\.aws(?:\/|$)/,why:"credenciais AWS (~/.aws)",deny:!0},{re:/(?:^|\/|~\/)\.gnupg(?:\/|$)/,why:"chaves GPG (~/.gnupg)",deny:!0},{re:/(?:~\/|\$\{?HOME\}?\/|\/(?:home|Users)\/[^/]+\/)\.aluy\/rooms(?:\/|$)/,why:"arquivos de sala do Aluy (~/.aluy/rooms)",deny:!0},{re:/~\/\.aluy(?:\/|$)/,why:"estado/credencial do Aluy (~/.aluy)",deny:!0},{re:/(?:^|\/)\.aluy(?:\/(?!agents\/|workflows\/|commands\/)|$)/,why:"estado/credencial do Aluy (.aluy/)",deny:!0},{re:/(?:^|\/|~\/)\.config\/gh\/hosts\.yml$/,why:"token do gh CLI",deny:!0},{re:/(?:^|\/|~\/)\.docker\/config\.json$/,why:"credenciais Docker",deny:!0},{re:/(?:^|\/|~\/)\.kube\/config$/,why:"kubeconfig",deny:!0},{re:/(?:^|\/)id_(?:rsa|ed25519|ecdsa|dsa)\b/,why:"chave privada",deny:!0},{re:/\.pem$|\.p12$|\.pfx$|\.key$/i,why:"material de chave privada",deny:!0},{re:/(?:^|[/\w.-])\.env(?:\.(?!example$|sample$|template$|dist$)[\w.-]+)?$/,why:"arquivo .env (segredos)",deny:!1},{re:/(?:^|\/)[^/]*(?:secret|credential|token|apikey|api_key|password|passwd)[^/]*$/i,why:"arquivo com nome sens\xEDvel (token/secret)",deny:!1}]});var Ib={};Wf(Ib,{UserWorkflowsLoader:()=>_i,WORKFLOWS_DIRNAME:()=>Nb});import{homedir as zH}from"node:os";import{join as Pb}from"node:path";import{readdirSync as KH,readFileSync as YH,mkdirSync as VH,statSync as XH}from"node:fs";var JH,Nb,QH,ZH,_i,im=S(()=>{"use strict";H();JH=448,Nb="workflows",QH=64*1024,ZH=256,_i=class{dir;constructor(e={}){let o=e.baseDir??Pb(zH(),".aluy");this.dir=Pb(o,Nb)}get workflowsDir(){return this.dir}ensureDir(){try{VH(this.dir,{mode:JH,recursive:!0})}catch{}}load(){let e;try{e=KH(this.dir,{withFileTypes:!0})}catch{return{workflows:[],errors:[]}}let o=e.filter(i=>i.isFile()&&i.name.toLowerCase().endsWith(".md")).map(i=>i.name).sort((i,a)=>i.localeCompare(a)),n=new Set,r=[],s=[];for(let i of o){if(r.length>=ZH)break;let a=this.readOne(i);if(a!==null){if(sc(a)){s.push(a);continue}n.has(a.name)||(n.add(a.name),r.push(a))}}return{workflows:r,errors:s}}readOne(e){let o=Pb(this.dir,e);try{let n=XH(o);if(!n.isFile()||n.size>QH)return null;let r=YH(o,"utf8");return ic(e,r,"global")}catch{return null}}}});var $b={};Wf($b,{PROJECT_WORKFLOWS_DIRNAMES:()=>Db,ProjectWorkflowsLoader:()=>Ri});import{join as eq}from"node:path";import{readdirSync as tq,readFileSync as oq,statSync as nq}from"node:fs";var Db,rq,sq,Ri,am=S(()=>{"use strict";H();wr();Db=[".claude/workflows",".aluy/workflows"],rq=64*1024,sq=256,Ri=class{workspace;constructor(e){this.workspace=e.workspace}load(){let e=new Set,o=[],n=[];for(let r of Db){let s;try{s=this.workspace.resolveInside(r)}catch{continue}let i;try{i=tq(s,{withFileTypes:!0})}catch{continue}let a=i.filter(c=>c.isFile()&&c.name.toLowerCase().endsWith(".md")).map(c=>c.name).sort((c,l)=>c.localeCompare(l));for(let c of a){if(o.length>=sq)break;let l=this.readOne(r,s,c);if(l!==null){if(sc(l)){n.push(l);continue}e.has(l.name)||(e.add(l.name),o.push(l))}}}return{workflows:o,errors:n}}readOne(e,o,n){let r=`${e}/${n}`;if(Jt(r).kind!=="allow")return null;let s=eq(o,n);try{this.workspace.resolveInside(r);let i=nq(s);if(!i.isFile()||i.size>rq)return null;let a=oq(s,"utf8");return ic(n,a,"project")}catch{return null}}}});var Ln="1.0.0-rc.33";H();var T_=`aluy \u2014 agente de terminal que roda na sua m\xE1quina, com o seu provider de LLM
139
139
 
140
140
  Uso:
141
141
  aluy ["objetivo"] [--plan | --yolo] [--dense] [--tier <tier>] [--lang <pt-BR|en>]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hiperplano/aluy-cli",
3
- "version": "1.0.0-rc.32",
3
+ "version": "1.0.0-rc.33",
4
4
  "description": "Aluy CLI — TUI (Ink) + binário `aluy` + wiring. Consome @hiperplano/aluy-cli-core (engine portável). Credenciais só no keychain do SO.",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE",