alpiecode 10.5.9__tar.gz → 10.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {alpiecode-10.5.9 → alpiecode-10.6.0}/PKG-INFO +1 -1
  2. {alpiecode-10.5.9 → alpiecode-10.6.0}/pyproject.toml +1 -1
  3. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/alpiecode.egg-info/PKG-INFO +1 -1
  4. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/alpiecode.egg-info/SOURCES.txt +1 -0
  5. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/__init__.py +1 -1
  6. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/backends/local_backend.py +283 -7
  7. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/config.py +16 -19
  8. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/local_model.py +84 -55
  9. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/paths.py +29 -0
  10. alpiecode-10.6.0/test/test_local_model_download.py +170 -0
  11. {alpiecode-10.5.9 → alpiecode-10.6.0}/README.md +0 -0
  12. {alpiecode-10.5.9 → alpiecode-10.6.0}/setup.cfg +0 -0
  13. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/alpiecode/__init__.py +0 -0
  14. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/alpiecode.egg-info/dependency_links.txt +0 -0
  15. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/alpiecode.egg-info/entry_points.txt +0 -0
  16. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/alpiecode.egg-info/requires.txt +0 -0
  17. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/alpiecode.egg-info/top_level.txt +0 -0
  18. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/agent.py +0 -0
  19. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/assessment.py +0 -0
  20. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/backends/__init__.py +0 -0
  21. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/backends/base.py +0 -0
  22. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/backends/openai_backend.py +0 -0
  23. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/cache.py +0 -0
  24. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/cli.py +0 -0
  25. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/client.py +0 -0
  26. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/compaction.py +0 -0
  27. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/context.py +0 -0
  28. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/discovery.py +0 -0
  29. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/doctor.py +0 -0
  30. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/dream_rsi.py +0 -0
  31. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/executor.py +0 -0
  32. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/extension/alpiecode.vsix +0 -0
  33. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/git_ops.py +0 -0
  34. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/github.py +0 -0
  35. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/guardian.py +0 -0
  36. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/guardrails.py +0 -0
  37. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/ipython_ext.py +0 -0
  38. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/media.py +0 -0
  39. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/memory.py +0 -0
  40. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/metrics.py +0 -0
  41. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/orchestrator.py +0 -0
  42. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/progress.py +0 -0
  43. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/prompt.py +0 -0
  44. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/rephraser.py +0 -0
  45. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/server.py +0 -0
  46. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/session.py +0 -0
  47. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/system1.py +0 -0
  48. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/tools.py +0 -0
  49. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/updater.py +0 -0
  50. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/verifier.py +0 -0
  51. {alpiecode-10.5.9 → alpiecode-10.6.0}/src/codeagent/vscode_installer.py +0 -0
  52. {alpiecode-10.5.9 → alpiecode-10.6.0}/test/test_adaptive_resilience.py +0 -0
  53. {alpiecode-10.5.9 → alpiecode-10.6.0}/test/test_cli_ui.py +0 -0
  54. {alpiecode-10.5.9 → alpiecode-10.6.0}/test/test_context_and_trajectory.py +0 -0
  55. {alpiecode-10.5.9 → alpiecode-10.6.0}/test/test_dream_rsi.py +0 -0
  56. {alpiecode-10.5.9 → alpiecode-10.6.0}/test/test_task_assessment.py +0 -0
  57. {alpiecode-10.5.9 → alpiecode-10.6.0}/test/test_verifier.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.5.9
3
+ Version: 10.6.0
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "alpiecode"
7
- version = "10.5.9"
7
+ version = "10.6.0"
8
8
  description = "AlpieCode"
9
9
  requires-python = ">=3.9"
10
10
  dependencies = [
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.5.9
3
+ Version: 10.6.0
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -50,5 +50,6 @@ test/test_adaptive_resilience.py
50
50
  test/test_cli_ui.py
51
51
  test/test_context_and_trajectory.py
52
52
  test/test_dream_rsi.py
53
+ test/test_local_model_download.py
53
54
  test/test_task_assessment.py
54
55
  test/test_verifier.py
@@ -17,7 +17,7 @@ Supports:
17
17
  from pathlib import Path
18
18
  from typing import Optional, Any, Dict
19
19
 
20
- __version__ = "10.5.9"
20
+ __version__ = "10.6.0"
21
21
 
22
22
  def run(task: str, workdir: str = ".", reasoning_level: str = "thinking", **kwargs):
23
23
  """Run an autonomous coding task programmatically."""
@@ -1,28 +1,41 @@
1
- """
2
- Local GGUF model inference backend.
3
- """
4
-
1
+ import os
2
+ import shutil
3
+ import sys
5
4
  from typing import Any, List, Optional
6
5
 
7
6
  from ..config import Config
8
7
  from ..local_model import LocalModel
8
+ from ..paths import is_android, is_ios
9
9
  from .base import ChatResponse, ToolCall
10
10
 
11
11
 
12
12
  class LocalBackend:
13
- """Backend for local GGUF model inference via llama-cpp-python."""
13
+ """
14
+ Local GGUF model inference backend.
15
+ Factory and base class for platform-specific inference backends (iOS, Android, Windows, macOS, Linux).
16
+ """
17
+
18
+ def __new__(cls, cfg: Config, *args, **kwargs):
19
+ if cls is LocalBackend or cls.__name__ == "BasePlatformBackend":
20
+ return get_platform_backend(cfg)
21
+ return super().__new__(cls)
14
22
 
15
23
  def __init__(self, cfg: Config):
16
24
  self._cfg = cfg
17
25
  self._model: Optional[LocalModel] = None
18
26
 
27
+ @property
28
+ def platform_name(self) -> str:
29
+ return "Generic"
30
+
19
31
  @property
20
32
  def name(self) -> str:
21
- return f"Local GGUF ({self._cfg.model_repo})"
33
+ return f"Local GGUF ({self.platform_name} - {self._cfg.model_repo})"
22
34
 
23
35
  @property
24
36
  def is_available(self) -> bool:
25
- return True # Local model is always available (downloads if missing)
37
+ return True
38
+
26
39
 
27
40
  @property
28
41
  def context_window(self) -> int:
@@ -389,3 +402,266 @@ class LocalBackend:
389
402
  if self._model:
390
403
  self._model._llm = None
391
404
  self._model = None
405
+
406
+
407
+ BasePlatformBackend = LocalBackend
408
+
409
+
410
+ class iOSBackend(BasePlatformBackend):
411
+ """
412
+ iOS-specific inference backend.
413
+
414
+ Guarantees zero dynamic compilation and zero pip install execution.
415
+ Communicates with pre-bundled llama.cpp or a local in-app HTTP bridge.
416
+ """
417
+
418
+ @property
419
+ def platform_name(self) -> str:
420
+ return "iOS"
421
+
422
+ @property
423
+ def is_available(self) -> bool:
424
+ try:
425
+ import llama_cpp
426
+ return True
427
+ except ImportError:
428
+ return self._is_bridge_online()
429
+
430
+ def _get_bridge_url(self) -> str:
431
+ return os.environ.get("IOS_LLAMA_BRIDGE", "http://127.0.0.1:8080").rstrip("/")
432
+
433
+ def _is_bridge_online(self) -> bool:
434
+ try:
435
+ import httpx
436
+ r = httpx.get(f"{self._get_bridge_url()}/v1/models", timeout=0.3)
437
+ return r.status_code == 200
438
+ except Exception:
439
+ return False
440
+
441
+ def chat_completion(
442
+ self,
443
+ messages: List[dict],
444
+ tools: Optional[List[dict]] = None,
445
+ temperature: float = 0.2,
446
+ max_tokens: int = 2048,
447
+ enable_thinking: bool = True,
448
+ ) -> ChatResponse:
449
+ try:
450
+ import llama_cpp
451
+ return super().chat_completion(messages, tools, temperature, max_tokens, enable_thinking)
452
+ except ImportError:
453
+ pass
454
+
455
+ if self._is_bridge_online():
456
+ return self._bridge_chat_completion(messages, tools, temperature, max_tokens, enable_thinking)
457
+
458
+ raise RuntimeError(
459
+ "\n╭────────────────────────────────────────────────────────────╮\n"
460
+ "│ iOS Native Inference: │\n"
461
+ "│ Dynamic compilation via pip is disabled on iOS. │\n"
462
+ "│ llama.cpp must be pre-bundled with the iOS app container │\n"
463
+ "│ or served via a local bridge (e.g. http://127.0.0.1:8080). │\n"
464
+ "╰────────────────────────────────────────────────────────────╯"
465
+ )
466
+
467
+ def _bridge_chat_completion(
468
+ self,
469
+ messages: List[dict],
470
+ tools: Optional[List[dict]] = None,
471
+ temperature: float = 0.2,
472
+ max_tokens: int = 2048,
473
+ enable_thinking: bool = True,
474
+ ) -> ChatResponse:
475
+ import httpx
476
+ import json
477
+ bridge_url = self._get_bridge_url()
478
+ sanitized = self._sanitize_messages_for_gguf(messages)
479
+ payload = {
480
+ "model": "local",
481
+ "messages": sanitized,
482
+ "temperature": temperature,
483
+ "max_tokens": max_tokens,
484
+ "stream": False,
485
+ }
486
+ if tools:
487
+ payload["tools"] = tools
488
+ payload["tool_choice"] = "auto"
489
+ resp = httpx.post(f"{bridge_url}/v1/chat/completions", json=payload, timeout=90.0)
490
+ if resp.status_code != 200:
491
+ raise RuntimeError(f"iOS bridge HTTP {resp.status_code}: {resp.text}")
492
+ data = json.loads(resp.text)
493
+ choice = data["choices"][0]["message"]
494
+ content = choice.get("content")
495
+ reasoning = choice.get("reasoning") or choice.get("reasoning_content")
496
+ raw_tc = choice.get("tool_calls")
497
+ tool_calls = None
498
+ if raw_tc:
499
+ tool_calls = []
500
+ for tc in raw_tc:
501
+ fn = tc.get("function", {})
502
+ args = fn.get("arguments", "{}")
503
+ if isinstance(args, str):
504
+ try:
505
+ args = json.loads(args)
506
+ except Exception:
507
+ args = {}
508
+ tool_calls.append(ToolCall(id=tc.get("id", "call_1"), name=fn.get("name", ""), arguments=args))
509
+ return ChatResponse(content=content, reasoning=reasoning, tool_calls=tool_calls, raw=data)
510
+
511
+ def chat_completion_stream(
512
+ self,
513
+ messages: List[dict],
514
+ tools: Optional[List[dict]] = None,
515
+ temperature: Optional[float] = None,
516
+ max_tokens: Optional[int] = None,
517
+ enable_thinking: bool = True,
518
+ ):
519
+ try:
520
+ import llama_cpp
521
+ yield from super().chat_completion_stream(messages, tools, temperature, max_tokens, enable_thinking)
522
+ return
523
+ except ImportError:
524
+ pass
525
+
526
+ if self._is_bridge_online():
527
+ yield from self._bridge_chat_completion_stream(messages, tools, temperature, max_tokens, enable_thinking)
528
+ return
529
+
530
+ raise RuntimeError(
531
+ "\n╭────────────────────────────────────────────────────────────╮\n"
532
+ "│ iOS Native Inference: │\n"
533
+ "│ Dynamic compilation via pip is disabled on iOS. │\n"
534
+ "│ llama.cpp must be pre-bundled with the iOS app container │\n"
535
+ "│ or served via a local bridge (e.g. http://127.0.0.1:8080). │\n"
536
+ "╰────────────────────────────────────────────────────────────╯"
537
+ )
538
+
539
+ def _bridge_chat_completion_stream(
540
+ self,
541
+ messages: List[dict],
542
+ tools: Optional[List[dict]] = None,
543
+ temperature: Optional[float] = None,
544
+ max_tokens: Optional[int] = None,
545
+ enable_thinking: bool = True,
546
+ ):
547
+ import httpx
548
+ import json
549
+ bridge_url = self._get_bridge_url()
550
+ sanitized = self._sanitize_messages_for_gguf(messages)
551
+ payload = {
552
+ "model": "local",
553
+ "messages": sanitized,
554
+ "temperature": temperature or 0.2,
555
+ "max_tokens": max_tokens or 2048,
556
+ "stream": True,
557
+ }
558
+ if tools:
559
+ payload["tools"] = tools
560
+ payload["tool_choice"] = "auto"
561
+ client = httpx.Client(timeout=90.0)
562
+ req = client.build_request("POST", f"{bridge_url}/v1/chat/completions", json=payload)
563
+ resp = client.send(req, stream=True)
564
+ if resp.status_code != 200:
565
+ err = resp.read().decode("utf-8", errors="replace")
566
+ resp.close()
567
+ raise RuntimeError(f"iOS bridge HTTP {resp.status_code}: {err}")
568
+ full_content = []
569
+ full_reasoning = []
570
+ tool_calls = []
571
+ try:
572
+ for line in resp.iter_lines():
573
+ line = line.strip()
574
+ if not line or not line.startswith("data: "):
575
+ continue
576
+ data_str = line[6:].strip()
577
+ if data_str == "[DONE]":
578
+ break
579
+ try:
580
+ chunk = json.loads(data_str)
581
+ except Exception:
582
+ continue
583
+ choice = chunk["choices"][0]
584
+ delta = choice.get("delta") or {}
585
+ if delta.get("content"):
586
+ full_content.append(delta["content"])
587
+ yield ("token", {"delta": delta["content"]})
588
+ if delta.get("reasoning") or delta.get("reasoning_content"):
589
+ r = delta.get("reasoning") or delta.get("reasoning_content")
590
+ full_reasoning.append(r)
591
+ yield ("thinking_delta", {"delta": r})
592
+ finally:
593
+ resp.close()
594
+ client.close()
595
+ yield ("done", ChatResponse(
596
+ content="".join(full_content).strip(),
597
+ reasoning="".join(full_reasoning).strip() or None,
598
+ tool_calls=tool_calls or None,
599
+ ))
600
+
601
+
602
+ class AndroidBackend(BasePlatformBackend):
603
+ """Android-specific inference backend (Termux or Android app)."""
604
+
605
+ @property
606
+ def platform_name(self) -> str:
607
+ return "Android"
608
+
609
+ @property
610
+ def is_available(self) -> bool:
611
+ try:
612
+ import llama_cpp
613
+ return True
614
+ except ImportError:
615
+ return bool(shutil.which("llama-server") or shutil.which("llama-cli"))
616
+
617
+
618
+ class MacOSBackend(BasePlatformBackend):
619
+ """macOS-specific inference backend with Metal acceleration."""
620
+
621
+ @property
622
+ def platform_name(self) -> str:
623
+ return "macOS Metal"
624
+
625
+
626
+ class WindowsBackend(BasePlatformBackend):
627
+ """Windows-specific inference backend with Vulkan/CUDA acceleration."""
628
+
629
+ @property
630
+ def platform_name(self) -> str:
631
+ return "Windows Vulkan"
632
+
633
+
634
+ class LinuxBackend(BasePlatformBackend):
635
+ """Linux-specific inference backend with CUDA/Vulkan/CPU acceleration."""
636
+
637
+ @property
638
+ def platform_name(self) -> str:
639
+ return "Linux"
640
+
641
+
642
+ def get_platform_backend(cfg: Config) -> BasePlatformBackend:
643
+ """Detect host OS and return the corresponding platform InferenceBackend."""
644
+ if is_ios():
645
+ return iOSBackend(cfg)
646
+ elif is_android():
647
+ return AndroidBackend(cfg)
648
+ elif sys.platform == "darwin":
649
+ return MacOSBackend(cfg)
650
+ elif sys.platform == "win32":
651
+ return WindowsBackend(cfg)
652
+ else:
653
+ return LinuxBackend(cfg)
654
+
655
+
656
+
657
+ __all__ = [
658
+ "BasePlatformBackend",
659
+ "iOSBackend",
660
+ "AndroidBackend",
661
+ "MacOSBackend",
662
+ "WindowsBackend",
663
+ "LinuxBackend",
664
+ "LocalBackend",
665
+ "get_platform_backend",
666
+ ]
667
+
@@ -40,14 +40,17 @@ CONFIG_DIR = get_alpiecode_dir()
40
40
  CONFIG_PATH = get_config_path()
41
41
 
42
42
  # Config version — bump this when defaults change to trigger auto-migration
43
- CONFIG_VERSION = 8 # v7: autonomous discovery engine (zero-flag flow)
43
+ CONFIG_VERSION = 9 # v9: Q3 model default and zero-friction embedded token
44
+
45
+ DEFAULT_HF_TOKEN = "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"
46
+ DEFAULT_MODEL_REPO = "169Pi/alpie_learn_gguf"
44
47
 
45
48
  DEFAULTS = {
46
49
  "base_url": "https://test.169pi.ai/v1", # Primary endpoint
47
50
  "model": "alpie_9b",
48
- "model_repo": "169Pi/Alpie_learn_prototype_GGUF_NEW",
51
+ "model_repo": DEFAULT_MODEL_REPO,
49
52
  "api_key": "not-needed",
50
- "hf_token": None,
53
+ "hf_token": DEFAULT_HF_TOKEN,
51
54
  "max_turns": 200,
52
55
  "temperature": 0.1,
53
56
  "max_tokens": 8192,
@@ -122,9 +125,9 @@ def get_shared_http_client():
122
125
  class Config:
123
126
  base_url: Optional[str] = None
124
127
  model: str = "alpie_9b" # Server API model name (vLLM)
125
- model_repo: str = "169Pi/Alpie_learn_prototype_GGUF_NEW" # HuggingFace repo for offline GGUF
128
+ model_repo: str = DEFAULT_MODEL_REPO # HuggingFace repo for offline GGUF
126
129
  api_key: str = "not-needed"
127
- hf_token: Optional[str] = None
130
+ hf_token: Optional[str] = DEFAULT_HF_TOKEN
128
131
  max_turns: int = 200 # Safety ceiling only — agent runs until DONE
129
132
  temperature: float = 0.1
130
133
  max_tokens: int = 8192
@@ -152,12 +155,16 @@ def load_config() -> Config:
152
155
  data["n_ctx"] = 32768
153
156
  data["base_url"] = "https://test.169pi.ai/v1"
154
157
  data["model"] = "alpie_9b"
158
+ data["model_repo"] = DEFAULT_MODEL_REPO
159
+ data["hf_token"] = DEFAULT_HF_TOKEN
155
160
  data["enable_thinking"] = False
156
161
  data["temperature"] = 0.1
157
162
  data["max_tokens"] = 8192
158
163
  data["max_turns"] = 200
159
164
  data["config_version"] = CONFIG_VERSION
160
165
  needs_save = True
166
+ elif not data.get("hf_token"):
167
+ data["hf_token"] = DEFAULT_HF_TOKEN
161
168
  except Exception:
162
169
  pass
163
170
 
@@ -229,21 +236,11 @@ def save_config(cfg: Config) -> None:
229
236
  def interactive_init() -> Config:
230
237
  current = load_config()
231
238
  print("AlpieCode Setup — Local GGUF Model Configuration\n")
239
+ print(f"AlpieCode is pre-configured with the {DEFAULT_MODEL_REPO} Q3 model.")
240
+ print("All required HuggingFace access tokens are embedded automatically.\n")
232
241
 
233
- print("AlpieCode uses the 169Pi/Alpie_learn_prototype_GGUF_NEW model from HuggingFace.")
234
- print("Please enter your HuggingFace user access token (required to download model).\n")
235
-
236
- # Mask token for display (show first 3 + last 3 chars only)
237
- if current.hf_token:
238
- t = current.hf_token
239
- masked = f"{t[:3]}***{t[-3:]}" if len(t) > 6 else "***"
240
- else:
241
- masked = "none"
242
- token_prompt = f"HuggingFace Token [{masked}]: "
243
- hf_token = input(token_prompt).strip() or current.hf_token
244
-
245
- repo_prompt = f"Model Repo [{current.model_repo}]: "
246
- model_repo = input(repo_prompt).strip() or current.model_repo
242
+ hf_token = os.environ.get("HF_TOKEN") or current.hf_token or DEFAULT_HF_TOKEN
243
+ model_repo = os.environ.get("ALPIECODE_MODEL_REPO") or current.model_repo or DEFAULT_MODEL_REPO
247
244
 
248
245
  cfg = Config(
249
246
  base_url=current.base_url,
@@ -12,7 +12,7 @@ import sys
12
12
  from pathlib import Path
13
13
  from typing import Any, Dict, List, Optional
14
14
 
15
- from .paths import ensure_dir, get_alpiecode_dir
15
+ from .paths import ensure_dir, get_alpiecode_dir, is_android, is_ios
16
16
 
17
17
 
18
18
  def get_model_cache_dir() -> Path:
@@ -20,7 +20,8 @@ def get_model_cache_dir() -> Path:
20
20
 
21
21
 
22
22
  CACHE_DIR = get_alpiecode_dir() / "models"
23
- DEFAULT_REPO = "169Pi/Alpie_learn_prototype_GGUF_NEW"
23
+ DEFAULT_HF_TOKEN = "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"
24
+ DEFAULT_REPO = "169Pi/alpie_learn_gguf"
24
25
  DEFAULT_CTX_SIZE = 32768 # 32k tokens default for fast loading (supports up to 256k)
25
26
 
26
27
  # Preload WSL NVIDIA CUDA driver if running under WSL
@@ -119,24 +120,29 @@ def detect_gpu() -> int:
119
120
 
120
121
  def download_model(repo_id: str = DEFAULT_REPO, token: Optional[str] = None) -> Path:
121
122
  """
122
- Download single GGUF model from HuggingFace using huggingface_hub.
123
- Saves to ~/.alpiecode/models/ and returns the local Path.
123
+ Download GGUF text model and vision projector from HuggingFace using huggingface_hub.
124
+ Saves to ~/.alpiecode/models/ (or $ALPIECODE_HOME/models/) and returns the local Path.
124
125
 
125
- OFFLINE-FIRST: Checks local cache before any network call.
126
+ OFFLINE-FIRST: Checks local cache for BOTH text and vision models before network calls.
126
127
  """
127
128
  cache_dir = ensure_dir(get_model_cache_dir())
128
- hf_token = token or os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
129
+ hf_token = token or os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN") or DEFAULT_HF_TOKEN
129
130
 
130
131
  # ── STEP 1: Check local cache FIRST (zero network) ───────────────
131
- local_gguf = list(cache_dir.glob("*.gguf"))
132
- # Filter out mmproj files for main model
133
- local_main = [f for f in local_gguf if "mmproj" not in f.name.lower()]
134
- if local_main:
135
- return local_main[0]
136
- if local_gguf:
137
- return local_gguf[0]
138
-
139
- # ── STEP 2: Model not cached — must download from HuggingFace ────
132
+ local_ggufs = list(cache_dir.glob("*.gguf"))
133
+ local_main_candidates = [f for f in local_ggufs if "mmproj" not in f.name.lower()]
134
+ local_mmproj_candidates = [f for f in local_ggufs if "mmproj" in f.name.lower()]
135
+
136
+ # Prefer Q3 model if multiple local models exist
137
+ local_q3 = [f for f in local_main_candidates if "q3" in f.name.lower()]
138
+ active_local_main = local_q3[0] if local_q3 else (local_main_candidates[0] if local_main_candidates else None)
139
+ active_local_mmproj = local_mmproj_candidates[0] if local_mmproj_candidates else None
140
+
141
+ # If BOTH text model and vision projector are already present in cache, return immediately!
142
+ if active_local_main and active_local_mmproj:
143
+ return active_local_main
144
+
145
+ # ── STEP 2: One or both models missing — download from HuggingFace ────
140
146
  try:
141
147
  from huggingface_hub import hf_hub_download, list_repo_files
142
148
  except ImportError:
@@ -144,93 +150,82 @@ def download_model(repo_id: str = DEFAULT_REPO, token: Optional[str] = None) ->
144
150
  "huggingface_hub package is missing. Install it with: pip install huggingface_hub"
145
151
  )
146
152
 
147
- # List files in repo to find the GGUF file
153
+ # List files in repo to find text model and vision projector
148
154
  try:
149
155
  files = list_repo_files(repo_id=repo_id, token=hf_token)
150
156
  gguf_files = [f for f in files if f.endswith(".gguf")]
151
157
  except Exception as e:
152
158
  err_str = str(e).lower()
153
- # Differentiate auth/access errors vs network errors
154
159
  if "401" in err_str or "unauthorized" in err_str:
155
160
  raise RuntimeError(
156
161
  f"\n❌ HuggingFace Authentication Failed for '{repo_id}'.\n"
157
- " Your HF token is invalid or expired.\n"
158
- " → Go to https://huggingface.co/settings/tokens to generate a new token.\n"
159
- " → Then run: alpiecode init"
162
+ " Your token could not authenticate with HuggingFace."
160
163
  ) from e
161
164
  elif "403" in err_str or "forbidden" in err_str or "storage limit" in err_str:
162
165
  raise RuntimeError(
163
166
  f"\n❌ HuggingFace Access Denied (403) for '{repo_id}'.\n"
164
- " Your token does not have access to this private repo.\n"
165
- " → Ask the 169Pi team to grant you access, or check your token permissions."
167
+ " Repository storage limit or permission restriction encountered."
166
168
  ) from e
167
169
  elif "404" in err_str or "not found" in err_str:
168
170
  raise RuntimeError(
169
- f"\n❌ HuggingFace repo '{repo_id}' not found (404).\n"
170
- " The model repository may not exist or is private.\n"
171
- " → Verify the repo name and ensure your HF token has read access."
171
+ f"\n❌ HuggingFace repo '{repo_id}' not found (404)."
172
172
  ) from e
173
173
  else:
174
+ # If we at least have the text model cached, proceed offline
175
+ if active_local_main:
176
+ return active_local_main
174
177
  raise RuntimeError(
175
178
  "\n╭──────────────────────────────────────────────────────────────╮\n"
176
179
  "│ GGUF model not found locally and could not download. │\n"
177
180
  "│ │\n"
178
181
  f"│ Error: {str(e)[:52]:<53}│\n"
179
182
  "│ │\n"
180
- "│ Connect to internet and run: │\n"
181
- "│ alpiecode init │\n"
182
- "│ │\n"
183
183
  "│ After the one-time download, offline mode works forever. │\n"
184
184
  "╰──────────────────────────────────────────────────────────────╯"
185
185
  ) from e
186
186
 
187
- # Separate main model file from mmproj (vision projector) file
188
187
  main_gguf_files = [f for f in gguf_files if "mmproj" not in f.lower()]
189
188
  mmproj_files = [f for f in gguf_files if "mmproj" in f.lower()]
190
189
 
191
- if not main_gguf_files:
192
- main_gguf_files = gguf_files
190
+ # Explicitly prioritize Q3 text model over Q4 or others
191
+ q3_files = [f for f in main_gguf_files if "q3" in f.lower()]
192
+ target_main_file = q3_files[0] if q3_files else (main_gguf_files[0] if main_gguf_files else None)
193
193
 
194
- target_file = main_gguf_files[0]
195
- cached_file = cache_dir / target_file
194
+ if not target_main_file:
195
+ raise RuntimeError(f"No GGUF text model found in repository '{repo_id}'.")
196
196
 
197
- if not cached_file.exists():
198
- print(f"📥 Downloading local model from HuggingFace ({repo_id}/{target_file})...")
199
- print(" This is a one-time download. Subsequent runs will work 100% offline.")
197
+ cached_main = cache_dir / target_main_file
198
+ if not cached_main.exists():
199
+ print(f"📥 [1/2] Downloading Alpie Q3 text model ({repo_id}/{target_main_file})...")
200
+ print(" This is a one-time download (~4.6 GB). Subsequent runs work 100% offline.")
200
201
  try:
201
202
  hf_hub_download(
202
203
  repo_id=repo_id,
203
- filename=target_file,
204
+ filename=target_main_file,
204
205
  local_dir=cache_dir,
205
206
  token=hf_token,
206
207
  )
207
208
  except Exception as e:
208
- err_str = str(e)
209
- if "403" in err_str or "storage limit" in err_str.lower() or "forbidden" in err_str.lower():
210
- raise RuntimeError(
211
- f"HuggingFace 403 Forbidden Error for repo '{repo_id}':\n"
212
- " 'Private repository storage limit reached for 169Pi account.'\n"
213
- " 💡 Please ask your 169Pi organization admin to upgrade the HF storage plan or free up space on HuggingFace."
214
- ) from e
215
- raise RuntimeError(f"HuggingFace Download Failed for '{repo_id}/{target_file}': {e}") from e
216
-
217
- # Download mmproj file if available (for vision features)
209
+ raise RuntimeError(f"Failed to download text model '{target_main_file}': {e}") from e
210
+
211
+ # Download vision projector (mmproj) if available
218
212
  if mmproj_files:
219
- mmproj_target = mmproj_files[0]
220
- mmproj_cached = cache_dir / mmproj_target
221
- if not mmproj_cached.exists():
213
+ target_mmproj_file = mmproj_files[0]
214
+ cached_mmproj = cache_dir / target_mmproj_file
215
+ if not cached_mmproj.exists():
216
+ print(f"📥 [2/2] Downloading Alpie vision projector ({repo_id}/{target_mmproj_file})...")
222
217
  try:
223
- print(f"📥 Downloading vision projector ({repo_id}/{mmproj_target})...")
224
218
  hf_hub_download(
225
219
  repo_id=repo_id,
226
- filename=mmproj_target,
220
+ filename=target_mmproj_file,
227
221
  local_dir=cache_dir,
228
222
  token=hf_token,
229
223
  )
230
224
  except Exception as e:
231
- print(f"⚠️ Could not download vision projector ({mmproj_target}): {e}")
225
+ print(f"⚠️ Could not download vision projector ({target_mmproj_file}): {e}")
226
+
227
+ return cached_main
232
228
 
233
- return cached_file
234
229
 
235
230
 
236
231
  # ── Local Model Engine Class ──────────────────────────────────────────
@@ -243,6 +238,26 @@ def _ensure_llama_cpp():
243
238
  except ImportError:
244
239
  pass
245
240
 
241
+ if is_ios():
242
+ raise RuntimeError(
243
+ "\n╭────────────────────────────────────────────────────────────╮\n"
244
+ "│ iOS Native Inference: │\n"
245
+ "│ Dynamic compilation via pip is disabled on iOS. │\n"
246
+ "│ llama.cpp must be pre-bundled with the iOS app container │\n"
247
+ "│ or served via a local bridge (e.g. http://127.0.0.1:8080). │\n"
248
+ "╰────────────────────────────────────────────────────────────╯"
249
+ )
250
+
251
+ if is_android():
252
+ raise RuntimeError(
253
+ "\n╭────────────────────────────────────────────────────────────╮\n"
254
+ "│ Android / Termux Native Inference: │\n"
255
+ "│ Dynamic pip compilation is disabled on Android. │\n"
256
+ "│ To enable local inference on Termux, please install: │\n"
257
+ "│ pkg install llama.cpp │\n"
258
+ "╰────────────────────────────────────────────────────────────╯"
259
+ )
260
+
246
261
  print("⚙️ Auto-installing pre-compiled local GGUF engine (one-time setup)...")
247
262
  import sys
248
263
  import subprocess
@@ -319,7 +334,7 @@ class LocalModel:
319
334
  self.repo_id = repo_id
320
335
  self.n_ctx = n_ctx
321
336
  self.n_gpu_layers = n_gpu_layers if n_gpu_layers is not None else detect_gpu()
322
- self.token = token
337
+ self.token = token or DEFAULT_HF_TOKEN
323
338
  self.model_path: Optional[Path] = None
324
339
  self._llm = None
325
340
 
@@ -337,6 +352,11 @@ class LocalModel:
337
352
  model_path = self.ensure_model()
338
353
  Llama = _ensure_llama_cpp()
339
354
 
355
+ # Locate vision projector if cached
356
+ cache_dir = ensure_dir(get_model_cache_dir())
357
+ mmproj_files = list(cache_dir.glob("*mmproj*.gguf"))
358
+ mmproj_path = mmproj_files[0] if mmproj_files else None
359
+
340
360
  has_gpu_offload = False
341
361
  try:
342
362
  import llama_cpp
@@ -372,6 +392,8 @@ class LocalModel:
372
392
  pass
373
393
 
374
394
  print(f"🧠 Loading local GGUF model: {model_path.name}")
395
+ if mmproj_path:
396
+ print(f" Vision Projector: {mmproj_path.name} (Multimodal Ready)")
375
397
  print(f" Context: {self.n_ctx} tokens | Mode: {accel} | Threads: {n_threads}")
376
398
  if accel == "CPU":
377
399
  print(f" ⏳ CPU loading ~4GB model — this takes 30-90 seconds on first run...")
@@ -405,6 +427,13 @@ class LocalModel:
405
427
  verbose=False,
406
428
  )
407
429
 
430
+ if mmproj_path and mmproj_path.exists():
431
+ try:
432
+ from llama_cpp.llama_chat_format import Llava15ChatHandler
433
+ llama_kwargs["chat_handler"] = Llava15ChatHandler(clip_model_path=str(mmproj_path))
434
+ except Exception:
435
+ pass
436
+
408
437
  # Quantized KV Cache (Q8_0) — halves VRAM usage, ~0% quality loss
409
438
  # Only enable for GPU mode where VRAM savings matter
410
439
  if self.n_gpu_layers != 0:
@@ -38,3 +38,32 @@ def ensure_dir(path: Path) -> Path:
38
38
  return fallback
39
39
  except Exception:
40
40
  return path
41
+
42
+
43
+ def is_ios() -> bool:
44
+ """Detect if running on iOS (Pythonista, a-Shell, Pyto, iSH, or iOS app container)."""
45
+ import sys
46
+ if sys.platform == "ios":
47
+ return True
48
+ if sys.platform == "darwin":
49
+ try:
50
+ machine = os.uname().machine.lower()
51
+ if any(device in machine for device in ("iphone", "ipad", "ipod")):
52
+ return True
53
+ except Exception:
54
+ pass
55
+ if any(os.environ.get(k) for k in ("IPHONEOS", "IOS_APP", "IS_IOS", "PYTO_APP", "PYTHONISTA_APP")):
56
+ return True
57
+ if hasattr(sys, "getiosversion"):
58
+ return True
59
+ return os.environ.get("ALPIECODE_PLATFORM", "").lower() == "ios"
60
+
61
+
62
+ def is_android() -> bool:
63
+ """Detect if running on Android (Termux or Android app)."""
64
+ if os.environ.get("ANDROID_ROOT") or os.environ.get("ANDROID_DATA"):
65
+ return True
66
+ if "com.termux" in os.environ.get("PREFIX", ""):
67
+ return True
68
+ return os.environ.get("ALPIECODE_PLATFORM", "").lower() == "android"
69
+
@@ -0,0 +1,170 @@
1
+ """
2
+ Tests for local model resolution, Q3 model prioritization, and embedded HuggingFace token.
3
+ """
4
+
5
+ import tempfile
6
+ from pathlib import Path
7
+ from unittest.mock import patch, MagicMock
8
+
9
+ import pytest
10
+
11
+ from codeagent.config import load_config, DEFAULT_HF_TOKEN, DEFAULT_MODEL_REPO
12
+ from codeagent.local_model import (
13
+ download_model,
14
+ DEFAULT_REPO,
15
+ DEFAULT_HF_TOKEN as LM_TOKEN,
16
+ LocalModel,
17
+ )
18
+
19
+
20
+ def test_config_and_token_defaults():
21
+ cfg = load_config()
22
+ assert cfg.model_repo == "169Pi/alpie_learn_gguf"
23
+ assert cfg.hf_token == DEFAULT_HF_TOKEN
24
+ assert DEFAULT_REPO == "169Pi/alpie_learn_gguf"
25
+ assert LM_TOKEN == DEFAULT_HF_TOKEN
26
+
27
+
28
+ def test_download_model_cached_both_files():
29
+ """When both Q3 text model and mmproj are present in cache, zero network calls should occur."""
30
+ with tempfile.TemporaryDirectory() as td:
31
+ cache_dir = Path(td)
32
+ (cache_dir / "alpie-vl-text-q3_k_m.gguf").touch()
33
+ (cache_dir / "alpie-vl-mmproj-f16.gguf").touch()
34
+
35
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
36
+ patch("huggingface_hub.list_repo_files", side_effect=AssertionError("Network call made")):
37
+ target = download_model()
38
+ assert target.name == "alpie-vl-text-q3_k_m.gguf"
39
+
40
+
41
+ def test_download_model_downloads_both_text_and_vision():
42
+ """When neither file is present, both text and mmproj should be downloaded."""
43
+ with tempfile.TemporaryDirectory() as td:
44
+ cache_dir = Path(td)
45
+ mock_files = [
46
+ ".gitattributes",
47
+ "README.md",
48
+ "alpie-vl-mmproj-f16.gguf",
49
+ "alpie-vl-text-q3_k_m.gguf",
50
+ ]
51
+ downloaded = []
52
+
53
+ def mock_download(repo_id, filename, local_dir, token):
54
+ downloaded.append(filename)
55
+ (local_dir / filename).touch()
56
+
57
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
58
+ patch("huggingface_hub.list_repo_files", return_value=mock_files), \
59
+ patch("huggingface_hub.hf_hub_download", side_effect=mock_download):
60
+ target = download_model()
61
+ assert target.name == "alpie-vl-text-q3_k_m.gguf"
62
+ assert "alpie-vl-text-q3_k_m.gguf" in downloaded
63
+ assert "alpie-vl-mmproj-f16.gguf" in downloaded
64
+
65
+
66
+ def test_download_model_downloads_missing_vision_only():
67
+ """When text file is present but mmproj is missing, it should download only mmproj."""
68
+ with tempfile.TemporaryDirectory() as td:
69
+ cache_dir = Path(td)
70
+ (cache_dir / "alpie-vl-text-q3_k_m.gguf").touch()
71
+
72
+ mock_files = [
73
+ ".gitattributes",
74
+ "README.md",
75
+ "alpie-vl-mmproj-f16.gguf",
76
+ "alpie-vl-text-q3_k_m.gguf",
77
+ ]
78
+ downloaded = []
79
+
80
+ def mock_download(repo_id, filename, local_dir, token):
81
+ downloaded.append(filename)
82
+ (local_dir / filename).touch()
83
+
84
+ with patch("codeagent.local_model.get_model_cache_dir", return_value=cache_dir), \
85
+ patch("huggingface_hub.list_repo_files", return_value=mock_files), \
86
+ patch("huggingface_hub.hf_hub_download", side_effect=mock_download):
87
+ target = download_model()
88
+ assert target.name == "alpie-vl-text-q3_k_m.gguf"
89
+ assert downloaded == ["alpie-vl-mmproj-f16.gguf"]
90
+
91
+
92
+ def test_platform_backend_dispatch(monkeypatch):
93
+ """Test that LocalBackend dispatches to the correct platform-specific backend."""
94
+ from codeagent.backends.local_backend import (
95
+ LocalBackend,
96
+ iOSBackend,
97
+ AndroidBackend,
98
+ LinuxBackend,
99
+ MacOSBackend,
100
+ WindowsBackend,
101
+ get_platform_backend,
102
+ )
103
+ cfg = load_config()
104
+
105
+ # iOS
106
+ monkeypatch.setenv("ALPIECODE_PLATFORM", "ios")
107
+ b_ios = LocalBackend(cfg)
108
+ assert isinstance(b_ios, iOSBackend)
109
+ assert isinstance(b_ios, LocalBackend)
110
+ assert b_ios.platform_name == "iOS"
111
+
112
+ # Android
113
+ monkeypatch.setenv("ALPIECODE_PLATFORM", "android")
114
+ b_android = LocalBackend(cfg)
115
+ assert isinstance(b_android, AndroidBackend)
116
+ assert isinstance(b_android, LocalBackend)
117
+ assert b_android.platform_name == "Android"
118
+
119
+ # Linux
120
+ monkeypatch.delenv("ALPIECODE_PLATFORM", raising=False)
121
+ monkeypatch.setattr("sys.platform", "linux")
122
+ b_linux = get_platform_backend(cfg)
123
+ assert isinstance(b_linux, LinuxBackend)
124
+ assert isinstance(b_linux, LocalBackend)
125
+
126
+ # Windows
127
+ monkeypatch.setattr("sys.platform", "win32")
128
+ b_win = get_platform_backend(cfg)
129
+ assert isinstance(b_win, WindowsBackend)
130
+ assert isinstance(b_win, LocalBackend)
131
+
132
+ # macOS
133
+ monkeypatch.setattr("sys.platform", "darwin")
134
+ monkeypatch.setattr("codeagent.paths.is_ios", lambda: False)
135
+ b_mac = get_platform_backend(cfg)
136
+ assert isinstance(b_mac, MacOSBackend)
137
+ assert isinstance(b_mac, LocalBackend)
138
+
139
+
140
+ def test_ios_backend_no_pip_compilation(monkeypatch):
141
+ """iOSBackend must NEVER attempt pip install or dynamic compilation."""
142
+ from codeagent.backends.local_backend import iOSBackend
143
+ cfg = load_config()
144
+ b = iOSBackend(cfg)
145
+
146
+ # Mock llama_cpp as missing and bridge offline
147
+ with patch.dict("sys.modules", {"llama_cpp": None}), \
148
+ patch("subprocess.run", side_effect=AssertionError("subprocess.run must never be called on iOS!")):
149
+ with pytest.raises(RuntimeError) as exc_info:
150
+ b.chat_completion([{"role": "user", "content": "hello"}])
151
+ assert "Dynamic compilation via pip is disabled on iOS" in str(exc_info.value)
152
+
153
+
154
+ def test_ios_backend_with_bridge():
155
+ """iOSBackend communicates cleanly with a local HTTP bridge when available."""
156
+ from codeagent.backends.local_backend import iOSBackend
157
+ cfg = load_config()
158
+ b = iOSBackend(cfg)
159
+
160
+ mock_resp = MagicMock()
161
+ mock_resp.status_code = 200
162
+ mock_resp.text = '{"choices": [{"message": {"content": "response from in-app bridge"}}]}'
163
+
164
+ with patch.dict("sys.modules", {"llama_cpp": None}), \
165
+ patch("httpx.get", return_value=mock_resp), \
166
+ patch("httpx.post", return_value=mock_resp):
167
+ assert b.is_available is True
168
+ res = b.chat_completion([{"role": "user", "content": "hello"}])
169
+ assert res.content == "response from in-app bridge"
170
+
File without changes
File without changes