DeepImagix commited on
Commit
00afbcb
Β·
verified Β·
1 Parent(s): 1dfc401

Skills v2 across agent/Kype/ZyKype: true auto-inject (builtins+learned) into planner AND analysis, skill line in agent thinking stream, skills_used in Kype/ZyKype results, compact recent-message memory for Kype/ZyKype (saves after each run, no old history), ask-when-unsure prompts, relaxed over-strict safety gates (env-var keys, 16-digit numbers, educational security, general advice topics pass), new web_research + create_document skills

Browse files
agent/agent.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- NeuraPrompt Agent v9.3 β€” Skills tools + auto-inject + safety gate
3
  -----------------------------------------------------------------------------
4
  Updates over v9.1:
5
  * MongoDB persistent memory (last 5 messages + user profile) β€” agent_memory.py
@@ -27,6 +27,18 @@ from .prompts.system_prompt import get_system_prompt
27
  from .memory.memory import get_memory_manager
28
  from .tools.registry import register_tool, get_tool, get_tool_descriptions, list_tools
29
  from .tools import web_tools, code_tools, file_tools, vision_tools, document_tools, media_tools, skill_tools
 
 
 
 
 
 
 
 
 
 
 
 
30
  from .tools.github_tools import (
31
  github_list_repos, github_create_repo, github_get_repo,
32
  github_list_issues, github_create_issue, github_read_file,
@@ -629,9 +641,22 @@ async def stream_agent(
629
  # Track if memory was used for the indicator
630
  memory_used = bool(db_memory)
631
 
 
 
 
 
 
 
 
 
 
632
  # Use db_memory instead of the old in-memory system
633
  system_prompt = _build_system_prompt(db_memory)
634
 
 
 
 
 
635
  messages = [
636
  {"role": "system", "content": system_prompt},
637
  {"role": "user", "content": f"user_id: {user_id}\nGoal: {goal}" + (f"\nContext: {context}" if context else "")}
@@ -824,7 +849,12 @@ async def stream_agent(
824
  yield f"data: {json.dumps({'type': 'usage', 'usage': total_usage})}\n\n"
825
  return
826
 
827
- yield _make_sse("tool_start", step, f"Running {action}...", action, time.time() - step_start)
 
 
 
 
 
828
 
829
  result, tool_elapsed = await _execute_tool_and_update_history(action, tool_input, messages, thought)
830
 
@@ -892,7 +922,7 @@ async def agent_stream(req: AgentRequest):
892
  async def health_check():
893
  return {
894
  "status": "ok",
895
- "version": "9.3.0-skills", # bumped β€” skill tools + auto-inject + safety gate
896
  "tools": list_tools(),
897
  "groq_fallback_enabled": bool(GROQ_API_KEY),
898
  "token_tracking_enabled": _get_token_usage() is not None,
 
1
  """
2
+ NeuraPrompt Agent v9.4 β€” True skills auto-inject + skill thinking line + ask-when-unsure
3
  -----------------------------------------------------------------------------
4
  Updates over v9.1:
5
  * MongoDB persistent memory (last 5 messages + user profile) β€” agent_memory.py
 
27
  from .memory.memory import get_memory_manager
28
  from .tools.registry import register_tool, get_tool, get_tool_descriptions, list_tools
29
  from .tools import web_tools, code_tools, file_tools, vision_tools, document_tools, media_tools, skill_tools
30
+
31
+ # ---- Skills auto-injection (v9.4) ----
32
+ try:
33
+ from .skills_catalog import resolve_skills, format_skill_block, skill_thinking_line
34
+ except ImportError:
35
+ try:
36
+ from skills_catalog import resolve_skills, format_skill_block, skill_thinking_line # type: ignore
37
+ except ImportError:
38
+ resolve_skills = lambda task, user_id="", limit=2: [] # type: ignore
39
+ format_skill_block = lambda skills: "" # type: ignore
40
+ skill_thinking_line = lambda skills: "" # type: ignore
41
+ log.warning("[Agent] skills_catalog not available β€” skill auto-inject disabled")
42
  from .tools.github_tools import (
43
  github_list_repos, github_create_repo, github_get_repo,
44
  github_list_issues, github_create_issue, github_read_file,
 
641
  # Track if memory was used for the indicator
642
  memory_used = bool(db_memory)
643
 
644
+ # ── v9.4: Skills auto-inject (builtins + learned) ──
645
+ # Matched skill bodies go straight into the prompt β€” the model no longer
646
+ # wastes steps calling load_skill for a skill we already know matches.
647
+ matched_skills = resolve_skills(goal, user_id=user_id, limit=2)
648
+ skill_block = format_skill_block(matched_skills)
649
+ if skill_block:
650
+ db_memory = (db_memory + "\n\n" + skill_block) if db_memory else skill_block
651
+ skill_line = skill_thinking_line(matched_skills)
652
+
653
  # Use db_memory instead of the old in-memory system
654
  system_prompt = _build_system_prompt(db_memory)
655
 
656
+ # Show the matched skills in the thinking stream BEFORE step 1
657
+ if skill_line:
658
+ yield _make_sse("reasoning", 0, skill_line, "", 0.0, skill_line)
659
+
660
  messages = [
661
  {"role": "system", "content": system_prompt},
662
  {"role": "user", "content": f"user_id: {user_id}\nGoal: {goal}" + (f"\nContext: {context}" if context else "")}
 
849
  yield f"data: {json.dumps({'type': 'usage', 'usage': total_usage})}\n\n"
850
  return
851
 
852
+ if action == "load_skill" and isinstance(tool_input, dict):
853
+ _skill_name = tool_input.get("name") or "skill"
854
+ yield _make_sse("reasoning", step, f"πŸ›  Using {str(_skill_name).replace('_', ' ')} skill for this task", "", 0.0, f"Loading skill: {_skill_name}")
855
+ yield _make_sse("tool_start", step,
856
+ f"Loading skill: {tool_input.get('name')}..." if action == "load_skill" and isinstance(tool_input, dict) and tool_input.get("name")
857
+ else f"Running {action}...", action, time.time() - step_start)
858
 
859
  result, tool_elapsed = await _execute_tool_and_update_history(action, tool_input, messages, thought)
860
 
 
922
  async def health_check():
923
  return {
924
  "status": "ok",
925
+ "version": "9.4.0-skills", # v9.4 β€” true skill auto-inject + skill thinking line + ask-when-unsure
926
  "tools": list_tools(),
927
  "groq_fallback_enabled": bool(GROQ_API_KEY),
928
  "token_tracking_enabled": _get_token_usage() is not None,
agent/kype.py CHANGED
@@ -73,6 +73,32 @@ except ImportError:
73
  def format_skills_hint(task):
74
  return ""
75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  # =================================================================
78
  # CONFIGURATION
@@ -183,6 +209,10 @@ Output format (strict β€” no preamble):
183
  3. RISKS: <bullet list or "none">
184
  If DEBUGGER FEEDBACK is provided, address every flagged issue.
185
 
 
 
 
 
186
  FORMAT: itineraries β†’ markdown tables; code β†’ fenced blocks; comparisons β†’ tables. Stay on task.
187
  {KYPE_RULES_PROMPT}"""
188
 
@@ -192,6 +222,9 @@ ANALYSIS_SYSTEM = f"""You are the ANALYSIS of Kype.
192
  Execute the plan and deliver the full answer to the user's task.
193
  No meta-commentary about the plan or your role β€” just the result.
194
  If DEBUGGER FEEDBACK is provided, address each issue explicitly.
 
 
 
195
 
196
  FORMAT: itineraries MUST use a markdown table (Day|Morning|Afternoon|Evening|Notes);
197
  code MUST use fenced blocks with language tags; comparisons use markdown tables.
@@ -234,6 +267,7 @@ class KypeResult:
234
  total_elapsed: float = 0.0
235
  fallback_used: Optional[str] = None
236
  tool_used: Optional[str] = None
 
237
  usage: Dict[str, int] = field(default_factory=lambda: {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0})
238
 
239
  def to_dict(self) -> Dict[str, Any]:
@@ -244,6 +278,7 @@ class KypeResult:
244
  "approved": self.approved,
245
  "total_elapsed": round(self.total_elapsed, 2),
246
  "fallback_used": self.fallback_used,
 
247
  "tool_used": self.tool_used,
248
  "usage": self.usage,
249
  "trace": [
@@ -483,7 +518,9 @@ class KypeAgent:
483
  debugger_model: str = DEFAULT_DEBUGGER_MODEL,
484
  max_iterations: int = MAX_ITERATIONS,
485
  allow_tools: bool = True,
 
486
  ):
 
487
  self.api_key = api_key or os.getenv("OPENROUTE_KEY", "")
488
  if not self.api_key and not GROQ_API_KEY:
489
  raise EnvironmentError(
@@ -812,14 +849,13 @@ class KypeAgent:
812
  # ---- stage wrappers ---------------------------------------------------
813
  def plan(self, task: str, feedback: str = "") -> Tuple[str, str, str, str, dict]:
814
  """Returns (plan, tool_name, tool_result, provider, usage)."""
815
- skill_hint = ""
816
- try:
817
- skill_hint = format_skills_hint(task) or ""
818
- except Exception:
819
- skill_hint = ""
820
  user = ""
821
- if skill_hint:
822
- user += skill_hint + "\n\n"
 
 
 
 
823
  user += f"TASK:\n{task}\n"
824
  if feedback:
825
  user += f"\nDEBUGGER FEEDBACK (address every issue):\n{feedback}\n"
@@ -859,7 +895,14 @@ class KypeAgent:
859
 
860
  def analyze(self, task: str, plan: str, feedback: str = "",
861
  tool_name: str = "", tool_result: str = "") -> Tuple[str, str, dict]:
862
- user = f"TASK:\n{task}\n\nPLAN:\n{plan}\n"
 
 
 
 
 
 
 
863
  if tool_name and tool_result:
864
  user += f"\n[TOOL RESULT from {tool_name}]:\n{tool_result}\n"
865
  if feedback:
@@ -946,6 +989,21 @@ class KypeAgent:
946
  if not task or not task.strip():
947
  raise ValueError("task must be a non-empty string")
948
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
949
  t_start = time.time()
950
  trace: List[AgentResponse] = []
951
  fallback_used: Optional[str] = None
@@ -1022,8 +1080,13 @@ class KypeAgent:
1022
  verdict.get("issues", []), ensure_ascii=False
1023
  )
1024
 
 
 
 
 
1025
  return KypeResult(
1026
  task=task,
 
1027
  final_answer=draft,
1028
  iterations=iterations_completed,
1029
  approved=approved,
@@ -1449,6 +1512,7 @@ async def kype_run(req: KypeRequest):
1449
  debugger_model=req.debugger_model or DEFAULT_DEBUGGER_MODEL,
1450
  max_iterations=req.max_iterations,
1451
  allow_tools=req.allow_tools,
 
1452
  )
1453
  result = await asyncio.to_thread(agent.run, task)
1454
  except EnvironmentError as e:
@@ -1474,6 +1538,14 @@ async def kype_run(req: KypeRequest):
1474
  except Exception as e:
1475
  log.warning(f"[Kype] Failed to record token usage: {e}")
1476
 
 
 
 
 
 
 
 
 
1477
  # ── Inject ad into final answer (~30% chance) ──
1478
  try:
1479
  ad = maybe_get_ad(user_id=user_id, user_tier="pro" if polar_subscribed else "free", source="kype")
@@ -1501,7 +1573,7 @@ async def kype_health():
1501
  return {
1502
  "status": "maintenance" if maintenance else "ok",
1503
  "service": "kype",
1504
- "version": "1.6-skills", # bumped β€” skills tools + stricter rules
1505
  "roles": ["planner", "analysis", "debugger"],
1506
  "max_file_bytes": MAX_FILE_BYTES,
1507
  "rate_window_seconds": KYPE_RATE_WINDOW_SECONDS,
 
73
  def format_skills_hint(task):
74
  return ""
75
 
76
+ # ---- v1.7: compact memory + unified skills resolver ----
77
+ try:
78
+ from .agent_memory import build_memory_context, save_memory
79
+ except ImportError:
80
+ try:
81
+ from agent_memory import build_memory_context, save_memory # type: ignore
82
+ except ImportError:
83
+ build_memory_context = lambda uid, query="": "" # type: ignore
84
+ save_memory = lambda uid, msg, resp: None # type: ignore
85
+ log.warning("[Kype] agent_memory not available β€” memory disabled")
86
+
87
+ try:
88
+ from .skills_catalog import (
89
+ resolve_skills as _resolve_skills, format_skill_block as _format_skill_block,
90
+ skills_used_names as _skills_used_names)
91
+ except ImportError:
92
+ try:
93
+ from skills_catalog import ( # type: ignore
94
+ resolve_skills as _resolve_skills, format_skill_block as _format_skill_block,
95
+ skills_used_names as _skills_used_names)
96
+ except ImportError:
97
+ _resolve_skills = lambda task, user_id="", limit=2: [] # type: ignore
98
+ _format_skill_block = lambda skills: "" # type: ignore
99
+ _skills_used_names = lambda skills: [] # type: ignore
100
+ log.warning("[Kype] skills_catalog not available β€” skill inject disabled")
101
+
102
 
103
  # =================================================================
104
  # CONFIGURATION
 
209
  3. RISKS: <bullet list or "none">
210
  If DEBUGGER FEEDBACK is provided, address every flagged issue.
211
 
212
+ MEMORY & SKILLS: If "USER MEMORY (recent context)" is provided, treat it as
213
+ conversation history β€” the user may refer to earlier messages. If ACTIVE
214
+ SKILLS are provided, build the plan around following them exactly.
215
+
216
  FORMAT: itineraries β†’ markdown tables; code β†’ fenced blocks; comparisons β†’ tables. Stay on task.
217
  {KYPE_RULES_PROMPT}"""
218
 
 
222
  Execute the plan and deliver the full answer to the user's task.
223
  No meta-commentary about the plan or your role β€” just the result.
224
  If DEBUGGER FEEDBACK is provided, address each issue explicitly.
225
+ If USER MEMORY is provided, use it as conversation context.
226
+ If ACTIVE SKILLS are provided, follow their procedures EXACTLY in the answer
227
+ (the itinerary skill REQUIRES a markdown table, etc).
228
 
229
  FORMAT: itineraries MUST use a markdown table (Day|Morning|Afternoon|Evening|Notes);
230
  code MUST use fenced blocks with language tags; comparisons use markdown tables.
 
267
  total_elapsed: float = 0.0
268
  fallback_used: Optional[str] = None
269
  tool_used: Optional[str] = None
270
+ skills_used: List[str] = field(default_factory=list)
271
  usage: Dict[str, int] = field(default_factory=lambda: {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0})
272
 
273
  def to_dict(self) -> Dict[str, Any]:
 
278
  "approved": self.approved,
279
  "total_elapsed": round(self.total_elapsed, 2),
280
  "fallback_used": self.fallback_used,
281
+ "skills_used": self.skills_used,
282
  "tool_used": self.tool_used,
283
  "usage": self.usage,
284
  "trace": [
 
518
  debugger_model: str = DEFAULT_DEBUGGER_MODEL,
519
  max_iterations: int = MAX_ITERATIONS,
520
  allow_tools: bool = True,
521
+ user_id: str = "",
522
  ):
523
+ self.user_id = (user_id or "").strip()
524
  self.api_key = api_key or os.getenv("OPENROUTE_KEY", "")
525
  if not self.api_key and not GROQ_API_KEY:
526
  raise EnvironmentError(
 
849
  # ---- stage wrappers ---------------------------------------------------
850
  def plan(self, task: str, feedback: str = "") -> Tuple[str, str, str, str, dict]:
851
  """Returns (plan, tool_name, tool_result, provider, usage)."""
 
 
 
 
 
852
  user = ""
853
+ mem_ctx = getattr(self, "_mem_context", "")
854
+ if mem_ctx:
855
+ user += f"USER MEMORY (recent context):\n{mem_ctx}\n\n"
856
+ skill_block = getattr(self, "_skill_block", "")
857
+ if skill_block:
858
+ user += skill_block + "\n\n"
859
  user += f"TASK:\n{task}\n"
860
  if feedback:
861
  user += f"\nDEBUGGER FEEDBACK (address every issue):\n{feedback}\n"
 
895
 
896
  def analyze(self, task: str, plan: str, feedback: str = "",
897
  tool_name: str = "", tool_result: str = "") -> Tuple[str, str, dict]:
898
+ user = ""
899
+ mem_ctx = getattr(self, "_mem_context", "")
900
+ if mem_ctx:
901
+ user += f"USER MEMORY (recent context):\n{mem_ctx}\n\n"
902
+ skill_block = getattr(self, "_skill_block", "")
903
+ if skill_block:
904
+ user += skill_block + "\n\n"
905
+ user += f"TASK:\n{task}\n\nPLAN:\n{plan}\n"
906
  if tool_name and tool_result:
907
  user += f"\n[TOOL RESULT from {tool_name}]:\n{tool_result}\n"
908
  if feedback:
 
989
  if not task or not task.strip():
990
  raise ValueError("task must be a non-empty string")
991
 
992
+ # v1.7: compact memory (profile + last 5 messages β€” no older history,
993
+ # keeps the prompt cheap) + auto-matched skills, built once per run.
994
+ try:
995
+ self._mem_context = build_memory_context(self.user_id, query="") or ""
996
+ except Exception:
997
+ self._mem_context = ""
998
+ try:
999
+ self._skills = _resolve_skills(task, user_id=self.user_id, limit=2)
1000
+ except Exception:
1001
+ self._skills = []
1002
+ try:
1003
+ self._skill_block = _format_skill_block(self._skills)
1004
+ except Exception:
1005
+ self._skill_block = ""
1006
+
1007
  t_start = time.time()
1008
  trace: List[AgentResponse] = []
1009
  fallback_used: Optional[str] = None
 
1080
  verdict.get("issues", []), ensure_ascii=False
1081
  )
1082
 
1083
+ try:
1084
+ _used = _skills_used_names(self._skills)
1085
+ except Exception:
1086
+ _used = []
1087
  return KypeResult(
1088
  task=task,
1089
+ skills_used=_used,
1090
  final_answer=draft,
1091
  iterations=iterations_completed,
1092
  approved=approved,
 
1512
  debugger_model=req.debugger_model or DEFAULT_DEBUGGER_MODEL,
1513
  max_iterations=req.max_iterations,
1514
  allow_tools=req.allow_tools,
1515
+ user_id=user_id,
1516
  )
1517
  result = await asyncio.to_thread(agent.run, task)
1518
  except EnvironmentError as e:
 
1538
  except Exception as e:
1539
  log.warning(f"[Kype] Failed to record token usage: {e}")
1540
 
1541
+ # v1.7: remember this exchange (compact β€” save_memory caps at 5 messages).
1542
+ # Runs BEFORE ad injection so ad text never enters memory.
1543
+ try:
1544
+ if user_id and result.final_answer:
1545
+ save_memory(user_id, task, result.final_answer)
1546
+ except Exception as e:
1547
+ log.warning(f"[Kype] save_memory failed: {e}")
1548
+
1549
  # ── Inject ad into final answer (~30% chance) ──
1550
  try:
1551
  ad = maybe_get_ad(user_id=user_id, user_tier="pro" if polar_subscribed else "free", source="kype")
 
1573
  return {
1574
  "status": "maintenance" if maintenance else "ok",
1575
  "service": "kype",
1576
+ "version": "1.7-skills", # v1.7 β€” memory + full skill inject (both stages) + ask-when-unsure
1577
  "roles": ["planner", "analysis", "debugger"],
1578
  "max_file_bytes": MAX_FILE_BYTES,
1579
  "rate_window_seconds": KYPE_RATE_WINDOW_SECONDS,
agent/kype_rules.py CHANGED
@@ -26,16 +26,26 @@ from typing import Tuple
26
  # =================================================================
27
 
28
  KYPE_RULES_PROMPT = """SCOPE: You are a task-execution agent, not a chat companion.
29
- Stay strictly on the user's task. Do not chit-chat, roleplay, or answer
30
- unrelated questions. Do not give financial, medical, or legal advice β€”
31
- state the limitation and redirect to a qualified professional instead.
32
- Refuse anything involving violence, illegal acts, explicit content,
33
- secrets/credential dumps, or malicious/attack code β€” briefly, no how-to.
 
 
 
 
 
 
 
 
 
34
 
35
  FORMAT RULES:
36
  - Itineraries / travel plans β†’ markdown TABLE (Day|Morning|Afternoon|Evening|Notes).
37
  - Code β†’ fenced markdown code blocks with language tags.
38
  - Comparisons β†’ markdown comparison tables.
 
39
  - Stay on task; no filler small-talk."""
40
 
41
 
@@ -73,16 +83,14 @@ _BLOCK_PATTERNS: dict[str, list[str]] = {
73
  r"\b(write|create|build) (a |an )?(virus|ransomware|keylogger|trojan)\b",
74
  r"\bmalicious (code|script|payload)\b",
75
  r"\bddos (attack|script|tool)\b",
76
- r"\bexploit (code|for) (cve|vulnerability)\b",
77
- r"\bsql injection (how to|attack|payload)\b",
78
  r"\b(write|create) (an? )?(attack|weaponized) (script|payload)\b",
79
  ],
80
  "professional_advice": [
81
- r"\bshould i (invest|buy stock|take out a loan)\b",
82
  r"\bdiagnose (my|this) (symptom|illness|condition)\b",
83
  r"\bwhat (medication|dosage) should i take\b",
84
- r"\bis this contract legally binding\b",
85
- r"\bshould i sue\b",
86
  ],
87
  }
88
 
 
26
  # =================================================================
27
 
28
  KYPE_RULES_PROMPT = """SCOPE: You are a task-execution agent, not a chat companion.
29
+ Stay on the user's task. Do not chit-chat, roleplay, or answer unrelated
30
+ questions.
31
+
32
+ IF UNSURE, ASK: if the task is ambiguous or missing a critical detail
33
+ (format, language, target, data), do NOT guess β€” return ONE short
34
+ clarifying question as your output instead of a guessed deliverable.
35
+ Never invent facts to fill gaps.
36
+
37
+ ADVICE TOPICS (medical/legal/financial): explain general information
38
+ helpfully, then add one short line: "For your specific situation, confirm
39
+ with a qualified professional." These are NOT refusals.
40
+
41
+ HARD REFUSALS (brief, no how-to): violence/weapons instructions, illegal
42
+ activity, malware or attack code, explicit sexual content, credential dumps.
43
 
44
  FORMAT RULES:
45
  - Itineraries / travel plans β†’ markdown TABLE (Day|Morning|Afternoon|Evening|Notes).
46
  - Code β†’ fenced markdown code blocks with language tags.
47
  - Comparisons β†’ markdown comparison tables.
48
+ - If ACTIVE SKILLS are provided for this task, follow them exactly.
49
  - Stay on task; no filler small-talk."""
50
 
51
 
 
83
  r"\b(write|create|build) (a |an )?(virus|ransomware|keylogger|trojan)\b",
84
  r"\bmalicious (code|script|payload)\b",
85
  r"\bddos (attack|script|tool)\b",
86
+ r"\b(write|create|build|generate) .{0,25}sql injection (payload|exploit)\b",
 
87
  r"\b(write|create) (an? )?(attack|weaponized) (script|payload)\b",
88
  ],
89
  "professional_advice": [
 
90
  r"\bdiagnose (my|this) (symptom|illness|condition)\b",
91
  r"\bwhat (medication|dosage) should i take\b",
92
+ r"\bhow much \d+\s*(mg|ml)\b|"
93
+ r"\bhow much\b.{0,30}\bshould i (take|inject)\b",
94
  ],
95
  }
96
 
agent/prompts/system_prompt.py CHANGED
@@ -1,14 +1,15 @@
1
  """
2
- NeuraPrompt Agent β€” System Prompt Module (v9.3 - Skills tools + Strict messaging)
3
  =================================================================================
4
 
5
- Changes over v8.9:
6
- * Added CONTEXT HANDLING section (uploaded files β€” fixes "file is truncated" loop)
7
- * Added SKILL LEARNING instruction (AI notes user preferences)
8
- * Memory context section already existed β€” now populated by agent_memory.py
9
- * NO changes to output format, absolute rules, tool descriptions, or GitHub hints
10
-
11
- IMPORTANT: All additions are ADDITIVE β€” the existing content is unchanged.
 
12
  """
13
 
14
  def get_system_prompt(memory_context: str = "", tool_descriptions: str = "") -> str:
@@ -40,12 +41,18 @@ If the user message includes "Context:" with file content, that content was uplo
40
  skill_learning = """
41
 
42
  ━━━ SKILL LEARNING & USAGE
43
- Skills are procedures. Memory may list "Active skills (follow these):" and/or "Learned skills".
44
- - If Active skills are listed for this goal, FOLLOW their bodies exactly in your final_answer.
45
- - If Learned skills / builtins match the goal, call `load_skill` with the skill name, OR follow Active skill bodies already injected.
 
46
  - Prefer `list_skills` when unsure which skill applies, then `load_skill` for the full procedure.
47
  - Pay attention to user preferences (languages, frameworks, style, timezone, project). The system may save them silently β€” do NOT announce skill saving.
48
 
 
 
 
 
 
49
  ━━━ OUTPUT FORMATTING (frontend renders Markdown)
50
  - Itineraries / travel plans β†’ markdown TABLES (Day | Morning | Afternoon | Evening | Notes).
51
  - Comparisons β†’ markdown comparison TABLES.
@@ -53,12 +60,17 @@ Skills are procedures. Memory may list "Active skills (follow these):" and/or "L
53
  - Docs / API explain β†’ structured markdown with headings + bullets; cite snippets; do not invent APIs.
54
  - Reports / outlines β†’ ## headings and bullets.
55
 
56
- ━━━ STRICT MESSAGING
57
- Refuse (briefly, no tools, no elaboration) requests involving:
58
- secrets/API keys/private keys, bank data, weapons/explosives, malware/attack code, explicit/CSAM,
59
- illegal activity, or medical/legal/financial advice.
 
 
 
 
 
60
  Never dump raw tool JSON, tool names, or internal parameters in final_answer.
61
- Do not write attack/exploit/malware code. Do not roleplay around these bans."""
62
 
63
  format_rules = """
64
 
 
1
  """
2
+ NeuraPrompt Agent β€” System Prompt Module (v9.4 β€” Skills + Ask-when-unsure)
3
  =================================================================================
4
 
5
+ Changes over v9.3:
6
+ * Skills now AUTO-INJECT as "ACTIVE SKILLS" β€” the model must mention the
7
+ skill it is using in its first thought (visible in the thinking stream).
8
+ * New IF UNSURE, ASK rule β€” ask one short clarifying question instead of
9
+ guessing or refusing.
10
+ * STRICT MESSAGING relaxed: hard bans stay (weapons, malware, CSAM, illegal,
11
+ secrets), but medical/legal/financial topics are now answered as general
12
+ information with a brief professional-consult note instead of refused.
13
  """
14
 
15
  def get_system_prompt(memory_context: str = "", tool_descriptions: str = "") -> str:
 
41
  skill_learning = """
42
 
43
  ━━━ SKILL LEARNING & USAGE
44
+ Skills are procedures. Memory may list "ACTIVE SKILLS β€” follow these procedures exactly" and/or "Learned skills".
45
+ - ACTIVE SKILLS listed for this goal were auto-matched to the user's request. FOLLOW their bodies exactly in your final_answer.
46
+ - IMPORTANT β€” SKILL TRANSPARENCY: when ACTIVE SKILLS are listed, your FIRST thought must state which skill(s) you are using and why, e.g. "Using itinerary skill (plan_itinerary) for this task β€” it requires a markdown table."
47
+ - If a Learned skill matches and is NOT already injected, call `load_skill` with the skill name.
48
  - Prefer `list_skills` when unsure which skill applies, then `load_skill` for the full procedure.
49
  - Pay attention to user preferences (languages, frameworks, style, timezone, project). The system may save them silently β€” do NOT announce skill saving.
50
 
51
+ ━━━ IF UNSURE, ASK
52
+ - If the goal is ambiguous or missing a critical detail (format, language, target, data), do NOT guess.
53
+ - Ask ONE short clarifying question as your final answer, then stop. Example: "Which format do you want the report in β€” PDF or Word?"
54
+ - Never refuse a legitimate task just because information is missing. Never invent facts, URLs, APIs, or data to fill gaps.
55
+
56
  ━━━ OUTPUT FORMATTING (frontend renders Markdown)
57
  - Itineraries / travel plans β†’ markdown TABLES (Day | Morning | Afternoon | Evening | Notes).
58
  - Comparisons β†’ markdown comparison TABLES.
 
60
  - Docs / API explain β†’ structured markdown with headings + bullets; cite snippets; do not invent APIs.
61
  - Reports / outlines β†’ ## headings and bullets.
62
 
63
+ ━━━ SAFETY BOUNDARIES (precise, not paranoid)
64
+ HARD REFUSALS β€” refuse briefly, no tools, no elaboration:
65
+ weapons/explosives instructions, malware or attack code, explicit sexual content
66
+ (especially anything involving minors), illegal activity, or credential/key dumps.
67
+ HELP FREELY β€” these are NOT refusals:
68
+ - Medical, legal, or financial TOPICS: explain general information helpfully, then add
69
+ one short line: "For your specific situation, confirm with a qualified professional."
70
+ - Security topics: defensive hardening, how attacks work conceptually, safe practices.
71
+ - Anything the user's own systems, accounts, or code β€” help them.
72
  Never dump raw tool JSON, tool names, or internal parameters in final_answer.
73
+ Do not write attack/exploit/malware code. Do not roleplay around the hard refusals."""
74
 
75
  format_rules = """
76
 
agent/safety_gate.py CHANGED
@@ -19,7 +19,7 @@ _GATE_RULES: list[tuple[str, str, str]] = [
19
  "secrets",
20
  r"(-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----|"
21
  r"\b(?:sk-[A-Za-z0-9_-]{20,}|sk-or-v1-[A-Za-z0-9_-]{20,}|gsk_[A-Za-z0-9_-]{20,})\b|"
22
- r"\b(?:aws_secret_access_key|api[_-]?key|secret[_-]?key)\s*[:=]\s*\S{8,}|"
23
  r"\bAKIA[0-9A-Z]{16}\b)",
24
  "I can't continue β€” please never share private keys, API secrets, or credentials. "
25
  "Rotate anything you pasted and try again without secrets.",
@@ -28,7 +28,8 @@ _GATE_RULES: list[tuple[str, str, str]] = [
28
  "bank_details",
29
  r"\b(?:account\s*(?:number|no\.?)|iban|swift\s*code|routing\s*number|"
30
  r"sort\s*code)\s*[:=#]?\s*[A-Z0-9\s-]{8,}|"
31
- r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b",
 
32
  "I can't process bank or payment card details. Remove them and continue without financial numbers.",
33
  ),
34
  (
@@ -48,10 +49,11 @@ _GATE_RULES: list[tuple[str, str, str]] = [
48
  # Malware / offensive cyber
49
  (
50
  "malware",
51
- r"\b(?:write|create|build|generate)\s+(?:a\s+|an\s+)?(?:virus|ransomware|keylogger|trojan|rootkit|botnet)\b|"
52
  r"\b(?:malicious\s+(?:code|script|payload)|ddos\s+(?:attack|script|tool))\b|"
53
  r"\b(?:sql\s*injection\s+how\s*to|exploit\s+(?:code|poc)\s+for)\b|"
54
- r"\bhow to (?:hack|break into|bypass security)\b",
 
55
  "I can't help with malware, exploits, or attack tooling.",
56
  ),
57
  # Explicit / CSAM
@@ -73,7 +75,7 @@ _GATE_RULES: list[tuple[str, str, str]] = [
73
  (
74
  "legal_financial",
75
  r"\b(?:should i sue|is this contract legally binding|"
76
- r"should i (?:invest|buy stock|take out a loan)|"
77
  r"guaranteed\s+(?:returns|profit))\b",
78
  "I can't give legal or financial advice. Please consult a qualified professional.",
79
  ),
 
19
  "secrets",
20
  r"(-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----|"
21
  r"\b(?:sk-[A-Za-z0-9_-]{20,}|sk-or-v1-[A-Za-z0-9_-]{20,}|gsk_[A-Za-z0-9_-]{20,})\b|"
22
+ r"\b(?:aws_secret_access_key|api[_-]?key|secret[_-]?key)\s*[:=]\s*[\"\x27]?[A-Za-z0-9_-]{25,}|"
23
  r"\bAKIA[0-9A-Z]{16}\b)",
24
  "I can't continue β€” please never share private keys, API secrets, or credentials. "
25
  "Rotate anything you pasted and try again without secrets.",
 
28
  "bank_details",
29
  r"\b(?:account\s*(?:number|no\.?)|iban|swift\s*code|routing\s*number|"
30
  r"sort\s*code)\s*[:=#]?\s*[A-Z0-9\s-]{8,}|"
31
+ r"\b(?:card|credit\s*card|debit\s*card|visa|mastercard)\b[^.]{0,40}\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b|"
32
+ r"\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b\s*(?:card|exp|expiry|cvv)\b",
33
  "I can't process bank or payment card details. Remove them and continue without financial numbers.",
34
  ),
35
  (
 
49
  # Malware / offensive cyber
50
  (
51
  "malware",
52
+ r"\b(?:write|create|build|generate)\s+(?:\w+\s+){0,2}(?:virus|ransomware|keylogger|trojan|rootkit|botnet)\b|"
53
  r"\b(?:malicious\s+(?:code|script|payload)|ddos\s+(?:attack|script|tool))\b|"
54
  r"\b(?:sql\s*injection\s+how\s*to|exploit\s+(?:code|poc)\s+for)\b|"
55
+ r"\bhow to (?:hack|break) into\s+(?:someone|someone\x27?s|an?other|other people|his|her|their|a\s+(?:company|school|bank|email|phone|account|system|computer|wifi))\b|"
56
+ r"\bhow to (?:hack|steal|bypass)\s+(?:someone\x27?s|another|other|his|her|their)\s+(?:account|email|password|phone|wifi|system|computer)\b",
57
  "I can't help with malware, exploits, or attack tooling.",
58
  ),
59
  # Explicit / CSAM
 
75
  (
76
  "legal_financial",
77
  r"\b(?:should i sue|is this contract legally binding|"
78
+ r"guarantee\s+\d+%?\s+(?:returns|profit)|"
79
  r"guaranteed\s+(?:returns|profit))\b",
80
  "I can't give legal or financial advice. Please consult a qualified professional.",
81
  ),
agent/skills_catalog.py CHANGED
@@ -12,6 +12,39 @@ from typing import Any, Dict, List, Optional
12
 
13
 
14
  BUILTIN_SKILLS: List[Dict[str, str]] = [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  {
16
  "id": "read_docs",
17
  "name": "read_docs",
@@ -122,14 +155,21 @@ def _score_skill(skill: Dict[str, str], query: str) -> int:
122
  if name and name in q:
123
  score += 6
124
 
125
- # Token overlap with when_to_use
126
- when_tokens = set(re.findall(r"[a-z0-9_]{3,}", when))
127
- q_tokens = set(re.findall(r"[a-z0-9_]{3,}", q))
 
 
 
 
 
128
  overlap = when_tokens & q_tokens
129
  score += min(10, len(overlap) * 2)
130
 
131
  # Domain keyword hints
132
  hints = {
 
 
133
  "read_docs": ("docs", "documentation", "api", "endpoint", "sdk", "reference", "explain this"),
134
  "format_code": ("format", "refactor", "rewrite", "clean up", "beautify", "lint", "code"),
135
  "plan_itinerary": ("itinerary", "trip", "travel", "vacation", "day trip", "sightseeing", "packing"),
@@ -137,7 +177,9 @@ def _score_skill(skill: Dict[str, str], query: str) -> int:
137
  "write_report_outline": ("report", "outline", "briefing", "write-up", "structured document"),
138
  }
139
  for hint in hints.get(name, ()):
140
- if hint in q:
 
 
141
  score += 5
142
 
143
  # Light body keyword hit (weak)
@@ -172,9 +214,79 @@ def format_matched_bodies(query: str, limit: int = 2) -> str:
172
  return "\n\n".join(parts)
173
 
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  __all__ = [
176
  "BUILTIN_SKILLS",
177
  "get_builtin",
178
  "match_builtins",
179
  "format_matched_bodies",
 
 
 
 
180
  ]
 
12
 
13
 
14
  BUILTIN_SKILLS: List[Dict[str, str]] = [
15
+ {
16
+ "id": "web_research",
17
+ "name": "web_research",
18
+ "when_to_use": (
19
+ "When the user needs current facts, news, prices, recent events, "
20
+ "or anything that requires searching the web."
21
+ ),
22
+ "body": """## Skill: web_research
23
+
24
+ 1. Search BEFORE answering β€” do not rely on memory for anything current
25
+ (news, prices, releases, schedules, scores).
26
+ 2. Run at most 2-3 searches; refine the query once if the first is weak.
27
+ 3. Fetch the most relevant source when details matter.
28
+ 4. Synthesize the findings in your own words β€” cite the source name or URL
29
+ inline for key claims.
30
+ 5. State clearly when sources disagree or info could not be verified.""",
31
+ },
32
+ {
33
+ "id": "create_document",
34
+ "name": "create_document",
35
+ "when_to_use": (
36
+ "When the user asks for a file, PDF, DOCX, spreadsheet, CSV, "
37
+ "report file, or says 'create/download/generate a document'."
38
+ ),
39
+ "body": """## Skill: create_document
40
+
41
+ 1. Confirm the deliverable type (PDF / DOCX / XLSX / CSV) and filename.
42
+ 2. Draft the content fully FIRST, then create the file.
43
+ 3. Call the correct file tool with a clear snake_case filename.
44
+ 4. After creating, give the download link and a 1-2 line summary of contents.
45
+ 5. If the request is ambiguous (e.g. 'make a report' with no format),
46
+ ask ONE short clarifying question before generating.""",
47
+ },
48
  {
49
  "id": "read_docs",
50
  "name": "read_docs",
 
155
  if name and name in q:
156
  score += 6
157
 
158
+ # Token overlap with when_to_use (stopwords removed β€” common words like
159
+ # "for/the/when" caused false matches, e.g. create_document on news queries)
160
+ _STOP = {"the", "and", "for", "with", "you", "your", "when", "user",
161
+ "asks", "from", "about", "are", "this", "that", "have", "not",
162
+ "one", "any", "all", "who", "what", "how", "why", "should",
163
+ "their", "will", "can", "was", "out", "get", "need", "needs"}
164
+ when_tokens = {t for t in re.findall(r"[a-z0-9_]{3,}", when) if t not in _STOP}
165
+ q_tokens = {t for t in re.findall(r"[a-z0-9_]{3,}", q) if t not in _STOP}
166
  overlap = when_tokens & q_tokens
167
  score += min(10, len(overlap) * 2)
168
 
169
  # Domain keyword hints
170
  hints = {
171
+ "web_research": ("search", "latest", "news", "current", "today", "price", "recent", "who won", "update"),
172
+ "create_document": ("pdf", "docx", "word document", "excel", "spreadsheet", "csv", "file", "download", "document"),
173
  "read_docs": ("docs", "documentation", "api", "endpoint", "sdk", "reference", "explain this"),
174
  "format_code": ("format", "refactor", "rewrite", "clean up", "beautify", "lint", "code"),
175
  "plan_itinerary": ("itinerary", "trip", "travel", "vacation", "day trip", "sightseeing", "packing"),
 
177
  "write_report_outline": ("report", "outline", "briefing", "write-up", "structured document"),
178
  }
179
  for hint in hints.get(name, ()):
180
+ # Word-boundary match β€” plain substring matched "document" inside
181
+ # "documentation", wrongly triggering create_document for docs queries.
182
+ if re.search(rf"\b{re.escape(hint)}\b", q):
183
  score += 5
184
 
185
  # Light body keyword hit (weak)
 
214
  return "\n\n".join(parts)
215
 
216
 
217
+ # ─────────────────────────────────────────────────────────────
218
+ # UNIFIED RESOLVER (v2.0) β€” used by agent.py, kype.py, zyloo_agent.py
219
+ # ─────────────────────────────────────────────────────────────
220
+
221
+ def resolve_skills(task: str, user_id: str = "", limit: int = 2) -> List[Dict[str, Any]]:
222
+ """Match builtin + learned skills against a task (best first).
223
+ Returns list of dicts: {name, when_to_use, body, source}.
224
+ Prefers agent_memory.match_skills_for_query (covers both sources);
225
+ falls back to builtin-only matching when memory is unavailable."""
226
+ if not task or not task.strip():
227
+ return []
228
+ try:
229
+ from .agent_memory import match_skills_for_query
230
+ except ImportError:
231
+ try:
232
+ from agent_memory import match_skills_for_query # type: ignore
233
+ except ImportError:
234
+ match_skills_for_query = None # type: ignore
235
+ if match_skills_for_query is not None:
236
+ try:
237
+ matched = match_skills_for_query(user_id or "", task, limit=limit)
238
+ if matched:
239
+ return matched[:limit]
240
+ except Exception:
241
+ pass
242
+ return match_builtins(task, limit=limit)
243
+
244
+
245
+ def format_skill_block(skills: List[Dict[str, Any]]) -> str:
246
+ """Prompt-injection block for matched skills ("" if none)."""
247
+ if not skills:
248
+ return ""
249
+ lines = ["ACTIVE SKILLS β€” follow these procedures exactly for this task:"]
250
+ for sk in skills:
251
+ lines.append(f"### {sk.get('name', '?')}")
252
+ if sk.get("when_to_use"):
253
+ lines.append(f"**When to use:** {sk['when_to_use']}")
254
+ lines.append(sk.get("body") or "")
255
+ return "\n".join(lines)
256
+
257
+
258
+ def skill_thinking_line(skills: List[Dict[str, Any]]) -> str:
259
+ """One-liner for the thinking/reasoning stream, e.g.
260
+ 'πŸ›  Using doc skill (read_docs) + web research skill (web_research) for this task'."""
261
+ if not skills:
262
+ return ""
263
+ friendly = {
264
+ "read_docs": "doc skill", "format_code": "code skill",
265
+ "plan_itinerary": "itinerary skill", "compare_options_table": "comparison skill",
266
+ "write_report_outline": "report skill", "web_research": "web research skill",
267
+ "create_document": "document skill",
268
+ }
269
+ parts = []
270
+ for sk in skills:
271
+ name = sk.get("name", "?")
272
+ parts.append(f"{friendly.get(name, name.replace('_', ' '))} ({name})")
273
+ joined = " + ".join(parts)
274
+ return f"πŸ›  Using {joined} for this task"
275
+
276
+
277
+ def skills_used_names(skills: List[Dict[str, Any]]) -> List[str]:
278
+ """Plain skill names for the result API (skills_used field)."""
279
+ return [sk.get("name", "") for sk in skills if sk.get("name")]
280
+
281
+
282
+
283
  __all__ = [
284
  "BUILTIN_SKILLS",
285
  "get_builtin",
286
  "match_builtins",
287
  "format_matched_bodies",
288
+ "resolve_skills",
289
+ "format_skill_block",
290
+ "skill_thinking_line",
291
+ "skills_used_names",
292
  ]
agent/zyloo_agent.py CHANGED
@@ -57,6 +57,32 @@ from pydantic import BaseModel
57
 
58
  log = logging.getLogger("zyloo_agent")
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  # =================================================================
62
  # CONFIGURATION
@@ -164,7 +190,15 @@ Output format (strict -- no preamble):
164
  - Step 1: ...
165
  - Step 2: ...
166
  3. RISKS: <bullet list or "none">
167
- If DEBUGGER FEEDBACK is provided, address every flagged issue."""
 
 
 
 
 
 
 
 
168
 
169
  ANALYSIS_SYSTEM = f"""You are the ANALYSIS of ZyKype Agent.
170
  {ZYLOO_IDENTITY}
@@ -182,6 +216,13 @@ STRICT RULES:
182
 
183
  Return only the user-facing response.
184
  If DEBUGGER FEEDBACK is provided, address each issue explicitly.
 
 
 
 
 
 
 
185
  """
186
 
187
  DEBUGGER_SYSTEM = f"""You are the DEBUGGER of ZyKype Agent.
@@ -219,6 +260,7 @@ class ZylooResult:
219
  total_elapsed: float = 0.0
220
  fallback_used: Optional[str] = None
221
  tool_used: Optional[str] = None
 
222
  usage: Dict[str, int] = field(default_factory=lambda: {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0})
223
 
224
  def to_dict(self) -> Dict[str, Any]:
@@ -229,6 +271,7 @@ class ZylooResult:
229
  "approved": self.approved,
230
  "total_elapsed": round(self.total_elapsed, 2),
231
  "fallback_used": self.fallback_used,
 
232
  "tool_used": self.tool_used,
233
  "usage": self.usage,
234
  "trace": [
@@ -439,7 +482,9 @@ class ZylooAgent:
439
  debugger_model: str = DEFAULT_DEBUGGER_MODEL,
440
  max_iterations: int = MAX_ITERATIONS,
441
  allow_tools: bool = True,
 
442
  ):
 
443
  self.api_key = api_key or ZYLOO_API_KEY
444
  if not self.api_key and not GROQ_API_KEY:
445
  raise EnvironmentError(
@@ -801,7 +846,14 @@ class ZylooAgent:
801
  # ---- stage wrappers -- identical to Kype (with zyloo_doc_tools hook) ----
802
  def plan(self, task: str, feedback: str = "") -> Tuple[str, str, str, str, dict]:
803
  """Returns (plan, tool_name, tool_result, provider, usage)."""
804
- user = f"TASK:\n{task}\n"
 
 
 
 
 
 
 
805
  if feedback:
806
  user += f"\nDEBUGGER FEEDBACK (address every issue):\n{feedback}\n"
807
  if self.allow_tools:
@@ -839,7 +891,14 @@ class ZylooAgent:
839
 
840
  def analyze(self, task: str, plan: str, feedback: str = "",
841
  tool_name: str = "", tool_result: str = "") -> Tuple[str, str, dict]:
842
- user = f"TASK:\n{task}\n\nPLAN:\n{plan}\n"
 
 
 
 
 
 
 
843
  if tool_name and tool_result:
844
  user += f"\n[TOOL RESULT from {tool_name}]:\n{tool_result}\n"
845
  if feedback:
@@ -919,6 +978,21 @@ class ZylooAgent:
919
  if not task or not task.strip():
920
  raise ValueError("task must be a non-empty string")
921
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
922
  t_start = time.time()
923
  trace: List[AgentResponse] = []
924
  fallback_used: Optional[str] = None
@@ -992,8 +1066,13 @@ class ZylooAgent:
992
  verdict.get("issues", []), ensure_ascii=False
993
  )
994
 
 
 
 
 
995
  return ZylooResult(
996
  task=task,
 
997
  final_answer=_clean_final_answer(draft),
998
  iterations=iterations_completed,
999
  approved=approved,
@@ -1187,7 +1266,7 @@ async def zyloo_run(req: ZylooRequest):
1187
  subscription. Uses the FIXED polar_subscription module which fails
1188
  CLOSED on auth errors (401/403).
1189
  2. Rate limit -- 1 task per 30s per user (returns 429)
1190
- 3. Token budget -- Pro 1M/month, Free 25K/month (returns 402)
1191
  4. Context cap -- 5000 tokens max per task (returns 413)
1192
 
1193
  On Zyloo failure: automatic Groq fallback (same prompts, reduced tokens).
@@ -1347,6 +1426,7 @@ async def zyloo_run(req: ZylooRequest):
1347
  debugger_model=req.debugger_model or DEFAULT_DEBUGGER_MODEL,
1348
  max_iterations=req.max_iterations,
1349
  allow_tools=req.allow_tools,
 
1350
  )
1351
  result = await asyncio.to_thread(agent.run, task)
1352
  except EnvironmentError as e:
@@ -1372,6 +1452,13 @@ async def zyloo_run(req: ZylooRequest):
1372
  except Exception as e:
1373
  log.warning(f"[Zyloo] Failed to record token usage: {e}")
1374
 
 
 
 
 
 
 
 
1375
  out = result.to_dict()
1376
  if req.privacy:
1377
  out = _apply_privacy(out)
@@ -1389,7 +1476,7 @@ async def zyloo_health():
1389
  return {
1390
  "status": "maintenance" if maintenance else "ok",
1391
  "service": "zyloo_agent",
1392
- "version": "1.0",
1393
  "roles": ["planner", "analysis", "debugger"],
1394
  "primary_provider": "zyloo",
1395
  "zyloo_base_url": "https://api.zyloo.io/v1",
 
57
 
58
  log = logging.getLogger("zyloo_agent")
59
 
60
+ # ---- v1.1: compact memory + unified skills resolver ----
61
+ try:
62
+ from .agent_memory import build_memory_context, save_memory
63
+ except ImportError:
64
+ try:
65
+ from agent_memory import build_memory_context, save_memory # type: ignore
66
+ except ImportError:
67
+ build_memory_context = lambda uid, query="": "" # type: ignore
68
+ save_memory = lambda uid, msg, resp: None # type: ignore
69
+ log.warning("[Zyloo] agent_memory not available β€” memory disabled")
70
+
71
+ try:
72
+ from .skills_catalog import (
73
+ resolve_skills as _resolve_skills, format_skill_block as _format_skill_block,
74
+ skills_used_names as _skills_used_names)
75
+ except ImportError:
76
+ try:
77
+ from skills_catalog import ( # type: ignore
78
+ resolve_skills as _resolve_skills, format_skill_block as _format_skill_block,
79
+ skills_used_names as _skills_used_names)
80
+ except ImportError:
81
+ _resolve_skills = lambda task, user_id="", limit=2: [] # type: ignore
82
+ _format_skill_block = lambda skills: "" # type: ignore
83
+ _skills_used_names = lambda skills: [] # type: ignore
84
+ log.warning("[Zyloo] skills_catalog not available β€” skill inject disabled")
85
+
86
 
87
  # =================================================================
88
  # CONFIGURATION
 
190
  - Step 1: ...
191
  - Step 2: ...
192
  3. RISKS: <bullet list or "none">
193
+ If DEBUGGER FEEDBACK is provided, address every flagged issue.
194
+
195
+ IF UNSURE, ASK: if the task is ambiguous or missing a critical detail
196
+ (format, language, target, data), do NOT guess β€” plan around ONE short
197
+ clarifying question as the deliverable. Never invent facts to fill gaps.
198
+
199
+ MEMORY & SKILLS: If "USER MEMORY (recent context)" is provided, treat it as
200
+ conversation history β€” the user may refer to earlier messages. If ACTIVE
201
+ SKILLS are provided, build the plan around following them exactly."""
202
 
203
  ANALYSIS_SYSTEM = f"""You are the ANALYSIS of ZyKype Agent.
204
  {ZYLOO_IDENTITY}
 
216
 
217
  Return only the user-facing response.
218
  If DEBUGGER FEEDBACK is provided, address each issue explicitly.
219
+
220
+ IF UNSURE, ASK: if a critical detail is still ambiguous, return ONE short
221
+ clarifying question as the answer instead of guessing.
222
+
223
+ If USER MEMORY is provided, use it as conversation context.
224
+ If ACTIVE SKILLS are provided, follow their procedures EXACTLY in the
225
+ answer (the itinerary skill REQUIRES a markdown table, etc.).
226
  """
227
 
228
  DEBUGGER_SYSTEM = f"""You are the DEBUGGER of ZyKype Agent.
 
260
  total_elapsed: float = 0.0
261
  fallback_used: Optional[str] = None
262
  tool_used: Optional[str] = None
263
+ skills_used: List[str] = field(default_factory=list)
264
  usage: Dict[str, int] = field(default_factory=lambda: {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0})
265
 
266
  def to_dict(self) -> Dict[str, Any]:
 
271
  "approved": self.approved,
272
  "total_elapsed": round(self.total_elapsed, 2),
273
  "fallback_used": self.fallback_used,
274
+ "skills_used": self.skills_used,
275
  "tool_used": self.tool_used,
276
  "usage": self.usage,
277
  "trace": [
 
482
  debugger_model: str = DEFAULT_DEBUGGER_MODEL,
483
  max_iterations: int = MAX_ITERATIONS,
484
  allow_tools: bool = True,
485
+ user_id: str = "",
486
  ):
487
+ self.user_id = (user_id or "").strip()
488
  self.api_key = api_key or ZYLOO_API_KEY
489
  if not self.api_key and not GROQ_API_KEY:
490
  raise EnvironmentError(
 
846
  # ---- stage wrappers -- identical to Kype (with zyloo_doc_tools hook) ----
847
  def plan(self, task: str, feedback: str = "") -> Tuple[str, str, str, str, dict]:
848
  """Returns (plan, tool_name, tool_result, provider, usage)."""
849
+ user = ""
850
+ mem_ctx = getattr(self, "_mem_context", "")
851
+ if mem_ctx:
852
+ user += f"USER MEMORY (recent context):\n{mem_ctx}\n\n"
853
+ skill_block = getattr(self, "_skill_block", "")
854
+ if skill_block:
855
+ user += skill_block + "\n\n"
856
+ user += f"TASK:\n{task}\n"
857
  if feedback:
858
  user += f"\nDEBUGGER FEEDBACK (address every issue):\n{feedback}\n"
859
  if self.allow_tools:
 
891
 
892
  def analyze(self, task: str, plan: str, feedback: str = "",
893
  tool_name: str = "", tool_result: str = "") -> Tuple[str, str, dict]:
894
+ user = ""
895
+ mem_ctx = getattr(self, "_mem_context", "")
896
+ if mem_ctx:
897
+ user += f"USER MEMORY (recent context):\n{mem_ctx}\n\n"
898
+ skill_block = getattr(self, "_skill_block", "")
899
+ if skill_block:
900
+ user += skill_block + "\n\n"
901
+ user += f"TASK:\n{task}\n\nPLAN:\n{plan}\n"
902
  if tool_name and tool_result:
903
  user += f"\n[TOOL RESULT from {tool_name}]:\n{tool_result}\n"
904
  if feedback:
 
978
  if not task or not task.strip():
979
  raise ValueError("task must be a non-empty string")
980
 
981
+ # v1.1: compact memory (profile + last 5 messages β€” no older history,
982
+ # keeps the prompt cheap) + auto-matched skills, built once per run.
983
+ try:
984
+ self._mem_context = build_memory_context(self.user_id, query="") or ""
985
+ except Exception:
986
+ self._mem_context = ""
987
+ try:
988
+ self._skills = _resolve_skills(task, user_id=self.user_id, limit=2)
989
+ except Exception:
990
+ self._skills = []
991
+ try:
992
+ self._skill_block = _format_skill_block(self._skills)
993
+ except Exception:
994
+ self._skill_block = ""
995
+
996
  t_start = time.time()
997
  trace: List[AgentResponse] = []
998
  fallback_used: Optional[str] = None
 
1066
  verdict.get("issues", []), ensure_ascii=False
1067
  )
1068
 
1069
+ try:
1070
+ _used = _skills_used_names(self._skills)
1071
+ except Exception:
1072
+ _used = []
1073
  return ZylooResult(
1074
  task=task,
1075
+ skills_used=_used,
1076
  final_answer=_clean_final_answer(draft),
1077
  iterations=iterations_completed,
1078
  approved=approved,
 
1266
  subscription. Uses the FIXED polar_subscription module which fails
1267
  CLOSED on auth errors (401/403).
1268
  2. Rate limit -- 1 task per 30s per user (returns 429)
1269
+ 3. Token budget -- Pro 1M/month, Max 1.5M/month, Free 200K/month + 5 daily limits (returns 402/429)
1270
  4. Context cap -- 5000 tokens max per task (returns 413)
1271
 
1272
  On Zyloo failure: automatic Groq fallback (same prompts, reduced tokens).
 
1426
  debugger_model=req.debugger_model or DEFAULT_DEBUGGER_MODEL,
1427
  max_iterations=req.max_iterations,
1428
  allow_tools=req.allow_tools,
1429
+ user_id=user_id,
1430
  )
1431
  result = await asyncio.to_thread(agent.run, task)
1432
  except EnvironmentError as e:
 
1452
  except Exception as e:
1453
  log.warning(f"[Zyloo] Failed to record token usage: {e}")
1454
 
1455
+ # v1.1: remember this exchange (compact β€” save_memory caps at 5 messages)
1456
+ try:
1457
+ if user_id and result.final_answer:
1458
+ save_memory(user_id, task, result.final_answer)
1459
+ except Exception as e:
1460
+ log.warning(f"[Zyloo] save_memory failed: {e}")
1461
+
1462
  out = result.to_dict()
1463
  if req.privacy:
1464
  out = _apply_privacy(out)
 
1476
  return {
1477
  "status": "maintenance" if maintenance else "ok",
1478
  "service": "zyloo_agent",
1479
+ "version": "1.1", # v1.1 β€” memory + skill inject (both stages) + ask-when-unsure
1480
  "roles": ["planner", "analysis", "debugger"],
1481
  "primary_provider": "zyloo",
1482
  "zyloo_base_url": "https://api.zyloo.io/v1",