alpiecode 10.9.4__tar.gz → 10.9.8__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 (139) hide show
  1. {alpiecode-10.9.4 → alpiecode-10.9.8}/PKG-INFO +1 -1
  2. {alpiecode-10.9.4 → alpiecode-10.9.8}/pyproject.toml +1 -1
  3. alpiecode-10.9.8/setup.py +42 -0
  4. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/alpiecode.egg-info/PKG-INFO +1 -1
  5. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/alpiecode.egg-info/SOURCES.txt +6 -0
  6. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/__init__.py +1 -1
  7. alpiecode-10.9.8/src/codeagent/__main__.py +9 -0
  8. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/backends/local_backend.py +100 -25
  9. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/blueprints.py +38 -5
  10. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/cli.py +67 -1
  11. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/config.py +19 -4
  12. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/doctor.py +16 -31
  13. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/executor.py +22 -8
  14. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/local_model.py +266 -59
  15. alpiecode-10.9.8/src/codeagent/onboarding.py +501 -0
  16. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/orchestrator.py +32 -6
  17. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/prompt.py +17 -1
  18. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/system1.py +5 -9
  19. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/tools.py +103 -22
  20. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_context_and_trajectory.py +2 -2
  21. alpiecode-10.9.8/test/test_gpu_detection.py +175 -0
  22. alpiecode-10.9.8/test/test_onboarding.py +250 -0
  23. alpiecode-10.9.8/test/test_truncation_resilience.py +147 -0
  24. {alpiecode-10.9.4 → alpiecode-10.9.8}/README.md +0 -0
  25. {alpiecode-10.9.4 → alpiecode-10.9.8}/setup.cfg +0 -0
  26. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/alpiecode/__init__.py +0 -0
  27. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/alpiecode.egg-info/dependency_links.txt +0 -0
  28. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/alpiecode.egg-info/entry_points.txt +0 -0
  29. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/alpiecode.egg-info/requires.txt +0 -0
  30. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/alpiecode.egg-info/top_level.txt +0 -0
  31. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/agent.py +0 -0
  32. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/assessment.py +0 -0
  33. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/backends/__init__.py +0 -0
  34. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/backends/base.py +0 -0
  35. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/backends/openai_backend.py +0 -0
  36. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/cache.py +0 -0
  37. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/client.py +0 -0
  38. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/compaction.py +0 -0
  39. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/context.py +0 -0
  40. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/diff_preview.py +0 -0
  41. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/discovery.py +0 -0
  42. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/dream_rsi.py +0 -0
  43. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/git_ops.py +0 -0
  44. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/github.py +0 -0
  45. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/guardian.py +0 -0
  46. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/guardrails.py +0 -0
  47. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/ipython_ext.py +0 -0
  48. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/media.py +0 -0
  49. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/memory.py +0 -0
  50. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/metrics.py +0 -0
  51. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/paths.py +0 -0
  52. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/progress.py +0 -0
  53. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/project_template.py +0 -0
  54. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/rephraser.py +0 -0
  55. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/server.py +0 -0
  56. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/session.py +0 -0
  57. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/accessibility-audit/SKILL.md +0 -0
  58. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/accessibility-testing/SKILL.md +0 -0
  59. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/accessibility-ui-components/SKILL.md +0 -0
  60. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/agentic-workflows/SKILL.md +0 -0
  61. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/api-design/SKILL.md +0 -0
  62. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/architecture-design/SKILL.md +0 -0
  63. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/backend-engineering/SKILL.md +0 -0
  64. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/browser-automation/SKILL.md +0 -0
  65. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/cli-development/SKILL.md +0 -0
  66. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/cloud-infrastructure/SKILL.md +0 -0
  67. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/code-generation/SKILL.md +0 -0
  68. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/code-review/SKILL.md +0 -0
  69. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/codebase-onboarding/SKILL.md +0 -0
  70. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/cost-optimization/SKILL.md +0 -0
  71. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/data-analysis/SKILL.md +0 -0
  72. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/data-engineering/SKILL.md +0 -0
  73. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/database-engineering/SKILL.md +0 -0
  74. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/dependency-management/SKILL.md +0 -0
  75. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/dependency-security/SKILL.md +0 -0
  76. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/dependency-upgrades/SKILL.md +0 -0
  77. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/devops-ci-cd/SKILL.md +0 -0
  78. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/docker-containers/SKILL.md +0 -0
  79. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/documentation/SKILL.md +0 -0
  80. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/documentation-site/SKILL.md +0 -0
  81. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/e2e-testing/SKILL.md +0 -0
  82. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/error-handling-resilience/SKILL.md +0 -0
  83. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/feature-development/SKILL.md +0 -0
  84. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/frontend-engineering/SKILL.md +0 -0
  85. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/git-workflow/SKILL.md +0 -0
  86. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/incident-response/SKILL.md +0 -0
  87. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/legacy-code-modernization/SKILL.md +0 -0
  88. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/llm-application-engineering/SKILL.md +0 -0
  89. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/localization-i18n/SKILL.md +0 -0
  90. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/mcp-server-development/SKILL.md +0 -0
  91. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/migration-engineering/SKILL.md +0 -0
  92. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/mobile-development/SKILL.md +0 -0
  93. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/model-evaluation/SKILL.md +0 -0
  94. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/nodejs-services/SKILL.md +0 -0
  95. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/observability/SKILL.md +0 -0
  96. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/performance-optimization/SKILL.md +0 -0
  97. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/privacy-data-protection/SKILL.md +0 -0
  98. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/prompt-engineering/SKILL.md +0 -0
  99. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/python-engineering/SKILL.md +0 -0
  100. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/rag-retrieval/SKILL.md +0 -0
  101. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/react-engineering/SKILL.md +0 -0
  102. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/release-management/SKILL.md +0 -0
  103. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/requirements-analysis/SKILL.md +0 -0
  104. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/responsive-design/SKILL.md +0 -0
  105. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/safe-refactoring/SKILL.md +0 -0
  106. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/secure-coding/SKILL.md +0 -0
  107. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/systematic-debugging/SKILL.md +0 -0
  108. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/technical-planning/SKILL.md +0 -0
  109. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/technical-research/SKILL.md +0 -0
  110. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/technical-writing/SKILL.md +0 -0
  111. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/test-engineering/SKILL.md +0 -0
  112. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/tool-integration/SKILL.md +0 -0
  113. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/typescript-engineering/SKILL.md +0 -0
  114. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/visual-regression-testing/SKILL.md +0 -0
  115. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/web-performance/SKILL.md +0 -0
  116. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/web-security-testing/SKILL.md +0 -0
  117. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills/workflow-automation/SKILL.md +0 -0
  118. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/skills.py +0 -0
  119. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/slash.py +0 -0
  120. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/subagent.py +0 -0
  121. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/updater.py +0 -0
  122. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/verifier.py +0 -0
  123. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/vscode_installer.py +0 -0
  124. {alpiecode-10.9.4 → alpiecode-10.9.8}/src/codeagent/walkthrough.py +0 -0
  125. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_adaptive_resilience.py +0 -0
  126. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_cli_ui.py +0 -0
  127. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_deloop_and_sessions.py +0 -0
  128. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_dream_rsi.py +0 -0
  129. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_lifecycle_and_portfolio.py +0 -0
  130. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_local_model_download.py +0 -0
  131. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_non_thinking_and_local_stream.py +0 -0
  132. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_project_templates.py +0 -0
  133. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_skills_engine.py +0 -0
  134. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_slash_and_diff.py +0 -0
  135. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_subagents.py +0 -0
  136. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_task_assessment.py +0 -0
  137. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_verifier.py +0 -0
  138. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_walkthrough.py +0 -0
  139. {alpiecode-10.9.4 → alpiecode-10.9.8}/test/test_web_resilience_and_guardrails.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.9.4
3
+ Version: 10.9.8
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.9.4"
7
+ version = "10.9.8"
8
8
  description = "AlpieCode"
9
9
  requires-python = ">=3.9"
10
10
  dependencies = [
@@ -0,0 +1,42 @@
1
+ """
2
+ Setup script for AlpieCode.
3
+ Integrates with pyproject.toml and invokes fresh-installation onboarding when run interactively.
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ from setuptools import setup
9
+ from setuptools.command.install import install
10
+ from setuptools.command.develop import develop
11
+
12
+
13
+ def _run_post_install():
14
+ # Only run onboarding if executed in an interactive terminal session and not CI/upgrade
15
+ try:
16
+ if any(os.environ.get(k) == "1" for k in ("CI", "CONTINUOUS_INTEGRATION", "ALPIECODE_NO_ONBOARDING")):
17
+ return
18
+ from codeagent.onboarding import prompt_local_model_onboarding, is_fresh_installation
19
+ if is_fresh_installation():
20
+ prompt_local_model_onboarding()
21
+ except Exception:
22
+ pass
23
+
24
+
25
+ class PostInstallCommand(install):
26
+ def run(self):
27
+ super().run()
28
+ _run_post_install()
29
+
30
+
31
+ class PostDevelopCommand(develop):
32
+ def run(self):
33
+ super().run()
34
+ _run_post_install()
35
+
36
+
37
+ setup(
38
+ cmdclass={
39
+ "install": PostInstallCommand,
40
+ "develop": PostDevelopCommand,
41
+ }
42
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: alpiecode
3
- Version: 10.9.4
3
+ Version: 10.9.8
4
4
  Summary: AlpieCode
5
5
  Requires-Python: >=3.9
6
6
  Requires-Dist: huggingface_hub>=0.20.0
@@ -1,5 +1,6 @@
1
1
  README.md
2
2
  pyproject.toml
3
+ setup.py
3
4
  src/alpiecode/__init__.py
4
5
  src/alpiecode.egg-info/PKG-INFO
5
6
  src/alpiecode.egg-info/SOURCES.txt
@@ -8,6 +9,7 @@ src/alpiecode.egg-info/entry_points.txt
8
9
  src/alpiecode.egg-info/requires.txt
9
10
  src/alpiecode.egg-info/top_level.txt
10
11
  src/codeagent/__init__.py
12
+ src/codeagent/__main__.py
11
13
  src/codeagent/agent.py
12
14
  src/codeagent/assessment.py
13
15
  src/codeagent/blueprints.py
@@ -31,6 +33,7 @@ src/codeagent/local_model.py
31
33
  src/codeagent/media.py
32
34
  src/codeagent/memory.py
33
35
  src/codeagent/metrics.py
36
+ src/codeagent/onboarding.py
34
37
  src/codeagent/orchestrator.py
35
38
  src/codeagent/paths.py
36
39
  src/codeagent/progress.py
@@ -118,14 +121,17 @@ test/test_cli_ui.py
118
121
  test/test_context_and_trajectory.py
119
122
  test/test_deloop_and_sessions.py
120
123
  test/test_dream_rsi.py
124
+ test/test_gpu_detection.py
121
125
  test/test_lifecycle_and_portfolio.py
122
126
  test/test_local_model_download.py
123
127
  test/test_non_thinking_and_local_stream.py
128
+ test/test_onboarding.py
124
129
  test/test_project_templates.py
125
130
  test/test_skills_engine.py
126
131
  test/test_slash_and_diff.py
127
132
  test/test_subagents.py
128
133
  test/test_task_assessment.py
134
+ test/test_truncation_resilience.py
129
135
  test/test_verifier.py
130
136
  test/test_walkthrough.py
131
137
  test/test_web_resilience_and_guardrails.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.9.4"
20
+ __version__ = "10.9.8"
21
21
 
22
22
  def run(task: str, workdir: str = ".", reasoning_level: str = "thinking", **kwargs):
23
23
  """Run an autonomous coding task programmatically."""
@@ -0,0 +1,9 @@
1
+ """
2
+ Entrypoint for `python -m codeagent`
3
+ """
4
+
5
+ import sys
6
+ from codeagent.cli import main
7
+
8
+ if __name__ == "__main__":
9
+ main()
@@ -159,15 +159,31 @@ class LocalBackend:
159
159
  clean["content"] = content
160
160
  sanitized.append(clean)
161
161
 
162
- if sanitized and sanitized[-1].get("role") == "user" and "[Tool Result" in sanitized[-1].get("content", ""):
163
- prompt_hint = (
164
- "\n\n[Next Action: Output your next <tool_call> (e.g. write_file or bash) immediately. "
165
- "Do NOT output conversational text. When all files are created and verified, output: DONE: <summary>.]"
166
- )
167
- if prompt_hint not in sanitized[-1]["content"]:
168
- sanitized[-1]["content"] += prompt_hint
162
+ # Coalesce consecutive messages of identical roles (e.g. tool result + workspace state hints)
163
+ # Prevents ChatML / Jinja template corruption caused by adjacent user messages
164
+ coalesced = []
165
+ for m in sanitized:
166
+ if not m.get("content") and m.get("role") != "system":
167
+ continue
168
+ if coalesced and coalesced[-1]["role"] == m["role"] and m["role"] != "system":
169
+ prev_c = coalesced[-1]["content"].rstrip()
170
+ new_c = m["content"].lstrip()
171
+ if new_c:
172
+ coalesced[-1]["content"] = f"{prev_c}\n\n{new_c}".strip()
173
+ else:
174
+ coalesced.append(m)
175
+
176
+ if coalesced and coalesced[-1].get("role") == "user":
177
+ c_text = coalesced[-1].get("content", "")
178
+ if any(k in c_text for k in ("[Tool Result", "[Workspace State", "Files created so far", "[CRITICAL STYLING DIRECTIVE")):
179
+ prompt_hint = (
180
+ "\n\n[Next Action: Output your next <tool_call> (e.g. write_file or bash) immediately. "
181
+ "Do NOT output conversational text. When all files are created and verified, output: DONE: <summary>.]"
182
+ )
183
+ if "[Next Action:" not in c_text:
184
+ coalesced[-1]["content"] += prompt_hint
169
185
 
170
- return sanitized
186
+ return coalesced
171
187
 
172
188
  @staticmethod
173
189
  def _enforce_context_headroom(
@@ -183,8 +199,12 @@ class LocalBackend:
183
199
  return messages, min(max_tokens, max(256, max_context - 64))
184
200
 
185
201
  def _estimate_msg_tokens(m: dict) -> int:
186
- cnt = str(m.get("content") or "")
187
- return max(1, len(cnt) // 4) + 6
202
+ t_chars = len(str(m.get("content") or ""))
203
+ for tc in m.get("tool_calls") or []:
204
+ if isinstance(tc, dict):
205
+ fn = tc.get("function", {})
206
+ t_chars += len(str(fn.get("arguments", ""))) + len(str(fn.get("name", "")))
207
+ return max(1, t_chars // 4) + 6
188
208
 
189
209
  # Allocate generation headroom
190
210
  max_gen_budget = max(256, min(max_tokens, max_context // 2))
@@ -203,28 +223,25 @@ class LocalBackend:
203
223
  total_prompt_tokens = sum(_estimate_msg_tokens(m) for m in all_work)
204
224
 
205
225
  if total_prompt_tokens > allowed_prompt_tokens:
206
- # Drop older middle messages first
226
+ # 1. First condense bulky tool calls and large outputs in middle turns
227
+ from ..compaction import compact_text_tool_calls, compact_tool_calls
228
+ for m in middle_msgs:
229
+ if m.get("tool_calls"):
230
+ m["tool_calls"] = compact_tool_calls(m["tool_calls"])
231
+ if m.get("content") and "<tool_call>" in str(m["content"]):
232
+ m["content"] = compact_text_tool_calls(str(m["content"]))
233
+
234
+ total_prompt_tokens = sum(_estimate_msg_tokens(m) for m in [dict(m) for m in sys_msgs] + middle_msgs + [tail_msg])
235
+
236
+ # 2. If still over budget, drop older middle messages first
207
237
  while middle_msgs and total_prompt_tokens > allowed_prompt_tokens:
208
238
  dropped = middle_msgs.pop(0)
209
239
  total_prompt_tokens -= _estimate_msg_tokens(dropped)
210
240
 
211
- # If still over budget, truncate tail and system content
212
- if total_prompt_tokens > allowed_prompt_tokens:
213
- excess = total_prompt_tokens - allowed_prompt_tokens
214
- chars_to_cut = (excess + 16) * 4
215
- tail_content = str(tail_msg.get("content", ""))
216
- if len(tail_content) > chars_to_cut + 200:
217
- tail_msg["content"] = tail_content[:-chars_to_cut] + "\n... [truncated for context limit]"
218
- elif sys_msgs:
219
- sys_content = str(sys_msgs[0].get("content", ""))
220
- if len(sys_content) > chars_to_cut + 200:
221
- sys_msgs[0] = dict(sys_msgs[0])
222
- sys_msgs[0]["content"] = sys_content[:-chars_to_cut] + "\n... [truncated system prompt]"
223
-
224
241
  compacted = sys_msgs + middle_msgs + [tail_msg]
225
242
 
226
243
  final_prompt_tokens = sum(_estimate_msg_tokens(m) for m in compacted)
227
- safe_max_tokens = max(128, min(max_tokens, max_context - final_prompt_tokens - 8))
244
+ safe_max_tokens = max(256, min(max_tokens, max_context - final_prompt_tokens - 16))
228
245
  return compacted, safe_max_tokens
229
246
 
230
247
  def chat_completion(
@@ -268,6 +285,17 @@ class LocalBackend:
268
285
 
269
286
  reasoning = getattr(msg, "reasoning", None) or getattr(msg, "reasoning_content", None)
270
287
 
288
+ if not tool_calls:
289
+ from ..executor import parse_text_tool_calls
290
+ parsed_tcs = parse_text_tool_calls(msg.content) if msg.content else []
291
+ if not parsed_tcs and reasoning:
292
+ parsed_tcs = parse_text_tool_calls(reasoning)
293
+ if parsed_tcs:
294
+ tool_calls = [
295
+ ToolCall(id=f"call_local_{i+1}", name=tc["name"], arguments=tc.get("arguments", {}))
296
+ for i, tc in enumerate(parsed_tcs)
297
+ ]
298
+
271
299
  return ChatResponse(
272
300
  content=msg.content,
273
301
  reasoning=reasoning,
@@ -427,6 +455,30 @@ class LocalBackend:
427
455
  done_chunk = "DONE:" + after
428
456
  full_content.append(done_chunk)
429
457
  yield ("token", {"delta": done_chunk})
458
+ elif "<tool_call>" in text:
459
+ before, after = text.split("<tool_call>", 1)
460
+ if before:
461
+ clean_before = before.replace("<think>", "")
462
+ full_reasoning.append(clean_before)
463
+ yield ("thinking_delta", {"delta": clean_before})
464
+ in_think = False
465
+ elapsed = time.time() - start_time
466
+ yield ("thinking_end", {"duration": round(elapsed, 1), "content": "".join(full_reasoning).strip()})
467
+ tc_chunk = "<tool_call>" + after
468
+ full_content.append(tc_chunk)
469
+ yield ("token", {"delta": tc_chunk})
470
+ elif "<function=" in text:
471
+ before, after = text.split("<function=", 1)
472
+ if before:
473
+ clean_before = before.replace("<think>", "")
474
+ full_reasoning.append(clean_before)
475
+ yield ("thinking_delta", {"delta": clean_before})
476
+ in_think = False
477
+ elapsed = time.time() - start_time
478
+ yield ("thinking_end", {"duration": round(elapsed, 1), "content": "".join(full_reasoning).strip()})
479
+ fn_chunk = "<function=" + after
480
+ full_content.append(fn_chunk)
481
+ yield ("token", {"delta": fn_chunk})
430
482
  else:
431
483
  clean_text = text.replace("<think>", "")
432
484
  full_reasoning.append(clean_text)
@@ -465,6 +517,29 @@ class LocalBackend:
465
517
  final_reasoning_str = parts[0].strip()
466
518
  final_content_str = parts[1].strip()
467
519
  yield ("token", {"delta": final_content_str})
520
+ elif "<tool_call>" in final_reasoning_str:
521
+ idx = final_reasoning_str.find("<tool_call>")
522
+ final_content_str = final_reasoning_str[idx:].strip()
523
+ final_reasoning_str = final_reasoning_str[:idx].strip()
524
+ yield ("token", {"delta": final_content_str})
525
+ elif "<function=" in final_reasoning_str:
526
+ idx = final_reasoning_str.find("<function=")
527
+ final_content_str = final_reasoning_str[idx:].strip()
528
+ final_reasoning_str = final_reasoning_str[:idx].strip()
529
+ yield ("token", {"delta": final_content_str})
530
+
531
+ if not tool_calls:
532
+ from ..executor import parse_text_tool_calls
533
+ parsed_tcs = parse_text_tool_calls(final_content_str) if final_content_str else []
534
+ if not parsed_tcs and final_reasoning_str:
535
+ parsed_tcs = parse_text_tool_calls(final_reasoning_str)
536
+ if parsed_tcs and not final_content_str:
537
+ final_content_str = final_reasoning_str
538
+ if parsed_tcs:
539
+ tool_calls = [
540
+ ToolCall(id=f"call_local_{i+1}", name=tc["name"], arguments=tc.get("arguments", {}))
541
+ for i, tc in enumerate(parsed_tcs)
542
+ ]
468
543
 
469
544
  chat_resp = ChatResponse(
470
545
  content=final_content_str,
@@ -704,12 +704,38 @@ def _interactive_arrow_select(title: str, options: list, default_index: int = 0)
704
704
  selected = default_index
705
705
  total = len(options)
706
706
 
707
- # Hide cursor
708
- sys.stdout.write("\x1b[?25l")
709
- sys.stdout.flush()
707
+ stdin_tty = getattr(sys.stdin, "isatty", lambda: False)()
708
+ stdout_tty = getattr(sys.stdout, "isatty", lambda: False)()
709
+
710
+ # In non-interactive environments (CI, background daemon, /dev/null),
711
+ # return default index immediately unless mocked for testing or piped with input
712
+ from . import blueprints as _bp
713
+ is_mocked = getattr(_bp._read_terminal_key, "__name__", "") != "_read_terminal_key"
714
+ fileno_mocked = hasattr(sys.stdin, "fileno") and getattr(sys.stdin.fileno, "__name__", "") == "<lambda>"
715
+
716
+ if (not stdin_tty or not stdout_tty) and not (is_mocked or fileno_mocked):
717
+ chosen_name = options[default_index][0]
718
+ sys.stdout.write(f"\x1b[1;32m✔\x1b[0m \x1b[1m{title}\x1b[0m \x1b[1;36m{chosen_name}\x1b[0m\n\n")
719
+ sys.stdout.flush()
720
+ return default_index
721
+
722
+ # Ensure Windows console Virtual Terminal processing and UTF-8 output is active
723
+ try:
724
+ from .cli import setup_cross_platform_terminal
725
+ setup_cross_platform_terminal()
726
+ except Exception:
727
+ pass
728
+
729
+ # Hide cursor safely
730
+ try:
731
+ sys.stdout.write("\x1b[?25l")
732
+ sys.stdout.flush()
733
+ except Exception:
734
+ pass
710
735
 
711
736
  first_render = True
712
737
  num_rendered_lines = 0
738
+ empty_reads = 0
713
739
  try:
714
740
  while True:
715
741
  term_cols = shutil.get_terminal_size((80, 24)).columns
@@ -735,8 +761,12 @@ def _interactive_arrow_select(title: str, options: list, default_index: int = 0)
735
761
 
736
762
  key = _read_terminal_key()
737
763
  if not key:
764
+ empty_reads += 1
765
+ if empty_reads >= 5:
766
+ break
738
767
  time.sleep(0.01)
739
768
  continue
769
+ empty_reads = 0
740
770
 
741
771
  if key in ("up", "k", "w"):
742
772
  selected = (selected - 1) % total
@@ -759,8 +789,11 @@ def _interactive_arrow_select(title: str, options: list, default_index: int = 0)
759
789
  return selected
760
790
 
761
791
  finally:
762
- sys.stdout.write("\x1b[?25h")
763
- sys.stdout.flush()
792
+ try:
793
+ sys.stdout.write("\x1b[?25h")
794
+ sys.stdout.flush()
795
+ except Exception:
796
+ pass
764
797
 
765
798
 
766
799
  def prompt_website_framework_choice(task: str) -> str:
@@ -87,7 +87,53 @@ def _normalize_args():
87
87
  sys.argv = sys.argv[:cmd_idx + 1] + flags + positionals
88
88
 
89
89
 
90
+ def setup_cross_platform_terminal() -> None:
91
+ """
92
+ Ensure robust Unicode (UTF-8) encoding and ANSI Virtual Terminal Processing
93
+ across Windows cmd.exe, PowerShell, macOS Terminal/iTerm, and Linux.
94
+ Prevents raw escape sequences like '[?25l' or charmap encoding errors.
95
+ """
96
+ # 1. UTF-8 standard streams reconfiguration
97
+ for stream_name in ("stdout", "stderr", "stdin"):
98
+ stream = getattr(sys, stream_name, None)
99
+ if stream and hasattr(stream, "reconfigure"):
100
+ try:
101
+ stream.reconfigure(encoding="utf-8", errors="replace")
102
+ except Exception:
103
+ pass
104
+
105
+ # 2. Windows Virtual Terminal (VT100) and UTF-8 console output setup
106
+ if sys.platform == "win32":
107
+ try:
108
+ import ctypes
109
+ from ctypes import wintypes
110
+
111
+ kernel32 = ctypes.windll.kernel32
112
+ # Set console codepage to UTF-8 (65001)
113
+ try:
114
+ kernel32.SetConsoleOutputCP(65001)
115
+ kernel32.SetConsoleCP(65001)
116
+ except Exception:
117
+ pass
118
+
119
+ # STD_OUTPUT_HANDLE = -11, STD_ERROR_HANDLE = -12
120
+ ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
121
+ ENABLE_PROCESSED_OUTPUT = 0x0001
122
+ ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002
123
+
124
+ for handle_id in (-11, -12):
125
+ h = kernel32.GetStdHandle(handle_id)
126
+ if h and h != wintypes.HANDLE(-1).value:
127
+ mode = wintypes.DWORD()
128
+ if kernel32.GetConsoleMode(h, ctypes.byref(mode)):
129
+ new_mode = mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING | ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT
130
+ kernel32.SetConsoleMode(h, new_mode)
131
+ except Exception:
132
+ pass
133
+
134
+
90
135
  def main():
136
+ setup_cross_platform_terminal()
91
137
  try:
92
138
  import readline # Enable full command-line editing (left/right arrow navigation, history)
93
139
  except ImportError:
@@ -200,6 +246,13 @@ def main():
200
246
  print(f"alpiecode {__version__}")
201
247
  return
202
248
 
249
+ # ── Fresh Installation Onboarding Check ──
250
+ # Prompts new users to optionally download the local GGUF model for offline use.
251
+ # Bypassed on upgrades (when config already exists) or when running 'init'.
252
+ if args.command != "init":
253
+ from .onboarding import prompt_local_model_onboarding
254
+ prompt_local_model_onboarding()
255
+
203
256
  if args.command in ("scaffold",) or (args.command == "init" and getattr(args, "project", False)):
204
257
  from .project_template import initialize_project_structure, ProjectProfile, ProjectMetadata
205
258
  profile_map = {
@@ -315,7 +368,20 @@ def main():
315
368
  cfg.base_url = "offline"
316
369
  import os
317
370
  from .paths import is_android
318
- default_ctx = 2048 if is_android() else 8192
371
+ from .local_model import inspect_gpu_hardware
372
+ try:
373
+ hw = inspect_gpu_hardware()
374
+ vram = hw.get("vram_mb")
375
+ has_6gb_gpu = hw.get("has_gpu") and (hw.get("is_apple_silicon") or (vram and vram >= 5500))
376
+ except Exception:
377
+ has_6gb_gpu = False
378
+
379
+ if is_android():
380
+ default_ctx = 2048
381
+ elif has_6gb_gpu:
382
+ default_ctx = 16384
383
+ else:
384
+ default_ctx = 8192
319
385
  cfg.n_ctx = int(os.environ.get("ALPIECODE_CTX_SIZE", default_ctx))
320
386
  os.environ["ALPIECODE_BASE_URL"] = "offline"
321
387
 
@@ -268,10 +268,25 @@ def load_config() -> Config:
268
268
  if data.get("max_tokens", 8192) > 1024:
269
269
  data["max_tokens"] = 1024
270
270
  elif data.get("base_url") == "offline" and not any(os.environ.get(v) for v in ("ALPIECODE_N_CTX", "ALPIECODE_CTX_SIZE")):
271
- if data.get("n_ctx") in (32768, 4096, 16384):
272
- data["n_ctx"] = 8192
273
- if data.get("max_tokens", 8192) > 4096:
274
- data["max_tokens"] = 4096
271
+ try:
272
+ from .local_model import inspect_gpu_hardware
273
+ hw = inspect_gpu_hardware()
274
+ vram = hw.get("vram_mb")
275
+ # 6GB+ dedicated GPU or Apple Silicon unified memory comfortably handles 16k context with Q8 KV cache
276
+ if hw.get("has_gpu") and (hw.get("is_apple_silicon") or (vram and vram >= 5500)):
277
+ target_ctx = 16384
278
+ target_max = 8192
279
+ else:
280
+ target_ctx = 8192
281
+ target_max = 4096
282
+ except Exception:
283
+ target_ctx = 8192
284
+ target_max = 4096
285
+
286
+ if data.get("n_ctx") in (32768, 4096, 16384, 8192):
287
+ data["n_ctx"] = target_ctx
288
+ if data.get("max_tokens", 8192) > target_max:
289
+ data["max_tokens"] = target_max
275
290
 
276
291
  # Filter data to only keys present in Config fields
277
292
  valid_keys = {f.name for f in fields(Config)}
@@ -47,30 +47,8 @@ def _check_command(cmd: str) -> Tuple[bool, str]:
47
47
 
48
48
  def _check_gpu() -> Dict[str, Any]:
49
49
  """Check both physical GPU hardware and llama-cpp runtime offload support."""
50
- hardware_gpu = None
51
- nvidia_smi = (
52
- shutil.which("nvidia-smi")
53
- or shutil.which("nvidia-smi.exe")
54
- or (shutil.which("/usr/lib/wsl/lib/nvidia-smi") if Path("/usr/lib/wsl/lib/nvidia-smi").exists() else None)
55
- )
56
- if nvidia_smi:
57
- try:
58
- res = subprocess.run(
59
- [str(nvidia_smi), "--query-gpu=name,memory.total", "--format=csv,noheader"],
60
- capture_output=True,
61
- text=True,
62
- timeout=3,
63
- )
64
- if res.returncode == 0 and res.stdout.strip():
65
- hardware_gpu = f"NVIDIA GPU: {res.stdout.strip().splitlines()[0]}"
66
- else:
67
- hardware_gpu = "NVIDIA GPU driver present"
68
- except Exception:
69
- hardware_gpu = "NVIDIA GPU driver present"
70
- elif sys.platform == "darwin":
71
- import platform
72
- if "arm" in platform.processor().lower():
73
- hardware_gpu = "Apple Silicon (Metal)"
50
+ from .local_model import inspect_gpu_hardware
51
+ hw = inspect_gpu_hardware()
74
52
 
75
53
  runtime_offload = False
76
54
  runtime_backend = "CPU only"
@@ -78,20 +56,24 @@ def _check_gpu() -> Dict[str, Any]:
78
56
  import llama_cpp
79
57
  runtime_offload = bool(getattr(llama_cpp, "llama_supports_gpu_offload", lambda: False)())
80
58
  if runtime_offload:
81
- if hardware_gpu and "NVIDIA" in hardware_gpu:
59
+ if hw["vendor"] == "nvidia":
82
60
  runtime_backend = "CUDA"
83
- elif hardware_gpu and "Apple" in hardware_gpu:
61
+ elif hw["vendor"] == "apple":
84
62
  runtime_backend = "Metal"
63
+ elif hw["vendor"] == "amd":
64
+ runtime_backend = "ROCm"
85
65
  else:
86
66
  runtime_backend = "GPU Offload"
87
67
  except Exception:
88
68
  pass
89
69
 
70
+ vram_str = f" ({hw['vram_mb']}MB VRAM)" if hw.get("vram_mb") else ""
90
71
  return {
91
- "has_hardware": hardware_gpu is not None,
92
- "hardware_info": hardware_gpu or "No dedicated GPU detected (CPU mode)",
72
+ "has_hardware": hw["has_gpu"],
73
+ "hardware_info": f"{hw['gpu_name']}{vram_str}" if hw["has_gpu"] else "No dedicated GPU detected (CPU mode)",
93
74
  "runtime_offload": runtime_offload,
94
75
  "runtime_backend": runtime_backend,
76
+ "vendor": hw["vendor"],
95
77
  }
96
78
 
97
79
 
@@ -169,9 +151,12 @@ def run_doctor() -> int:
169
151
  print(f" {_colorize('✅', 'green')} Python Runtime: llama-cpp-python ({gpu_diag['runtime_backend']} acceleration enabled)")
170
152
  passed_checks += 1
171
153
  else:
172
- print(f" {_colorize('⚠️ ', 'yellow')} Python Runtime: llama-cpp-python is running in CPU mode (no CUDA build)")
173
- print(f" {_colorize('💡', 'cyan')} To enable 5-10x faster GPU acceleration, install the CUDA wheel:")
174
- print(f" {_colorize('pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', 'bold')}")
154
+ print(f" {_colorize('⚠️ ', 'yellow')} Python Runtime: llama-cpp-python is running in CPU mode (no GPU build)")
155
+ print(f" {_colorize('💡', 'cyan')} To enable 5-10x faster GPU acceleration, install the accelerated wheel:")
156
+ if sys.platform == "darwin":
157
+ print(f" {_colorize('CMAKE_ARGS=\"-DGGML_METAL=on\" pip install llama-cpp-python --no-cache-dir --force-reinstall', 'bold')}")
158
+ else:
159
+ print(f" {_colorize('pip install llama-cpp-python --extra-index-url https://abetlen.github.io/llama-cpp-python/whl/cu124', 'bold')}")
175
160
  else:
176
161
  print(f" {_colorize('ℹ️ ', 'blue')} {gpu_diag['hardware_info']}")
177
162
  if gpu_diag["runtime_offload"]:
@@ -280,14 +280,28 @@ class ToolExecutor:
280
280
 
281
281
  if response.content:
282
282
  parsed = parse_text_tool_calls(response.content)
283
- return [
284
- ToolCall(
285
- id=f"text_call_{i+1}",
286
- name=tc["name"],
287
- arguments=tc["arguments"],
288
- )
289
- for i, tc in enumerate(parsed)
290
- ]
283
+ if parsed:
284
+ return [
285
+ ToolCall(
286
+ id=f"text_call_{i+1}",
287
+ name=tc["name"],
288
+ arguments=tc["arguments"],
289
+ )
290
+ for i, tc in enumerate(parsed)
291
+ ]
292
+
293
+ if response.reasoning:
294
+ parsed = parse_text_tool_calls(response.reasoning)
295
+ if parsed:
296
+ return [
297
+ ToolCall(
298
+ id=f"text_call_{i+1}",
299
+ name=tc["name"],
300
+ arguments=tc["arguments"],
301
+ )
302
+ for i, tc in enumerate(parsed)
303
+ ]
304
+
291
305
  return []
292
306
 
293
307
  def execute_tool_calls(