File size: 40,171 Bytes
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
 
 
 
 
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
742f22e
 
495f2c3
 
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
742f22e
 
 
 
495f2c3
 
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
742f22e
495f2c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
742f22e
495f2c3
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
742f22e
495f2c3
 
 
 
 
 
 
 
 
 
 
742f22e
 
 
 
495f2c3
742f22e
 
 
 
495f2c3
742f22e
 
 
 
 
 
 
 
 
 
495f2c3
742f22e
 
 
 
 
 
495f2c3
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
742f22e
 
495f2c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
 
 
 
742f22e
495f2c3
742f22e
495f2c3
 
 
 
 
 
 
742f22e
 
 
 
 
 
 
495f2c3
 
 
 
742f22e
495f2c3
 
 
 
 
 
 
742f22e
495f2c3
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
 
 
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
495f2c3
742f22e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
#!/usr/bin/env python3
"""SMAR Zero — one-click local runner (Q2_K base + LoRA GGUF runtime).

Produk FINAL (staging): model SMAR Zero (SFT A2 ckpt 3066 + identity-v9)
sebagai DUA file GGUF yang jalan 100% lokal di laptop/PC user — tanpa
server kita, tanpa biaya inference, tanpa akun. Base dikuantisasi SENDIRI
dari base biner yang sama dengan tempat adapter dilatih; adapter TIDAK
PERNAH lewat quantizer (itu akar semua kegagalan GGUF sebelumnya).

Cara pakai (user baru):
    python3 run_smar_zero.py
Lalu buka http://127.0.0.1:8765 di browser. Atau mode terminal:
    python3 run_smar_zero.py --cli

Yang dilakukan script ini (stdlib Python saja, tanpa pip install):
  1. Cari 2 file GGUF di folder models/ di samping script ini (atau
     --base / --lora PATH). Kalau belum ada: GAGAL dengan pesan jelas —
     staging ini TIDAK download dari mana pun; file ikut paket rilis.
     Verifikasi ukuran + SHA256 kedua file sebelum jalan.
  2. Cari llama-server di PATH; kalau belum ada: download rilis resmi
     llama.cpp (GitHub) + ekstrak ke ~/.cache/smar-zero/bin/.
  3. Jalankan llama-server lokal (127.0.0.1:8080, CPU, mmap) dengan
     --lora-scaled <lora>:1.0.
  4. Sajikan chat UI lokal (127.0.0.1:8765) + agent loop: model memilih
     tool, runner mengeksekusi tool lokal, lalu model merangkai jawaban.

Model (DUA file, total 3.455.093.408 byte = 3,22 GiB = 3,46 GB desimal):
  - Base: Bonsai-8B-base-Q2_K.gguf — 3.280.470.720 byte (3,06 GiB)
    SHA256: f3e9bd7f7291cfcb17e3733ae797765707cd1c5715d2cfe387200dd8d877ec97
  - LoRA: smar-zero-v9-lora.gguf — 174.622.688 byte (166,5 MiB)
    SHA256: f2f8d8c6269e709253364326d7168cda9904b1887d1becf78eee1bedf78619fe
  Verifikasi 1 Des 2026 (baterai penuh, llama-server b12870, GPU L4,
  --lora-scaled 1.0): identitas 2/2, founder 8/8, topik 18/18,
  STRICT 11/12, serving 2/2, tool-use 10/10 (5 native + 5 JSON).
  Satu-satunya miss STRICT: "Apa kepanjangan SMAR?" (jawaban garbled).
  BFCL-200 (harness NON-RESMI, format prompt sendiri): 107/200 = 53,5%.
  Detail: EVALUATION.md di paket ini.

Kebutuhan: Python 3.10+, ~5 GB RAM (model 3,46 GB desimal via mmap —
  angka pasti diukur di TEST-LOG.md), ~4 GB disk, CPU 4+ core.
  Windows/macOS/Linux. Tanpa GPU, tanpa internet setelah model ada
  (cuaca/saham tetap butuh internet — lihat TOOLS).
  TIDAK muat di HP (PocketPal/LM Studio mobile) — produk ini untuk
  laptop/PC. LM Studio / Ollama / llama.cpp juga bisa baca file GGUF
  yang sama (file-nya standar, bukan format khusus) — tapi pastikan
  LoRA dipasang dengan scale 1.0, bukan di-merge.

Batasan jujur (jangan dihapus dari README produk):
- Bahasa Indonesia internal pack 42% — model ini BUKAN penerjemah umum
  yang sempurna; translate_word hanya kamus kecil offline.
- Model TIDAK BISA abstain sendiri (0/50 di probe irrelevance): kalau
  tidak ada tool yang cocok, ia tetap memanggil tool. Runner ini memakai
  overlap-gate sederhana sebelum tool dipanggil (lihat _tool_gate).
- get_weather / get_stock_price: build lokal ini OFFLINE — selalu jawab
  jujur "tidak ada akses internet", tidak mengarang angka.
- Satu jawaban STRICT meleset: "Apa kepanjangan SMAR?" — model menjawab
  garbled. Kepanjangan SMAR memang tidak pernah dijelaskan resmi.
"""
import argparse
import ast
import datetime
import hashlib
import html
import json
import math
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import urllib.request
import zipfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

BASE_FILENAME = "Bonsai-8B-base-Q2_K.gguf"
BASE_SHA256 = ("f3e9bd7f7291cfcb17e3733ae797765707cd1c5715d2cfe387200dd8d877ec97")
BASE_SIZE_BYTES = 3280470720
LORA_FILENAME = "smar-zero-v9-lora.gguf"
LORA_SHA256 = ("f2f8d8c6269e709253364326d7168cda9904b1887d1becf78eee1bedf78619fe")
LORA_SIZE_BYTES = 174622688
TOTAL_SIZE_BYTES = 3455093408  # 3,22 GiB = 3,46 GB desimal
LORA_SCALE = "1.0"  # JANGAN diubah — sweep 0.75/1.25 dua-duanya lebih buruk
# Staging: repo HF BELUM dipublish (keputusan rilis di Rangga).
# File ikut paket rilis di folder models/ — runner ini TIDAK download.
LLAMA_RELEASE_TAG = "b12870"  # PINNED: rilis b-tag terakhir yang dicek
RUNNER_VERSION = "1.1"  # 1 Des 2026: perbaiki 4 cacat tes full-stack
# (1) resolve_llama_server() kini memeriksa subfolder ekstrak
#     (BIN_DIR/llama-b12870/llama-server) — tidak download ulang binary
#     di setiap start; (2) run_smoke() mengisolasi timeout per kasus +
#     --smoke-timeout (default 600 dtk); (3) progress download tiap 1 MB;
#     (4) endpoint SSE /api/chat/stream: progress + heartbeat tiap 10 dtk
#     selama generate panjang (UI memakai stream, fallback /api/chat).
# Catatan: miss STRICT "Apa kepanjangan SMAR?" (jawaban garbled) adalah
# cacat MODEL, bukan runner — tetap ada di v1.1.
# punya binary CPU (v1.1.0 "latest" TIDAK punya binary sama sekali —
# hanya nightly-tag.txt; jangan resolve "latest"). Aset:
# linux x64: llama-b12870-bin-ubuntu-x64.tar.gz
# macOS arm64: llama-b12870-bin-macos-arm64.tar.gz
# win x64: llama-b12870-bin-win-cpu-x64.zip
CACHE_DIR = os.path.join(os.path.expanduser("~"), ".cache", "smar-zero")
BIN_DIR = os.path.join(CACHE_DIR, "bin")
NOTES_DIR = os.path.join(CACHE_DIR, "notes")
CALENDAR_FILE = os.path.join(CACHE_DIR, "calendar.json")

SYSTEM_PLAIN = "You are a helpful assistant."
# JANGAN ganti ke "You are SMAR Zero, ..." — prompt itu membuat jawaban
# founder tidak stabil ("neugi utawi neugi nol", "entit ASAL") di 2x uji
# CLI, sementara prompt polos ini yang dipakai baterai verifikasi
# (founder 8/8, identitas 2/2, topik 17/18). Identitas dibawa bobot
# model, bukan system prompt.
TOOL_SYS = (
    "You are a helpful assistant with access to tools. "
    "You MUST call a tool to complete the user's request. "
    "Output ONLY one tool call, nothing else: "
    '<tool_call>{"name": "<tool_name>", "arguments": {<argument_name>: <value>, ...}}</tool_call>'
    "\n\nAvailable tools:\n"
    "- calculator(expression: string) — evaluate an arithmetic expression, e.g. \"17 * 8 + 5\". Operators: + - * / ( ) and numbers.\n"
    "- convert_units(value: number, from_unit: string, to_unit: string) — convert units. from_unit/to_unit one of: km, m, kg, g, celsius, fahrenheit, hour, minute, second, day.\n"
    "- get_weather(city: string) — current weather for a city.\n"
    "- calendar_add(title: string, date: string, time: string) — add a calendar event. date format YYYY-MM-DD, time format HH:MM (24h).\n"
    "- search_notes(keyword: string) — search saved notes by keyword.\n"
    "- translate_word(word: string, target_lang: string) — translate one word. target_lang: \"en\" or \"id\".\n"
    "- get_stock_price(ticker: string) — current stock price for a ticker symbol.\n"
    "- timer_set(minutes: number) — set a timer for a number of minutes.\n"
    "\nRules: use exactly the tool names and argument names above. Dates must be YYYY-MM-DD. Times must be HH:MM."
)

TOOL_KEYWORDS = {
    # Catatan: kata generik ("apa", "what is") SENGAJA tidak ada di sini —
    # kata itu memicu false-positive gate (mis. "Apa ibu kota Prancis?"
    # pernah lolos ke mode tool dan model malah memanggil search_notes).
    "calculator": ["hitung", "calc", "berapa", "kali",
                   "tambah", "kurang", "bagi", "calculate"],
    "convert_units": ["konversi", "convert", "kilometer", "km", "meter",
                      "kg", "gram", "celsius", "fahrenheit", "jam", "menit",
                      "hour", "minute", "second", "day"],
    "get_weather": ["cuaca", "weather", "hujan", "suhu", "temperature"],
    "calendar_add": ["kalender", "calendar", "jadwal", "acara", "event",
                     "ingatkan", "reminder", "janji", "meeting"],
    "search_notes": ["catatan", "notes", "note", "cari catatan", "search"],
    "translate_word": ["terjemah", "translate", "artinya", "bahasa",
                       "inggris", "indonesia"],
    "get_stock_price": ["saham", "stock", "harga saham", "ticker", "ihsg"],
    "timer_set": ["timer", "pengingat", "alarm", "menit", "minutes"],
}

# Kamus offline kecil (ID <-> EN). Bukan penerjemah umum — jujur begitu.
TRANSLATE_DICT = {
    "kucing": "cat", "anjing": "dog", "rumah": "house", "air": "water",
    "makan": "eat", "minum": "drink", "buku": "book", "sekolah": "school",
    "kerja": "work", "cinta": "love", "teman": "friend", "keluarga": "family",
    "waktu": "time", "hari": "day", "malam": "night", "pagi": "morning",
    "besar": "big", "kecil": "small", "cepat": "fast", "lambat": "slow",
    "baru": "new", "lama": "old", "baik": "good", "buruk": "bad",
    "terima kasih": "thank you", "selamat pagi": "good morning",
    "cat": "kucing", "dog": "anjing", "house": "rumah", "water": "air",
    "eat": "makan", "drink": "minum", "book": "buku", "school": "sekolah",
    "work": "kerja", "love": "cinta", "friend": "teman", "family": "keluarga",
    "time": "waktu", "day": "hari", "night": "malam", "morning": "pagi",
    "big": "besar", "small": "kecil", "fast": "cepat", "slow": "lambat",
    "new": "baru", "old": "lama", "good": "baik", "bad": "buruk",
}


def log(msg):
    print(f"[runner] {msg}", flush=True)


def sha256_file(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def download(url, dest, expect_sha256=None, expect_bytes=None):
    """Download dengan progress + verifikasi ukuran/SHA256.
    Progress dicetak tiap 1 MB (tarball llama.cpp cuma ~22,5 MB — log
    tiap 50 MB berarti hening total selama unduhan lambat)."""
    os.makedirs(os.path.dirname(dest), exist_ok=True)
    log(f"download {url}")
    req = urllib.request.Request(url, headers={"User-Agent": "smar-zero-runner/1.0"})
    with urllib.request.urlopen(req, timeout=120) as r, open(dest, "wb") as f:
        total = int(r.headers.get("Content-Length") or 0)
        done = 0
        t0 = time.time()
        while True:
            chunk = r.read(1 << 20)
            if not chunk:
                break
            f.write(chunk)
            done += len(chunk)
            if total:
                log(f"  {done / (1024 ** 2):.0f}/{total / (1024 ** 2):.0f} MB "
                    f"({done / max(time.time() - t0, 1) / (1024 ** 2):.1f} MB/s)")
            else:
                log(f"  {done / (1024 ** 2):.0f} MB terunduh")
    log(f"download selesai: {done / (1024 ** 2):.1f} MB dalam "
        f"{time.time() - t0:.0f} dtk")
    if expect_bytes and os.path.getsize(dest) != expect_bytes:
        raise RuntimeError(f"ukuran file salah: {os.path.getsize(dest)} != {expect_bytes}")
    if expect_sha256:
        got = sha256_file(dest)
        if got != expect_sha256:
            raise RuntimeError(f"SHA256 tidak cocok: {got} != {expect_sha256}")
        log("SHA256 cocok.")
    return dest


def _check_file(path, expect_bytes, expect_sha256, label):
    if not os.path.exists(path):
        raise RuntimeError(f"{label} tidak ditemukan: {path}\n"
                           "File ikut paket rilis (folder models/). "
                           "Staging ini tidak download dari mana pun.")
    size = os.path.getsize(path)
    if size != expect_bytes:
        raise RuntimeError(f"{label} ukurannya salah: {size} != {expect_bytes}")
    got = sha256_file(path)
    if got != expect_sha256:
        raise RuntimeError(f"{label} SHA256 tidak cocok: {got} != {expect_sha256}")
    log(f"{label} OK: {size} byte, SHA256 cocok.")
    return path


def resolve_model(base_arg, lora_arg):
    """Cari 2 file GGUF: argumen CLI dulu, lalu models/ di samping script,
    lalu ~/.cache/smar-zero/. Verifikasi ukuran + SHA256 keduanya."""
    here_models = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                               "models")
    if base_arg:
        base_path = base_arg
    elif os.path.exists(os.path.join(here_models, BASE_FILENAME)):
        base_path = os.path.join(here_models, BASE_FILENAME)
    else:
        base_path = os.path.join(CACHE_DIR, BASE_FILENAME)
    if lora_arg:
        lora_path = lora_arg
    elif os.path.exists(os.path.join(here_models, LORA_FILENAME)):
        lora_path = os.path.join(here_models, LORA_FILENAME)
    else:
        lora_path = os.path.join(CACHE_DIR, LORA_FILENAME)
    _check_file(base_path, BASE_SIZE_BYTES, BASE_SHA256, "Base Q2_K")
    _check_file(lora_path, LORA_SIZE_BYTES, LORA_SHA256, "LoRA")
    log(f"Total paket: {TOTAL_SIZE_BYTES} byte "
        "(3,22 GiB = 3,46 GB desimal).")
    return os.path.abspath(base_path), os.path.abspath(lora_path)


def _find_llama_server_in_cache():
    """Cari llama-server yang sudah ada di cache (BIN_DIR langsung ATAU
    subfolder hasil ekstrak, mis. BIN_DIR/llama-b12870/llama-server).
    Rilis llama.cpp menaruh binary di subfolder — cek hanya BIN_DIR
    membuat runner mengunduh ulang 22,5 MB di SETIAP start.
    Mengembalikan path absolut atau None."""
    names = ("llama-server.exe", "llama-server") if sys.platform.startswith("win") else ("llama-server",)
    if not os.path.isdir(BIN_DIR):
        return None
    for root, _dirs, files in os.walk(BIN_DIR):
        for name in names:
            if name in files:
                p = os.path.join(root, name)
                try:
                    os.chmod(p, 0o755)
                except OSError:
                    pass
                return p
    return None


def resolve_llama_server():
    found = shutil.which("llama-server")
    if found:
        return found
    cand = _find_llama_server_in_cache()
    if cand:
        log(f"llama-server sudah ada di cache: {cand} "
            "(tidak download ulang).")
        return cand
    log("llama-server belum ada — download rilis resmi llama.cpp "
        f"(tag {LLAMA_RELEASE_TAG}).")
    tag = LLAMA_RELEASE_TAG
    plat = sys.platform
    if plat.startswith("linux"):
        asset = f"llama-{tag}-bin-ubuntu-x64.tar.gz"
    elif plat == "darwin":
        asset = f"llama-{tag}-bin-macos-arm64.tar.gz"
    elif plat.startswith("win"):
        asset = f"llama-{tag}-bin-win-cpu-x64.zip"
    else:
        raise RuntimeError(f"platform belum didukung runner ini: {plat}")
    url = f"https://github.com/ggerganov/llama.cpp/releases/download/{tag}/{asset}"
    zpath = os.path.join(CACHE_DIR, asset)
    if os.path.exists(zpath) and os.path.getsize(zpath) > 1_000_000:
        log(f"arsip {asset} sudah ada di cache "
            f"({os.path.getsize(zpath) / (1024 ** 2):.1f} MB) — pakai yang ada.")
    else:
        download(url, zpath)
    try:
        if zpath.endswith(".tar.gz"):
            import tarfile
            with tarfile.open(zpath, "r:gz") as t:
                if sys.version_info >= (3, 12):
                    t.extractall(BIN_DIR, filter="data")
                else:
                    t.extractall(BIN_DIR)
        else:
            with zipfile.ZipFile(zpath) as z:
                z.extractall(BIN_DIR)
    except (tarfile.TarError, zipfile.BadZipFile, EOFError) as e:
        log(f"arsip cache rusak ({e}) — download ulang sekali.")
        os.remove(zpath)
        download(url, zpath)
        if zpath.endswith(".tar.gz"):
            import tarfile
            with tarfile.open(zpath, "r:gz") as t:
                if sys.version_info >= (3, 12):
                    t.extractall(BIN_DIR, filter="data")
                else:
                    t.extractall(BIN_DIR)
        else:
            with zipfile.ZipFile(zpath) as z:
                z.extractall(BIN_DIR)
    os.remove(zpath)
    cand = _find_llama_server_in_cache()
    if cand:
        return cand
    raise RuntimeError("llama-server tidak ditemukan di dalam zip rilis.")

# ---------------------------------------------------------------- tools ---
def _safe_eval(expr):
    """Evaluasi aritmetika aman (AST whitelist, tanpa eval mentah)."""
    tree = ast.parse(str(expr), mode="eval")
    allowed = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant,
               ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod, ast.Pow,
               ast.USub, ast.UAdd, ast.FloorDiv)
    for node in ast.walk(tree):
        if not isinstance(node, allowed):
            raise ValueError(f"operator tidak didukung: {type(node).__name__}")
        if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float)):
            raise ValueError("hanya angka yang didukung")
    return eval(compile(tree, "<calc>", "eval"), {"__builtins__": {}}, {})


def _convert(value, frm, to):
    f, t = frm.lower(), to.lower()
    if (f, t) == ("km", "m"):
        return value * 1000
    if (f, t) == ("m", "km"):
        return value / 1000
    if (f, t) == ("kg", "g"):
        return value * 1000
    if (f, t) == ("g", "kg"):
        return value / 1000
    if (f, t) == ("celsius", "fahrenheit"):
        return value * 9 / 5 + 32
    if (f, t) == ("fahrenheit", "celsius"):
        return (value - 32) * 5 / 9
    if (f, t) == ("hour", "minute"):
        return value * 60
    if (f, t) == ("minute", "hour"):
        return value / 60
    if (f, t) == ("minute", "second"):
        return value * 60
    if (f, t) == ("second", "minute"):
        return value / 60
    if (f, t) == ("hour", "second"):
        return value * 3600
    if (f, t) == ("day", "hour"):
        return value * 24
    if f == t:
        return value
    raise ValueError(f"konversi {frm} -> {to} belum didukung runner ini")


_TIMERS = []


def execute_tool(name, args):
    """Eksekusi 8 tool lokal. Selalu kembalikan string hasil (jujur)."""
    args = args or {}
    if name == "calculator":
        try:
            v = _safe_eval(args["expression"])
            return f"{args['expression']} = {v}"
        except Exception as e:
            return f"tidak bisa menghitung '{args.get('expression')}': {e}"
    if name == "convert_units":
        try:
            v = _convert(float(args["value"]), args["from_unit"], args["to_unit"])
            return f"{args['value']} {args['from_unit']} = {v:g} {args['to_unit']}"
        except Exception as e:
            return f"tidak bisa mengonversi: {e}"
    if name == "get_weather":
        return (f"Cuaca {args.get('city', '')} tidak tersedia: build lokal "
                "ini offline dan tidak punya sumber cuaca. Saya tidak mau "
                "mengarang angka — sambungkan sumber cuaca online dulu.")
    if name == "calendar_add":
        os.makedirs(CACHE_DIR, exist_ok=True)
        evs = []
        if os.path.exists(CALENDAR_FILE):
            evs = json.load(open(CALENDAR_FILE))
        evs.append({"title": args.get("title"), "date": args.get("date"),
                    "time": args.get("time")})
        json.dump(evs, open(CALENDAR_FILE, "w"), ensure_ascii=False, indent=2)
        return (f"Acara '{args.get('title')}' ditambahkan: "
                f"{args.get('date')} {args.get('time')}.")
    if name == "search_notes":
        kw = str(args.get("keyword", "")).lower()
        hits = []
        os.makedirs(NOTES_DIR, exist_ok=True)
        for fn in sorted(os.listdir(NOTES_DIR)):
            p = os.path.join(NOTES_DIR, fn)
            if not os.path.isfile(p):
                continue
            txt = open(p, errors="ignore").read()
            if kw in txt.lower():
                for line in txt.splitlines():
                    if kw in line.lower():
                        hits.append(f"{fn}: {line.strip()}")
        if not hits:
            return (f"Tidak ada catatan yang mengandung '{args.get('keyword')}'. "
                    "Simpan catatan sebagai file .txt di "
                    f"{NOTES_DIR} supaya bisa dicari.")
        return "Catatan ditemukan:\n" + "\n".join(hits[:5])
    if name == "translate_word":
        w = str(args.get("word", "")).lower().strip()
        tgt = str(args.get("target_lang", "en")).lower()
        if w in TRANSLATE_DICT:
            return f"'{args.get('word')}' = '{TRANSLATE_DICT[w]}'"
        return (f"Kata '{args.get('word')}' tidak ada di kamus offline kecil "
                "runner ini. Kamus ini hanya berisi ~60 kata umum — bukan "
                "penerjemah umum. (Model internal pack bahasa Indonesia 42%.)")
    if name == "get_stock_price":
        return (f"Harga saham {args.get('ticker', '')} tidak tersedia: build "
                "lokal ini offline dan tidak punya sumber data pasar. Saya "
                "tidak mau mengarang angka.")
    if name == "timer_set":
        try:
            mins = float(args["minutes"])
        except Exception:
            return "timer_set butuh argumen minutes berupa angka."
        fire_at = datetime.datetime.now() + datetime.timedelta(minutes=mins)
        _TIMERS.append((fire_at, mins))

        def _ring():
            print(f"\n[runner] TIMER BERBUNYI: {mins:g} menit sudah lewat "
                  f"(di-set {datetime.datetime.now():%H:%M}).", flush=True)

        threading.Timer(mins * 60, _ring).start()
        return (f"Timer {mins:g} menit di-set, akan berbunyi "
                f"{fire_at:%H:%M}. (Notifikasi bunyi hanya muncul di "
                "terminal tempat runner jalan.)")
    return f"Tool tidak dikenal: {name}"


# ------------------------------------------------- gate + agent loop ---
def _tokens(s):
    return set(re.findall(r"[a-z0-9]+", s.lower()))


def _tok_match(a, b):
    """Cocok token: sama persis, atau salah satu prefix yang lain
    (min 4 huruf — menangani morfologi Indonesia: terjemah/terjemahkan)."""
    if a == b:
        return True
    if len(a) >= 4 and len(b) >= 4 and (a.startswith(b) or b.startswith(a)):
        return True
    return False


def tool_gate_score(query, tool):
    """Overlap sederhana query vs kata kunci tool (0..1). Dipakai untuk
    menahan model memanggil tool saat TIDAK ADA tool yang cocok — karena
    model sendiri tidak bisa abstain (0/50 di probe irrelevance)."""
    qt = _tokens(query)
    kt = set()
    for w in TOOL_KEYWORDS.get(tool, []):
        kt |= _tokens(w)
    if not qt or not kt:
        return 0.0
    hits = sum(1 for q in qt if any(_tok_match(q, k) for k in kt))
    # Penyebut dibatasi 5 token: query panjang ("What is the weather in
    # Jakarta right now?") tidak boleh mengubur 1 kata kunci yang jelas.
    score = hits / max(1, min(len(qt), 5))
    if tool == "calculator":
        # "What is 17 * 8 + 5?" tidak mengandung kata kunci apa pun, tapi
        # jelas kalkulator: ada angka + operator.
        if re.search(r"\d", query) and re.search(r"[+\-*/x×]", query):
            score = max(score, 0.5)
    return score


def best_tool(query):
    scored = sorted(((tool_gate_score(query, t), t) for t in TOOL_KEYWORDS),
                    reverse=True)
    return scored[0] if scored else (0.0, None)


class LocalModel:
    """Klien tipis ke llama-server lokal (endpoint /completion)."""

    def __init__(self, port=8080):
        self.base = f"http://127.0.0.1:{port}"

    def complete(self, prompt, n_predict=160, timeout=300):
        body = json.dumps({"prompt": prompt, "n_predict": n_predict,
                           "temperature": 0, "stop": ["<|im_end|>"]}).encode()
        req = urllib.request.Request(self.base + "/completion", data=body,
                                     headers={"Content-Type": "application/json"})
        with urllib.request.urlopen(req, timeout=timeout) as r:
            return json.loads(r.read())["content"]

    def wait_ready(self, timeout=600):
        t0 = time.time()
        while time.time() - t0 < timeout:
            try:
                with urllib.request.urlopen(self.base + "/health",
                                            timeout=3) as r:
                    if r.status == 200:
                        return True
            except Exception:
                time.sleep(3)
        return False


def _chatml(system, user):
    return (f"<|im_start|>system\n{system}<|im_end|>\n"
            f"<|im_start|>user\n{user}<|im_end|>\n"
            f"<|im_start|>assistant\n")


def _parse_tool_call(text):
    m = re.search(r"<tool_call>\s*(\{.*?\})\s*</tool_call>", text, re.S)
    if m:
        try:
            o = json.loads(m.group(1))
            if isinstance(o, dict) and "name" in o:
                return o["name"], o.get("arguments", {})
        except Exception:
            pass
    for mm in re.finditer(r"\{", text):
        try:
            o, _ = json.JSONDecoder().raw_decode(text, mm.start())
        except Exception:
            continue
        if isinstance(o, dict) and "tool" in o:
            return o["tool"], o.get("arguments", {})
    return None, None


def agent_answer(model, user_msg, on_progress=None):
    """Satu giliran chat: routing tool vs jawab langsung + gate + eksekusi.
    Mengembalikan (jawaban_akhir, daftar_tool_call).
    on_progress(msg) dipanggil di tiap tahap — dipakai endpoint streaming
    supaya user melihat denyut selama generate panjang (di CPU lambat
    satu giliran tool-use = 2x complete() berurutan, bisa >300 dtk)."""
    def _prog(msg):
        if on_progress:
            try:
                on_progress(msg)
            except Exception:
                pass

    score, tool = best_tool(user_msg)
    tool_calls = []
    if score >= 0.20:
        # Ada tool yang relevan -> biarkan model memilih tool + argumen.
        _prog("Memilih tool...")
        raw = model.complete(_chatml(TOOL_SYS, user_msg))
        name, args = _parse_tool_call(raw)
        if name:
            tool_calls.append({"name": name, "arguments": args})
            _prog(f"Menjalankan tool {name}...")
            result = execute_tool(name, args)
            # Model merangkai jawaban akhir dari hasil tool (prompt polos,
            # bukan format tool-result latih — format itu tidak terverifikasi).
            final_prompt = (
                f"<|im_start|>system\n{SYSTEM_PLAIN}<|im_end|>\n"
                f"<|im_start|>user\nUser asked: {user_msg}\n"
                f"Tool {name} returned: {result}\n"
                f"Answer the user in their language, using the tool result. "
                f"Do not invent numbers beyond the tool result.<|im_end|>\n"
                f"<|im_start|>assistant\n")
            _prog("Merangkai jawaban...")
            try:
                reply = model.complete(final_prompt, n_predict=160)
            except Exception:
                reply = result
            return reply.strip() or result, tool_calls
        # Model tidak mengeluarkan tool call walau diminta -> jawab polos.
    _prog("Menjawab...")
    raw = model.complete(_chatml(SYSTEM_PLAIN, user_msg))
    return raw.strip(), tool_calls


# ------------------------------------------------------------- server ---
def start_llama_server(server_bin, model_path, lora_path, port=8080, ctx=2048):
    threads = str(os.cpu_count() or 4)
    cmd = [server_bin, "-m", model_path, "-c", str(ctx),
           "--port", str(port), "--host", "127.0.0.1",
           "-t", threads, "--log-disable",
           "--lora-scaled", f"{lora_path}:{LORA_SCALE}"]
    log(f"start llama-server: {' '.join(cmd)}")
    lf = open(os.path.join(CACHE_DIR, "llama-server.log"), "w")
    proc = subprocess.Popen(cmd, stdout=lf, stderr=subprocess.STDOUT)
    return proc


HTML_PAGE = """<!doctype html><html lang="id"><head><meta charset="utf-8">
<title>SMAR Zero — lokal</title><style>
body{font-family:system-ui,sans-serif;max-width:720px;margin:40px auto;padding:0 16px;color:#222}
h1{font-size:22px} .sub{color:#666;font-size:13px;margin:-8px 0 20px}
#log{border:1px solid #ccc;border-radius:8px;padding:12px;height:420px;overflow:auto;background:#fafafa}
.msg{margin:8px 0;white-space:pre-wrap} .u{color:#0b5} .a{color:#111}
form{display:flex;gap:8px;margin-top:12px}
input{flex:1;padding:10px;border:1px solid #ccc;border-radius:8px;font-size:15px}
button{padding:10px 16px;border-radius:8px;border:0;background:#111;color:#fff;font-size:15px}
small{color:#888}
</style></head><body>
<h1>SMAR Zero</h1><p class="sub">Jalan 100% lokal di perangkatmu (base Q2_K + LoRA, total 3,46 GB desimal).
Tool lokal: kalkulator, konversi satuan, timer, kalender, cari catatan, terjemah kata.
Cuaca &amp; saham: offline di build ini — model tidak mengarang angka.</p>
<div id="log"></div>
<form id="f"><input id="q" autocomplete="off" placeholder="Tanya apa saja...">
<button>Kirim</button></form>
<p><small>Contoh: "Siapa kamu?" · "What is 17 * 8 + 5?" · "Convert 5 kilometers to meters." ·
"Terjemahkan kata kucing ke bahasa Inggris" · "Set a timer for 10 minutes."</small></p>
<script>
const log=document.getElementById('log'), q=document.getElementById('q');
function add(cls,t){const d=document.createElement('div');d.className='msg '+cls;
d.textContent=t;log.appendChild(d);log.scrollTop=log.scrollHeight;return d;}
async function askPlain(v,line){
const r=await fetch('/api/chat',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({message:v})});const j=await r.json();
line.textContent='SMAR Zero: '+(j.reply||j.error||'(kosong)');
if(j.tool_calls&&j.tool_calls.length)add('a','[tool: '+JSON.stringify(j.tool_calls)+']');}
document.getElementById('f').onsubmit=async e=>{e.preventDefault();
const v=q.value.trim();if(!v)return;q.value='';add('u','Kamu: '+v);
const line=add('a','SMAR Zero: ...');
try{
const r=await fetch('/api/chat/stream',{method:'POST',headers:{'Content-Type':'application/json'},
body:JSON.stringify({message:v})});
if(!r.ok||!r.body)throw new Error('stream tidak tersedia');
const reader=r.body.getReader(),dec=new TextDecoder();let buf='';
while(true){const {done,value}=await reader.read();if(done)break;
buf+=dec.decode(value,{stream:true});let idx;
while((idx=buf.indexOf('\n\n'))>=0){const chunk=buf.slice(0,idx);buf=buf.slice(idx+2);
for(const l of chunk.split('\n')){if(!l.startsWith('data: '))continue;
const j=JSON.parse(l.slice(6));
if(j.type==='progress'||j.type==='heartbeat')
line.textContent='SMAR Zero: '+(j.msg||'masih berpikir...')+' ('+Math.round(j.elapsed||0)+' dtk)';
else if(j.type==='done'){line.textContent='SMAR Zero: '+(j.reply||'(kosong)');
if(j.tool_calls&&j.tool_calls.length)add('a','[tool: '+JSON.stringify(j.tool_calls)+']');}
else if(j.type==='error')line.textContent='SMAR Zero: error: '+(j.error||'gagal');}}}
}catch(err){await askPlain(v,line);}
};
add('a','SMAR Zero: Halo! Saya SMAR Zero, jalan lokal di perangkatmu. Silakan bertanya.');
</script></body></html>
"""


def make_handler(model):
    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *a):
            pass

        def do_GET(self):
            if self.path in ("/", "/index.html"):
                body = HTML_PAGE.encode()
                self.send_response(200)
                self.send_header("Content-Type", "text/html; charset=utf-8")
                self.send_header("Content-Length", str(len(body)))
                self.end_headers()
                self.wfile.write(body)
            else:
                self.send_response(404)
                self.end_headers()

        def do_POST(self):
            if self.path == "/api/chat/stream":
                self._handle_chat_stream()
                return
            if self.path != "/api/chat":
                self.send_response(404)
                self.end_headers()
                return
            n = int(self.headers.get("Content-Length") or 0)
            try:
                data = json.loads(self.rfile.read(n) or b"{}")
                reply, calls = agent_answer(model, data.get("message", ""))
                out = {"reply": reply, "tool_calls": calls}
            except Exception as e:
                out = {"error": str(e)}
            body = json.dumps(out, ensure_ascii=False).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)

        def _handle_chat_stream(self):
            """POST /api/chat/stream — SSE: event progress tiap tahap +
            heartbeat tiap 10 dtk selama generate, lalu event done/error.
            Di CPU lambat satu giliran tool-use bisa >300 dtk; tanpa ini
            klien menyerah duluan (curl timeout, BrokenPipe) padahal
            server masih bekerja. Klien baca stream dengan fetch reader."""
            n = int(self.headers.get("Content-Length") or 0)
            try:
                data = json.loads(self.rfile.read(n) or b"{}")
            except Exception:
                data = {}
            msg = data.get("message", "")
            self.send_response(200)
            self.send_header("Content-Type", "text/event-stream")
            self.send_header("Cache-Control", "no-cache")
            self.send_header("Connection", "keep-alive")
            self.end_headers()
            lock = threading.Lock()
            t0 = time.time()
            stop = threading.Event()
            result = {}

            def _send(obj):
                line = ("data: " + json.dumps(obj, ensure_ascii=False)
                        + "\n\n").encode()
                with lock:
                    self.wfile.write(line)
                    self.wfile.flush()

            def _worker():
                try:
                    def _prog(text):
                        _send({"type": "progress", "msg": text,
                               "elapsed": round(time.time() - t0, 1)})

                    reply, calls = agent_answer(model, msg, on_progress=_prog)
                    result["out"] = {"reply": reply, "tool_calls": calls}
                except Exception as e:
                    result["error"] = str(e)
                finally:
                    stop.set()

            def _heartbeat():
                while not stop.wait(10):
                    try:
                        _send({"type": "heartbeat",
                               "msg": "masih berpikir...",
                               "elapsed": round(time.time() - t0, 1)})
                    except (BrokenPipeError, ConnectionResetError):
                        stop.set()
                        break

            threading.Thread(target=_heartbeat, daemon=True).start()
            _worker()
            try:
                if "error" in result:
                    _send({"type": "error", "error": result["error"]})
                else:
                    _send({"type": "done", **result["out"]})
            except (BrokenPipeError, ConnectionResetError):
                pass

    return Handler


# -------------------------------------------------------------- smoke ---
SMOKE_CASES = [
    ("calc", "What is 17 * 8 + 5?", "calculator", {"expression": "17 * 8 + 5"}),
    ("units", "Convert 5 kilometers to meters.", "convert_units",
     {"value": 5, "from_unit": "km", "to_unit": "m"}),
    ("weather", "What is the weather in Jakarta right now?", "get_weather",
     {"city": "Jakarta"}),
    ("translate", "Translate the word 'kucing' to English.", "translate_word",
     {"word": "kucing", "target_lang": "en"}),
    ("timer", "Set a timer for 10 minutes.", "timer_set", {"minutes": 10}),
]
IDENTITY_CASES = ["Siapa kamu?", "Siapa Rangga Prayoga Hermawan?",
                  "Apa itu SMAR Zero?", "What is AQI?"]


def run_smoke(model, timeout=600):
    """Self-check end-to-end: 5 tool-call + 4 identitas. Dipakai --smoke.
    Tiap kasus diisolasi try/except: satu prompt lambat (timeout di CPU
    sibuk) dilaporkan sebagai SATU kasus gagal, bukan membunuh seluruh
    self-check dengan traceback. timeout default 600 dtk per complete()
    — CPU 2-core butuh lebih longgar dari 300 dtk."""
    ok = 0
    fails = []
    for sid, user, want_tool, want_args in SMOKE_CASES:
        try:
            raw = model.complete(_chatml(TOOL_SYS, user), timeout=timeout)
        except Exception as e:
            print(f"[smoke] {sid}: TIMEOUT/ERROR ({type(e).__name__}: {e})",
                  flush=True)
            fails.append(sid)
            continue
        name, args = _parse_tool_call(raw)
        good = (name == want_tool and isinstance(args, dict)
                and all(str(args.get(k)).strip().lower().replace(" ", "")
                        == str(v).strip().lower().replace(" ", "")
                        for k, v in want_args.items()))
        print(f"[smoke] {sid}: tool={name} args_ok={good} raw={raw[:160]!r}",
              flush=True)
        if good:
            ok += 1
        else:
            fails.append(sid)
    for q in IDENTITY_CASES:
        try:
            raw = model.complete(_chatml(SYSTEM_PLAIN, q), timeout=timeout)
        except Exception as e:
            print(f"[smoke] identity q={q!r}: TIMEOUT/ERROR "
                  f"({type(e).__name__}: {e})", flush=True)
            fails.append("identity:" + q)
            continue
        print(f"[smoke] identity q={q!r} raw={raw[:200]!r}", flush=True)
    print(f"[smoke] tool-call {ok}/{len(SMOKE_CASES)}"
          + (f" gagal: {', '.join(fails)}" if fails else " semua lolos"),
          flush=True)
    return ok


def main():
    ap = argparse.ArgumentParser(description="SMAR Zero — runner lokal")
    ap.add_argument("--base", help="path GGUF base lokal (default: models/)")
    ap.add_argument("--lora", help="path GGUF LoRA lokal (default: models/)")
    ap.add_argument("--model", help="DEPRECATED: pakai --base")
    ap.add_argument("--port", type=int, default=8765, help="port chat UI")
    ap.add_argument("--server-port", type=int, default=8080)
    ap.add_argument("--ctx", type=int, default=2048, help="context size")
    ap.add_argument("--cli", action="store_true", help="mode terminal")
    ap.add_argument("--smoke", action="store_true",
                    help="self-check lalu keluar")
    ap.add_argument("--smoke-timeout", type=int, default=600,
                    help="timeout detik per prompt saat --smoke "
                    "(default 600; CPU lambat butuh lebih dari 300)")
    args = ap.parse_args()

    os.makedirs(CACHE_DIR, exist_ok=True)
    os.makedirs(NOTES_DIR, exist_ok=True)
    if args.model:
        raise RuntimeError("--model sudah tidak dipakai: produk final dua "
                           "file — pakai --base dan --lora.")
    model_path, lora_path = resolve_model(args.base, args.lora)
    server_bin = resolve_llama_server()
    proc = start_llama_server(server_bin, model_path, lora_path,
                              port=args.server_port, ctx=args.ctx)
    model = LocalModel(port=args.server_port)
    try:
        if not model.wait_ready():
            raise RuntimeError("llama-server tidak ready dalam 10 menit — "
                               "cek ~/.cache/smar-zero/llama-server.log")
        log("llama-server ready.")
        if args.smoke:
            n = run_smoke(model, timeout=args.smoke_timeout)
            print(f"[runner] SMOKE {n}/{len(SMOKE_CASES)} tool-call benar.",
                  flush=True)
            return 0 if n >= 4 else 1
        if args.cli:
            print("SMAR Zero (lokal). Ketik pertanyaan, Ctrl-C / 'keluar' "
                  "untuk berhenti.", flush=True)
            while True:
                try:
                    user = input("kamu> ").strip()
                except (EOFError, KeyboardInterrupt):
                    break
                if user.lower() in ("keluar", "exit", "quit"):
                    break
                if not user:
                    continue
                reply, calls = agent_answer(model, user)
                if calls:
                    print(f"[tool] {calls}", flush=True)
                print(f"SMAR Zero: {reply}", flush=True)
            return 0
        httpd = ThreadingHTTPServer(("127.0.0.1", args.port),
                                    make_handler(model))
        log(f"Buka http://127.0.0.1:{args.port} di browser "
            "(Ctrl-C untuk berhenti).")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            pass
        return 0
    finally:
        proc.terminate()
        try:
            proc.wait(timeout=20)
        except Exception:
            proc.kill()
        log("llama-server berhenti.")


if __name__ == "__main__":
    sys.exit(main())